about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTrevor Spiteri <trevor.spiteri@um.edu.mt>2019-08-21 14:10:40 +0200
committerTrevor Spiteri <trevor.spiteri@um.edu.mt>2019-08-21 14:10:40 +0200
commit39260d9016db6925414541ad2dce6502dded3a64 (patch)
tree1112f22a0c0b7bdf005765e8a4bae7712b6ecc6f
parentbea0372a1a7a31b81f28cc4d9a83a2dc9a79d008 (diff)
downloadrust-39260d9016db6925414541ad2dce6502dded3a64.tar.gz
rust-39260d9016db6925414541ad2dce6502dded3a64.zip
make abs, wrapping_abs, and overflowing_abs const functions
-rw-r--r--src/libcore/num/mod.rs30
1 files changed, 9 insertions, 21 deletions
diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs
index b46e06f8d8a..df1c00ccd18 100644
--- a/src/libcore/num/mod.rs
+++ b/src/libcore/num/mod.rs
@@ -1401,12 +1401,8 @@ $EndFeature, "
 ```"),
             #[stable(feature = "no_panic_abs", since = "1.13.0")]
             #[inline]
-            pub fn wrapping_abs(self) -> Self {
-                if self.is_negative() {
-                    self.wrapping_neg()
-                } else {
-                    self
-                }
+            pub const fn wrapping_abs(self) -> Self {
+                (self ^ (self >> ($BITS - 1))).wrapping_sub(self >> ($BITS - 1))
             }
         }
 
@@ -1764,12 +1760,8 @@ $EndFeature, "
 ```"),
             #[stable(feature = "no_panic_abs", since = "1.13.0")]
             #[inline]
-            pub fn overflowing_abs(self) -> (Self, bool) {
-                if self.is_negative() {
-                    self.overflowing_neg()
-                } else {
-                    (self, false)
-                }
+            pub const fn overflowing_abs(self) -> (Self, bool) {
+                (self ^ (self >> ($BITS - 1))).overflowing_sub(self >> ($BITS - 1))
             }
         }
 
@@ -1973,15 +1965,11 @@ $EndFeature, "
             #[stable(feature = "rust1", since = "1.0.0")]
             #[inline]
             #[rustc_inherit_overflow_checks]
-            pub fn abs(self) -> Self {
-                if self.is_negative() {
-                    // Note that the #[inline] above means that the overflow
-                    // semantics of this negation depend on the crate we're being
-                    // inlined into.
-                    -self
-                } else {
-                    self
-                }
+            pub const fn abs(self) -> Self {
+                // Note that the #[inline] above means that the overflow
+                // semantics of the subtraction depend on the crate we're being
+                // inlined into.
+                (self ^ (self >> ($BITS - 1))) - (self >> ($BITS - 1))
             }
         }