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

Commit 62f97d9

Browse files
committed
NonZero checked_abs.
1 parent a433b06 commit 62f97d9

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
@@ -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

Comments
 (0)