Make saturating_mul a const fn

Co-Authored-By: 9999years <rbt@sent.as>
This commit is contained in:
Dylan MacKenzie 2020-02-03 13:16:38 -08:00
parent de52a541d5
commit b422a19c43
2 changed files with 13 additions and 6 deletions

View File

@ -75,6 +75,7 @@
#![feature(const_int_checked)] #![feature(const_int_checked)]
#![feature(const_int_euclidean)] #![feature(const_int_euclidean)]
#![feature(const_int_overflowing)] #![feature(const_int_overflowing)]
#![feature(const_int_saturating)]
#![feature(const_panic)] #![feature(const_panic)]
#![feature(const_fn_union)] #![feature(const_fn_union)]
#![feature(const_generics)] #![feature(const_generics)]

View File

@ -1142,17 +1142,19 @@ assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($Self
$EndFeature, " $EndFeature, "
```"), ```"),
#[stable(feature = "wrapping", since = "1.7.0")] #[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_unstable(feature = "const_int_saturating", issue = "53718")]
#[must_use = "this returns the result of the operation, \ #[must_use = "this returns the result of the operation, \
without modifying the original"] without modifying the original"]
#[inline] #[inline]
pub fn saturating_mul(self, rhs: Self) -> Self { pub const fn saturating_mul(self, rhs: Self) -> Self {
self.checked_mul(rhs).unwrap_or_else(|| { match self.checked_mul(rhs) {
if (self < 0) == (rhs < 0) { Some(x) => x,
None => if (self < 0) == (rhs < 0) {
Self::max_value() Self::max_value()
} else { } else {
Self::min_value() Self::min_value()
} }
}) }
} }
} }
@ -3195,11 +3197,15 @@ assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($Se
"::MAX);", $EndFeature, " "::MAX);", $EndFeature, "
```"), ```"),
#[stable(feature = "wrapping", since = "1.7.0")] #[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_unstable(feature = "const_int_saturating", issue = "53718")]
#[must_use = "this returns the result of the operation, \ #[must_use = "this returns the result of the operation, \
without modifying the original"] without modifying the original"]
#[inline] #[inline]
pub fn saturating_mul(self, rhs: Self) -> Self { pub const fn saturating_mul(self, rhs: Self) -> Self {
self.checked_mul(rhs).unwrap_or(Self::max_value()) match self.checked_mul(rhs) {
Some(x) => x,
None => Self::max_value(),
}
} }
} }