Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NAN preserving clamp_lower/upper #122

Merged
merged 6 commits into from
Sep 14, 2019
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,17 +371,55 @@ pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
}
}

/// A value bounded by a minimum value
///
/// If input is less than min then this returns min.
/// Otherwise this returns input.
/// Preserves `NaN` different from `min`.
cuviper marked this conversation as resolved.
Show resolved Hide resolved
#[inline]
pub fn clamp_lower<T: PartialOrd>(input: T, min: T) -> T {
if input < min {
min
} else {
input
}
}

/// A value bounded by a maximum value
///
/// If input is less than min then this returns min.
cuviper marked this conversation as resolved.
Show resolved Hide resolved
/// Otherwise this returns input.
/// Preserves `NaN` different from `max`.
#[inline]
pub fn clamp_upper<T: PartialOrd>(input: T, max: T) -> T {
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));
assert_eq!(1, clamp_lower(1, -1));
assert_eq!(-1, clamp_lower(-2, -1));
assert_eq!(-1, clamp_upper(1, -1));
assert_eq!(-2, clamp_upper(-2, -1));

// 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));
assert_eq!(1.0, clamp_lower(1.0, -1.0));
assert_eq!(-1.0, clamp_lower(-2.0, -1.0));
assert_eq!(-1.0, clamp_upper(1.0, -1.0));
assert_eq!(-2.0, clamp_upper(-2.0, -1.0));
assert!(clamp_lower(::core::f32::NAN, 1.0).is_nan());
assert!(clamp_upper(::core::f32::NAN, 1.0).is_nan());
cuviper marked this conversation as resolved.
Show resolved Hide resolved
}

#[test]
Expand Down