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