Skip to content

Commit b632ea9

Browse files
committed
add Null and TryNull traits
Signed-off-by: Dave Huseby <[email protected]>
1 parent 87df85a commit b632ea9

File tree

3 files changed

+59
-3
lines changed

3 files changed

+59
-3
lines changed

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
[package]
22
name = "multitrait"
3-
version = "0.1.9"
3+
version = "0.1.10"
44
edition = "2021"
5-
authors = ["Dave Huseby <dwh@linuxprogrammer.org>"]
5+
authors = ["Dave Grantham <dwg@linuxprogrammer.org>"]
66
description = "Common traits for multiformats types"
77
repository = "https://github.com/cryptidtech/multitrait.git"
88
readme = "README.md"

src/lib.rs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,17 @@ pub use error::Error;
2525
pub mod enc_into;
2626
pub use enc_into::EncodeInto;
2727

28+
/// Null and TryNull traits
29+
pub mod null;
30+
pub use null::{Null, TryNull};
31+
2832
/// TryDecodeFrom trait
2933
pub mod try_decode_from;
3034
pub use try_decode_from::TryDecodeFrom;
3135

3236
/// one-stop shop for all exported symbols
3337
pub mod prelude {
34-
pub use super::{enc_into::*, try_decode_from::*};
38+
pub use super::{enc_into::*, null::*, try_decode_from::*};
3539
}
3640

3741
#[cfg(test)]
@@ -98,4 +102,38 @@ mod test {
98102
let (num, _) = usize::try_decode_from(&buf).unwrap();
99103
assert_eq!(0xffeeddcc_usize, num);
100104
}
105+
106+
struct Foo(usize);
107+
108+
impl Null for Foo {
109+
fn null() -> Self {
110+
Foo(0)
111+
}
112+
fn is_null(&self) -> bool {
113+
self.0 == 0
114+
}
115+
}
116+
117+
impl TryNull for Foo {
118+
type Error = &'static str;
119+
120+
fn try_null() -> Result<Self, Self::Error> {
121+
Ok(Foo(0))
122+
}
123+
fn is_null(&self) -> bool {
124+
self.0 == 0
125+
}
126+
}
127+
128+
#[test]
129+
fn test_null_value() {
130+
let f = Foo::null();
131+
assert!(Null::is_null(&f));
132+
}
133+
134+
#[test]
135+
fn test_try_null_value() {
136+
let f = Foo::try_null().unwrap();
137+
assert!(TryNull::is_null(&f));
138+
}
101139
}

src/null.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/// This trait is for multiformat objects that have a NULL value
2+
pub trait Null {
3+
/// return an instance of Self where is_null(&self) -> true
4+
fn null() -> Self;
5+
/// verify if self is the null value
6+
fn is_null(&self) -> bool;
7+
}
8+
9+
/// This trait is a fallible version of Null
10+
pub trait TryNull: Sized {
11+
/// the error type to return when constructing a null value fails
12+
type Error;
13+
14+
/// try to construct a Null value of Self
15+
fn try_null() -> Result<Self, Self::Error>;
16+
/// verify if self is the null value
17+
fn is_null(&self) -> bool;
18+
}

0 commit comments

Comments
 (0)