Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit a433b06

Browse files
committed
NonZero abs.
1 parent f7a1a9d commit a433b06

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,51 @@ nonzero_unsigned_operations! {
429429
NonZeroUsize(usize);
430430
}
431431

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+
432477
macro_rules! nonzero_unsigned_is_power_of_two {
433478
( $( $Ty: ident )+ ) => {
434479
$(

0 commit comments

Comments
 (0)