arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/math/src/modulus/impl_u64/montgomery.rs
math/src/modulus/impl_u64/montgomery.rsRaw
  1
  2use crate::modulus::ReduceOnce;
  3use crate::modulus::montgomery::{MontgomeryPrecomp, Montgomery};
  4use crate::modulus::barrett::BarrettPrecomp;
  5use crate::modulus::{REDUCEMOD, ONCE};
  6extern crate test;
  7
  8/// MontgomeryPrecomp is a set of methods implemented for MontgomeryPrecomp<u64>
  9/// enabling Montgomery arithmetic over u64 values.
 10impl MontgomeryPrecomp<u64>{
 11
 12    /// Returns an new instance of MontgomeryPrecomp<u64>.
 13    /// This method will fail if gcd(q, 2^64) != 1.
 14    #[inline(always)]
 15    pub fn new(q: u64) -> MontgomeryPrecomp<u64>{
 16        assert!(q & 1 != 0, "Invalid argument: gcd(q={}, radix=2^64) != 1", q);
 17        let mut q_inv: u64 = 1;
 18        let mut q_pow = q;
 19        for _i in 0..63{
 20            q_inv = q_inv.wrapping_mul(q_pow);
 21            q_pow = q_pow.wrapping_mul(q_pow);
 22        }
 23        let mut precomp = Self{ 
 24            q: q,
 25            two_q: q<<1,
 26            four_q: q<<2,
 27            barrett: BarrettPrecomp::new(q), 
 28            q_inv: q_inv,
 29            one: 0,
 30            minus_one:0,
 31        };
 32
 33        precomp.one = precomp.prepare::<ONCE>(1);
 34        precomp.minus_one = q-precomp.one;
 35
 36        precomp
 37    }
 38
 39    /// Returns 2^64 mod q as a Montgomery<u64>.
 40    #[inline(always)]
 41    pub fn one(&self) -> Montgomery<u64>{
 42        self.one
 43    }
 44
 45    /// Returns (q-1) * 2^64 mod q as a Montgomery<u64>.
 46    #[inline(always)]
 47    pub fn minus_one(&self) -> Montgomery<u64>{
 48        self.minus_one
 49    }
 50
 51    /// Applies a modular reduction on x based on REDUCE:
 52    /// - LAZY: no modular reduction.
 53    /// - ONCE: subtracts q if x >= q.
 54    /// - FULL: maps x to x mod q using Barrett reduction.
 55    #[inline(always)]
 56    pub fn reduce<const REDUCE:REDUCEMOD>(&self, x: u64) -> u64{
 57        let mut r: u64 = x;
 58        self.reduce_assign::<REDUCE>(&mut r);
 59        r
 60    }
 61
 62    /// Applies a modular reduction on x based on REDUCE:
 63    /// - LAZY: no modular reduction.
 64    /// - ONCE: subtracts q if x >= q.
 65    /// - FULL: maps x to x mod q using Barrett reduction.
 66    #[inline(always)]
 67    pub fn reduce_assign<const REDUCE:REDUCEMOD>(&self, x: &mut u64){
 68        self.barrett.reduce_assign::<REDUCE>(x);
 69    }
 70
 71    /// Returns lhs * 2^64 mod q as a Montgomery<u64>.
 72    #[inline(always)]
 73    pub fn prepare<const REDUCE:REDUCEMOD>(&self, lhs: u64) -> Montgomery<u64>{
 74        let mut rhs: u64 = 0;
 75        self.prepare_assign::<REDUCE>(lhs, &mut rhs);
 76        rhs
 77    }
 78
 79    /// Assigns lhs * 2^64 mod q to rhs.
 80    #[inline(always)]
 81    pub fn prepare_assign<const REDUCE:REDUCEMOD>(&self, lhs: u64, rhs: &mut Montgomery<u64>){
 82        let (_, mhi) = lhs.widening_mul(*self.barrett.value_lo());
 83        *rhs = (lhs.wrapping_mul(*self.barrett.value_hi()).wrapping_add(mhi)).wrapping_mul(self.q).wrapping_neg();
 84        self.reduce_assign::<REDUCE>(rhs); 
 85    }
 86
 87    /// Returns lhs * (2^64)^-1 mod q as a u64.
 88    #[inline(always)]
 89    pub fn unprepare<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>) -> u64{
 90        let mut rhs = 0u64;
 91        self.unprepare_assign::<REDUCE>(lhs, &mut rhs);
 92        rhs
 93    }
 94
 95    /// Assigns lhs * (2^64)^-1 mod q to rhs.
 96    #[inline(always)]
 97    pub fn unprepare_assign<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>, rhs: &mut u64){
 98        let (_, r) = self.q.widening_mul(lhs.wrapping_mul(self.q_inv));
 99        *rhs = self.reduce::<REDUCE>(self.q.wrapping_sub(r));        
100    }
101
102    /// Returns lhs * rhs * (2^{64})^-1 mod q.
103    #[inline(always)]
104    pub fn mul_external<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>, rhs: u64) -> u64{
105        let mut r: u64 = rhs;
106        self.mul_external_assign::<REDUCE>(lhs, &mut r);
107        r
108    }
109
110    /// Assigns lhs * rhs * (2^{64})^-1 mod q to rhs.
111    #[inline(always)]
112    pub fn mul_external_assign<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>, rhs: &mut u64){
113        let (mlo, mhi) = lhs.widening_mul(*rhs);
114        let (_, hhi) = self.q.widening_mul(mlo.wrapping_mul(self.q_inv));
115        *rhs = self.reduce::<REDUCE>(mhi.wrapping_sub(hhi).wrapping_add(self.q));
116    }
117
118    /// Returns lhs * rhs * (2^{64})^-1 mod q in range [0, 2q-1].
119    #[inline(always)]
120    pub fn mul_internal<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>, rhs: Montgomery<u64>) -> Montgomery<u64>{
121        self.mul_external::<REDUCE>(lhs, rhs)
122    }
123
124    /// Assigns lhs * rhs * (2^{64})^-1 mod q to rhs.
125    #[inline(always)]
126    pub fn mul_internal_assign<const REDUCE:REDUCEMOD>(&self, lhs: Montgomery<u64>, rhs: &mut Montgomery<u64>){
127        self.mul_external_assign::<REDUCE>(lhs, rhs);
128    }
129
130    #[inline(always)]
131    pub fn add_internal(&self, lhs: Montgomery<u64>, rhs: Montgomery<u64>) -> Montgomery<u64>{
132        rhs + lhs
133    }
134
135    /// Assigns lhs + rhs to rhs.
136    #[inline(always)]
137    pub fn add_internal_lazy_assign(&self, lhs: Montgomery<u64>, rhs: &mut Montgomery<u64>){
138        *rhs += lhs
139    }
140
141    /// Assigns lhs + rhs - q if (lhs + rhs) >= q to rhs.
142    #[inline(always)]
143    pub fn add_internal_reduce_once_assign<const LAZY:bool>(&self, lhs: Montgomery<u64>, rhs: &mut Montgomery<u64>){
144        self.add_internal_lazy_assign(lhs, rhs);
145        rhs.reduce_once_assign(self.q);
146    }
147
148    /// Returns (x^exponent) * 2^64 mod q.
149    #[inline(always)]
150    pub fn pow(&self, x: Montgomery<u64>, exponent:u64) -> Montgomery<u64>{
151        let mut y: Montgomery<u64> = self.one();
152        let mut x_mut: Montgomery<u64> = x;
153        let mut i: u64 = exponent;
154        while i > 0{
155            if i & 1 == 1{
156                self.mul_internal_assign::<ONCE>(x_mut, &mut y);
157            }
158            self.mul_internal_assign::<ONCE>(x_mut, &mut x_mut);
159            i >>= 1;
160        }
161
162        y.reduce_once_assign(self.q);
163        y
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use crate::modulus::montgomery;
170    use super::*;
171    use test::Bencher;
172
173    #[test]
174    fn test_mul_external() {
175        let q: u64 = 0x1fffffffffe00001;
176    	let m_precomp = montgomery::MontgomeryPrecomp::new(q);
177        let x: u64 = 0x5f876e514845cc8b;
178        let y: u64 = 0xad726f98f24a761a;
179        let y_mont = m_precomp.prepare::<ONCE>(y);
180    	assert!(m_precomp.mul_external::<ONCE>(y_mont, x) == (x as u128 * y as u128 % q as u128) as u64);
181    }
182
183    #[bench]
184    fn bench_mul_external(b: &mut Bencher){
185        let q: u64 = 0x1fffffffffe00001;
186    	let m_precomp = montgomery::MontgomeryPrecomp::new(q);
187        let mut x: u64 = 0x5f876e514845cc8b;
188        let y: u64 = 0xad726f98f24a761a;
189        let y_mont = m_precomp.prepare::<ONCE>(y);
190        b.iter(|| m_precomp.mul_external_assign::<ONCE>(y_mont, &mut x));
191    }
192}