Skip to content

Commit

Permalink
Add stability test for sort_by_cached_key
Browse files Browse the repository at this point in the history
  • Loading branch information
varkor committed Mar 19, 2018
1 parent 785e3c3 commit eca1e18
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/liballoc/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,24 +485,29 @@ fn test_sort_stability() {
// the second item represents which occurrence of that
// number this element is, i.e. the second elements
// will occur in sorted order.
let mut v: Vec<_> = (0..len)
let mut orig: Vec<_> = (0..len)
.map(|_| {
let n = thread_rng().gen::<usize>() % 10;
counts[n] += 1;
(n, counts[n])
})
.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.
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
// will need to be ordered with increasing
// counts... i.e. exactly asserting that this sort is
// stable.
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]));
}
}
}
Expand Down

0 comments on commit eca1e18

Please sign in to comment.