crypto_bigint/modular/monty_form/
sub.rs1use super::MontyForm;
4use crate::modular::sub::sub_montgomery_form;
5use core::ops::{Sub, SubAssign};
6
7impl<const LIMBS: usize> MontyForm<LIMBS> {
8 pub const fn sub(&self, rhs: &Self) -> Self {
10 Self {
11 montgomery_form: sub_montgomery_form(
12 &self.montgomery_form,
13 &rhs.montgomery_form,
14 &self.params.modulus,
15 ),
16 params: self.params,
17 }
18 }
19}
20
21impl<const LIMBS: usize> Sub<&MontyForm<LIMBS>> for &MontyForm<LIMBS> {
22 type Output = MontyForm<LIMBS>;
23 fn sub(self, rhs: &MontyForm<LIMBS>) -> MontyForm<LIMBS> {
24 debug_assert_eq!(self.params, rhs.params);
25 self.sub(rhs)
26 }
27}
28
29impl<const LIMBS: usize> Sub<MontyForm<LIMBS>> for &MontyForm<LIMBS> {
30 type Output = MontyForm<LIMBS>;
31 #[allow(clippy::op_ref)]
32 fn sub(self, rhs: MontyForm<LIMBS>) -> MontyForm<LIMBS> {
33 self - &rhs
34 }
35}
36
37impl<const LIMBS: usize> Sub<&MontyForm<LIMBS>> for MontyForm<LIMBS> {
38 type Output = MontyForm<LIMBS>;
39 #[allow(clippy::op_ref)]
40 fn sub(self, rhs: &MontyForm<LIMBS>) -> MontyForm<LIMBS> {
41 &self - rhs
42 }
43}
44
45impl<const LIMBS: usize> Sub<MontyForm<LIMBS>> for MontyForm<LIMBS> {
46 type Output = MontyForm<LIMBS>;
47 fn sub(self, rhs: MontyForm<LIMBS>) -> MontyForm<LIMBS> {
48 &self - &rhs
49 }
50}
51
52impl<const LIMBS: usize> SubAssign<&MontyForm<LIMBS>> for MontyForm<LIMBS> {
53 fn sub_assign(&mut self, rhs: &MontyForm<LIMBS>) {
54 *self = *self - rhs;
55 }
56}
57
58impl<const LIMBS: usize> SubAssign<MontyForm<LIMBS>> for MontyForm<LIMBS> {
59 fn sub_assign(&mut self, rhs: MontyForm<LIMBS>) {
60 *self -= &rhs;
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use crate::{
67 modular::{MontyForm, MontyParams},
68 Odd, U256,
69 };
70
71 #[test]
72 fn sub_overflow() {
73 let params = MontyParams::new_vartime(Odd::<U256>::from_be_hex(
74 "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
75 ));
76
77 let x =
78 U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56");
79 let mut x_mod = MontyForm::new(&x, params);
80
81 let y =
82 U256::from_be_hex("d5777c45019673125ad240f83094d4252d829516fac8601ed01979ec1ec1a251");
83 let y_mod = MontyForm::new(&y, params);
84
85 x_mod -= &y_mod;
86
87 let expected =
88 U256::from_be_hex("6f357a71e1d5a03167f34879d469352add829491c6df41ddff65387d7ed56f56");
89
90 assert_eq!(expected, x_mod.retrieve());
91 }
92}