Clamp

Trait Clamp 

Source
pub trait Clamp {
    // Required method
    fn clamp(self, min: &Self, max: &Self) -> Self;
}
Expand description

Trait for clamping a value between minimum and maximum bounds.

This trait provides functionality to restrict a value to lie within a specified range. If the value is less than the minimum, it returns the minimum. If greater than the maximum, it returns the maximum. Otherwise, it returns the value unchanged.

§Examples

use num_valid::functions::Clamp;

let result = Clamp::clamp(5.0f64, &0.0, &10.0);
assert_eq!(result, 5.0);

let result = Clamp::clamp(-5.0f64, &0.0, &10.0);
assert_eq!(result, 0.0);

let result = Clamp::clamp(15.0f64, &0.0, &10.0);
assert_eq!(result, 10.0);

Required Methods§

Source

fn clamp(self, min: &Self, max: &Self) -> Self

Clamp the value within the specified bounds.

Returns max if self is greater than max, and min if self is less than min. Otherwise this returns self.

Note that this function returns NaN if the initial value was NaN as well.

§Panics

Panics if min > max, min is NaN, or max is NaN.

use num_valid::functions::Clamp;

assert!(Clamp::clamp(-3.0f64, &-2.0, &1.0) == -2.0);
assert!(Clamp::clamp(0.0f64, &-2.0, &1.0) == 0.0);
assert!(Clamp::clamp(2.0f64, &-2.0, &1.0) == 1.0);
assert!(Clamp::clamp(f64::NAN, &-2.0, &1.0).is_nan());

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl Clamp for f64

Source§

fn clamp(self, min: &Self, max: &Self) -> Self

Clamp the value within the specified bounds.

Returns max if self is greater than max, and min if self is less than min. Otherwise this returns self.

Note that this function returns NaN if the initial value was NaN as well.

§Panics

Panics if min > max, min is NaN, or max is NaN.

use num_valid::functions::Clamp;

assert!(Clamp::clamp(-3.0f64, &-2.0, &1.0) == -2.0);
assert!(Clamp::clamp(0.0f64, &-2.0, &1.0) == 0.0);
assert!(Clamp::clamp(2.0f64, &-2.0, &1.0) == 1.0);
assert!(Clamp::clamp(f64::NAN, &-2.0, &1.0).is_nan());

Implementors§