diff options
| author | bors <bors@rust-lang.org> | 2019-04-25 17:26:20 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2019-04-25 17:26:20 +0000 |
| commit | c32171bd5efedd58fd471c21802e23005c2918fc (patch) | |
| tree | c792b35572465de3c7edb85f7faf73a7f9ce1567 /src/libcore/num | |
| parent | bd31c392f286d61caac0babee68c900cdaa8b504 (diff) | |
| parent | c7d47c8cf4cd4db4226a38884a2d5fad371d9330 (diff) | |
| download | rust-c32171bd5efedd58fd471c21802e23005c2918fc.tar.gz rust-c32171bd5efedd58fd471c21802e23005c2918fc.zip | |
Auto merge of #60192 - t-rapp:tr-saturating-funcs, r=alexcrichton
Implement saturating_abs() and saturating_neg() functions for signed integer types Similar to wrapping_abs() / wrapping_neg() functions but saturating at the numeric bounds instead of wrapping around. Complements the existing set of functions with saturation mechanics. cc #59983
Diffstat (limited to 'src/libcore/num')
| -rw-r--r-- | src/libcore/num/mod.rs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index f1325f383ee..718222ee0f4 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -959,6 +959,62 @@ $EndFeature, " } doc_comment! { + concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN` +instead of overflowing. + +# Examples + +Basic usage: + +``` +", $Feature, "#![feature(saturating_neg)] +assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100); +assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100); +assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT), +"::max_value()); +assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT), +"::min_value() + 1);", +$EndFeature, " +```"), + + #[unstable(feature = "saturating_neg", issue = "59983")] + #[inline] + pub fn saturating_neg(self) -> Self { + intrinsics::saturating_sub(0, self) + } + } + + doc_comment! { + concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == +MIN` instead of overflowing. + +# Examples + +Basic usage: + +``` +", $Feature, "#![feature(saturating_neg)] +assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100); +assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100); +assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT), +"::max_value()); +assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT), +"::max_value());", +$EndFeature, " +```"), + + #[unstable(feature = "saturating_neg", issue = "59983")] + #[inline] + pub fn saturating_abs(self) -> Self { + if self.is_negative() { + self.saturating_neg() + } else { + self + } + } + } + + doc_comment! { concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds instead of overflowing. |
