competitive/tools/
totalord.rs

1use std::{
2    cmp::Ordering,
3    hash::{Hash, Hasher},
4};
5
6#[derive(Debug, Clone, Copy, Default)]
7/// implement Ord by PartialOrd
8///
9/// # Example
10///
11/// ```
12/// # use competitive::tools::TotalOrd;
13/// let mut a = vec![3.1, 4.1, 5.9, 2.6];
14/// a.sort_by_key(|&x| TotalOrd(x));
15/// ```
16///
17pub struct TotalOrd<T>(pub T);
18impl<T> PartialEq for TotalOrd<T>
19where
20    T: PartialEq,
21{
22    fn eq(&self, other: &Self) -> bool {
23        self.0 == other.0
24    }
25}
26impl<T> Eq for TotalOrd<T> where T: PartialEq {}
27impl<T> PartialOrd for TotalOrd<T>
28where
29    T: PartialOrd,
30{
31    fn partial_cmp(&self, other: &TotalOrd<T>) -> Option<Ordering> {
32        Some(self.cmp(other))
33    }
34}
35impl<T> Ord for TotalOrd<T>
36where
37    T: PartialOrd,
38{
39    fn cmp(&self, other: &TotalOrd<T>) -> Ordering {
40        self.0.partial_cmp(&other.0).unwrap()
41    }
42}
43impl<T> Hash for TotalOrd<T>
44where
45    T: Hash,
46{
47    fn hash<H>(&self, state: &mut H)
48    where
49        H: Hasher,
50    {
51        self.0.hash(state);
52    }
53}
54pub trait AsTotalOrd {
55    fn as_total_ord(&self) -> TotalOrd<&Self>;
56}
57impl<T: PartialOrd> AsTotalOrd for T {
58    fn as_total_ord(&self) -> TotalOrd<&Self> {
59        TotalOrd(self)
60    }
61}