Skip to content

Commit 8f9caff

Browse files
committed
Add helper functions for next_power_of_two and checked_next_power_of_two
1 parent f7bd370 commit 8f9caff

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/libcore/num/mod.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2327,6 +2327,18 @@ macro_rules! uint_impl {
23272327
(self.wrapping_sub(1)) & self == 0 && !(self == 0)
23282328
}
23292329

2330+
fn round_up_to_one_less_than_a_power_of_two(self) -> Self {
2331+
let bits = size_of::<Self>() as u32 * 8;
2332+
let z = self.leading_zeros();
2333+
(if z == bits { 0 as Self } else { !0 }).wrapping_shr(z)
2334+
}
2335+
2336+
fn one_less_than_next_power_of_two(self) -> Self {
2337+
self.wrapping_sub(1)
2338+
.round_up_to_one_less_than_a_power_of_two()
2339+
.wrapping_add(if self == 0 { 1 } else { 0 })
2340+
}
2341+
23302342
/// Returns the smallest power of two greater than or equal to `self`.
23312343
/// More details about overflow behavior can be found in [RFC 560].
23322344
///
@@ -2343,13 +2355,7 @@ macro_rules! uint_impl {
23432355
#[stable(feature = "rust1", since = "1.0.0")]
23442356
#[inline]
23452357
pub fn next_power_of_two(self) -> Self {
2346-
let bits = size_of::<Self>() * 8;
2347-
let one: Self = 1;
2348-
if self == 0 {
2349-
1
2350-
} else {
2351-
one << (bits - (self - one).leading_zeros() as usize)
2352-
}
2358+
self.one_less_than_next_power_of_two() + 1
23532359
}
23542360

23552361
/// Returns the smallest power of two greater than or equal to `n`. If
@@ -2367,9 +2373,7 @@ macro_rules! uint_impl {
23672373
/// ```
23682374
#[stable(feature = "rust1", since = "1.0.0")]
23692375
pub fn checked_next_power_of_two(self) -> Option<Self> {
2370-
let bits = size_of::<Self>() * 8;
2371-
let one: Self = 1;
2372-
let npot = one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits);
2376+
let npot = self.one_less_than_next_power_of_two().wrapping_add(1);
23732377
if npot >= self {
23742378
Some(npot)
23752379
} else {

0 commit comments

Comments
 (0)