@@ -2327,6 +2327,18 @@ macro_rules! uint_impl {
2327
2327
( self . wrapping_sub( 1 ) ) & self == 0 && !( self == 0 )
2328
2328
}
2329
2329
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
+
2330
2342
/// Returns the smallest power of two greater than or equal to `self`.
2331
2343
/// More details about overflow behavior can be found in [RFC 560].
2332
2344
///
@@ -2343,13 +2355,7 @@ macro_rules! uint_impl {
2343
2355
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
2344
2356
#[ inline]
2345
2357
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
2353
2359
}
2354
2360
2355
2361
/// Returns the smallest power of two greater than or equal to `n`. If
@@ -2367,9 +2373,7 @@ macro_rules! uint_impl {
2367
2373
/// ```
2368
2374
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
2369
2375
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 ) ;
2373
2377
if npot >= self {
2374
2378
Some ( npot)
2375
2379
} else {
0 commit comments