partial_min_max/lib.rs
1//! `min` and `max` functions that work with `PartialOrd`.
2//!
3//! When given `NaN`s and other values that don't have total orderings, the
4//! functions have well-defined (but arbitrary) behavior: return the second
5//! argument.
6//!
7//! ```
8//! use partial_min_max::{min, max};
9//! use std::f32::NAN;
10//!
11//! // Does what you expect for the easy cases...
12//! assert_eq!(min(0.0, 1.0), 0.0);
13//! assert_eq!(max(0.0, 1.0), 1.0);
14//!
15//! // In the case of comparisons with NaN or other partial orderings, returns the
16//! // second value.
17//! assert!(min(0.0, NAN).is_nan());
18//! assert_eq!(min(NAN, 0.0), 0.0);
19//! ```
20
21/// A version of `std::cmp::min` that works with `PartialOrd` types.
22///
23/// If `a < b` return `a`, otherwise return `b`.
24///
25/// # Example
26///
27/// ```
28/// use partial_min_max::min;
29/// use std::f32::NAN;
30///
31/// assert_eq!(min(0.0, 1.0), 0.0);
32///
33/// assert!(min(0.0, NAN).is_nan());
34/// assert_eq!(min(NAN, 0.0), 0.0);
35/// ```
36#[inline]
37pub fn min<T: PartialOrd>(a: T, b: T) -> T {
38 if a < b {
39 a
40 } else {
41 b
42 }
43}
44
45/// A version of `std::cmp::max` that works with `PartialOrd` types.
46///
47/// If `a > b` return `a`, otherwise return `b`.
48///
49/// # Example
50///
51/// ```
52/// use partial_min_max::max;
53/// use std::f32::NAN;
54///
55/// assert_eq!(max(0.0, 1.0), 1.0);
56///
57/// assert!(max(0.0, NAN).is_nan());
58/// assert_eq!(max(NAN, 0.0), 0.0);
59/// ```
60#[inline]
61pub fn max<T: PartialOrd>(a: T, b: T) -> T {
62 if a > b {
63 a
64 } else {
65 b
66 }
67}