Skip to content

Commit 0589cac

Browse files
committed
Simplify BigNum::bit_length() with log2()
Thank you to @scottmcm for suggesting the handy `log2()` function.
1 parent 424f38f commit 0589cac

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

library/core/src/num/bignum.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -158,17 +158,15 @@ macro_rules! define_bignum {
158158
/// Returns the number of bits necessary to represent this value. Note that zero
159159
/// is considered to need 0 bits.
160160
pub fn bit_length(&self) -> usize {
161-
// Skip over the most significant digits which are zero.
161+
let digitbits = <$ty>::BITS as usize;
162162
let digits = self.digits();
163-
let zeros = digits.iter().rev().take_while(|&&x| x == 0).count();
164-
let end = digits.len() - zeros;
165-
if end == 0 {
163+
// Find the most significant non-zero digit.
164+
let msd = digits.iter().rposition(|&x| x != 0);
165+
match msd {
166+
Some(msd) => msd * digitbits + digits[msd].log2() as usize + 1,
166167
// There are no non-zero digits, i.e., the number is zero.
167-
return 0;
168+
_ => 0,
168169
}
169-
let digitbits = <$ty>::BITS as usize;
170-
let end_leading_zeros = digits[end - 1].leading_zeros() as usize;
171-
end * digitbits - end_leading_zeros
172170
}
173171

174172
/// Adds `other` to itself and returns its own mutable reference.

0 commit comments

Comments
 (0)