Skip to content

Commit 50d8ea8

Browse files
committed
Add some checked operations, just in case
1 parent 8b02d04 commit 50d8ea8

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

src/hazmat/lucas.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,9 +187,12 @@ fn decompose<const L: usize>(n: &Odd<Uint<L>>) -> (u32, Odd<Uint<L>>) {
187187

188188
let s = n.trailing_ones();
189189
let d = if s < n.bits_precision() {
190-
// This won't overflow since the original `n` was odd, so we right-shifted at least once.
190+
// The shift won't overflow because of the check above.
191+
// The addition won't overflow since the original `n` was odd,
192+
// so we right-shifted at least once.
191193
n.as_ref()
192-
.wrapping_shr(s)
194+
.overflowing_shr(s)
195+
.expect("shift within range")
193196
.checked_add(&Uint::ONE)
194197
.expect("Integer overflow")
195198
} else {

src/hazmat/miller_rabin.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ impl<const L: usize> MillerRabin<L> {
4343
} else {
4444
let candidate_minus_one = candidate.wrapping_sub(&Uint::ONE);
4545
let s = candidate_minus_one.trailing_zeros_vartime();
46-
let d = candidate_minus_one.wrapping_shr_vartime(s);
46+
// Will not overflow because `candidate` is odd and greater than 1.
47+
let d = candidate_minus_one
48+
.overflowing_shr_vartime(s)
49+
.expect("shift within range");
4750
(s, d)
4851
};
4952

src/hazmat/sieve.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ pub fn random_odd_uint<const L: usize>(
3737
random |= Uint::<L>::ONE;
3838

3939
// Make sure it's the correct bit size
40-
random |= Uint::<L>::ONE.wrapping_shl_vartime(bit_length - 1);
40+
// Will not overflow since `bit_length` is ensured to be within the size of the integer.
41+
random |= Uint::<L>::ONE
42+
.overflowing_shl_vartime(bit_length - 1)
43+
.expect("shift within range");
4144

4245
Odd::new(random).expect("ensured to be odd")
4346
}

0 commit comments

Comments
 (0)