Skip to content

Commit 8948390

Browse files
committed
Optimize checked_ilog when base is a power of two
if base == 2 ** k, then log(base, n) == log(2, n) / k
1 parent 4056082 commit 8948390

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

library/core/src/num/uint_macros.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1571,9 +1571,14 @@ macro_rules! uint_impl {
15711571
// applied by the compiler. If you want those specific bases,
15721572
// use `.checked_ilog2()` or `.checked_ilog10()` directly.
15731573
if core::intrinsics::is_val_statically_known(base) {
1574-
if base == 2 {
1575-
return self.checked_ilog2();
1576-
} else if base == 10 {
1574+
// change of base:
1575+
// if base == 2 ** k, then
1576+
// log(base, n) == log(2, n) / k
1577+
if base.is_power_of_two() && base > 1 {
1578+
let k = base.ilog2();
1579+
return Some(try_opt!(self.checked_ilog2()) / k);
1580+
}
1581+
if base == 10 {
15771582
return self.checked_ilog10();
15781583
}
15791584
}

0 commit comments

Comments
 (0)