Add stability test for sort_by_cached_key

This commit is contained in:
varkor
2018-03-19 00:11:47 +00:00
parent 785e3c38fe
commit eca1e18cd7

View File

@@ -485,7 +485,7 @@ fn test_sort_stability() {
// the second item represents which occurrence of that // the second item represents which occurrence of that
// number this element is, i.e. the second elements // number this element is, i.e. the second elements
// will occur in sorted order. // will occur in sorted order.
let mut v: Vec<_> = (0..len) let mut orig: Vec<_> = (0..len)
.map(|_| { .map(|_| {
let n = thread_rng().gen::<usize>() % 10; let n = thread_rng().gen::<usize>() % 10;
counts[n] += 1; counts[n] += 1;
@@ -493,16 +493,21 @@ fn test_sort_stability() {
}) })
.collect(); .collect();
// only sort on the first element, so an unstable sort let mut v = orig.clone();
// Only sort on the first element, so an unstable sort
// may mix up the counts. // may mix up the counts.
v.sort_by(|&(a, _), &(b, _)| a.cmp(&b)); v.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
// this comparison includes the count (the second item // This comparison includes the count (the second item
// of the tuple), so elements with equal first items // of the tuple), so elements with equal first items
// will need to be ordered with increasing // will need to be ordered with increasing
// counts... i.e. exactly asserting that this sort is // counts... i.e. exactly asserting that this sort is
// stable. // stable.
assert!(v.windows(2).all(|w| w[0] <= w[1])); assert!(v.windows(2).all(|w| w[0] <= w[1]));
let mut v = orig.clone();
v.sort_by_cached_key(|&(x, _)| x);
assert!(v.windows(2).all(|w| w[0] <= w[1]));
} }
} }
} }