-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
false positive: a - b > b
is not really an underflow check
#2457
Comments
The performance difference is a tangent, but FWIW I explored this in godbolt. I think the key is that my code wants to return |
Your thoughts seems reasonable to me. |
This comment was marked as duplicate.
This comment was marked as duplicate.
1 similar comment
I also have a case where clippy marks: if a + b < a {
let new = a + b;
// do something with `new`
} But if I replace this with the following, as Clippy suggests: let (new, overflow) = a.overflowing_add(b);
if !overflow {
// do something with `new`
} It actually changes the logic. So yeah. I think something's wrong here. |
I also got this lint today by typing |
In the original PR for
overflow_check_conditional
, I found this comment suggesting checks for subtraction: #741 (comment)I agree with linting
a - b > a
-- there's no way for this to be true without underflow. You can also look at this algebraically, where this simplifies to0 > b
, which is nonsense for an unsigned type.I disagree with linting
a - b > b
-- if you already know thata - b
won't underflow (from a separate test or precondition), then this is a legitimate way of testinga > 2 * b
, with the benefit of avoiding potential overflow in2 * b
.One could alternately write this as
a > b.saturating_mul(2)
ora > b.saturating_add(b)
, but I tried this in one of my Project Euler solutions, and it was measurably slower. Even a rawa > 2 * b
was slower thana - b > b
!Thoughts?
The text was updated successfully, but these errors were encountered: