]> git.lizzy.rs Git - rust.git/commitdiff
Add saturating_abs() and saturating_neg() functions to signed integer types
authorTobias Rapp <t.rapp@noa-archive.com>
Wed, 17 Apr 2019 13:28:57 +0000 (15:28 +0200)
committerTobias Rapp <t.rapp@noa-archive.com>
Thu, 25 Apr 2019 15:04:11 +0000 (17:04 +0200)
Similar to wrapping_abs() / wrapping_neg() functions but saturating at
the numeric bounds instead of wrapping around. Complements the existing
set of functions with saturation mechanics.

src/libcore/num/mod.rs

index c8a4ff7ca61e7cef706c5b11ac99e99d06183999..88cdac073c7c598cc0fc0cd8309e83ea05fe3773 100644 (file)
@@ -930,6 +930,62 @@ pub const fn saturating_sub(self, rhs: Self) -> Self {
             }
         }
 
+        doc_comment! {
+            concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
+instead of overflowing.
+
+# Examples
+
+Basic usage:
+
+```
+", $Feature, "#![feature(saturating_neg)]
+assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
+assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
+assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
+"::max_value());
+assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
+"::min_value() + 1);",
+$EndFeature, "
+```"),
+
+            #[unstable(feature = "saturating_neg", issue = "59983")]
+            #[inline]
+            pub fn saturating_neg(self) -> Self {
+                intrinsics::saturating_sub(0, self)
+            }
+        }
+
+        doc_comment! {
+            concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
+MIN` instead of overflowing.
+
+# Examples
+
+Basic usage:
+
+```
+", $Feature, "#![feature(saturating_neg)]
+assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
+assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
+assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
+"::max_value());
+assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
+"::max_value());",
+$EndFeature, "
+```"),
+
+            #[unstable(feature = "saturating_neg", issue = "59983")]
+            #[inline]
+            pub fn saturating_abs(self) -> Self {
+                if self.is_negative() {
+                    self.saturating_neg()
+                } else {
+                    self
+                }
+            }
+        }
+
         doc_comment! {
             concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
 numeric bounds instead of overflowing.