Skip to content

Implement signum with Ord #106798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions library/core/src/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2574,12 +2574,13 @@ macro_rules! int_impl {
#[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 _
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's of course not a big deal, but self <=> 0 does feel nicer to me here than needing &0 and autoref.

(Just mentioning it, @joshtriplett, since I'd brought up spaceship in the meeting today. Obviously it's not a blocker for this PR.)

}

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