]> git.lizzy.rs Git - rust.git/commitdiff
Add and use saturating_div instead of impl inside Saturating
authorMichael Watzko <michael@watzko.de>
Thu, 19 Aug 2021 08:08:58 +0000 (10:08 +0200)
committerMichael Watzko <michael@watzko.de>
Thu, 19 Aug 2021 08:08:58 +0000 (10:08 +0200)
library/core/src/num/int_macros.rs
library/core/src/num/saturating.rs

index 0bc646995c7c7a13b1d3f91320e25f68e7aa114d..f5966a53ed26ecde0072e208341902a04f00da57 100644 (file)
@@ -918,6 +918,32 @@ pub const fn saturating_mul(self, rhs: Self) -> Self {
             }
         }
 
+        /// Saturating integer division. Computes `self / rhs`, saturating at the
+        /// numeric bounds instead of overflowing.
+        ///
+        /// # Examples
+        ///
+        /// Basic usage:
+        ///
+        /// ```
+        ///
+        /// ```
+        #[unstable(feature = "saturating_int_impl", issue = "87920")]
+        #[rustc_const_unstable(feature = "saturating_int_impl", issue = "87920")]
+        #[must_use = "this returns the result of the operation, \
+                      without modifying the original"]
+        #[inline]
+        pub const fn saturating_div(self, rhs: Self) -> Self {
+            match self.checked_div(rhs) {
+                Some(x) => x,
+                None => if (self < 0) == (rhs < 0) {
+                    Self::MAX
+                } else {
+                    Self::MIN
+                }
+            }
+        }
+
         /// Saturating integer exponentiation. Computes `self.pow(exp)`,
         /// saturating at the numeric bounds instead of overflowing.
         ///
index b06ed36689cdaeaf19239e19722209f0b03ae9d2..4b346409ebf0ba9ab2553b92b7f2885340863c8c 100644 (file)
@@ -871,16 +871,7 @@ impl Div for Saturating<$t> {
 
             #[inline]
             fn div(self, other: Saturating<$t>) -> Saturating<$t> {
-                let expected_signum = self.0.signum() * other.0.signum();
-                let (result, overflowed) = self.0.overflowing_div(other.0);
-
-                if !overflowed {
-                    Saturating(result)
-                } else if expected_signum < 0 {
-                    Saturating(<$t>::MIN)
-                } else {
-                    Saturating(<$t>::MAX)
-                }
+                Saturating(self.0.saturating_div(other.0))
             }
         }
         forward_ref_binop! { impl Div, div for Saturating<$t>, Saturating<$t>,