commit
d561e4b702
|
@ -81,7 +81,7 @@ pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded,
|
||||||
one, zero, abs, abs_sub, signum,
|
one, zero, abs, abs_sub, signum,
|
||||||
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
|
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
|
||||||
PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast,
|
PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast,
|
||||||
pow, checked_pow};
|
pow, checked_pow, clamp};
|
||||||
|
|
||||||
#[cfg(feature = "num-bigint")]
|
#[cfg(feature = "num-bigint")]
|
||||||
pub mod bigint {
|
pub mod bigint {
|
||||||
|
|
|
@ -241,6 +241,36 @@ macro_rules! float_trait_impl {
|
||||||
}
|
}
|
||||||
float_trait_impl!(Num for f32 f64);
|
float_trait_impl!(Num for f32 f64);
|
||||||
|
|
||||||
|
/// A value bounded by a minimum and a maximum
|
||||||
|
///
|
||||||
|
/// If input is less than min then this returns min.
|
||||||
|
/// If input is greater than max then this returns max.
|
||||||
|
/// Otherwise this returns input.
|
||||||
|
#[inline]
|
||||||
|
pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
|
||||||
|
debug_assert!(min <= max, "min must be less than or equal to max");
|
||||||
|
if input < min {
|
||||||
|
min
|
||||||
|
} else if input > max {
|
||||||
|
max
|
||||||
|
} else {
|
||||||
|
input
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_test() {
|
||||||
|
// Int test
|
||||||
|
assert_eq!(1, clamp(1, -1, 2));
|
||||||
|
assert_eq!(-1, clamp(-2, -1, 2));
|
||||||
|
assert_eq!(2, clamp(3, -1, 2));
|
||||||
|
|
||||||
|
// Float test
|
||||||
|
assert_eq!(1.0, clamp(1.0, -1.0, 2.0));
|
||||||
|
assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0));
|
||||||
|
assert_eq!(2.0, clamp(3.0, -1.0, 2.0));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn from_str_radix_unwrap() {
|
fn from_str_radix_unwrap() {
|
||||||
// The Result error must impl Debug to allow unwrap()
|
// The Result error must impl Debug to allow unwrap()
|
||||||
|
|
Loading…
Reference in New Issue