From c4fe4c9e4f1f63abf5a52462d706828537291b18 Mon Sep 17 00:00:00 2001 From: Matt Palmer Date: Mon, 27 Mar 2023 11:20:51 +1100 Subject: [PATCH] Add PlainText::From, fix u8 conversion corner case --- src/plaintext.rs | 53 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/src/plaintext.rs b/src/plaintext.rs index 5e156ef..8bdd8dc 100644 --- a/src/plaintext.rs +++ b/src/plaintext.rs @@ -12,16 +12,17 @@ impl PlainText { } } -macro_rules! from_type_to_plaintext { +macro_rules! from_uint_to_plaintext { ($ty:ident) => { impl From<$ty> for PlainText { fn from(value: $ty) -> PlainText { - let mut u = value; + let mut u = value as u128; let mut p = [0u16; N]; for i in 0..N { - p[N - i as usize - 1] = (u % W as $ty) as u16; - u /= W as $ty; + dbg!(i, N, W, u, stringify!($ty)); + p[N - i as usize - 1] = (u as u128 % W as u128) as u16; + u /= W as u128; } assert!( @@ -36,11 +37,17 @@ macro_rules! from_type_to_plaintext { }; } -from_type_to_plaintext!(u128); -from_type_to_plaintext!(u64); -from_type_to_plaintext!(u32); -from_type_to_plaintext!(u16); -from_type_to_plaintext!(u8); +from_uint_to_plaintext!(u128); +from_uint_to_plaintext!(u64); +from_uint_to_plaintext!(u32); +from_uint_to_plaintext!(u16); +from_uint_to_plaintext!(u8); + +impl From for PlainText { + fn from(value: bool) -> PlainText { + PlainText::::from(u8::from(value)) + } +} #[cfg(test)] mod tests { @@ -110,4 +117,32 @@ mod tests { ); } } + + mod pt_1_256 { + use super::*; + + #[test] + fn zero() { + assert_eq!([0u16], PlainText::<1, 256>::from(0u8).0); + } + + #[test] + fn tiny() { + assert_eq!([42u16], PlainText::<1, 256>::from(42u8).0); + } + } + + mod pt_1_2_bool { + use super::*; + + #[test] + fn from_true() { + assert_eq!([1u16; 1], PlainText::<1, 2>::from(true).0); + } + + #[test] + fn from_false() { + assert_eq!([0u16], PlainText::<1, 2>::from(false).0); + } + } }