Skip to content

Commit

Permalink
Add PlainText::From<bool>, fix u8 conversion corner case
Browse files Browse the repository at this point in the history
  • Loading branch information
mpalmer committed Mar 27, 2023
1 parent 82aa4ae commit c4fe4c9
Showing 1 changed file with 44 additions and 9 deletions.
53 changes: 44 additions & 9 deletions src/plaintext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ impl<const N: usize, const W: u16> PlainText<N, W> {
}
}

macro_rules! from_type_to_plaintext {
macro_rules! from_uint_to_plaintext {
($ty:ident) => {
impl<const N: usize, const W: u16> From<$ty> for PlainText<N, W> {
fn from(value: $ty) -> PlainText<N, W> {
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!(
Expand All @@ -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<const N: usize, const W: u16> From<bool> for PlainText<N, W> {
fn from(value: bool) -> PlainText<N, W> {
PlainText::<N, W>::from(u8::from(value))
}
}

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -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);
}
}
}

0 comments on commit c4fe4c9

Please sign in to comment.