crypto_bigint/boxed/uint/
cmp.rs

1//! [`BoxedUint`] comparisons.
2//!
3//! By default these are all constant-time and use the `subtle` crate.
4
5use super::BoxedUint;
6use crate::Limb;
7use subtle::{Choice, ConstantTimeEq};
8
9impl ConstantTimeEq for BoxedUint {
10    #[inline]
11    fn ct_eq(&self, other: &Self) -> Choice {
12        let (shorter, longer) = Self::sort_by_precision(self, other);
13        let mut ret = Choice::from(1u8);
14
15        for i in 0..longer.limbs.len() {
16            let a = shorter.limbs.get(i).unwrap_or(&Limb::ZERO);
17            let b = longer.limbs.get(i).unwrap_or(&Limb::ZERO);
18            ret &= a.ct_eq(b);
19        }
20
21        ret
22    }
23}
24
25impl Eq for BoxedUint {}
26impl PartialEq for BoxedUint {
27    fn eq(&self, other: &Self) -> bool {
28        self.ct_eq(other).into()
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::BoxedUint;
35    use subtle::ConstantTimeEq;
36
37    #[test]
38    fn ct_eq() {
39        let a = BoxedUint::zero();
40        let b = BoxedUint::one();
41
42        assert!(bool::from(a.ct_eq(&a)));
43        assert!(!bool::from(a.ct_eq(&b)));
44        assert!(!bool::from(b.ct_eq(&a)));
45        assert!(bool::from(b.ct_eq(&b)));
46    }
47}