1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Macros for nicer min and max.
//! Also contains macros for min/max of f64s.

/// Returns the lowest value (Ord) of the passed parameters.
///
/// # Examples
/// ```
/// min!(3, 7, 2, 5);
/// = 2
/// ```
#[macro_export]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($xs: expr), +) => {
        {
            use std::cmp::min;
            min($x, min!($($xs), +))
        }
    }
}

/// Returns the highest value (Ord) of the passed parameters.
///
/// # Examples
/// ```
/// max!(3, 7, 2, 5);
/// = 7
/// ```
#[macro_export]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($xs: expr), +) => {
        {
            use std::cmp::max;
            max($x, max!($($xs), +))
        }
    }
}

/// f(x, y) form of f64's x.min(y)
/// Used in min_f!
#[allow(dead_code)]
pub fn min_f64(x: f64, y: f64) -> f64 {
    x.min(y)
}

/// f(x, y) form of f64's x.max(y)
/// Used in max_f!
#[allow(dead_code)]
pub fn max_f64(x: f64, y: f64) -> f64 {
    x.max(y)
}

/// Returns the lowest value (f64) of the passed parameters.
///
/// # Examples
/// ```
/// min_f!(3.1, 7.6, 2.3, 5.0);
/// = 2.3
/// ```
#[macro_export]
macro_rules! min_f {
    ($x: expr) => ($x as f64);
    ($x: expr, $($xs: expr), +) => {
        {
            use min_max_macros::min_f64;
            min_f64($x as f64, min_f!($($xs), +))
        }
    }
}

/// Returns the highest value (f64) of the passed parameters.
///
/// # Examples
/// ```
/// max_f!(3.1, 7.6, 2.3, 5.0);
/// = 7.6
/// ```
#[macro_export]
macro_rules! max_f {
    ($x: expr) => ($x as f64);
    ($x: expr, $($xs: expr), +) => {
        {
            use min_max_macros::max_f64;
            max_f64($x as f64, max_f!($($xs), +))
        }
    }
}

#[test]
fn test_min() {
    assert!(min!(1) == 1);
    assert!(min!(1, 2, 3) == 1);
    assert!(min!(-1, 0, 1) == -1);
}

#[test]
fn test_max() {
    assert!(max!(1) == 1);
    assert!(max!(1, 2, 3) == 3);
    assert!(max!(-1, 0, 1) == 1);
}

//#[test]
//fn test_min_f() {
//    assert!(min_f!(1.0) == 1.0);
//    assert!(min_f!(1.2, 3.4, 5.6) == 1.2);
//    assert!(min_f!(-1.0, 0.0, 1.0) == -1.0);
//}
//
//#[test]
//fn test_max_f() {
//    assert!(max_f!(1.0) == 1.0);
//    assert!(max_f!(1.2, 3.4, 5.6) == 5.6);
//    assert!(max_f!(-1.0, 0.0, 1.0) == 1.0);
//}