Skip to content

Commit 7300c19

Browse files
committed
Add a specialized BoxedUint::shl1 implementation
1 parent 4e88bb8 commit 7300c19

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/uint/boxed/shl.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,21 @@ impl BoxedUint {
8989

9090
/// Computes `self >> 1` in constant-time.
9191
pub(crate) fn shl1(&self) -> Self {
92-
// TODO(tarcieri): optimized implementation
93-
self.shl_vartime(1).expect("shift within range")
92+
let mut ret = self.clone();
93+
ret.shl1_assign();
94+
ret
9495
}
9596

9697
/// Computes `self >> 1` in-place in constant-time.
9798
pub(crate) fn shl1_assign(&mut self) {
98-
// TODO(tarcieri): optimized implementation
99-
*self = self.shl1();
99+
let mut carry = self.limbs[0].0 >> Limb::HI_BIT;
100+
self.limbs[0].shl_assign(1);
101+
for i in 1..self.limbs.len() {
102+
let new_carry = self.limbs[i].0 >> Limb::HI_BIT;
103+
self.limbs[i].shl_assign(1);
104+
self.limbs[i].0 |= carry;
105+
carry = new_carry
106+
}
100107
}
101108
}
102109

@@ -129,6 +136,14 @@ impl ShlAssign<u32> for BoxedUint {
129136
mod tests {
130137
use super::BoxedUint;
131138

139+
#[test]
140+
fn shl1_assign() {
141+
let mut n = BoxedUint::from(0x3c442b21f19185fe433f0a65af902b8fu128);
142+
let n_shl1 = BoxedUint::from(0x78885643e3230bfc867e14cb5f20571eu128);
143+
n.shl1_assign();
144+
assert_eq!(n, n_shl1);
145+
}
146+
132147
#[test]
133148
fn shl() {
134149
let one = BoxedUint::one_with_precision(128);

0 commit comments

Comments
 (0)