summaryrefslogtreecommitdiffstats
path: root/src/util.rs
blob: f838a9bee283b5ef52177c29b1e0c226d0dbb952 (plain)
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
//! Internal utilities.

use std::cmp::Ordering;

/// A wrapper that converts a partial ordering into a total one by panicking.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Ordered<T>(T);

impl<T> Ordered<T> {
    /// Wrap a value.
    pub fn new(item: T) -> Self {
        Self(item)
    }
}

impl<T> From<T> for Ordered<T> {
    fn from(item: T) -> Self {
        Self::new(item)
    }
}

impl<T: PartialOrd> Ord for Ordered<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).expect("Comparison between unordered items")
    }
}

impl<T: PartialEq> Eq for Ordered<T> {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ordered() {
        let one = Ordered::new(1.0);
        let two = Ordered::new(2.0);

        assert_eq!(one.cmp(&one), Ordering::Equal);
        assert_eq!(one.cmp(&two), Ordering::Less);
        assert_eq!(two.cmp(&one), Ordering::Greater);
    }

    #[test]
    #[should_panic(expected = "Comparison between unordered items")]
    fn test_unordered() {
        let one = Ordered::new(1.0);
        let nan = Ordered::new(f64::NAN);

        assert!(!(one < nan));
        assert!(!(nan < one));
        let _ = one.cmp(&nan);
    }
}