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

Commit 7e7b316

Browse files
committed
NonZero unsigned_abs.
1 parent b6589bb commit 7e7b316

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,39 @@ macro_rules! nonzero_signed_operations {
594594
// SAFETY: absolute value of nonzero cannot yield zero values.
595595
unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
596596
}
597+
598+
/// Computes the absolute value of self
599+
/// without any wrapping or panicking.
600+
///
601+
/// # Example
602+
///
603+
/// ```
604+
/// #![feature(nonzero_ops)]
605+
/// # #![feature(try_trait)]
606+
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
607+
#[doc = concat!("# use std::num::", stringify!($Uty), ";")]
608+
///
609+
/// # fn main() -> Result<(), std::option::NoneError> {
610+
#[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
611+
#[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
612+
#[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
613+
#[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
614+
stringify!($Int), "::MIN)?;")]
615+
#[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
616+
stringify!($Uint), "::MAX / 2 + 1)?;")]
617+
///
618+
/// assert_eq!(u_pos, i_pos.unsigned_abs());
619+
/// assert_eq!(u_pos, i_neg.unsigned_abs());
620+
/// assert_eq!(u_max, i_min.unsigned_abs());
621+
/// # Ok(())
622+
/// # }
623+
/// ```
624+
#[unstable(feature = "nonzero_ops", issue = "84186")]
625+
#[inline]
626+
pub const fn unsigned_abs(self) -> $Uty {
627+
// SAFETY: absolute value of nonzero cannot yield zero values.
628+
unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
629+
}
597630
}
598631
)+
599632
}

0 commit comments

Comments
 (0)