diff --git a/src/storable.rs b/src/storable.rs index bbd59a66..dfcb55e8 100644 --- a/src/storable.rs +++ b/src/storable.rs @@ -344,6 +344,27 @@ impl Storable for u8 { }; } +impl Storable for bool { + fn to_bytes(&self) -> Cow<[u8]> { + let num: u8 = if *self { 1 } else { 0 }; + Cow::Owned(num.to_be_bytes().to_vec()) + } + + fn from_bytes(bytes: Cow<[u8]>) -> Self { + assert_eq!(bytes.len(), 1); + match bytes[0] { + 0 => false, + 1 => true, + other => panic!("Invalid bool encoding: expected 0 or 1, found {}", other), + } + } + + const BOUND: Bound = Bound::Bounded { + max_size: 1, + is_fixed_size: true, + }; +} + impl Storable for [u8; N] { fn to_bytes(&self) -> Cow<[u8]> { Cow::Borrowed(&self[..]) diff --git a/src/storable/tests.rs b/src/storable/tests.rs index 47c2fe5d..e04c55e5 100644 --- a/src/storable/tests.rs +++ b/src/storable/tests.rs @@ -169,3 +169,9 @@ fn to_bytes_checked_fixed_element_correct_size_no_panic() { assert_eq!(X.to_bytes_checked(), Cow::Borrowed(&[1, 2, 3, 4, 5])); } + +#[test] +fn storable_for_bool() { + assert!(!bool::from_bytes(false.to_bytes())); + assert!(bool::from_bytes(true.to_bytes())); +}