Skip to content

Suggest usage of Ord::clamp, f32::clamp, and f64::clamp to simplify code #9477

@Xaeroxe

Description

@Xaeroxe

What it does

Identifies good opportunities for a clamp function from std or core, and suggests using it.

clamp functions

f32::clamp
f64::clamp
Ord::clamp

Lint Name

clamping_without_clamp

Category

complexity

Advantage

It's much shorter and easier to read, also doesn't use any control flow.

Drawbacks

The clamp functions panic in some circumstances which the original patterns will merely malfunction on. Namely, Ord types will panic if max < min and the floating point functions will additionally panic if min.is_nan() or max.is_nan(). Some may consider this a perk, but I'm listing it as a drawback because it may introduce panics where there weren't any before.

Example

if input > max {
    max
}
else if input < min {
    min
} else {
    input
}
input.max(min).min(max)
match input {
    input if input > max => max,
    input if input < min => min,
    input => input,
}

Could all be written as:

input.clamp(min, max)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions