Skip to content

Commit

Permalink
Add and use saturating_div instead of impl inside Saturating
Browse files Browse the repository at this point in the history
  • Loading branch information
kellerkindt committed Aug 19, 2021
1 parent 8049230 commit 742d450
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
26 changes: 26 additions & 0 deletions library/core/src/num/int_macros.rs
Expand Up @@ -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.
///
Expand Down
11 changes: 1 addition & 10 deletions library/core/src/num/saturating.rs
Expand Up @@ -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>,
Expand Down

0 comments on commit 742d450

Please sign in to comment.