diff options
| author | blake2-ppc <blake2-ppc> | 2013-09-12 05:05:12 +0200 |
|---|---|---|
| committer | blake2-ppc <blake2-ppc> | 2013-09-16 15:04:48 +0200 |
| commit | 2017cc3ce45a4c1827c5ccee400199bca8f22594 (patch) | |
| tree | 392f6e69e8bd2da6b161cf6e4bb67a52b3148692 /src/libstd | |
| parent | d87078be727f06581b0d1fc6642abcc3ea6aae31 (diff) | |
| download | rust-2017cc3ce45a4c1827c5ccee400199bca8f22594.tar.gz rust-2017cc3ce45a4c1827c5ccee400199bca8f22594.zip | |
std::num: Add uint::next_power_of_two_opt
Like next_power_of_two, but returns None on overflow.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/num/uint.rs | 12 |
1 files changed, 11 insertions, 1 deletions
diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs index dfdd6cf72f7..38a4df270fc 100644 --- a/src/libstd/num/uint.rs +++ b/src/libstd/num/uint.rs @@ -101,7 +101,17 @@ pub fn next_power_of_two(n: uint) -> uint { let mut tmp: uint = n - 1u; let mut shift: uint = 1u; while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } - return tmp + 1u; + tmp + 1u +} + +/// Returns the smallest power of 2 greater than or equal to `n` +#[inline] +pub fn next_power_of_two_opt(n: uint) -> Option<uint> { + let halfbits: uint = sys::size_of::<uint>() * 4u; + let mut tmp: uint = n - 1u; + let mut shift: uint = 1u; + while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } + tmp.checked_add(&1) } #[cfg(target_word_size = "32")] |
