Skip to content

Commit 428f89a

Browse files
bors[bot]termoshtt
andauthored
Merge #122
122: NAN preserving clamp_lower/upper r=cuviper a=termoshtt `NAN` preserving lower- and upper-clamp. Cc: rust-ndarray/ndarray#470 (comment) Co-authored-by: Toshiki Teramura <[email protected]>
2 parents 3add713 + 0e7c2a4 commit 428f89a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/lib.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,17 +376,56 @@ pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
376376
}
377377
}
378378

379+
/// A value bounded by a minimum value
380+
///
381+
/// If input is less than min then this returns min.
382+
/// Otherwise this returns input.
383+
/// `clamp_min(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::min(std::f32::NAN, 1.0)`.
384+
#[inline]
385+
pub fn clamp_min<T: PartialOrd>(input: T, min: T) -> T {
386+
if input < min {
387+
min
388+
} else {
389+
input
390+
}
391+
}
392+
393+
/// A value bounded by a maximum value
394+
///
395+
/// If input is greater than max then this returns max.
396+
/// Otherwise this returns input.
397+
/// `clamp_max(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::max(std::f32::NAN, 1.0)`.
398+
#[inline]
399+
pub fn clamp_max<T: PartialOrd>(input: T, max: T) -> T {
400+
if input > max {
401+
max
402+
} else {
403+
input
404+
}
405+
}
406+
379407
#[test]
380408
fn clamp_test() {
381409
// Int test
382410
assert_eq!(1, clamp(1, -1, 2));
383411
assert_eq!(-1, clamp(-2, -1, 2));
384412
assert_eq!(2, clamp(3, -1, 2));
413+
assert_eq!(1, clamp_min(1, -1));
414+
assert_eq!(-1, clamp_min(-2, -1));
415+
assert_eq!(-1, clamp_max(1, -1));
416+
assert_eq!(-2, clamp_max(-2, -1));
385417

386418
// Float test
387419
assert_eq!(1.0, clamp(1.0, -1.0, 2.0));
388420
assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0));
389421
assert_eq!(2.0, clamp(3.0, -1.0, 2.0));
422+
assert_eq!(1.0, clamp_min(1.0, -1.0));
423+
assert_eq!(-1.0, clamp_min(-2.0, -1.0));
424+
assert_eq!(-1.0, clamp_max(1.0, -1.0));
425+
assert_eq!(-2.0, clamp_max(-2.0, -1.0));
426+
assert!(clamp(::core::f32::NAN, -1.0, 1.0).is_nan());
427+
assert!(clamp_min(::core::f32::NAN, 1.0).is_nan());
428+
assert!(clamp_max(::core::f32::NAN, 1.0).is_nan());
390429
}
391430

392431
#[test]

0 commit comments

Comments
 (0)