/// Supplies a `clamp` helper for numeric types.
///
/// Contract (minimum): return a value within the inclusive range `[min, max]`.
/// Implementers must document how incomparable values (e.g., `NaN`) and invalid
/// bounds (`min > max`) are handled.
pub trait Clamp: Sized {
fn clamp(self, min: Self, max: Self) -> Self;
}
macro_rules! impl_clamp {
($($ty:ty),+ $(,)?) => {
$(
impl Clamp for $ty {
/// Closed-interval clamp; returns `self` unchanged if comparisons
/// are not `true` (e.g., `NaN`). Debug builds assert `min <= max`.
fn clamp(self, min: Self, max: Self) -> Self {
debug_assert!(min <= max, "invalid clamp bounds");
if self < min {
min
} else if self > max {
max
} else {
self
}
}
}
)+
};
}
impl_clamp!(i8, i16, i32, i64, i128, isize,);
impl_clamp!(u8, u16, u32, u64, u128, usize,);
impl_clamp!(f32, f64,);