From 95d3e81ab31dbea246f482011c7a19bba5e1233a Mon Sep 17 00:00:00 2001 From: Rigidity <35380458+Rigidity@users.noreply.github.com> Date: Tue, 23 Apr 2024 17:09:35 -0400 Subject: [PATCH] Add impls for ToClvm and FromClvm to bool (#487) --- crates/clvm-traits/src/from_clvm.rs | 26 ++++++++++++++++++++++++++ crates/clvm-traits/src/to_clvm.rs | 13 +++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/clvm-traits/src/from_clvm.rs b/crates/clvm-traits/src/from_clvm.rs index 6b409d875..abbc3110b 100644 --- a/crates/clvm-traits/src/from_clvm.rs +++ b/crates/clvm-traits/src/from_clvm.rs @@ -55,6 +55,19 @@ clvm_primitive!(i128); clvm_primitive!(usize); clvm_primitive!(isize); +impl FromClvm for bool { + fn from_clvm(decoder: &impl ClvmDecoder, node: N) -> Result { + let atom = decoder.decode_atom(&node)?; + match atom.as_ref() { + [] => Ok(false), + [1] => Ok(true), + _ => Err(FromClvmError::Custom( + "expected boolean value of either `()` or `1`".to_string(), + )), + } + } +} + impl FromClvm for (A, B) where A: FromClvm, @@ -211,6 +224,19 @@ mod tests { assert_eq!(decode(a, "8180"), Ok(-128i8)); } + #[test] + fn test_bool() { + let a = &mut Allocator::new(); + assert_eq!(decode(a, "80"), Ok(false)); + assert_eq!(decode(a, "01"), Ok(true)); + assert_eq!( + decode::(a, "05"), + Err(FromClvmError::Custom( + "expected boolean value of either `()` or `1`".to_string(), + )) + ) + } + #[test] fn test_pair() { let a = &mut Allocator::new(); diff --git a/crates/clvm-traits/src/to_clvm.rs b/crates/clvm-traits/src/to_clvm.rs index 8dfef8480..bff469d07 100644 --- a/crates/clvm-traits/src/to_clvm.rs +++ b/crates/clvm-traits/src/to_clvm.rs @@ -40,6 +40,12 @@ clvm_primitive!(i128); clvm_primitive!(usize); clvm_primitive!(isize); +impl ToClvm for bool { + fn to_clvm(&self, encoder: &mut impl ClvmEncoder) -> Result { + (if *self { 1 } else { 0 }).to_clvm(encoder) + } +} + impl ToClvm for &T where T: ToClvm, @@ -173,6 +179,13 @@ mod tests { assert_eq!(encode(a, -128i8), Ok("8180".to_owned())); } + #[test] + fn test_bool() { + let a = &mut Allocator::new(); + assert_eq!(encode(a, true), Ok("01".to_owned())); + assert_eq!(encode(a, false), Ok("80".to_owned())); + } + #[test] fn test_reference() { let a = &mut Allocator::new();