Skip to content

Commit

Permalink
add Null and TryNull traits
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Huseby <dwh@linuxprogrammer.org>
  • Loading branch information
dhuseby committed Apr 3, 2024
1 parent 87df85a commit b632ea9
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 3 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[package]
name = "multitrait"
version = "0.1.9"
version = "0.1.10"
edition = "2021"
authors = ["Dave Huseby <dwh@linuxprogrammer.org>"]
authors = ["Dave Grantham <dwg@linuxprogrammer.org>"]
description = "Common traits for multiformats types"
repository = "https://github.com/cryptidtech/multitrait.git"
readme = "README.md"
Expand Down
40 changes: 39 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,17 @@ pub use error::Error;
pub mod enc_into;
pub use enc_into::EncodeInto;

/// Null and TryNull traits
pub mod null;
pub use null::{Null, TryNull};

/// TryDecodeFrom trait
pub mod try_decode_from;
pub use try_decode_from::TryDecodeFrom;

/// one-stop shop for all exported symbols
pub mod prelude {
pub use super::{enc_into::*, try_decode_from::*};
pub use super::{enc_into::*, null::*, try_decode_from::*};
}

#[cfg(test)]
Expand Down Expand Up @@ -98,4 +102,38 @@ mod test {
let (num, _) = usize::try_decode_from(&buf).unwrap();
assert_eq!(0xffeeddcc_usize, num);
}

struct Foo(usize);

impl Null for Foo {
fn null() -> Self {
Foo(0)
}
fn is_null(&self) -> bool {
self.0 == 0
}
}

impl TryNull for Foo {
type Error = &'static str;

fn try_null() -> Result<Self, Self::Error> {
Ok(Foo(0))
}
fn is_null(&self) -> bool {
self.0 == 0
}
}

#[test]
fn test_null_value() {
let f = Foo::null();
assert!(Null::is_null(&f));
}

#[test]
fn test_try_null_value() {
let f = Foo::try_null().unwrap();
assert!(TryNull::is_null(&f));
}
}
18 changes: 18 additions & 0 deletions src/null.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/// This trait is for multiformat objects that have a NULL value
pub trait Null {
/// return an instance of Self where is_null(&self) -> true
fn null() -> Self;
/// verify if self is the null value
fn is_null(&self) -> bool;
}

/// This trait is a fallible version of Null
pub trait TryNull: Sized {
/// the error type to return when constructing a null value fails
type Error;

/// try to construct a Null value of Self
fn try_null() -> Result<Self, Self::Error>;
/// verify if self is the null value
fn is_null(&self) -> bool;
}

0 comments on commit b632ea9

Please sign in to comment.