rust-lang / rust-lang/rust-clippy

Possible lint for when range contains is being done against type bounds

Open
#12,926 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

This lint would change (0u8..X).contains(&Y) to Y < X in cases where 0u8 can be replaced with the lower bound for the type. It would also do the same for the upper bound for the type, e.g. (X..u8::max_value()).contains(Y) into Y > X.

There is also the matter of (u8::min_value()..=u8::max_value()).contains(&5) doesn't throw any sort of warning about checking the full range of all values for a value. Should I open another issue about adding a lint for that too?

Advantage

Clarifies that range is being checked all the way to the type bounds.

Intuitive corollary to manual_range_contains.

Drawbacks

To my knowledge, in order to implement range requires implementing PartialOrd, but implementing PartialOrd doesn't include any surefire way to check the bounds of the type. However, my testing seems to show that using single sided ranges (..X) works for types that implement their own PartialOrd, so I must just be missing something.

I'm unsure where this should be listed, but there is also a borrow that doesn't have to be done if the comparison is being done instead of the contains check.

Example
assert!((0..5).contains(&2u8));
assert!((0..=5).contains(&5u8));

Could be written as:

assert!(2u8 < 5);
assert!(5u8 <= 5);

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 by reviewing the existing manual_range_contains lint referenced in the issue and compare it with the proposed inclusive and exclusive range examples. Determine how type bounds and custom PartialOrd implementations affect the lint, and clarify whether the full-range case belongs in this issue or a separate one. Done means the intended cases and limitations are resolved sufficiently to specify the lint.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.