Skip to content

Commit bb0c932

Browse files
committed
bigint::monty: deduplicate mr.n and mr.p
1 parent b380880 commit bb0c932

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

bigint/src/monty.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ use traits::Zero;
44
use biguint::BigUint;
55

66
struct MontyReducer<'a> {
7-
p: &'a BigUint,
8-
n: Vec<u32>,
7+
n: &'a BigUint,
98
n0inv: u32
109
}
1110

@@ -46,10 +45,9 @@ fn inv_mod_u32(num: u32) -> u32 {
4645
}
4746

4847
impl<'a> MontyReducer<'a> {
49-
fn new(p: &'a BigUint) -> Self {
50-
let n : Vec<u32> = p.data.clone();
51-
let n0inv = inv_mod_u32(n[0]);
52-
MontyReducer { p: p, n: n, n0inv: n0inv }
48+
fn new(n: &'a BigUint) -> Self {
49+
let n0inv = inv_mod_u32(n.data[0]);
50+
MontyReducer { n: n, n0inv: n0inv }
5351
}
5452
}
5553

@@ -59,7 +57,7 @@ impl<'a> MontyReducer<'a> {
5957
// Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 2.6
6058
fn monty_redc(a: BigUint, mr: &MontyReducer) -> BigUint {
6159
let mut c = a.data;
62-
let n = &mr.n;
60+
let n = &mr.n.data;
6361
let n_size = n.len();
6462

6563
// Allocate sufficient work space
@@ -84,10 +82,10 @@ fn monty_redc(a: BigUint, mr: &MontyReducer) -> BigUint {
8482
let ret = BigUint::new(c[n_size..].to_vec());
8583

8684
// 5: if R >= β^n then return R-N else return R.
87-
if &ret < mr.p {
85+
if &ret < mr.n {
8886
ret
8987
} else {
90-
ret - mr.p
88+
ret - mr.n
9189
}
9290
}
9391

@@ -106,15 +104,15 @@ pub fn monty_modpow(a: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint{
106104
let mr = MontyReducer::new(modulus);
107105

108106
// Calculate the Montgomery parameter
109-
let mut v = vec![0; mr.p.data.len()];
107+
let mut v = vec![0; modulus.data.len()];
110108
v.push(1);
111109
let r = BigUint::new(v);
112110

113111
// Map the base to the Montgomery domain
114-
let mut apri = a * &r % mr.p;
112+
let mut apri = a * &r % modulus;
115113

116114
// Binary exponentiation
117-
let mut ans = &r % mr.p;
115+
let mut ans = &r % modulus;
118116
let mut e = exp.clone();
119117
while !e.is_zero() {
120118
if e.is_odd() {

0 commit comments

Comments
 (0)