1 // run-pass
2 
3 use std::fmt::Debug;
4 use std::cmp::{self, PartialOrd, Ordering};
5 
6 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
7 struct Foo {
8     n: u8,
9     name: &'static str
10 }
11 
12 impl PartialOrd for Foo {
partial_cmp(&self, other: &Foo) -> Option<Ordering>13     fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
14         Some(self.cmp(other))
15     }
16 }
17 
18 impl Ord for Foo {
cmp(&self, other: &Foo) -> Ordering19     fn cmp(&self, other: &Foo) -> Ordering {
20         self.n.cmp(&other.n)
21     }
22 }
23 
main()24 fn main() {
25     let a = Foo { n: 4, name: "a" };
26     let b = Foo { n: 4, name: "b" };
27     let c = Foo { n: 8, name: "c" };
28     let d = Foo { n: 8, name: "d" };
29     let e = Foo { n: 22, name: "e" };
30     let f = Foo { n: 22, name: "f" };
31 
32     let data = [a, b, c, d, e, f];
33 
34     // `min` should return the left when the values are equal
35     assert_eq!(data.iter().min(), Some(&a));
36     assert_eq!(data.iter().min_by_key(|a| a.n), Some(&a));
37     assert_eq!(cmp::min(a, b), a);
38     assert_eq!(cmp::min(b, a), b);
39 
40     // `max` should return the right when the values are equal
41     assert_eq!(data.iter().max(), Some(&f));
42     assert_eq!(data.iter().max_by_key(|a| a.n), Some(&f));
43     assert_eq!(cmp::max(e, f), f);
44     assert_eq!(cmp::max(f, e), e);
45 
46     let mut presorted = data.to_vec();
47     presorted.sort();
48     assert_stable(&presorted);
49 
50     let mut presorted = data.to_vec();
51     presorted.sort_by(|a, b| a.cmp(b));
52     assert_stable(&presorted);
53 
54     // Assert that sorted and min/max are the same
55     fn assert_stable<T: Ord + Debug>(presorted: &[T]) {
56         for slice in presorted.windows(2) {
57             let a = &slice[0];
58             let b = &slice[1];
59 
60             assert_eq!(a, cmp::min(a, b));
61             assert_eq!(b, cmp::max(a, b));
62         }
63     }
64 }
65