@@ -379,6 +379,42 @@ macro_rules! nonzero_unsigned_operations {
379
379
// SAFETY: The caller ensures there is no overflow.
380
380
unsafe { $Ty:: new_unchecked( self . get( ) . unchecked_add( other) ) }
381
381
}
382
+
383
+ /// Returns the smallest power of two greater than or equal to n.
384
+ /// If the next power of two is greater than the type’s maximum value,
385
+ /// [`None`] is returned, otherwise the power of two is wrapped in [`Some`].
386
+ ///
387
+ /// # Examples
388
+ ///
389
+ /// ```
390
+ /// #![feature(nonzero_ops)]
391
+ /// # #![feature(try_trait)]
392
+ #[ doc = concat!( "# use std::num::" , stringify!( $Ty) , ";" ) ]
393
+ ///
394
+ /// # fn main() -> Result<(), std::option::NoneError> {
395
+ #[ doc = concat!( "let two = " , stringify!( $Ty) , "::new(2)?;" ) ]
396
+ #[ doc = concat!( "let three = " , stringify!( $Ty) , "::new(3)?;" ) ]
397
+ #[ doc = concat!( "let four = " , stringify!( $Ty) , "::new(4)?;" ) ]
398
+ #[ doc = concat!( "let max = " , stringify!( $Ty) , "::new(" ,
399
+ stringify!( $Int) , "::MAX)?;" ) ]
400
+ ///
401
+ /// assert_eq!(Some(two), two.checked_next_power_of_two() );
402
+ /// assert_eq!(Some(four), three.checked_next_power_of_two() );
403
+ /// assert_eq!(None, max.checked_next_power_of_two() );
404
+ /// # Ok(())
405
+ /// # }
406
+ /// ```
407
+ #[ unstable( feature = "nonzero_ops" , issue = "84186" ) ]
408
+ #[ inline]
409
+ pub const fn checked_next_power_of_two( self ) -> Option <$Ty> {
410
+ if let Some ( nz) = self . get( ) . checked_next_power_of_two( ) {
411
+ // SAFETY: The next power of two is positive
412
+ // and overflow is checked.
413
+ Some ( unsafe { $Ty:: new_unchecked( nz) } )
414
+ } else {
415
+ None
416
+ }
417
+ }
382
418
}
383
419
) +
384
420
}
0 commit comments