diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 0bc646995c7c..f5966a53ed26 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -918,6 +918,32 @@ macro_rules! int_impl { } } + /// 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. /// diff --git a/library/core/src/num/saturating.rs b/library/core/src/num/saturating.rs index b06ed36689cd..4b346409ebf0 100644 --- a/library/core/src/num/saturating.rs +++ b/library/core/src/num/saturating.rs @@ -871,16 +871,7 @@ macro_rules! saturating_int_impl_signed { #[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>,