178. Ord::clamp — Stop Writing min(max, max(min, x))
Bounding a value between two limits is one of those tiny operations where everyone hand-rolls a confusing nest of min/max calls. Ord::clamp is the single-call version, and it works on anything that’s Ord or PartialOrd — not just numbers.
You’ve seen this somewhere in every codebase:
| |
Both work. Both make you stop and squint to figure out which bound is which. clamp says exactly what it does:
| |
It’s defined for Ord on integers, and as f32::clamp / f64::clamp for floats (which need PartialOrd because of NaN). Same shape on all of them:
| |
It’s not just for numbers. Anything Ord works — char, &str, String, your own types:
| |
One gotcha: clamp panics if min > max. That’s deliberate — a backwards range is almost always a bug, and silently returning either bound would hide it. If your bounds come from user input or config, validate them once at the boundary:
| |
For floats there’s one more wrinkle: f64::clamp propagates NaN if the input is NaN, but panics if either bound is NaN. So x.clamp(0.0, 1.0) is safe as long as your bounds are real numbers — which they always should be.