Skip to content

Commit 8234ac3

Browse files
committed
Add saturating_abs() and saturating_neg() functions to 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.
1 parent 3bee49f commit 8234ac3

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/libcore/num/mod.rs

+56
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,62 @@ $EndFeature, "
930930
}
931931
}
932932

933+
doc_comment! {
934+
concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
935+
instead of overflowing.
936+
937+
# Examples
938+
939+
Basic usage:
940+
941+
```
942+
", $Feature, "#![feature(saturating_neg)]
943+
assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
944+
assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
945+
assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
946+
"::max_value());
947+
assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
948+
"::min_value() + 1);",
949+
$EndFeature, "
950+
```"),
951+
952+
#[unstable(feature = "saturating_neg", issue = "59983")]
953+
#[inline]
954+
pub fn saturating_neg(self) -> Self {
955+
intrinsics::saturating_sub(0, self)
956+
}
957+
}
958+
959+
doc_comment! {
960+
concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
961+
MIN` instead of overflowing.
962+
963+
# Examples
964+
965+
Basic usage:
966+
967+
```
968+
", $Feature, "#![feature(saturating_neg)]
969+
assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
970+
assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
971+
assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
972+
"::max_value());
973+
assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
974+
"::max_value());",
975+
$EndFeature, "
976+
```"),
977+
978+
#[unstable(feature = "saturating_neg", issue = "59983")]
979+
#[inline]
980+
pub fn saturating_abs(self) -> Self {
981+
if self.is_negative() {
982+
self.saturating_neg()
983+
} else {
984+
self
985+
}
986+
}
987+
}
988+
933989
doc_comment! {
934990
concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
935991
numeric bounds instead of overflowing.

0 commit comments

Comments
 (0)