]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/sort.rs
RustWrapper: simplify removing attributes
[rust.git] / library / core / src / slice / sort.rs
1 //! Slice sorting
2 //!
3 //! This module contains a sorting algorithm based on Orson Peters' pattern-defeating quicksort,
4 //! published at: <https://github.com/orlp/pdqsort>
5 //!
6 //! Unstable sorting is compatible with libcore because it doesn't allocate memory, unlike our
7 //! stable sorting implementation.
8
9 use crate::cmp;
10 use crate::mem::{self, MaybeUninit};
11 use crate::ptr;
12
13 /// When dropped, copies from `src` into `dest`.
14 struct CopyOnDrop<T> {
15     src: *mut T,
16     dest: *mut T,
17 }
18
19 impl<T> Drop for CopyOnDrop<T> {
20     fn drop(&mut self) {
21         // SAFETY:  This is a helper class.
22         //          Please refer to its usage for correctness.
23         //          Namely, one must be sure that `src` and `dst` does not overlap as required by `ptr::copy_nonoverlapping`.
24         unsafe {
25             ptr::copy_nonoverlapping(self.src, self.dest, 1);
26         }
27     }
28 }
29
30 /// Shifts the first element to the right until it encounters a greater or equal element.
31 fn shift_head<T, F>(v: &mut [T], is_less: &mut F)
32 where
33     F: FnMut(&T, &T) -> bool,
34 {
35     let len = v.len();
36     // SAFETY: The unsafe operations below involves indexing without a bounds check (by offsetting a
37     // pointer) and copying memory (`ptr::copy_nonoverlapping`).
38     //
39     // a. Indexing:
40     //  1. We checked the size of the array to >=2.
41     //  2. All the indexing that we will do is always between {0 <= index < len} at most.
42     //
43     // b. Memory copying
44     //  1. We are obtaining pointers to references which are guaranteed to be valid.
45     //  2. They cannot overlap because we obtain pointers to difference indices of the slice.
46     //     Namely, `i` and `i-1`.
47     //  3. If the slice is properly aligned, the elements are properly aligned.
48     //     It is the caller's responsibility to make sure the slice is properly aligned.
49     //
50     // See comments below for further detail.
51     unsafe {
52         // If the first two elements are out-of-order...
53         if len >= 2 && is_less(v.get_unchecked(1), v.get_unchecked(0)) {
54             // Read the first element into a stack-allocated variable. If a following comparison
55             // operation panics, `hole` will get dropped and automatically write the element back
56             // into the slice.
57             let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(0)));
58             let v = v.as_mut_ptr();
59             let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.add(1) };
60             ptr::copy_nonoverlapping(v.add(1), v.add(0), 1);
61
62             for i in 2..len {
63                 if !is_less(&*v.add(i), &*tmp) {
64                     break;
65                 }
66
67                 // Move `i`-th element one place to the left, thus shifting the hole to the right.
68                 ptr::copy_nonoverlapping(v.add(i), v.add(i - 1), 1);
69                 hole.dest = v.add(i);
70             }
71             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
72         }
73     }
74 }
75
76 /// Shifts the last element to the left until it encounters a smaller or equal element.
77 fn shift_tail<T, F>(v: &mut [T], is_less: &mut F)
78 where
79     F: FnMut(&T, &T) -> bool,
80 {
81     let len = v.len();
82     // SAFETY: The unsafe operations below involves indexing without a bound check (by offsetting a
83     // pointer) and copying memory (`ptr::copy_nonoverlapping`).
84     //
85     // a. Indexing:
86     //  1. We checked the size of the array to >= 2.
87     //  2. All the indexing that we will do is always between `0 <= index < len-1` at most.
88     //
89     // b. Memory copying
90     //  1. We are obtaining pointers to references which are guaranteed to be valid.
91     //  2. They cannot overlap because we obtain pointers to difference indices of the slice.
92     //     Namely, `i` and `i+1`.
93     //  3. If the slice is properly aligned, the elements are properly aligned.
94     //     It is the caller's responsibility to make sure the slice is properly aligned.
95     //
96     // See comments below for further detail.
97     unsafe {
98         // If the last two elements are out-of-order...
99         if len >= 2 && is_less(v.get_unchecked(len - 1), v.get_unchecked(len - 2)) {
100             // Read the last element into a stack-allocated variable. If a following comparison
101             // operation panics, `hole` will get dropped and automatically write the element back
102             // into the slice.
103             let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(len - 1)));
104             let v = v.as_mut_ptr();
105             let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.add(len - 2) };
106             ptr::copy_nonoverlapping(v.add(len - 2), v.add(len - 1), 1);
107
108             for i in (0..len - 2).rev() {
109                 if !is_less(&*tmp, &*v.add(i)) {
110                     break;
111                 }
112
113                 // Move `i`-th element one place to the right, thus shifting the hole to the left.
114                 ptr::copy_nonoverlapping(v.add(i), v.add(i + 1), 1);
115                 hole.dest = v.add(i);
116             }
117             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
118         }
119     }
120 }
121
122 /// Partially sorts a slice by shifting several out-of-order elements around.
123 ///
124 /// Returns `true` if the slice is sorted at the end. This function is *O*(*n*) worst-case.
125 #[cold]
126 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
127 where
128     F: FnMut(&T, &T) -> bool,
129 {
130     // Maximum number of adjacent out-of-order pairs that will get shifted.
131     const MAX_STEPS: usize = 5;
132     // If the slice is shorter than this, don't shift any elements.
133     const SHORTEST_SHIFTING: usize = 50;
134
135     let len = v.len();
136     let mut i = 1;
137
138     for _ in 0..MAX_STEPS {
139         // SAFETY: We already explicitly did the bound checking with `i < len`.
140         // All our subsequent indexing is only in the range `0 <= index < len`
141         unsafe {
142             // Find the next pair of adjacent out-of-order elements.
143             while i < len && !is_less(v.get_unchecked(i), v.get_unchecked(i - 1)) {
144                 i += 1;
145             }
146         }
147
148         // Are we done?
149         if i == len {
150             return true;
151         }
152
153         // Don't shift elements on short arrays, that has a performance cost.
154         if len < SHORTEST_SHIFTING {
155             return false;
156         }
157
158         // Swap the found pair of elements. This puts them in correct order.
159         v.swap(i - 1, i);
160
161         // Shift the smaller element to the left.
162         shift_tail(&mut v[..i], is_less);
163         // Shift the greater element to the right.
164         shift_head(&mut v[i..], is_less);
165     }
166
167     // Didn't manage to sort the slice in the limited number of steps.
168     false
169 }
170
171 /// Sorts a slice using insertion sort, which is *O*(*n*^2) worst-case.
172 fn insertion_sort<T, F>(v: &mut [T], is_less: &mut F)
173 where
174     F: FnMut(&T, &T) -> bool,
175 {
176     for i in 1..v.len() {
177         shift_tail(&mut v[..i + 1], is_less);
178     }
179 }
180
181 /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case.
182 #[cold]
183 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
184 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
185 where
186     F: FnMut(&T, &T) -> bool,
187 {
188     // This binary heap respects the invariant `parent >= child`.
189     let mut sift_down = |v: &mut [T], mut node| {
190         loop {
191             // Children of `node`:
192             let left = 2 * node + 1;
193             let right = 2 * node + 2;
194
195             // Choose the greater child.
196             let greater =
197                 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
198
199             // Stop if the invariant holds at `node`.
200             if greater >= v.len() || !is_less(&v[node], &v[greater]) {
201                 break;
202             }
203
204             // Swap `node` with the greater child, move one step down, and continue sifting.
205             v.swap(node, greater);
206             node = greater;
207         }
208     };
209
210     // Build the heap in linear time.
211     for i in (0..v.len() / 2).rev() {
212         sift_down(v, i);
213     }
214
215     // Pop maximal elements from the heap.
216     for i in (1..v.len()).rev() {
217         v.swap(0, i);
218         sift_down(&mut v[..i], 0);
219     }
220 }
221
222 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
223 /// to `pivot`.
224 ///
225 /// Returns the number of elements smaller than `pivot`.
226 ///
227 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
228 /// This idea is presented in the [BlockQuicksort][pdf] paper.
229 ///
230 /// [pdf]: https://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
231 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
232 where
233     F: FnMut(&T, &T) -> bool,
234 {
235     // Number of elements in a typical block.
236     const BLOCK: usize = 128;
237
238     // The partitioning algorithm repeats the following steps until completion:
239     //
240     // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
241     // 2. Trace a block from the right side to identify elements smaller than the pivot.
242     // 3. Exchange the identified elements between the left and right side.
243     //
244     // We keep the following variables for a block of elements:
245     //
246     // 1. `block` - Number of elements in the block.
247     // 2. `start` - Start pointer into the `offsets` array.
248     // 3. `end` - End pointer into the `offsets` array.
249     // 4. `offsets - Indices of out-of-order elements within the block.
250
251     // The current block on the left side (from `l` to `l.add(block_l)`).
252     let mut l = v.as_mut_ptr();
253     let mut block_l = BLOCK;
254     let mut start_l = ptr::null_mut();
255     let mut end_l = ptr::null_mut();
256     let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
257
258     // The current block on the right side (from `r.sub(block_r)` to `r`).
259     // SAFETY: The documentation for .add() specifically mention that `vec.as_ptr().add(vec.len())` is always safe`
260     let mut r = unsafe { l.add(v.len()) };
261     let mut block_r = BLOCK;
262     let mut start_r = ptr::null_mut();
263     let mut end_r = ptr::null_mut();
264     let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
265
266     // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
267     // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
268
269     // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
270     fn width<T>(l: *mut T, r: *mut T) -> usize {
271         assert!(mem::size_of::<T>() > 0);
272         (r as usize - l as usize) / mem::size_of::<T>()
273     }
274
275     loop {
276         // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
277         // some patch-up work in order to partition the remaining elements in between.
278         let is_done = width(l, r) <= 2 * BLOCK;
279
280         if is_done {
281             // Number of remaining elements (still not compared to the pivot).
282             let mut rem = width(l, r);
283             if start_l < end_l || start_r < end_r {
284                 rem -= BLOCK;
285             }
286
287             // Adjust block sizes so that the left and right block don't overlap, but get perfectly
288             // aligned to cover the whole remaining gap.
289             if start_l < end_l {
290                 block_r = rem;
291             } else if start_r < end_r {
292                 block_l = rem;
293             } else {
294                 // There were the same number of elements to switch on both blocks during the last
295                 // iteration, so there are no remaining elements on either block. Cover the remaining
296                 // items with roughly equally-sized blocks.
297                 block_l = rem / 2;
298                 block_r = rem - block_l;
299             }
300             debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
301             debug_assert!(width(l, r) == block_l + block_r);
302         }
303
304         if start_l == end_l {
305             // Trace `block_l` elements from the left side.
306             start_l = MaybeUninit::slice_as_mut_ptr(&mut offsets_l);
307             end_l = start_l;
308             let mut elem = l;
309
310             for i in 0..block_l {
311                 // SAFETY: The unsafety operations below involve the usage of the `offset`.
312                 //         According to the conditions required by the function, we satisfy them because:
313                 //         1. `offsets_l` is stack-allocated, and thus considered separate allocated object.
314                 //         2. The function `is_less` returns a `bool`.
315                 //            Casting a `bool` will never overflow `isize`.
316                 //         3. We have guaranteed that `block_l` will be `<= BLOCK`.
317                 //            Plus, `end_l` was initially set to the begin pointer of `offsets_` which was declared on the stack.
318                 //            Thus, we know that even in the worst case (all invocations of `is_less` returns false) we will only be at most 1 byte pass the end.
319                 //        Another unsafety operation here is dereferencing `elem`.
320                 //        However, `elem` was initially the begin pointer to the slice which is always valid.
321                 unsafe {
322                     // Branchless comparison.
323                     *end_l = i as u8;
324                     end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
325                     elem = elem.offset(1);
326                 }
327             }
328         }
329
330         if start_r == end_r {
331             // Trace `block_r` elements from the right side.
332             start_r = MaybeUninit::slice_as_mut_ptr(&mut offsets_r);
333             end_r = start_r;
334             let mut elem = r;
335
336             for i in 0..block_r {
337                 // SAFETY: The unsafety operations below involve the usage of the `offset`.
338                 //         According to the conditions required by the function, we satisfy them because:
339                 //         1. `offsets_r` is stack-allocated, and thus considered separate allocated object.
340                 //         2. The function `is_less` returns a `bool`.
341                 //            Casting a `bool` will never overflow `isize`.
342                 //         3. We have guaranteed that `block_r` will be `<= BLOCK`.
343                 //            Plus, `end_r` was initially set to the begin pointer of `offsets_` which was declared on the stack.
344                 //            Thus, we know that even in the worst case (all invocations of `is_less` returns true) we will only be at most 1 byte pass the end.
345                 //        Another unsafety operation here is dereferencing `elem`.
346                 //        However, `elem` was initially `1 * sizeof(T)` past the end and we decrement it by `1 * sizeof(T)` before accessing it.
347                 //        Plus, `block_r` was asserted to be less than `BLOCK` and `elem` will therefore at most be pointing to the beginning of the slice.
348                 unsafe {
349                     // Branchless comparison.
350                     elem = elem.offset(-1);
351                     *end_r = i as u8;
352                     end_r = end_r.offset(is_less(&*elem, pivot) as isize);
353                 }
354             }
355         }
356
357         // Number of out-of-order elements to swap between the left and right side.
358         let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
359
360         if count > 0 {
361             macro_rules! left {
362                 () => {
363                     l.offset(*start_l as isize)
364                 };
365             }
366             macro_rules! right {
367                 () => {
368                     r.offset(-(*start_r as isize) - 1)
369                 };
370             }
371
372             // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
373             // permutation. This is not strictly equivalent to swapping, but produces a similar
374             // result using fewer memory operations.
375
376             // SAFETY: The use of `ptr::read` is valid because there is at least one element in
377             // both `offsets_l` and `offsets_r`, so `left!` is a valid pointer to read from.
378             //
379             // The uses of `left!` involve calls to `offset` on `l`, which points to the
380             // beginning of `v`. All the offsets pointed-to by `start_l` are at most `block_l`, so
381             // these `offset` calls are safe as all reads are within the block. The same argument
382             // applies for the uses of `right!`.
383             //
384             // The calls to `start_l.offset` are valid because there are at most `count-1` of them,
385             // plus the final one at the end of the unsafe block, where `count` is the minimum number
386             // of collected offsets in `offsets_l` and `offsets_r`, so there is no risk of there not
387             // being enough elements. The same reasoning applies to the calls to `start_r.offset`.
388             //
389             // The calls to `copy_nonoverlapping` are safe because `left!` and `right!` are guaranteed
390             // not to overlap, and are valid because of the reasoning above.
391             unsafe {
392                 let tmp = ptr::read(left!());
393                 ptr::copy_nonoverlapping(right!(), left!(), 1);
394
395                 for _ in 1..count {
396                     start_l = start_l.offset(1);
397                     ptr::copy_nonoverlapping(left!(), right!(), 1);
398                     start_r = start_r.offset(1);
399                     ptr::copy_nonoverlapping(right!(), left!(), 1);
400                 }
401
402                 ptr::copy_nonoverlapping(&tmp, right!(), 1);
403                 mem::forget(tmp);
404                 start_l = start_l.offset(1);
405                 start_r = start_r.offset(1);
406             }
407         }
408
409         if start_l == end_l {
410             // All out-of-order elements in the left block were moved. Move to the next block.
411
412             // block-width-guarantee
413             // SAFETY: if `!is_done` then the slice width is guaranteed to be at least `2*BLOCK` wide. There
414             // are at most `BLOCK` elements in `offsets_l` because of its size, so the `offset` operation is
415             // safe. Otherwise, the debug assertions in the `is_done` case guarantee that
416             // `width(l, r) == block_l + block_r`, namely, that the block sizes have been adjusted to account
417             // for the smaller number of remaining elements.
418             l = unsafe { l.offset(block_l as isize) };
419         }
420
421         if start_r == end_r {
422             // All out-of-order elements in the right block were moved. Move to the previous block.
423
424             // SAFETY: Same argument as [block-width-guarantee]. Either this is a full block `2*BLOCK`-wide,
425             // or `block_r` has been adjusted for the last handful of elements.
426             r = unsafe { r.offset(-(block_r as isize)) };
427         }
428
429         if is_done {
430             break;
431         }
432     }
433
434     // All that remains now is at most one block (either the left or the right) with out-of-order
435     // elements that need to be moved. Such remaining elements can be simply shifted to the end
436     // within their block.
437
438     if start_l < end_l {
439         // The left block remains.
440         // Move its remaining out-of-order elements to the far right.
441         debug_assert_eq!(width(l, r), block_l);
442         while start_l < end_l {
443             // remaining-elements-safety
444             // SAFETY: while the loop condition holds there are still elements in `offsets_l`, so it
445             // is safe to point `end_l` to the previous element.
446             //
447             // The `ptr::swap` is safe if both its arguments are valid for reads and writes:
448             //  - Per the debug assert above, the distance between `l` and `r` is `block_l`
449             //    elements, so there can be at most `block_l` remaining offsets between `start_l`
450             //    and `end_l`. This means `r` will be moved at most `block_l` steps back, which
451             //    makes the `r.offset` calls valid (at that point `l == r`).
452             //  - `offsets_l` contains valid offsets into `v` collected during the partitioning of
453             //    the last block, so the `l.offset` calls are valid.
454             unsafe {
455                 end_l = end_l.offset(-1);
456                 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
457                 r = r.offset(-1);
458             }
459         }
460         width(v.as_mut_ptr(), r)
461     } else if start_r < end_r {
462         // The right block remains.
463         // Move its remaining out-of-order elements to the far left.
464         debug_assert_eq!(width(l, r), block_r);
465         while start_r < end_r {
466             // SAFETY: See the reasoning in [remaining-elements-safety].
467             unsafe {
468                 end_r = end_r.offset(-1);
469                 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
470                 l = l.offset(1);
471             }
472         }
473         width(v.as_mut_ptr(), l)
474     } else {
475         // Nothing else to do, we're done.
476         width(v.as_mut_ptr(), l)
477     }
478 }
479
480 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
481 /// equal to `v[pivot]`.
482 ///
483 /// Returns a tuple of:
484 ///
485 /// 1. Number of elements smaller than `v[pivot]`.
486 /// 2. True if `v` was already partitioned.
487 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
488 where
489     F: FnMut(&T, &T) -> bool,
490 {
491     let (mid, was_partitioned) = {
492         // Place the pivot at the beginning of slice.
493         v.swap(0, pivot);
494         let (pivot, v) = v.split_at_mut(1);
495         let pivot = &mut pivot[0];
496
497         // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
498         // operation panics, the pivot will be automatically written back into the slice.
499
500         // SAFETY: `pivot` is a reference to the first element of `v`, so `ptr::read` is safe.
501         let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
502         let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
503         let pivot = &*tmp;
504
505         // Find the first pair of out-of-order elements.
506         let mut l = 0;
507         let mut r = v.len();
508
509         // SAFETY: The unsafety below involves indexing an array.
510         // For the first one: We already do the bounds checking here with `l < r`.
511         // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
512         //                     From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
513         unsafe {
514             // Find the first element greater than or equal to the pivot.
515             while l < r && is_less(v.get_unchecked(l), pivot) {
516                 l += 1;
517             }
518
519             // Find the last element smaller that the pivot.
520             while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
521                 r -= 1;
522             }
523         }
524
525         (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
526
527         // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
528         // variable) back into the slice where it originally was. This step is critical in ensuring
529         // safety!
530     };
531
532     // Place the pivot between the two partitions.
533     v.swap(0, mid);
534
535     (mid, was_partitioned)
536 }
537
538 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
539 ///
540 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
541 /// elements smaller than the pivot.
542 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
543 where
544     F: FnMut(&T, &T) -> bool,
545 {
546     // Place the pivot at the beginning of slice.
547     v.swap(0, pivot);
548     let (pivot, v) = v.split_at_mut(1);
549     let pivot = &mut pivot[0];
550
551     // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
552     // operation panics, the pivot will be automatically written back into the slice.
553     // SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
554     let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
555     let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
556     let pivot = &*tmp;
557
558     // Now partition the slice.
559     let mut l = 0;
560     let mut r = v.len();
561     loop {
562         // SAFETY: The unsafety below involves indexing an array.
563         // For the first one: We already do the bounds checking here with `l < r`.
564         // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
565         //                     From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
566         unsafe {
567             // Find the first element greater than the pivot.
568             while l < r && !is_less(pivot, v.get_unchecked(l)) {
569                 l += 1;
570             }
571
572             // Find the last element equal to the pivot.
573             while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
574                 r -= 1;
575             }
576
577             // Are we done?
578             if l >= r {
579                 break;
580             }
581
582             // Swap the found pair of out-of-order elements.
583             r -= 1;
584             let ptr = v.as_mut_ptr();
585             ptr::swap(ptr.add(l), ptr.add(r));
586             l += 1;
587         }
588     }
589
590     // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
591     l + 1
592
593     // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
594     // back into the slice where it originally was. This step is critical in ensuring safety!
595 }
596
597 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
598 /// partitions in quicksort.
599 #[cold]
600 fn break_patterns<T>(v: &mut [T]) {
601     let len = v.len();
602     if len >= 8 {
603         // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
604         let mut random = len as u32;
605         let mut gen_u32 = || {
606             random ^= random << 13;
607             random ^= random >> 17;
608             random ^= random << 5;
609             random
610         };
611         let mut gen_usize = || {
612             if usize::BITS <= 32 {
613                 gen_u32() as usize
614             } else {
615                 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
616             }
617         };
618
619         // Take random numbers modulo this number.
620         // The number fits into `usize` because `len` is not greater than `isize::MAX`.
621         let modulus = len.next_power_of_two();
622
623         // Some pivot candidates will be in the nearby of this index. Let's randomize them.
624         let pos = len / 4 * 2;
625
626         for i in 0..3 {
627             // Generate a random number modulo `len`. However, in order to avoid costly operations
628             // we first take it modulo a power of two, and then decrease by `len` until it fits
629             // into the range `[0, len - 1]`.
630             let mut other = gen_usize() & (modulus - 1);
631
632             // `other` is guaranteed to be less than `2 * len`.
633             if other >= len {
634                 other -= len;
635             }
636
637             v.swap(pos - 1 + i, other);
638         }
639     }
640 }
641
642 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
643 ///
644 /// Elements in `v` might be reordered in the process.
645 fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
646 where
647     F: FnMut(&T, &T) -> bool,
648 {
649     // Minimum length to choose the median-of-medians method.
650     // Shorter slices use the simple median-of-three method.
651     const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
652     // Maximum number of swaps that can be performed in this function.
653     const MAX_SWAPS: usize = 4 * 3;
654
655     let len = v.len();
656
657     // Three indices near which we are going to choose a pivot.
658     let mut a = len / 4 * 1;
659     let mut b = len / 4 * 2;
660     let mut c = len / 4 * 3;
661
662     // Counts the total number of swaps we are about to perform while sorting indices.
663     let mut swaps = 0;
664
665     if len >= 8 {
666         // Swaps indices so that `v[a] <= v[b]`.
667         // SAFETY: `len >= 8` so there are at least two elements in the neighborhoods of
668         // `a`, `b` and `c`. This means the three calls to `sort_adjacent` result in
669         // corresponding calls to `sort3` with valid 3-item neighborhoods around each
670         // pointer, which in turn means the calls to `sort2` are done with valid
671         // references. Thus the `v.get_unchecked` calls are safe, as is the `ptr::swap`
672         // call.
673         let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
674             if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
675                 ptr::swap(a, b);
676                 swaps += 1;
677             }
678         };
679
680         // Swaps indices so that `v[a] <= v[b] <= v[c]`.
681         let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
682             sort2(a, b);
683             sort2(b, c);
684             sort2(a, b);
685         };
686
687         if len >= SHORTEST_MEDIAN_OF_MEDIANS {
688             // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
689             let mut sort_adjacent = |a: &mut usize| {
690                 let tmp = *a;
691                 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
692             };
693
694             // Find medians in the neighborhoods of `a`, `b`, and `c`.
695             sort_adjacent(&mut a);
696             sort_adjacent(&mut b);
697             sort_adjacent(&mut c);
698         }
699
700         // Find the median among `a`, `b`, and `c`.
701         sort3(&mut a, &mut b, &mut c);
702     }
703
704     if swaps < MAX_SWAPS {
705         (b, swaps == 0)
706     } else {
707         // The maximum number of swaps was performed. Chances are the slice is descending or mostly
708         // descending, so reversing will probably help sort it faster.
709         v.reverse();
710         (len - 1 - b, true)
711     }
712 }
713
714 /// Sorts `v` recursively.
715 ///
716 /// If the slice had a predecessor in the original array, it is specified as `pred`.
717 ///
718 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
719 /// this function will immediately switch to heapsort.
720 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
721 where
722     F: FnMut(&T, &T) -> bool,
723 {
724     // Slices of up to this length get sorted using insertion sort.
725     const MAX_INSERTION: usize = 20;
726
727     // True if the last partitioning was reasonably balanced.
728     let mut was_balanced = true;
729     // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
730     let mut was_partitioned = true;
731
732     loop {
733         let len = v.len();
734
735         // Very short slices get sorted using insertion sort.
736         if len <= MAX_INSERTION {
737             insertion_sort(v, is_less);
738             return;
739         }
740
741         // If too many bad pivot choices were made, simply fall back to heapsort in order to
742         // guarantee `O(n * log(n))` worst-case.
743         if limit == 0 {
744             heapsort(v, is_less);
745             return;
746         }
747
748         // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
749         // some elements around. Hopefully we'll choose a better pivot this time.
750         if !was_balanced {
751             break_patterns(v);
752             limit -= 1;
753         }
754
755         // Choose a pivot and try guessing whether the slice is already sorted.
756         let (pivot, likely_sorted) = choose_pivot(v, is_less);
757
758         // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
759         // selection predicts the slice is likely already sorted...
760         if was_balanced && was_partitioned && likely_sorted {
761             // Try identifying several out-of-order elements and shifting them to correct
762             // positions. If the slice ends up being completely sorted, we're done.
763             if partial_insertion_sort(v, is_less) {
764                 return;
765             }
766         }
767
768         // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
769         // slice. Partition the slice into elements equal to and elements greater than the pivot.
770         // This case is usually hit when the slice contains many duplicate elements.
771         if let Some(p) = pred {
772             if !is_less(p, &v[pivot]) {
773                 let mid = partition_equal(v, pivot, is_less);
774
775                 // Continue sorting elements greater than the pivot.
776                 v = &mut { v }[mid..];
777                 continue;
778             }
779         }
780
781         // Partition the slice.
782         let (mid, was_p) = partition(v, pivot, is_less);
783         was_balanced = cmp::min(mid, len - mid) >= len / 8;
784         was_partitioned = was_p;
785
786         // Split the slice into `left`, `pivot`, and `right`.
787         let (left, right) = { v }.split_at_mut(mid);
788         let (pivot, right) = right.split_at_mut(1);
789         let pivot = &pivot[0];
790
791         // Recurse into the shorter side only in order to minimize the total number of recursive
792         // calls and consume less stack space. Then just continue with the longer side (this is
793         // akin to tail recursion).
794         if left.len() < right.len() {
795             recurse(left, is_less, pred, limit);
796             v = right;
797             pred = Some(pivot);
798         } else {
799             recurse(right, is_less, Some(pivot), limit);
800             v = left;
801         }
802     }
803 }
804
805 /// Sorts `v` using pattern-defeating quicksort, which is *O*(*n* \* log(*n*)) worst-case.
806 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
807 where
808     F: FnMut(&T, &T) -> bool,
809 {
810     // Sorting has no meaningful behavior on zero-sized types.
811     if mem::size_of::<T>() == 0 {
812         return;
813     }
814
815     // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
816     let limit = usize::BITS - v.len().leading_zeros();
817
818     recurse(v, &mut is_less, None, limit);
819 }
820
821 fn partition_at_index_loop<'a, T, F>(
822     mut v: &'a mut [T],
823     mut index: usize,
824     is_less: &mut F,
825     mut pred: Option<&'a T>,
826 ) where
827     F: FnMut(&T, &T) -> bool,
828 {
829     loop {
830         // For slices of up to this length it's probably faster to simply sort them.
831         const MAX_INSERTION: usize = 10;
832         if v.len() <= MAX_INSERTION {
833             insertion_sort(v, is_less);
834             return;
835         }
836
837         // Choose a pivot
838         let (pivot, _) = choose_pivot(v, is_less);
839
840         // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
841         // slice. Partition the slice into elements equal to and elements greater than the pivot.
842         // This case is usually hit when the slice contains many duplicate elements.
843         if let Some(p) = pred {
844             if !is_less(p, &v[pivot]) {
845                 let mid = partition_equal(v, pivot, is_less);
846
847                 // If we've passed our index, then we're good.
848                 if mid > index {
849                     return;
850                 }
851
852                 // Otherwise, continue sorting elements greater than the pivot.
853                 v = &mut v[mid..];
854                 index = index - mid;
855                 pred = None;
856                 continue;
857             }
858         }
859
860         let (mid, _) = partition(v, pivot, is_less);
861
862         // Split the slice into `left`, `pivot`, and `right`.
863         let (left, right) = { v }.split_at_mut(mid);
864         let (pivot, right) = right.split_at_mut(1);
865         let pivot = &pivot[0];
866
867         if mid < index {
868             v = right;
869             index = index - mid - 1;
870             pred = Some(pivot);
871         } else if mid > index {
872             v = left;
873         } else {
874             // If mid == index, then we're done, since partition() guaranteed that all elements
875             // after mid are greater than or equal to mid.
876             return;
877         }
878     }
879 }
880
881 pub fn partition_at_index<T, F>(
882     v: &mut [T],
883     index: usize,
884     mut is_less: F,
885 ) -> (&mut [T], &mut T, &mut [T])
886 where
887     F: FnMut(&T, &T) -> bool,
888 {
889     use cmp::Ordering::Greater;
890     use cmp::Ordering::Less;
891
892     if index >= v.len() {
893         panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
894     }
895
896     if mem::size_of::<T>() == 0 {
897         // Sorting has no meaningful behavior on zero-sized types. Do nothing.
898     } else if index == v.len() - 1 {
899         // Find max element and place it in the last position of the array. We're free to use
900         // `unwrap()` here because we know v must not be empty.
901         let (max_index, _) = v
902             .iter()
903             .enumerate()
904             .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
905             .unwrap();
906         v.swap(max_index, index);
907     } else if index == 0 {
908         // Find min element and place it in the first position of the array. We're free to use
909         // `unwrap()` here because we know v must not be empty.
910         let (min_index, _) = v
911             .iter()
912             .enumerate()
913             .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
914             .unwrap();
915         v.swap(min_index, index);
916     } else {
917         partition_at_index_loop(v, index, &mut is_less, None);
918     }
919
920     let (left, right) = v.split_at_mut(index);
921     let (pivot, right) = right.split_at_mut(1);
922     let pivot = &mut pivot[0];
923     (left, pivot, right)
924 }