]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/minmax-stability-issue-23687.rs
Auto merge of #27786 - alexcrichton:start-testing-msvc, r=brson
[rust.git] / src / test / run-pass / minmax-stability-issue-23687.rs
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.
4 //
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.
10
11 #![feature(iter_min_max, cmp_partial, iter_cmp)]
12
13 use std::fmt::Debug;
14 use std::cmp::{self, PartialOrd, Ordering};
15
16 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
17 struct Foo {
18     n: u8,
19     name: &'static str
20 }
21
22 impl PartialOrd for Foo {
23     fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
24         Some(self.cmp(other))
25     }
26 }
27
28 impl Ord for Foo {
29     fn cmp(&self, other: &Foo) -> Ordering {
30         self.n.cmp(&other.n)
31     }
32 }
33
34 fn main() {
35     let a = Foo { n: 4, name: "a" };
36     let b = Foo { n: 4, name: "b" };
37     let c = Foo { n: 8, name: "c" };
38     let d = Foo { n: 8, name: "d" };
39     let e = Foo { n: 22, name: "e" };
40     let f = Foo { n: 22, name: "f" };
41
42     let data = [a, b, c, d, e, f];
43
44     // `min` should return the left when the values are equal
45     assert_eq!(data.iter().min(), Some(&a));
46     assert_eq!(data.iter().min_by(|a| a.n), Some(&a));
47     assert_eq!(cmp::min(a, b), a);
48     assert_eq!(cmp::min(b, a), b);
49
50     // `max` should return the right when the values are equal
51     assert_eq!(data.iter().max(), Some(&f));
52     assert_eq!(data.iter().max_by(|a| a.n), Some(&f));
53     assert_eq!(cmp::max(e, f), f);
54     assert_eq!(cmp::max(f, e), e);
55
56     let mut presorted = data.to_vec();
57     presorted.sort();
58     assert_stable(&presorted);
59
60     let mut presorted = data.to_vec();
61     presorted.sort_by(|a, b| a.cmp(b));
62     assert_stable(&presorted);
63
64     // Assert that sorted and min/max are the same
65     fn assert_stable<T: Ord + Debug>(presorted: &[T]) {
66         for slice in presorted.windows(2) {
67             let a = &slice[0];
68             let b = &slice[1];
69
70             assert_eq!(a, cmp::min(a, b));
71             assert_eq!(b, cmp::max(a, b));
72         }
73     }
74 }