use core::mem;
use core::ops::{Add, AddAssign};
use tc_bigint::PaddedBigUint;
use super::PaddedMontyForm;
use crate::monty::add_mod_assign;
impl<'a> AddAssign<&PaddedMontyForm<'a>> for PaddedMontyForm<'a> {
fn add_assign(&mut self, rhs: &PaddedMontyForm<'a>) {
self.assert_same_modulus(rhs);
let mut sum = mem::take(&mut self.value).into_limbs();
add_mod_assign(
&mut sum,
rhs.value.as_limbs(),
self.params.modulus.as_limbs(),
);
self.value = PaddedBigUint::new(sum);
}
}
impl<'a> AddAssign<PaddedMontyForm<'a>> for PaddedMontyForm<'a> {
fn add_assign(&mut self, rhs: PaddedMontyForm<'a>) {
*self += &rhs;
}
}
impl<'a> Add<&PaddedMontyForm<'a>> for PaddedMontyForm<'a> {
type Output = PaddedMontyForm<'a>;
fn add(mut self, rhs: &PaddedMontyForm<'a>) -> PaddedMontyForm<'a> {
self += rhs;
self
}
}
impl<'a> Add<PaddedMontyForm<'a>> for PaddedMontyForm<'a> {
type Output = PaddedMontyForm<'a>;
fn add(mut self, rhs: PaddedMontyForm<'a>) -> PaddedMontyForm<'a> {
self += &rhs;
self
}
}
impl<'a> Add<PaddedMontyForm<'a>> for &PaddedMontyForm<'a> {
type Output = PaddedMontyForm<'a>;
fn add(self, mut rhs: PaddedMontyForm<'a>) -> PaddedMontyForm<'a> {
rhs += self;
rhs
}
}
impl<'a> Add<&PaddedMontyForm<'a>> for &PaddedMontyForm<'a> {
type Output = PaddedMontyForm<'a>;
fn add(self, rhs: &PaddedMontyForm<'a>) -> PaddedMontyForm<'a> {
self.clone() + rhs
}
}
impl PaddedMontyForm<'_> {
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}");
}
}
}
}