use core::ops::{Add, AddAssign};
use super::BigMontyForm;
use crate::monty::add_mod_assign;
impl<'a> AddAssign<&BigMontyForm<'a>> for BigMontyForm<'a> {
fn add_assign(&mut self, rhs: &BigMontyForm<'a>) {
self.assert_same_modulus(rhs);
add_mod_assign(&mut self.value, &rhs.value, self.params.modulus.as_limbs());
}
}
impl<'a> AddAssign<BigMontyForm<'a>> for BigMontyForm<'a> {
fn add_assign(&mut self, rhs: BigMontyForm<'a>) {
*self += &rhs;
}
}
impl<'a> Add<&BigMontyForm<'a>> for BigMontyForm<'a> {
type Output = BigMontyForm<'a>;
fn add(mut self, rhs: &BigMontyForm<'a>) -> BigMontyForm<'a> {
self += rhs;
self
}
}
impl<'a> Add<BigMontyForm<'a>> for BigMontyForm<'a> {
type Output = BigMontyForm<'a>;
fn add(mut self, rhs: BigMontyForm<'a>) -> BigMontyForm<'a> {
self += &rhs;
self
}
}
impl<'a> Add<BigMontyForm<'a>> for &BigMontyForm<'a> {
type Output = BigMontyForm<'a>;
fn add(self, mut rhs: BigMontyForm<'a>) -> BigMontyForm<'a> {
rhs += self;
rhs
}
}
impl<'a> Add<&BigMontyForm<'a>> for &BigMontyForm<'a> {
type Output = BigMontyForm<'a>;
fn add(self, rhs: &BigMontyForm<'a>) -> BigMontyForm<'a> {
self.clone() + rhs
}
}
impl BigMontyForm<'_> {
pub fn double(&self) -> Self {
let mut doubled = self.clone();
doubled += self;
doubled
}
}
#[cfg(test)]
mod tests {
use super::super::testing::{MODULI, VALUES, form, int, params};
fn add_mod(a: u64, b: u64, m: u64) -> u64 {
((u128::from(a % m) + u128::from(b % m)) % u128::from(m)) as u64
}
#[test]
fn the_sum_is_the_primitive_sum_reduced_by_the_modulus() {
for m in MODULI {
let params = params(m);
for a in VALUES {
for b in VALUES {
let sum = (form(a, ¶ms) + form(b, ¶ms)).retrieve();
assert_eq!(sum, int(add_mod(a, b, m)), "{a} {b} {m}");
}
}
}
}
#[test]
fn doubling_is_adding_to_itself() {
for m in MODULI {
let params = params(m);
for a in VALUES {
let doubled = form(a, ¶ms).double().retrieve();
assert_eq!(doubled, int(add_mod(a, a, m)), "{a} {m}");
}
}
}
}