@@ -460,6 +460,39 @@ macro_rules! nonzero_signed_operations {
460460 // SAFETY: This cannot overflow to zero.
461461 unsafe { $Ty:: new_unchecked( self . get( ) . abs( ) ) }
462462 }
463+
464+ /// Checked absolute value.
465+ /// Returns [`None`] if
466+ #[ doc = concat!( "`self == " , stringify!( $Int) , "::MIN`." ) ]
467+ ///
468+ /// # Example
469+ ///
470+ /// ```
471+ /// #![feature(nonzero_ops)]
472+ /// # #![feature(try_trait)]
473+ #[ doc = concat!( "# use std::num::" , stringify!( $Ty) , ";" ) ]
474+ ///
475+ /// # fn main() -> Result<(), std::option::NoneError> {
476+ #[ doc = concat!( "let pos = " , stringify!( $Ty) , "::new(1)?;" ) ]
477+ #[ doc = concat!( "let neg = " , stringify!( $Ty) , "::new(-1)?;" ) ]
478+ #[ doc = concat!( "let min = " , stringify!( $Ty) , "::new(" ,
479+ stringify!( $Int) , "::MIN)?;" ) ]
480+ ///
481+ /// assert_eq!(Some(pos), neg.checked_abs());
482+ /// assert_eq!(None, min.checked_abs());
483+ /// # Ok(())
484+ /// # }
485+ /// ```
486+ #[ unstable( feature = "nonzero_ops" , issue = "84186" ) ]
487+ #[ inline]
488+ pub const fn checked_abs( self ) -> Option <$Ty> {
489+ if let Some ( nz) = self . get( ) . checked_abs( ) {
490+ // SAFETY: absolute value of nonzero cannot yield zero values.
491+ Some ( unsafe { $Ty:: new_unchecked( nz) } )
492+ } else {
493+ None
494+ }
495+ }
463496 }
464497 ) +
465498 }
0 commit comments