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

Commit 65e7321

Browse files
committed
NonZero saturating_abs.
1 parent 6083b0a commit 65e7321

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,40 @@ macro_rules! nonzero_signed_operations {
527527
flag,
528528
)
529529
}
530+
531+
/// Saturating absolute value, see
532+
#[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
533+
///
534+
/// # Example
535+
///
536+
/// ```
537+
/// #![feature(nonzero_ops)]
538+
/// # #![feature(try_trait)]
539+
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
540+
///
541+
/// # fn main() -> Result<(), std::option::NoneError> {
542+
#[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
543+
#[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
544+
#[doc = concat!("let min = ", stringify!($Ty), "::new(",
545+
stringify!($Int), "::MIN)?;")]
546+
#[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
547+
stringify!($Int), "::MIN + 1)?;")]
548+
#[doc = concat!("let max = ", stringify!($Ty), "::new(",
549+
stringify!($Int), "::MAX)?;")]
550+
///
551+
/// assert_eq!(pos, pos.saturating_abs());
552+
/// assert_eq!(pos, neg.saturating_abs());
553+
/// assert_eq!(max, min.saturating_abs());
554+
/// assert_eq!(max, min_plus.saturating_abs());
555+
/// # Ok(())
556+
/// # }
557+
/// ```
558+
#[unstable(feature = "nonzero_ops", issue = "84186")]
559+
#[inline]
560+
pub const fn saturating_abs(self) -> $Ty {
561+
// SAFETY: absolute value of nonzero cannot yield zero values.
562+
unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
563+
}
530564
}
531565
)+
532566
}

0 commit comments

Comments
 (0)