Skip to content

Commit 8f19ce6

Browse files
committed
Optimize checked_ilog when base is a power of two
Make use of the identity `log(base, n) == log(2, n) / log(2, base)` to optimize when `base` is a power of two.
1 parent 4056082 commit 8f19ce6

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

library/core/src/num/uint_macros.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1573,7 +1573,15 @@ macro_rules! uint_impl {
15731573
if core::intrinsics::is_val_statically_known(base) {
15741574
if base == 2 {
15751575
return self.checked_ilog2();
1576-
} else if base == 10 {
1576+
}
1577+
// change of base: log(base, n) == log(2, n) / log(2, base)
1578+
if base.is_power_of_two() {
1579+
return match self.checked_ilog2() {
1580+
Some(log2) => Some(log2 / base.ilog2()),
1581+
None => None,
1582+
};
1583+
}
1584+
if base == 10 {
15771585
return self.checked_ilog10();
15781586
}
15791587
}

0 commit comments

Comments
 (0)