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

Commit 742d450

Browse files
committed
Add and use saturating_div instead of impl inside Saturating
1 parent 8049230 commit 742d450

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

library/core/src/num/int_macros.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -918,6 +918,32 @@ macro_rules! int_impl {
918918
}
919919
}
920920

921+
/// Saturating integer division. Computes `self / rhs`, saturating at the
922+
/// numeric bounds instead of overflowing.
923+
///
924+
/// # Examples
925+
///
926+
/// Basic usage:
927+
///
928+
/// ```
929+
///
930+
/// ```
931+
#[unstable(feature = "saturating_int_impl", issue = "87920")]
932+
#[rustc_const_unstable(feature = "saturating_int_impl", issue = "87920")]
933+
#[must_use = "this returns the result of the operation, \
934+
without modifying the original"]
935+
#[inline]
936+
pub const fn saturating_div(self, rhs: Self) -> Self {
937+
match self.checked_div(rhs) {
938+
Some(x) => x,
939+
None => if (self < 0) == (rhs < 0) {
940+
Self::MAX
941+
} else {
942+
Self::MIN
943+
}
944+
}
945+
}
946+
921947
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
922948
/// saturating at the numeric bounds instead of overflowing.
923949
///

library/core/src/num/saturating.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -871,16 +871,7 @@ macro_rules! saturating_int_impl_signed {
871871

872872
#[inline]
873873
fn div(self, other: Saturating<$t>) -> Saturating<$t> {
874-
let expected_signum = self.0.signum() * other.0.signum();
875-
let (result, overflowed) = self.0.overflowing_div(other.0);
876-
877-
if !overflowed {
878-
Saturating(result)
879-
} else if expected_signum < 0 {
880-
Saturating(<$t>::MIN)
881-
} else {
882-
Saturating(<$t>::MAX)
883-
}
874+
Saturating(self.0.saturating_div(other.0))
884875
}
885876
}
886877
forward_ref_binop! { impl Div, div for Saturating<$t>, Saturating<$t>,

0 commit comments

Comments
 (0)