diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 3230873883e19..ffa0d76180d93 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -1195,9 +1195,18 @@ pub trait Saturating { /// Saturating subtraction operator. /// Returns a-b, saturating at the numeric bounds instead of overflowing. fn saturating_sub(self, v: Self) -> Self; + + /// Saturating multiplication operator. + /// Returns a\*b, saturating at the numeric bounds instead of overflowing. + fn saturating_mul(self, v: Self) -> Self; + + /// Saturating division operator. + /// Returns a/b, saturating at the numeric bounds instead of overflowing. + fn saturating_div(self, v: Self) -> Self; } -impl Saturating for T { +impl +Saturating for T { #[inline] fn saturating_add(self, v: T) -> T { match self.checked_add(&v) { @@ -1221,6 +1230,32 @@ impl Saturating for T } } } + + #[inline] + fn saturating_mul(self, v: T) -> T { + match self.checked_mul(&v) { + Some(x) => x, + None => if (self < Zero::zero()) == (v < Zero::zero()) { + Bounded::max_value() + } else { + Bounded::min_value() + } + } + } + + #[inline] + fn saturating_div(self, v: T) -> T { + match self.checked_div(&v) { + Some(x) => x, + None => if v == Zero::zero() { + fail!("div by zero cannot be saturated") + } else if (self < Zero::zero()) == (v < Zero::zero()) { + Bounded::max_value() + } else { + Bounded::min_value() + } + } + } } /// Performs addition that returns `None` instead of wrapping around on overflow.