Skip to content

Commit 782da86

Browse files
authored
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>
2 parents 192eecd + fcbc12e commit 782da86

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

library/core/src/num/int_macros.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -2574,12 +2574,13 @@ macro_rules! int_impl {
25742574
#[must_use = "this returns the result of the operation, \
25752575
without modifying the original"]
25762576
#[inline(always)]
2577+
#[rustc_allow_const_fn_unstable(const_cmp)]
25772578
pub const fn signum(self) -> Self {
2578-
match self {
2579-
n if n > 0 => 1,
2580-
0 => 0,
2581-
_ => -1,
2582-
}
2579+
// Picking the right way to phrase this is complicated
2580+
// (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>)
2581+
// so delegate it to `Ord` which is already producing -1/0/+1
2582+
// exactly like we need and can be the place to deal with the complexity.
2583+
self.cmp(&0) as _
25832584
}
25842585

25852586
/// Returns `true` if `self` is positive and `false` if the number is zero or

0 commit comments

Comments
 (0)