about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIago-lito <iago-lito@etak>2021-04-15 12:23:02 +0200
committerIago-lito <iago-lito@etak>2021-06-09 17:28:32 +0200
commit65e7321457912340cd424b57f58beb32659dfcfb (patch)
treeaac787c300c0fa49ab1beae97b9f34fd3ee0ebd1
parent6083b0ad2a145651d78813d5c1da1e0296146949 (diff)
downloadrust-65e7321457912340cd424b57f58beb32659dfcfb.tar.gz
rust-65e7321457912340cd424b57f58beb32659dfcfb.zip
NonZero saturating_abs.
-rw-r--r--library/core/src/num/nonzero.rs34
1 files changed, 34 insertions, 0 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index 9294184ca4d..6183cc7f011 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -527,6 +527,40 @@ macro_rules! nonzero_signed_operations {
                         flag,
                     )
                 }
+
+                /// Saturating absolute value, see
+                #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
+                ///
+                /// # Example
+                ///
+                /// ```
+                /// #![feature(nonzero_ops)]
+                /// # #![feature(try_trait)]
+                #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
+                ///
+                /// # fn main() -> Result<(), std::option::NoneError> {
+                #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
+                #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
+                #[doc = concat!("let min = ", stringify!($Ty), "::new(",
+                                stringify!($Int), "::MIN)?;")]
+                #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
+                                stringify!($Int), "::MIN + 1)?;")]
+                #[doc = concat!("let max = ", stringify!($Ty), "::new(",
+                                stringify!($Int), "::MAX)?;")]
+                ///
+                /// assert_eq!(pos, pos.saturating_abs());
+                /// assert_eq!(pos, neg.saturating_abs());
+                /// assert_eq!(max, min.saturating_abs());
+                /// assert_eq!(max, min_plus.saturating_abs());
+                /// # Ok(())
+                /// # }
+                /// ```
+                #[unstable(feature = "nonzero_ops", issue = "84186")]
+                #[inline]
+                pub const fn saturating_abs(self) -> $Ty {
+                    // SAFETY: absolute value of nonzero cannot yield zero values.
+                    unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
+                }
             }
         )+
     }