|
| 1 | +use core::ops::{Sub, SubAssign}; |
| 2 | + |
| 3 | +use crate::{ |
| 4 | + modular::{sub::sub_montgomery_form, SubResidue}, |
| 5 | + Uint, |
| 6 | +}; |
| 7 | + |
| 8 | +use super::DynResidue; |
| 9 | + |
| 10 | +impl<const LIMBS: usize> SubResidue for DynResidue<LIMBS> { |
| 11 | + fn sub(&self, rhs: &Self) -> Self { |
| 12 | + debug_assert_eq!(self.residue_params, rhs.residue_params); |
| 13 | + Self { |
| 14 | + montgomery_form: sub_montgomery_form( |
| 15 | + &self.montgomery_form, |
| 16 | + &rhs.montgomery_form, |
| 17 | + &self.residue_params.modulus, |
| 18 | + ), |
| 19 | + residue_params: self.residue_params, |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl<const LIMBS: usize> SubAssign for DynResidue<LIMBS> { |
| 25 | + fn sub_assign(&mut self, rhs: Self) { |
| 26 | + self.montgomery_form = sub_montgomery_form( |
| 27 | + &self.montgomery_form, |
| 28 | + &rhs.montgomery_form, |
| 29 | + &self.residue_params.modulus, |
| 30 | + ); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl<const LIMBS: usize> SubAssign<Uint<LIMBS>> for DynResidue<LIMBS> { |
| 35 | + fn sub_assign(&mut self, rhs: Uint<LIMBS>) { |
| 36 | + self.montgomery_form = sub_montgomery_form( |
| 37 | + &self.montgomery_form, |
| 38 | + &DynResidue::new(rhs, self.residue_params).montgomery_form, |
| 39 | + &self.residue_params.modulus, |
| 40 | + ); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl<const LIMBS: usize> Sub for DynResidue<LIMBS> { |
| 45 | + type Output = DynResidue<LIMBS>; |
| 46 | + |
| 47 | + fn sub(mut self, rhs: Self) -> Self::Output { |
| 48 | + self -= rhs; |
| 49 | + self |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +#[cfg(test)] |
| 54 | +mod tests { |
| 55 | + use crate::{ |
| 56 | + modular::runtime_mod::{DynResidue, DynResidueParams}, |
| 57 | + U256, |
| 58 | + }; |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn sub_overflow() { |
| 62 | + let params = DynResidueParams::new(U256::from_be_hex( |
| 63 | + "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", |
| 64 | + )); |
| 65 | + |
| 66 | + let x = |
| 67 | + U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56"); |
| 68 | + let mut x_mod = DynResidue::new(x, params); |
| 69 | + |
| 70 | + let y = |
| 71 | + U256::from_be_hex("d5777c45019673125ad240f83094d4252d829516fac8601ed01979ec1ec1a251"); |
| 72 | + |
| 73 | + x_mod -= y; |
| 74 | + |
| 75 | + let expected = |
| 76 | + U256::from_be_hex("6f357a71e1d5a03167f34879d469352add829491c6df41ddff65387d7ed56f56"); |
| 77 | + |
| 78 | + assert_eq!(expected, x_mod.retrieve()); |
| 79 | + } |
| 80 | +} |
0 commit comments