1//! [`UInt`] negation modulus operations.
23use crate::{Limb, NegMod, UInt};
45impl<const LIMBS: usize> UInt<LIMBS> {
6/// Computes `-a mod p` in constant time.
7 /// Assumes `self` is in `[0, p)`.
8pub const fn neg_mod(&self, p: &Self) -> Self {
9let z = self.ct_is_nonzero();
10let mut ret = p.sbb(self, Limb::ZERO).0;
11let mut i = 0;
12while i < LIMBS {
13// Set ret to 0 if the original value was 0, in which
14 // case ret would be p.
15ret.limbs[i].0 &= z;
16 i += 1;
17 }
18 ret
19 }
2021/// Computes `-a mod p` in constant time for the special modulus
22 /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`].
23pub const fn neg_mod_special(&self, c: Limb) -> Self {
24Self::ZERO.sub_mod_special(self, c)
25 }
26}
2728impl<const LIMBS: usize> NegMod for UInt<LIMBS> {
29type Output = Self;
3031fn neg_mod(&self, p: &Self) -> Self {
32debug_assert!(self < p);
33self.neg_mod(p)
34 }
35}
3637#[cfg(test)]
38mod tests {
39use crate::U256;
4041#[test]
42fn neg_mod_random() {
43let x =
44 U256::from_be_hex("8d16e171674b4e6d8529edba4593802bf30b8cb161dd30aa8e550d41380007c2");
45let p =
46 U256::from_be_hex("928334a4e4be0843ec225a4c9c61df34bdc7a81513e4b6f76f2bfa3148e2e1b5");
4748let actual = x.neg_mod(&p);
49let expected =
50 U256::from_be_hex("056c53337d72b9d666f86c9256ce5f08cabc1b63b207864ce0d6ecf010e2d9f3");
5152assert_eq!(expected, actual);
53 }
5455#[test]
56fn neg_mod_zero() {
57let x =
58 U256::from_be_hex("0000000000000000000000000000000000000000000000000000000000000000");
59let p =
60 U256::from_be_hex("928334a4e4be0843ec225a4c9c61df34bdc7a81513e4b6f76f2bfa3148e2e1b5");
6162let actual = x.neg_mod(&p);
63let expected =
64 U256::from_be_hex("0000000000000000000000000000000000000000000000000000000000000000");
6566assert_eq!(expected, actual);
67 }
68}