Skip to content

Commit d1e854e

Browse files
committed
Saturate the conversions in BitUint::set_bit
1 parent 5aaf369 commit d1e854e

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/biguint.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2743,12 +2743,16 @@ impl BigUint {
27432743
/// Note that setting a bit greater than the current bit length, a reallocation may be needed
27442744
/// to store the new digits
27452745
pub fn set_bit(&mut self, bit: u64, value: bool) {
2746+
// Note: we're saturating `digit_index` and `new_len` -- any such case is guaranteed to
2747+
// fail allocation, and that's more consistent than adding our own overflow panics.
27462748
let bits_per_digit = u64::from(big_digit::BITS);
2747-
let digit_index = (bit / bits_per_digit).to_usize().unwrap();
2749+
let digit_index = (bit / bits_per_digit)
2750+
.to_usize()
2751+
.unwrap_or(core::usize::MAX);
27482752
let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
27492753
if value {
27502754
if digit_index >= self.data.len() {
2751-
let new_len = digit_index.checked_add(1).unwrap();
2755+
let new_len = digit_index.saturating_add(1);
27522756
self.data.resize(new_len, 0);
27532757
}
27542758
self.data[digit_index] |= bit_mask;

0 commit comments

Comments
 (0)