Skip to content
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

Improve performance of rem_euclid() for signed integers #103913

Merged
merged 3 commits into from
Nov 12, 2022
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
14 changes: 9 additions & 5 deletions library/core/src/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2068,11 +2068,15 @@ macro_rules! int_impl {
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 {
if rhs < 0 {
r - rhs
} else {
r + rhs
}
// Semantically equivalent to `if rhs < 0 { r - rhs } else { r + rhs }`.
// If `rhs` is not `Self::MIN`, then `r + abs(rhs)` will not overflow
// and is clearly equivalent, because `r` is negative.
// Otherwise, `rhs` is `Self::MIN`, then we have
// `r.wrapping_add(Self::MIN.wrapping_abs())`, which evaluates
// to `r.wrapping_add(Self::MIN)`, which is equivalent to
// `r - Self::MIN`, which is what we wanted (and will not overflow
// for negative `r`).
r.wrapping_add(rhs.wrapping_abs())
} else {
r
}
Expand Down