@@ -429,6 +429,51 @@ nonzero_unsigned_operations! {
429
429
NonZeroUsize ( usize ) ;
430
430
}
431
431
432
+ // A bunch of methods for signed nonzero types only.
433
+ macro_rules! nonzero_signed_operations {
434
+ ( $( $Ty: ident( $Int: ty) -> $Uty: ident( $Uint: ty) ; ) + ) => {
435
+ $(
436
+ impl $Ty {
437
+ /// Computes the absolute value of self.
438
+ #[ doc = concat!( "See [`" , stringify!( $Int) , "::abs`]" ) ]
439
+ /// for documentation on overflow behaviour.
440
+ ///
441
+ /// # Example
442
+ ///
443
+ /// ```
444
+ /// #![feature(nonzero_ops)]
445
+ /// # #![feature(try_trait)]
446
+ #[ doc = concat!( "# use std::num::" , stringify!( $Ty) , ";" ) ]
447
+ ///
448
+ /// # fn main() -> Result<(), std::option::NoneError> {
449
+ #[ doc = concat!( "let pos = " , stringify!( $Ty) , "::new(1)?;" ) ]
450
+ #[ doc = concat!( "let neg = " , stringify!( $Ty) , "::new(-1)?;" ) ]
451
+ ///
452
+ /// assert_eq!(pos, pos.abs());
453
+ /// assert_eq!(pos, neg.abs());
454
+ /// # Ok(())
455
+ /// # }
456
+ /// ```
457
+ #[ unstable( feature = "nonzero_ops" , issue = "84186" ) ]
458
+ #[ inline]
459
+ pub const fn abs( self ) -> $Ty {
460
+ // SAFETY: This cannot overflow to zero.
461
+ unsafe { $Ty:: new_unchecked( self . get( ) . abs( ) ) }
462
+ }
463
+ }
464
+ ) +
465
+ }
466
+ }
467
+
468
+ nonzero_signed_operations ! {
469
+ NonZeroI8 ( i8 ) -> NonZeroU8 ( u8 ) ;
470
+ NonZeroI16 ( i16 ) -> NonZeroU16 ( u16 ) ;
471
+ NonZeroI32 ( i32 ) -> NonZeroU32 ( u32 ) ;
472
+ NonZeroI64 ( i64 ) -> NonZeroU64 ( u64 ) ;
473
+ NonZeroI128 ( i128 ) -> NonZeroU128 ( u128 ) ;
474
+ NonZeroIsize ( isize ) -> NonZeroUsize ( usize ) ;
475
+ }
476
+
432
477
macro_rules! nonzero_unsigned_is_power_of_two {
433
478
( $( $Ty: ident ) + ) => {
434
479
$(
0 commit comments