Skip to content

Commit d561e4b

Browse files
authored
Merge pull request #262 from Xaeroxe23/master
Add clamp function
2 parents 817ab00 + c78a48f commit d561e4b

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded,
8181
one, zero, abs, abs_sub, signum,
8282
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
8383
PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast,
84-
pow, checked_pow};
84+
pow, checked_pow, clamp};
8585

8686
#[cfg(feature = "num-bigint")]
8787
pub mod bigint {

traits/src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,36 @@ macro_rules! float_trait_impl {
241241
}
242242
float_trait_impl!(Num for f32 f64);
243243

244+
/// A value bounded by a minimum and a maximum
245+
///
246+
/// If input is less than min then this returns min.
247+
/// If input is greater than max then this returns max.
248+
/// Otherwise this returns input.
249+
#[inline]
250+
pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
251+
debug_assert!(min <= max, "min must be less than or equal to max");
252+
if input < min {
253+
min
254+
} else if input > max {
255+
max
256+
} else {
257+
input
258+
}
259+
}
260+
261+
#[test]
262+
fn clamp_test() {
263+
// Int test
264+
assert_eq!(1, clamp(1, -1, 2));
265+
assert_eq!(-1, clamp(-2, -1, 2));
266+
assert_eq!(2, clamp(3, -1, 2));
267+
268+
// Float test
269+
assert_eq!(1.0, clamp(1.0, -1.0, 2.0));
270+
assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0));
271+
assert_eq!(2.0, clamp(3.0, -1.0, 2.0));
272+
}
273+
244274
#[test]
245275
fn from_str_radix_unwrap() {
246276
// The Result error must impl Debug to allow unwrap()

0 commit comments

Comments
 (0)