1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![feature(iter_min_max, cmp_partial, iter_cmp)]
14 use std::cmp::{self, PartialOrd, Ordering};
15 use std::iter::MinMaxResult::MinMax;
17 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
23 impl PartialOrd for Foo {
24 fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
30 fn cmp(&self, other: &Foo) -> Ordering {
36 let a = Foo { n: 4, name: "a" };
37 let b = Foo { n: 4, name: "b" };
38 let c = Foo { n: 8, name: "c" };
39 let d = Foo { n: 8, name: "d" };
40 let e = Foo { n: 22, name: "e" };
41 let f = Foo { n: 22, name: "f" };
43 let data = [a, b, c, d, e, f];
45 // `min` should return the left when the values are equal
46 assert_eq!(data.iter().min(), Some(&a));
47 assert_eq!(data.iter().min_by(|a| a.n), Some(&a));
48 assert_eq!(cmp::min(a, b), a);
49 assert_eq!(cmp::min(b, a), b);
50 assert_eq!(cmp::partial_min(a, b), Some(a));
51 assert_eq!(cmp::partial_min(b, a), Some(b));
53 // `max` should return the right when the values are equal
54 assert_eq!(data.iter().max(), Some(&f));
55 assert_eq!(data.iter().max_by(|a| a.n), Some(&f));
56 assert_eq!(cmp::max(e, f), f);
57 assert_eq!(cmp::max(f, e), e);
58 assert_eq!(cmp::partial_max(e, f), Some(f));
59 assert_eq!(cmp::partial_max(f, e), Some(e));
61 // Similar for `min_max`
62 assert_eq!(data.iter().min_max(), MinMax(&a, &f));
63 assert_eq!(data[1..5].iter().min_max(), MinMax(&b, &e));
64 assert_eq!(data[2..4].iter().min_max(), MinMax(&c, &d));
66 let mut presorted = data.to_vec();
68 assert_stable(&presorted);
70 let mut presorted = data.to_vec();
71 presorted.sort_by(|a, b| a.cmp(b));
72 assert_stable(&presorted);
74 // Assert that sorted and min/max are the same
75 fn assert_stable<T: Ord + Debug>(presorted: &[T]) {
76 for slice in presorted.windows(2) {
80 assert_eq!(a, cmp::min(a, b));
81 assert_eq!(b, cmp::max(a, b));