crypto_bigint/uint/
split.rs

1// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits.
2macro_rules! impl_split {
3    ($(($name:ident, $bits:expr)),+) => {
4        $(
5            impl $name {
6                /// Split this number in half, returning its high and low components
7                /// respectively.
8                pub const fn split(&self) -> (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) {
9                    let mut lo = [Limb::ZERO; nlimbs!($bits) / 2];
10                    let mut hi = [Limb::ZERO; nlimbs!($bits) / 2];
11                    let mut i = 0;
12                    let mut j = 0;
13
14                    while j < (nlimbs!($bits) / 2) {
15                        lo[j] = self.limbs[i];
16                        i += 1;
17                        j += 1;
18                    }
19
20                    j = 0;
21                    while j < (nlimbs!($bits) / 2) {
22                        hi[j] = self.limbs[i];
23                        i += 1;
24                        j += 1;
25                    }
26
27                    (UInt { limbs: hi }, UInt { limbs: lo })
28                }
29            }
30
31            impl Split for $name {
32                type Output = UInt<{nlimbs!($bits) / 2}>;
33
34                fn split(&self) -> (Self::Output, Self::Output) {
35                    self.split()
36                }
37            }
38
39            impl From<$name> for (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) {
40                fn from(num: $name) -> (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) {
41                    num.split()
42                }
43            }
44        )+
45     };
46}
47
48#[cfg(test)]
49mod tests {
50    use crate::{U128, U64};
51
52    #[test]
53    fn split() {
54        let (hi, lo) = U128::from_be_hex("00112233445566778899aabbccddeeff").split();
55        assert_eq!(hi, U64::from_u64(0x0011223344556677));
56        assert_eq!(lo, U64::from_u64(0x8899aabbccddeeff));
57    }
58}