Skip to main content

crypto_bigint/uint/
sub_mod.rs

1//! [`UInt`] subtraction modulus operations.
2
3use crate::{Limb, SubMod, UInt};
4
5impl<const LIMBS: usize> UInt<LIMBS> {
6    /// Computes `self - rhs mod p` in constant time.
7    ///
8    /// Assumes `self` and `rhs` are `< p`.
9    pub const fn sub_mod(&self, rhs: &UInt<LIMBS>, p: &UInt<LIMBS>) -> UInt<LIMBS> {
10        let (mut out, borrow) = self.sbb(rhs, Limb::ZERO);
11
12        // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise
13        // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the modulus.
14        let mut carry = Limb::ZERO;
15        let mut i = 0;
16
17        while i < LIMBS {
18            let (l, c) = out.limbs[i].adc(p.limbs[i].bitand(borrow), carry);
19            out.limbs[i] = l;
20            carry = c;
21            i += 1;
22        }
23
24        out
25    }
26}
27
28macro_rules! impl_sub_mod {
29    ($($size:expr),+) => {
30        $(
31            impl SubMod for UInt<$size> {
32                type Output = Self;
33
34                fn sub_mod(&self, rhs: &Self, p: &Self) -> Self {
35                    debug_assert!(self < p);
36                    debug_assert!(rhs < p);
37                    self.sub_mod(rhs, p)
38                }
39            }
40        )+
41    };
42}
43
44impl_sub_mod!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
45
46#[cfg(all(test, feature = "rand"))]
47mod tests {
48    use crate::UInt;
49
50    macro_rules! test_sub_mod {
51        ($size:expr, $test_name:ident) => {
52            #[test]
53            fn $test_name() {
54                use crate::Limb;
55                use rand_core::SeedableRng;
56
57                let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1);
58
59                let moduli = [UInt::<$size>::random(&mut rng), UInt::random(&mut rng)];
60
61                for p in &moduli {
62                    let base_cases = [
63                        (1u64, 0u64, 1u64.into()),
64                        (0, 1, p.wrapping_sub(&1u64.into())),
65                        (0, 0, 0u64.into()),
66                    ];
67                    for (a, b, c) in &base_cases {
68                        let a: UInt<$size> = (*a).into();
69                        let b: UInt<$size> = (*b).into();
70
71                        let x = a.sub_mod(&b, p);
72                        assert_eq!(*c, x, "{} - {} mod {} = {} != {}", a, b, p, x, c);
73                    }
74
75                    if $size > 1 {
76                        for _i in 0..100 {
77                            let a: UInt<$size> = Limb::random(&mut rng).into();
78                            let b: UInt<$size> = Limb::random(&mut rng).into();
79                            let (a, b) = if a < b { (b, a) } else { (a, b) };
80
81                            let c = a.sub_mod(&b, p);
82                            assert!(c < *p, "not reduced");
83                            assert_eq!(c, a.wrapping_sub(&b), "result incorrect");
84                        }
85                    }
86
87                    for _i in 0..100 {
88                        let a = UInt::<$size>::random_mod(&mut rng, p);
89                        let b = UInt::<$size>::random_mod(&mut rng, p);
90
91                        let c = a.sub_mod(&b, p);
92                        assert!(c < *p, "not reduced: {} >= {} ", c, p);
93
94                        let x = a.wrapping_sub(&b);
95                        if a >= b && x < *p {
96                            assert_eq!(c, x, "incorrect result");
97                        }
98                    }
99                }
100            }
101        };
102    }
103
104    // Test requires 1-limb is capable of representing a 64-bit integer
105    #[cfg(target_pointer_width = "64")]
106    test_sub_mod!(1, sub1);
107
108    test_sub_mod!(2, sub2);
109    test_sub_mod!(3, sub3);
110    test_sub_mod!(4, sub4);
111    test_sub_mod!(5, sub5);
112    test_sub_mod!(6, sub6);
113    test_sub_mod!(7, sub7);
114    test_sub_mod!(8, sub8);
115    test_sub_mod!(9, sub9);
116    test_sub_mod!(10, sub10);
117    test_sub_mod!(11, sub11);
118    test_sub_mod!(12, sub12);
119}