]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass-fulldeps/sort-unstable.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / test / run-pass-fulldeps / sort-unstable.rs
1 // Copyright 2017 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(rustc_private, sort_internals)]
12
13 extern crate core;
14 extern crate rand;
15
16 use std::cmp::Ordering::{Equal, Greater, Less};
17 use core::slice::heapsort;
18
19 use rand::{Rng, XorShiftRng};
20
21 fn main() {
22 let mut v = [0; 600];
23 let mut tmp = [0; 600];
24 let mut rng = XorShiftRng::new_unseeded();
25
26 for len in (2..25).chain(500..510) {
27 let v = &mut v[0..len];
28 let tmp = &mut tmp[0..len];
29
30 for &modulus in &[5, 10, 100, 1000] {
31 for _ in 0..100 {
32 for i in 0..len {
33 v[i] = rng.gen::<i32>() % modulus;
34 }
35
36 // Sort in default order.
37 tmp.copy_from_slice(v);
38 tmp.sort_unstable();
39 assert!(tmp.windows(2).all(|w| w[0] <= w[1]));
40
41 // Sort in ascending order.
42 tmp.copy_from_slice(v);
43 tmp.sort_unstable_by(|a, b| a.cmp(b));
44 assert!(tmp.windows(2).all(|w| w[0] <= w[1]));
45
46 // Sort in descending order.
47 tmp.copy_from_slice(v);
48 tmp.sort_unstable_by(|a, b| b.cmp(a));
49 assert!(tmp.windows(2).all(|w| w[0] >= w[1]));
50
51 // Test heapsort using `<` operator.
52 tmp.copy_from_slice(v);
53 heapsort(tmp, |a, b| a < b);
54 assert!(tmp.windows(2).all(|w| w[0] <= w[1]));
55
56 // Test heapsort using `>` operator.
57 tmp.copy_from_slice(v);
58 heapsort(tmp, |a, b| a > b);
59 assert!(tmp.windows(2).all(|w| w[0] >= w[1]));
60 }
61 }
62 }
63
64 // Sort using a completely random comparison function.
65 // This will reorder the elements *somehow*, but won't panic.
66 for i in 0..v.len() {
67 v[i] = i as i32;
68 }
69 v.sort_unstable_by(|_, _| *rng.choose(&[Less, Equal, Greater]).unwrap());
70 v.sort_unstable();
71 for i in 0..v.len() {
72 assert_eq!(v[i], i as i32);
73 }
74
75 // Should not panic.
76 [0i32; 0].sort_unstable();
77 [(); 10].sort_unstable();
78 [(); 100].sort_unstable();
79
80 let mut v = [0xDEADBEEFu64];
81 v.sort_unstable();
82 assert!(v == [0xDEADBEEF]);
83 }