Skip to content

Commit 2017cc3

Browse files
author
blake2-ppc
committed
std::num: Add uint::next_power_of_two_opt
Like next_power_of_two, but returns None on overflow.
1 parent d87078b commit 2017cc3

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/libstd/num/uint.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,17 @@ pub fn next_power_of_two(n: uint) -> uint {
101101
let mut tmp: uint = n - 1u;
102102
let mut shift: uint = 1u;
103103
while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
104-
return tmp + 1u;
104+
tmp + 1u
105+
}
106+
107+
/// Returns the smallest power of 2 greater than or equal to `n`
108+
#[inline]
109+
pub fn next_power_of_two_opt(n: uint) -> Option<uint> {
110+
let halfbits: uint = sys::size_of::<uint>() * 4u;
111+
let mut tmp: uint = n - 1u;
112+
let mut shift: uint = 1u;
113+
while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
114+
tmp.checked_add(&1)
105115
}
106116

107117
#[cfg(target_word_size = "32")]

0 commit comments

Comments
 (0)