Skip to content

Clippy suggests !RangeInclusive::contains for exclusive float range comparisons #6455

@eldruin

Description

@eldruin

I tried this code:

if humidity_percentage < 0.0 || humidity_percentage > 100.0 {
// ...
}

I expected to see this happen: no lint

Instead, this happened:
Clippy suggested to replace the "manual range implementation" with this: !(0.0..=100.0).contains(&humidity_percentage)
However, as some floating point numbers might not be exactly representable in IEEE-754, I think creating a range that does contain them (independently of what approximation the compiler actually settles for, the code suggests an exact number range) and presumably checking for equality on the edges (only to negate the whole thing afterwards) is not a nice suggestion.

I think it would be better not to suggest this in this case and maybe also not on similar cases concerning floating point numbers.

Meta

  • cargo clippy -V: clippy 0.0.212 (1700ca0 2020-12-08)
  • rustc -Vv:
rustc 1.50.0-nightly (1700ca07c 2020-12-08)
binary: rustc
commit-hash: 1700ca07c6dd7becff85678409a5df6ad4cf4f47
commit-date: 2020-12-08
host: x86_64-unknown-linux-gnu
release: 1.50.0-nightly

This lint has also already made it to the beta channel.

Backtrace

warning: manual `!RangeInclusive::contains` implementation
  --> src/app_mode.rs:65:12
   |
65 |           if humidity_percentage < 0.0
   |  ____________^
66 | |             || humidity_percentage > 100.0
   | |__________________________________________^ help: use: `!(0.0..=100.0).contains(&humidity_percentage)`
   |
   = note: `#[warn(clippy::manual_range_contains)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_range_contains

warning: 1 warning emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.01s

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingS-needs-discussionStatus: Needs further discussion before merging or work can be started

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions