Skip to main content

crypto_bigint/modular/boxed_monty_form/
neg.rs

1//! Negations of boxed integers in Montgomery form.
2
3use super::BoxedMontyForm;
4use core::ops::Neg;
5
6impl BoxedMontyForm {
7    /// Negates the number.
8    #[must_use]
9    pub fn neg(&self) -> Self {
10        Self {
11            montgomery_form: self
12                .montgomery_form
13                .neg_mod(self.params.modulus().as_nz_ref()),
14            params: self.params.clone(),
15        }
16    }
17}
18
19impl Neg for BoxedMontyForm {
20    type Output = Self;
21    fn neg(self) -> Self {
22        BoxedMontyForm::neg(&self)
23    }
24}
25
26impl Neg for &BoxedMontyForm {
27    type Output = BoxedMontyForm;
28    fn neg(self) -> BoxedMontyForm {
29        BoxedMontyForm::neg(self)
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use crate::{
36        BoxedUint,
37        modular::{BoxedMontyForm, BoxedMontyParams},
38    };
39    use hex_literal::hex;
40
41    #[test]
42    fn neg_expected() {
43        let modulus = BoxedUint::from_be_slice(
44            &hex!("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
45            256,
46        )
47        .expect("error creating modulus");
48        let params = BoxedMontyParams::new(modulus.to_odd().unwrap());
49
50        let x = BoxedUint::from_be_slice(
51            &hex!("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56"),
52            256,
53        )
54        .expect("error creating boxeduint");
55
56        let x_mod = BoxedMontyForm::new(x, &params);
57        assert!(bool::from((x_mod.neg() + x_mod).is_zero()));
58    }
59}