From f8dcec366b93e3d40e301d12c33698cc3c1bd2d8 Mon Sep 17 00:00:00 2001 From: Jacob Kiesel Date: Tue, 7 Feb 2017 13:02:32 -0700 Subject: [PATCH] Made requested changes. --- src/lib.rs | 14 +------------- traits/src/lib.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9e92a91..8eefb08 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,7 +81,7 @@ pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded, one, zero, abs, abs_sub, signum, Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast, - pow, checked_pow}; + pow, checked_pow, clamp}; #[cfg(feature = "num-bigint")] pub mod bigint { @@ -109,15 +109,3 @@ pub mod traits { pub mod rational { pub use num_rational::*; } - -/// A value bounded by a minimum and a maximum -/// -/// If input is less than min then min is returned, if input is greater than max then max is -/// returned. Otherwise input is returned. -#[inline] -pub fn clamp(input: T, min: T, max: T) -> T { - debug_assert!(min < max, "min must be less than max"); - if input <= min {min} - else if input >= max {max} - else {input} -} diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 341d1f4..49904c4 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -241,6 +241,35 @@ macro_rules! float_trait_impl { } float_trait_impl!(Num for f32 f64); +/// A value bounded by a minimum and a maximum +/// +/// If input is less than min then min is returned, if input is greater than max then max is +/// returned. Otherwise input is returned. +#[inline] +pub fn clamp(input: T, min: T, max: T) -> T { + debug_assert!(min <= max, "min must be less than 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] fn from_str_radix_unwrap() { // The Result error must impl Debug to allow unwrap()