Rollup merge of #106798 - scottmcm:signum-via-cmp, r=Mark-Simulacrum

Implement `signum` with `Ord`

Rather than needing to do things like #105840 for `signum` too, might as well just implement that method using `Ord`, since it's doing the same "I need `-1`/`0`/`+1`" behaviour that `cmp` is already doing.

This also seems to slightly improve the assembly: <https://rust.godbolt.org/z/5oEEqbxK1>
This commit is contained in:
Matthias Krüger 2023-01-29 20:03:36 +01:00 committed by GitHub
commit 782da867c8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2574,12 +2574,13 @@ pub const fn abs_diff(self, other: Self) -> $UnsignedT {
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_cmp)]
pub const fn signum(self) -> Self {
match self {
n if n > 0 => 1,
0 => 0,
_ => -1,
}
// Picking the right way to phrase this is complicated
// (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>)
// so delegate it to `Ord` which is already producing -1/0/+1
// exactly like we need and can be the place to deal with the complexity.
self.cmp(&0) as _
}
/// Returns `true` if `self` is positive and `false` if the number is zero or