rust-lang / rust-lang/rust-clippy

indexing_slicing should not warn with find/starts_with

Open
#12,236 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 using find and starts_with the warning should obviously be suppressed.

Lint Name

indexing_slicing

Reproducer

I tried this code:

fn get_fallback(target: &str) -> Result<String, FallbackError> {
  use FallbackError::*;
  // find the scheme
  let scheme = {
    let colon = target.find(':').ok_or(NotAnUrl)?;
    let scheme = &target[..colon];
    if !scheme.starts_with("web+") {
      return Err(NotAnUrl);
    }
    let scheme = &scheme[4..];
    if is_scheme_invalid(scheme) {
      return Err(NotAnUrl);
    }
    scheme
  };
  // bunch of other stuff
}

I saw this happen:

warning: slicing may panic
   --> crates/api_common/src/request.rs:374:19
    |
374 |     let scheme = &target[..colon];
    |                   ^^^^^^^^^^^^^^^
    |
    = help: consider using `.get(..n)`or `.get_mut(..n)` instead
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing
    = note: requested on the command line with `-D clippy::indexing-slicing`

warning: slicing may panic
   --> crates/api_common/src/request.rs:378:19
    |
378 |     let scheme = &scheme[4..];
    |                   ^^^^^^^^^^^
    |
    = help: consider using `.get(n..)` or .get_mut(n..)` instead
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing

I expected to see this happen:

It should simply not.

Version
rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-gnu
release: 1.75.0
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

Start with the indexing_slicing lint and reproduce the warning using the get_fallback example, including the slices in crates/api_common/src/request.rs. Check how find and starts_with are handled, then verify that these cases no longer emit the lint warning while other indexing-slicing cases still do.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.