crypto_bigint/uint/modular/constant_mod/
const_add.rs1use core::ops::{Add, AddAssign};
2
3use crate::modular::add::add_montgomery_form;
4
5use super::{Residue, ResidueParams};
6
7impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> Residue<MOD, LIMBS> {
8 pub const fn add(&self, rhs: &Residue<MOD, LIMBS>) -> Self {
10 Self {
11 montgomery_form: add_montgomery_form(
12 &self.montgomery_form,
13 &rhs.montgomery_form,
14 &MOD::MODULUS,
15 ),
16 phantom: core::marker::PhantomData,
17 }
18 }
19}
20
21impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> Add<&Residue<MOD, LIMBS>>
22 for &Residue<MOD, LIMBS>
23{
24 type Output = Residue<MOD, LIMBS>;
25 fn add(self, rhs: &Residue<MOD, LIMBS>) -> Residue<MOD, LIMBS> {
26 self.add(rhs)
27 }
28}
29
30impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> Add<Residue<MOD, LIMBS>>
31 for &Residue<MOD, LIMBS>
32{
33 type Output = Residue<MOD, LIMBS>;
34 #[allow(clippy::op_ref)]
35 fn add(self, rhs: Residue<MOD, LIMBS>) -> Residue<MOD, LIMBS> {
36 self + &rhs
37 }
38}
39
40impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> Add<&Residue<MOD, LIMBS>>
41 for Residue<MOD, LIMBS>
42{
43 type Output = Residue<MOD, LIMBS>;
44 #[allow(clippy::op_ref)]
45 fn add(self, rhs: &Residue<MOD, LIMBS>) -> Residue<MOD, LIMBS> {
46 &self + rhs
47 }
48}
49
50impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> Add<Residue<MOD, LIMBS>>
51 for Residue<MOD, LIMBS>
52{
53 type Output = Residue<MOD, LIMBS>;
54 fn add(self, rhs: Residue<MOD, LIMBS>) -> Residue<MOD, LIMBS> {
55 &self + &rhs
56 }
57}
58
59impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> AddAssign<&Self> for Residue<MOD, LIMBS> {
60 fn add_assign(&mut self, rhs: &Self) {
61 *self = *self + rhs;
62 }
63}
64
65impl<MOD: ResidueParams<LIMBS>, const LIMBS: usize> AddAssign<Self> for Residue<MOD, LIMBS> {
66 fn add_assign(&mut self, rhs: Self) {
67 *self += &rhs;
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use crate::{const_residue, impl_modulus, modular::constant_mod::ResidueParams, U256};
74
75 impl_modulus!(
76 Modulus,
77 U256,
78 "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"
79 );
80
81 #[test]
82 fn add_overflow() {
83 let x =
84 U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56");
85 let mut x_mod = const_residue!(x, Modulus);
86
87 let y =
88 U256::from_be_hex("d5777c45019673125ad240f83094d4252d829516fac8601ed01979ec1ec1a251");
89 let y_mod = const_residue!(y, Modulus);
90
91 x_mod += &y_mod;
92
93 let expected =
94 U256::from_be_hex("1a2472fde50286541d97ca6a3592dd75beb9c9646e40c511b82496cfc3926956");
95
96 assert_eq!(expected, x_mod.retrieve());
97 }
98}