Open Scripter17 opened 3 weeks ago
By design arithmetic_side_effects
mostly sees the lhs/rhs expressions of the arithmetic operation and generally ignores the surrounding environment.
The indicated example happens to be using a locally known length but that is not always to case.
// If `string_ref` is zero, then `a.len()-b.len()` will underflow.
fn foo(string_ref: &str) {
let mut a = string_ref.to_string();
let b = "c";
if a.ends_with(b) {a.truncate(a.len()-b.len())};
}
If you know for sure that an operation will never introduce surprising side-effects, then you can directly call wrapping_sub
.
Summary
When calling
str::ends_with
with a&str
, Rust doesn't know that, for the method to returntrue
, the length of the haystack has to be greater than or equal to the length of the needle.Lint Name
arithmetic_side_effects
Reproducer
I tried this code:
with
--warn clippy::arithmetic_side_effects
I saw this happen:
I expected to see this happen:
No warning because the thing being warned about can't happen.
Version
Additional Labels
No response