use num_traits::WrappingAdd;
use num_traits::ops::overflowing::OverflowingSub;
use tc_bigint::FixedBigUint;
use tc_constant_time::{Choice, ConditionallySelectable};
use crate::{ModSub, NonZero};
use tc_zeroize::Zeroizing;
impl<const N: usize> ModSub for FixedBigUint<N> {
type Output = Self;
fn mod_sub(&self, rhs: &Self, modulus: &NonZero<Self>) -> Self {
let modulus: &Self = modulus;
let residues = (
Zeroizing::new(self % modulus),
Zeroizing::new(rhs % modulus),
);
let (difference, borrowed) = residues.0.overflowing_sub(&residues.1);
let difference = Zeroizing::new(difference);
let raised = Zeroizing::new(difference.wrapping_add(modulus));
Self::conditional_select(&difference, &raised, Choice::from_lsb(u8::from(borrowed)))
}
}
#[cfg(test)]
mod tests {
use tc_bigint::{FixedBigUint, Word};
use crate::{ModSub, NonZero};
const LIMBS: usize = (u128::BITS / Word::BITS) as usize;
const VALUES: [u128; 8] = [
0,
1,
255,
u64::MAX as u128,
u64::MAX as u128 + 1,
i128::MAX as u128,
u128::MAX - 1,
u128::MAX,
];
fn expected(a: u128, b: u128, m: u128) -> u128 {
let (a, b) = (a % m, b % m);
if a >= b { a - b } else { m - (b - a) }
}
#[test]
fn the_difference_is_the_primitive_difference_reduced_by_the_modulus() {
for m in &VALUES[1..] {
let modulus = NonZero::new(FixedBigUint::<LIMBS>::from(*m)).unwrap();
for a in VALUES {
for b in VALUES {
let (x, y) = (
FixedBigUint::<LIMBS>::from(a),
FixedBigUint::<LIMBS>::from(b),
);
let expected = FixedBigUint::<LIMBS>::from(expected(a, b, *m));
assert_eq!(x.mod_sub(&y, &modulus), expected, "{a} {b} {m}");
}
}
}
}
#[test]
fn a_difference_below_zero_is_raised_by_the_modulus() {
let modulus = NonZero::new(FixedBigUint::<LIMBS>::from(u128::MAX)).unwrap();
let (x, y) = (
FixedBigUint::<LIMBS>::from(1u8),
FixedBigUint::<LIMBS>::from(2u8),
);
assert_eq!(
x.mod_sub(&y, &modulus),
FixedBigUint::<LIMBS>::from(u128::MAX - 1)
);
}
}