-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Description
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:
pedanticorcomplexity- similar to other "could write it shorter" lints like the ones forIteratorcombinators.
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 themin_maxlint should be updated to also catch this. -
foo.clamp(y, x)is not strictly equal tofoo.min(x).max(y)orfoo.max(y).min(x); it panics ifx < ybut the original code would returnyorxrespectively. But I'm not sure if there can be a situation where the user wants this behavior, rather than either replacing the whole expr withy/xor fixing the order of the operands. -
JP-Ellis points out in this comment that
f32::clampandf64::clamppanic when either parameter is NaN, which is also a deviation from the behavior off32::minandf32::maxwhich always return the non-NaN value.
Example
As above.