Skip to content

Suggest foo.clamp(y, x) for foo.min(x).max(y) and foo.max(y).min(x) #6751

@Arnavion

Description

@Arnavion

What it does

Rust 1.50 stabilized std::cmp::Ord::clamp, f32::clamp and f64::clamp.

When the user writes foo.min(x).max(y) or foo.max(y).min(x) where foo is T: Ord or f32 or f64, clippy should suggest foo.clamp(y, x)

Also, the existing lint min_max should be extended to check for instances of foo.clamp(big, small), such as if the user manually translated foo.min(big).max(small) to foo.clamp(big, small) instead of foo.clamp(small, big)

Categories (optional)

  • Kind: pedantic or complexity - similar to other "could write it shorter" lints like the ones for Iterator combinators.

What is the advantage of the recommended code over the original code

Shorter code.

Drawbacks

  • Easier to silently mess up the order and call foo.clamp(big, small) without the instructive names "min" and "max" visible. That's why I suggest the min_max lint should be updated to also catch this.

  • foo.clamp(y, x) is not strictly equal to foo.min(x).max(y) or foo.max(y).min(x); it panics if x < y but the original code would return y or x respectively. But I'm not sure if there can be a situation where the user wants this behavior, rather than either replacing the whole expr with y / x or fixing the order of the operands.

  • JP-Ellis points out in this comment that f32::clamp and f64::clamp panic when either parameter is NaN, which is also a deviation from the behavior of f32::min and f32::max which always return the non-NaN value.

Example

As above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-styleLint: Belongs in the style lint groupT-middleType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions