Skip to content

Commit 39260d9

Browse files
committed
make abs, wrapping_abs, and overflowing_abs const functions
1 parent bea0372 commit 39260d9

File tree

1 file changed

+9
-21
lines changed

1 file changed

+9
-21
lines changed

src/libcore/num/mod.rs

+9-21
Original file line numberDiff line numberDiff line change
@@ -1401,12 +1401,8 @@ $EndFeature, "
14011401
```"),
14021402
#[stable(feature = "no_panic_abs", since = "1.13.0")]
14031403
#[inline]
1404-
pub fn wrapping_abs(self) -> Self {
1405-
if self.is_negative() {
1406-
self.wrapping_neg()
1407-
} else {
1408-
self
1409-
}
1404+
pub const fn wrapping_abs(self) -> Self {
1405+
(self ^ (self >> ($BITS - 1))).wrapping_sub(self >> ($BITS - 1))
14101406
}
14111407
}
14121408

@@ -1764,12 +1760,8 @@ $EndFeature, "
17641760
```"),
17651761
#[stable(feature = "no_panic_abs", since = "1.13.0")]
17661762
#[inline]
1767-
pub fn overflowing_abs(self) -> (Self, bool) {
1768-
if self.is_negative() {
1769-
self.overflowing_neg()
1770-
} else {
1771-
(self, false)
1772-
}
1763+
pub const fn overflowing_abs(self) -> (Self, bool) {
1764+
(self ^ (self >> ($BITS - 1))).overflowing_sub(self >> ($BITS - 1))
17731765
}
17741766
}
17751767

@@ -1973,15 +1965,11 @@ $EndFeature, "
19731965
#[stable(feature = "rust1", since = "1.0.0")]
19741966
#[inline]
19751967
#[rustc_inherit_overflow_checks]
1976-
pub fn abs(self) -> Self {
1977-
if self.is_negative() {
1978-
// Note that the #[inline] above means that the overflow
1979-
// semantics of this negation depend on the crate we're being
1980-
// inlined into.
1981-
-self
1982-
} else {
1983-
self
1984-
}
1968+
pub const fn abs(self) -> Self {
1969+
// Note that the #[inline] above means that the overflow
1970+
// semantics of the subtraction depend on the crate we're being
1971+
// inlined into.
1972+
(self ^ (self >> ($BITS - 1))) - (self >> ($BITS - 1))
19851973
}
19861974
}
19871975

0 commit comments

Comments
 (0)