From b632ea98bc372a8b46c3316cfa8fdfe009a3716e Mon Sep 17 00:00:00 2001 From: Dave Huseby Date: Wed, 3 Apr 2024 12:58:25 -0600 Subject: [PATCH] add Null and TryNull traits Signed-off-by: Dave Huseby --- Cargo.toml | 4 ++-- src/lib.rs | 40 +++++++++++++++++++++++++++++++++++++++- src/null.rs | 18 ++++++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 src/null.rs diff --git a/Cargo.toml b/Cargo.toml index 12c0c27..5c3d265 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "multitrait" -version = "0.1.9" +version = "0.1.10" edition = "2021" -authors = ["Dave Huseby "] +authors = ["Dave Grantham "] description = "Common traits for multiformats types" repository = "https://github.com/cryptidtech/multitrait.git" readme = "README.md" diff --git a/src/lib.rs b/src/lib.rs index 6fab6ed..03e006a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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)] @@ -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 { + 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)); + } } diff --git a/src/null.rs b/src/null.rs new file mode 100644 index 0000000..3f29065 --- /dev/null +++ b/src/null.rs @@ -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; + /// verify if self is the null value + fn is_null(&self) -> bool; +}