Rollup merge of #40947 - stjepang:test-sort-random-cmp, r=alexcrichton
Test sort algorithms using a random cmp function This ensures that sorting using a broken comparison function doesn't panic nor fail in some other way (especially not segfault). r? @alexcrichton
This commit is contained in:
commit
54b3f6aa21
@ -383,9 +383,11 @@ fn test_reverse() {
|
||||
|
||||
#[test]
|
||||
fn test_sort() {
|
||||
let mut rng = thread_rng();
|
||||
|
||||
for len in (2..25).chain(500..510) {
|
||||
for _ in 0..100 {
|
||||
let mut v: Vec<_> = thread_rng().gen_iter::<i32>().take(len).collect();
|
||||
let mut v: Vec<_> = rng.gen_iter::<i32>().take(len).collect();
|
||||
let mut v1 = v.clone();
|
||||
|
||||
v.sort();
|
||||
@ -399,6 +401,18 @@ fn test_sort() {
|
||||
}
|
||||
}
|
||||
|
||||
// Sort using a completely random comparison function.
|
||||
// This will reorder the elements *somehow*, but won't panic.
|
||||
let mut v = [0; 500];
|
||||
for i in 0..v.len() {
|
||||
v[i] = i as i32;
|
||||
}
|
||||
v.sort_by(|_, _| *rng.choose(&[Less, Equal, Greater]).unwrap());
|
||||
v.sort();
|
||||
for i in 0..v.len() {
|
||||
assert_eq!(v[i], i as i32);
|
||||
}
|
||||
|
||||
// Should not panic.
|
||||
[0i32; 0].sort();
|
||||
[(); 10].sort();
|
||||
|
@ -8,6 +8,7 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use core::cmp::Ordering::{Equal, Greater, Less};
|
||||
use core::slice::heapsort;
|
||||
use core::result::Result::{Ok, Err};
|
||||
use rand::{Rng, XorShiftRng};
|
||||
@ -268,6 +269,17 @@ fn sort_unstable() {
|
||||
}
|
||||
}
|
||||
|
||||
// Sort using a completely random comparison function.
|
||||
// This will reorder the elements *somehow*, but won't panic.
|
||||
for i in 0..v.len() {
|
||||
v[i] = i as i32;
|
||||
}
|
||||
v.sort_unstable_by(|_, _| *rng.choose(&[Less, Equal, Greater]).unwrap());
|
||||
v.sort_unstable();
|
||||
for i in 0..v.len() {
|
||||
assert_eq!(v[i], i as i32);
|
||||
}
|
||||
|
||||
// Should not panic.
|
||||
[0i32; 0].sort_unstable();
|
||||
[(); 10].sort_unstable();
|
||||
|
Loading…
Reference in New Issue
Block a user