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