argmin_math/primitives/
minmax.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::ArgminMinMax;
9
10macro_rules! make_minmax {
11    ($t:ty) => {
12        impl ArgminMinMax for $t {
13            #[inline]
14            fn min(x: &Self, y: &Self) -> $t {
15                if x <= y {
16                    *x
17                } else {
18                    *y
19                }
20            }
21
22            fn max(x: &Self, y: &Self) -> $t {
23                if x >= y {
24                    *x
25                } else {
26                    *y
27                }
28            }
29        }
30    };
31}
32
33make_minmax!(f32);
34make_minmax!(f64);
35make_minmax!(i8);
36make_minmax!(i16);
37make_minmax!(i32);
38make_minmax!(i64);
39make_minmax!(u8);
40make_minmax!(u16);
41make_minmax!(u32);
42make_minmax!(u64);
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47    use paste::item;
48
49    macro_rules! make_test {
50        ($t:ty) => {
51            item! {
52                #[test]
53                fn [<test_minmax_ $t>]() {
54                    let x = 5 as $t;
55                    let y = 10 as $t;
56                    assert_eq!(<$t as ArgminMinMax>::min(&x, &y).to_ne_bytes(), x.to_ne_bytes());
57                    assert_eq!(<$t as ArgminMinMax>::max(&x, &y).to_ne_bytes(), y.to_ne_bytes());
58                    assert_eq!(<$t as ArgminMinMax>::min(&y, &x).to_ne_bytes(), x.to_ne_bytes());
59                    assert_eq!(<$t as ArgminMinMax>::max(&y, &x).to_ne_bytes(), y.to_ne_bytes());
60                }
61            }
62        };
63    }
64
65    make_test!(f32);
66    make_test!(f64);
67    make_test!(i8);
68    make_test!(u8);
69    make_test!(i16);
70    make_test!(u16);
71    make_test!(i32);
72    make_test!(u32);
73    make_test!(i64);
74    make_test!(u64);
75}