Skip to main content

crypto_bigint/uint/
neg_mod.rs

1//! [`UInt`] subtraction modulus operations.
2
3use crate::{Limb, NegMod, UInt};
4
5impl<const LIMBS: usize> UInt<LIMBS> {
6    /// Computes `-a mod p` in constant time.
7    pub const fn neg_mod(&self, p: &Self) -> Self {
8        let mut tmp = [Limb::ZERO; LIMBS];
9
10        // Subtract `a` from `p` to negate. Ignore the final
11        // borrow because it cannot underflow; a is guaranteed to
12        // be in the field.
13        let mut borrow = Limb::ZERO;
14        let mut i = 0;
15
16        while i < LIMBS {
17            let (l, b) = p.limbs[i].sbb(self.limbs[i], borrow);
18            tmp[i] = l;
19            borrow = b;
20
21            i += 1;
22        }
23
24        // `tmp` could be `p` if `a` was zero. Create a mask that is
25        // zero if `a` was zero, and `Limb::MAX` if self was nonzero.
26        // FIXME: constant time comparison
27        let mut self_or = self.limbs[0];
28        let mut i = 1;
29
30        while i < LIMBS {
31            self_or = self_or.bitor(self.limbs[i]);
32            i += 1;
33        }
34
35        let v = if self_or.eq_vartime(&Limb::ZERO) {
36            Limb::ONE
37        } else {
38            Limb::ZERO
39        };
40
41        let mask = v.wrapping_sub(Limb::ONE);
42
43        let mut i = 0;
44
45        while i < LIMBS {
46            tmp[i] = tmp[i].bitand(mask);
47            i += 1;
48        }
49
50        UInt::new(tmp)
51    }
52}
53
54macro_rules! impl_neg_mod {
55    ($($size:expr),+) => {
56        $(
57            impl NegMod for UInt<$size> {
58                type Output = Self;
59
60                fn neg_mod(&self, p: &Self) -> Self {
61                    debug_assert!(self < p);
62                    self.neg_mod(p)
63                }
64            }
65        )+
66    };
67}
68
69impl_neg_mod!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);