diff --git a/src/lib.rs b/src/lib.rs index 1bc9e7b..73fcdb3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -364,6 +364,8 @@ float_trait_impl!(Num for f32 f64); /// If input is less than min then this returns min. /// If input is greater than max then this returns max. /// Otherwise this returns input. +/// +/// **Panics** in debug mode if `!(min <= max)`. #[inline] pub fn clamp(input: T, min: T, max: T) -> T { debug_assert!(min <= max, "min must be less than or equal to max"); @@ -381,8 +383,11 @@ pub fn clamp(input: T, min: T, max: T) -> T { /// If input is less than min then this returns min. /// Otherwise this returns input. /// `clamp_min(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::min(std::f32::NAN, 1.0)`. +/// +/// **Panics** in debug mode if `!(min == min)`. (This occurs if `min` is `NAN`.) #[inline] pub fn clamp_min(input: T, min: T) -> T { + debug_assert!(min == min, "min must not be NAN"); if input < min { min } else { @@ -395,8 +400,11 @@ pub fn clamp_min(input: T, min: T) -> T { /// If input is greater than max then this returns max. /// Otherwise this returns input. /// `clamp_max(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::max(std::f32::NAN, 1.0)`. +/// +/// **Panics** in debug mode if `!(max == max)`. (This occurs if `max` is `NAN`.) #[inline] pub fn clamp_max(input: T, max: T) -> T { + debug_assert!(max == max, "max must not be NAN"); if input > max { max } else { @@ -428,6 +436,41 @@ fn clamp_test() { assert!(clamp_max(::core::f32::NAN, 1.0).is_nan()); } +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_min() { + clamp(0., ::core::f32::NAN, 1.); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_max() { + clamp(0., -1., ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_nan_min_max() { + clamp(0., ::core::f32::NAN, ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_min_nan_min() { + clamp_min(0., ::core::f32::NAN); +} + +#[test] +#[should_panic] +#[cfg(debug_assertions)] +fn clamp_max_nan_max() { + clamp_max(0., ::core::f32::NAN); +} + #[test] fn from_str_radix_unwrap() { // The Result error must impl Debug to allow unwrap()