rust-lang / rust-lang/rust-clippy

`haystack.ends_with(needle)` doesn't silence `clippy::arithmetic_side_effects` caused by `haystack.len()-needle.len()`

Open
#12,704 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

When calling str::ends_with with a &str, Rust doesn't know that, for the method to return true, 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:

fn main() {
    let mut a = "abc".to_string();
    let b = "c";
    if a.ends_with(b) {a.truncate(a.len()-b.len())};
}

with --warn clippy::arithmetic_side_effects

I saw this happen:

warning: arithmetic operation that can potentially result in unexpected side-effects
 --> src/main.rs:4:35
  |
4 |     if a.ends_with(b) {a.truncate(a.len()-b.len())};
  |                                   ^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#arithmetic_side_effects
  = note: requested on the command line with `-W clippy::arithmetic-side-effects`

warning: `asetest` (bin "asetest") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.05s

I expected to see this happen:

No warning because the thing being warned about can't happen.

Version
rustc 1.77.2 (25ef9e3d8 2024-04-09)
binary: rustc
commit-hash: 25ef9e3d85d934b27d9dada2f9dd52b1dc63bb04
commit-date: 2024-04-09
host: x86_64-unknown-linux-gnu
release: 1.77.2
LLVM version: 17.0.6
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the warning with the Rust example and --warn clippy::arithmetic_side_effects. Start by tracing how this lint handles the haystack.len()-needle.len() expression after str::ends_with; done means the demonstrated subtraction is no longer warned about when guarded by ends_with.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.