Skip to content

Commit

Permalink
Add saturating_abs() and saturating_neg() functions to signed integer…
Browse files Browse the repository at this point in the history
… 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.
  • Loading branch information
t-rapp committed Apr 25, 2019
1 parent 3bee49f commit 8234ac3
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/libcore/num/mod.rs
Expand Up @@ -930,6 +930,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.
Expand Down

0 comments on commit 8234ac3

Please sign in to comment.