-
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:
pedantic
orcomplexity
- similar to other "could write it shorter" lints like the ones forIterator
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 themin_max
lint 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 < y
but the original code would returny
orx
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 withy
/x
or fixing the order of the operands. -
JP-Ellis points out in this comment that
f32::clamp
andf64::clamp
panic when either parameter is NaN, which is also a deviation from the behavior off32::min
andf32::max
which always return the non-NaN value.
Example
As above.