Skip to content

missing_asserts_for_indexing is emitted when length is checked with "==" (instead of ">") #11835

Closed
@SylvainDe

Description

@SylvainDe

Summary

The suggestion for lint missing_asserts_for_indexing ( assert!(foobar.len() > 42);) works fine to disable the lint. However, sometimes, it makes more sense to check the length with equality (assert!(foobar.len() == 43);). I'd expect this to disable the lint as well but it does not seem to be the case.

Lint Name

missing_asserts_for_indexing

Reproducer

I tried this code:

fn intersection_1d((beg1, end1): Range, (beg2, end2): Range) -> Option<Range> {
    // Return list of disjoint sets with booleans to know whether the chunk
    // belong to range 1 and/or range 2
    assert!(beg1 <= end1);
    assert!(beg2 <= end2);
    let mut points = [beg1, end1, beg2, end2];
    points.sort_unstable();
    for win in points.windows(2) {
        assert!(win.len() == 2);
        let (beg, end) = (win[0], win[1]);
        if beg < end && value_in_range(beg, (beg1, end1)) && value_in_range(beg, (beg2, end2)) {
            return Some((beg, end));
        }
    }
    None
}

I saw this happen:

error: indexing into a slice multiple times without an `assert`
   --> src/2021/day22.rs:223:27
    |
223 |         let (beg, end) = (win[0], win[1]);
    |                           ^^^^^^^^^^^^^^
    |
    = help: consider asserting the length before indexing: `assert!(win.len() > 1);`
note: slice indexed here
   --> src/2021/day22.rs:223:27
    |
223 |         let (beg, end) = (win[0], win[1]);
    |                           ^^^^^^
note: slice indexed here
   --> src/2021/day22.rs:223:35
    |
223 |         let (beg, end) = (win[0], win[1]);
    |                                   ^^^^^^
    = note: asserting the length before indexing will elide bounds checks
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_asserts_for_indexing
    = note: `-D clippy::missing-asserts-for-indexing` implied by `-D clippy::restriction`
    = help: to override `-D clippy::restriction` add `#[allow(clippy::missing_asserts_for_indexing)]`

I expected to see this happen: no error.

Version

rustc 1.74.0 (79e9716c9 2023-11-13)
binary: rustc
commit-hash: 79e9716c980570bfd1f666e3b16ac583f0168962
commit-date: 2023-11-13
host: x86_64-unknown-linux-gnu
release: 1.74.0
LLVM version: 17.0.4

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions