• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! In addition it also contains the core logic of the stable sort used by `slice::sort` based on
10 //! TimSort.
11 
12 use crate::cmp;
13 use crate::mem::{self, MaybeUninit, SizedTypeProperties};
14 use crate::ptr;
15 
16 // When dropped, copies from `src` into `dest`.
17 struct InsertionHole<T> {
18     src: *const T,
19     dest: *mut T,
20 }
21 
22 impl<T> Drop for InsertionHole<T> {
drop(&mut self)23     fn drop(&mut self) {
24         // SAFETY: This is a helper class. Please refer to its usage for correctness. Namely, one
25         // must be sure that `src` and `dst` does not overlap as required by
26         // `ptr::copy_nonoverlapping` and are both valid for writes.
27         unsafe {
28             ptr::copy_nonoverlapping(self.src, self.dest, 1);
29         }
30     }
31 }
32 
33 /// Inserts `v[v.len() - 1]` into pre-sorted sequence `v[..v.len() - 1]` so that whole `v[..]`
34 /// becomes sorted.
insert_tail<T, F>(v: &mut [T], is_less: &mut F) where F: FnMut(&T, &T) -> bool,35 unsafe fn insert_tail<T, F>(v: &mut [T], is_less: &mut F)
36 where
37     F: FnMut(&T, &T) -> bool,
38 {
39     debug_assert!(v.len() >= 2);
40 
41     let arr_ptr = v.as_mut_ptr();
42     let i = v.len() - 1;
43 
44     // SAFETY: caller must ensure v is at least len 2.
45     unsafe {
46         // See insert_head which talks about why this approach is beneficial.
47         let i_ptr = arr_ptr.add(i);
48 
49         // It's important that we use i_ptr here. If this check is positive and we continue,
50         // We want to make sure that no other copy of the value was seen by is_less.
51         // Otherwise we would have to copy it back.
52         if is_less(&*i_ptr, &*i_ptr.sub(1)) {
53             // It's important, that we use tmp for comparison from now on. As it is the value that
54             // will be copied back. And notionally we could have created a divergence if we copy
55             // back the wrong value.
56             let tmp = mem::ManuallyDrop::new(ptr::read(i_ptr));
57             // Intermediate state of the insertion process is always tracked by `hole`, which
58             // serves two purposes:
59             // 1. Protects integrity of `v` from panics in `is_less`.
60             // 2. Fills the remaining hole in `v` in the end.
61             //
62             // Panic safety:
63             //
64             // If `is_less` panics at any point during the process, `hole` will get dropped and
65             // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
66             // initially held exactly once.
67             let mut hole = InsertionHole { src: &*tmp, dest: i_ptr.sub(1) };
68             ptr::copy_nonoverlapping(hole.dest, i_ptr, 1);
69 
70             // SAFETY: We know i is at least 1.
71             for j in (0..(i - 1)).rev() {
72                 let j_ptr = arr_ptr.add(j);
73                 if !is_less(&*tmp, &*j_ptr) {
74                     break;
75                 }
76 
77                 ptr::copy_nonoverlapping(j_ptr, hole.dest, 1);
78                 hole.dest = j_ptr;
79             }
80             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
81         }
82     }
83 }
84 
85 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
86 ///
87 /// This is the integral subroutine of insertion sort.
insert_head<T, F>(v: &mut [T], is_less: &mut F) where F: FnMut(&T, &T) -> bool,88 unsafe fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
89 where
90     F: FnMut(&T, &T) -> bool,
91 {
92     debug_assert!(v.len() >= 2);
93 
94     // SAFETY: caller must ensure v is at least len 2.
95     unsafe {
96         if is_less(v.get_unchecked(1), v.get_unchecked(0)) {
97             let arr_ptr = v.as_mut_ptr();
98 
99             // There are three ways to implement insertion here:
100             //
101             // 1. Swap adjacent elements until the first one gets to its final destination.
102             //    However, this way we copy data around more than is necessary. If elements are big
103             //    structures (costly to copy), this method will be slow.
104             //
105             // 2. Iterate until the right place for the first element is found. Then shift the
106             //    elements succeeding it to make room for it and finally place it into the
107             //    remaining hole. This is a good method.
108             //
109             // 3. Copy the first element into a temporary variable. Iterate until the right place
110             //    for it is found. As we go along, copy every traversed element into the slot
111             //    preceding it. Finally, copy data from the temporary variable into the remaining
112             //    hole. This method is very good. Benchmarks demonstrated slightly better
113             //    performance than with the 2nd method.
114             //
115             // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
116             let tmp = mem::ManuallyDrop::new(ptr::read(arr_ptr));
117 
118             // Intermediate state of the insertion process is always tracked by `hole`, which
119             // serves two purposes:
120             // 1. Protects integrity of `v` from panics in `is_less`.
121             // 2. Fills the remaining hole in `v` in the end.
122             //
123             // Panic safety:
124             //
125             // If `is_less` panics at any point during the process, `hole` will get dropped and
126             // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
127             // initially held exactly once.
128             let mut hole = InsertionHole { src: &*tmp, dest: arr_ptr.add(1) };
129             ptr::copy_nonoverlapping(arr_ptr.add(1), arr_ptr.add(0), 1);
130 
131             for i in 2..v.len() {
132                 if !is_less(&v.get_unchecked(i), &*tmp) {
133                     break;
134                 }
135                 ptr::copy_nonoverlapping(arr_ptr.add(i), arr_ptr.add(i - 1), 1);
136                 hole.dest = arr_ptr.add(i);
137             }
138             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
139         }
140     }
141 }
142 
143 /// Sort `v` assuming `v[..offset]` is already sorted.
144 ///
145 /// Never inline this function to avoid code bloat. It still optimizes nicely and has practically no
146 /// performance impact. Even improving performance in some cases.
147 #[inline(never)]
insertion_sort_shift_left<T, F>(v: &mut [T], offset: usize, is_less: &mut F) where F: FnMut(&T, &T) -> bool,148 pub(super) fn insertion_sort_shift_left<T, F>(v: &mut [T], offset: usize, is_less: &mut F)
149 where
150     F: FnMut(&T, &T) -> bool,
151 {
152     let len = v.len();
153 
154     // Using assert here improves performance.
155     assert!(offset != 0 && offset <= len);
156 
157     // Shift each element of the unsorted region v[i..] as far left as is needed to make v sorted.
158     for i in offset..len {
159         // SAFETY: we tested that `offset` must be at least 1, so this loop is only entered if len
160         // >= 2. The range is exclusive and we know `i` must be at least 1 so this slice has at
161         // >least len 2.
162         unsafe {
163             insert_tail(&mut v[..=i], is_less);
164         }
165     }
166 }
167 
168 /// Sort `v` assuming `v[offset..]` is already sorted.
169 ///
170 /// Never inline this function to avoid code bloat. It still optimizes nicely and has practically no
171 /// performance impact. Even improving performance in some cases.
172 #[inline(never)]
insertion_sort_shift_right<T, F>(v: &mut [T], offset: usize, is_less: &mut F) where F: FnMut(&T, &T) -> bool,173 fn insertion_sort_shift_right<T, F>(v: &mut [T], offset: usize, is_less: &mut F)
174 where
175     F: FnMut(&T, &T) -> bool,
176 {
177     let len = v.len();
178 
179     // Using assert here improves performance.
180     assert!(offset != 0 && offset <= len && len >= 2);
181 
182     // Shift each element of the unsorted region v[..i] as far left as is needed to make v sorted.
183     for i in (0..offset).rev() {
184         // SAFETY: we tested that `offset` must be at least 1, so this loop is only entered if len
185         // >= 2.We ensured that the slice length is always at least 2 long. We know that start_found
186         // will be at least one less than end, and the range is exclusive. Which gives us i always
187         // <= (end - 2).
188         unsafe {
189             insert_head(&mut v[i..len], is_less);
190         }
191     }
192 }
193 
194 /// Partially sorts a slice by shifting several out-of-order elements around.
195 ///
196 /// Returns `true` if the slice is sorted at the end. This function is *O*(*n*) worst-case.
197 #[cold]
partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool where F: FnMut(&T, &T) -> bool,198 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
199 where
200     F: FnMut(&T, &T) -> bool,
201 {
202     // Maximum number of adjacent out-of-order pairs that will get shifted.
203     const MAX_STEPS: usize = 5;
204     // If the slice is shorter than this, don't shift any elements.
205     const SHORTEST_SHIFTING: usize = 50;
206 
207     let len = v.len();
208     let mut i = 1;
209 
210     for _ in 0..MAX_STEPS {
211         // SAFETY: We already explicitly did the bound checking with `i < len`.
212         // All our subsequent indexing is only in the range `0 <= index < len`
213         unsafe {
214             // Find the next pair of adjacent out-of-order elements.
215             while i < len && !is_less(v.get_unchecked(i), v.get_unchecked(i - 1)) {
216                 i += 1;
217             }
218         }
219 
220         // Are we done?
221         if i == len {
222             return true;
223         }
224 
225         // Don't shift elements on short arrays, that has a performance cost.
226         if len < SHORTEST_SHIFTING {
227             return false;
228         }
229 
230         // Swap the found pair of elements. This puts them in correct order.
231         v.swap(i - 1, i);
232 
233         if i >= 2 {
234             // Shift the smaller element to the left.
235             insertion_sort_shift_left(&mut v[..i], i - 1, is_less);
236 
237             // Shift the greater element to the right.
238             insertion_sort_shift_right(&mut v[..i], 1, is_less);
239         }
240     }
241 
242     // Didn't manage to sort the slice in the limited number of steps.
243     false
244 }
245 
246 /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case.
247 #[cold]
248 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
heapsort<T, F>(v: &mut [T], mut is_less: F) where F: FnMut(&T, &T) -> bool,249 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
250 where
251     F: FnMut(&T, &T) -> bool,
252 {
253     // This binary heap respects the invariant `parent >= child`.
254     let mut sift_down = |v: &mut [T], mut node| {
255         loop {
256             // Children of `node`.
257             let mut child = 2 * node + 1;
258             if child >= v.len() {
259                 break;
260             }
261 
262             // Choose the greater child.
263             if child + 1 < v.len() {
264                 // We need a branch to be sure not to out-of-bounds index,
265                 // but it's highly predictable.  The comparison, however,
266                 // is better done branchless, especially for primitives.
267                 child += is_less(&v[child], &v[child + 1]) as usize;
268             }
269 
270             // Stop if the invariant holds at `node`.
271             if !is_less(&v[node], &v[child]) {
272                 break;
273             }
274 
275             // Swap `node` with the greater child, move one step down, and continue sifting.
276             v.swap(node, child);
277             node = child;
278         }
279     };
280 
281     // Build the heap in linear time.
282     for i in (0..v.len() / 2).rev() {
283         sift_down(v, i);
284     }
285 
286     // Pop maximal elements from the heap.
287     for i in (1..v.len()).rev() {
288         v.swap(0, i);
289         sift_down(&mut v[..i], 0);
290     }
291 }
292 
293 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
294 /// to `pivot`.
295 ///
296 /// Returns the number of elements smaller than `pivot`.
297 ///
298 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
299 /// This idea is presented in the [BlockQuicksort][pdf] paper.
300 ///
301 /// [pdf]: https://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize where F: FnMut(&T, &T) -> bool,302 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
303 where
304     F: FnMut(&T, &T) -> bool,
305 {
306     // Number of elements in a typical block.
307     const BLOCK: usize = 128;
308 
309     // The partitioning algorithm repeats the following steps until completion:
310     //
311     // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
312     // 2. Trace a block from the right side to identify elements smaller than the pivot.
313     // 3. Exchange the identified elements between the left and right side.
314     //
315     // We keep the following variables for a block of elements:
316     //
317     // 1. `block` - Number of elements in the block.
318     // 2. `start` - Start pointer into the `offsets` array.
319     // 3. `end` - End pointer into the `offsets` array.
320     // 4. `offsets` - Indices of out-of-order elements within the block.
321 
322     // The current block on the left side (from `l` to `l.add(block_l)`).
323     let mut l = v.as_mut_ptr();
324     let mut block_l = BLOCK;
325     let mut start_l = ptr::null_mut();
326     let mut end_l = ptr::null_mut();
327     let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
328 
329     // The current block on the right side (from `r.sub(block_r)` to `r`).
330     // SAFETY: The documentation for .add() specifically mention that `vec.as_ptr().add(vec.len())` is always safe
331     let mut r = unsafe { l.add(v.len()) };
332     let mut block_r = BLOCK;
333     let mut start_r = ptr::null_mut();
334     let mut end_r = ptr::null_mut();
335     let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
336 
337     // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
338     // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
339 
340     // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
341     fn width<T>(l: *mut T, r: *mut T) -> usize {
342         assert!(mem::size_of::<T>() > 0);
343         // FIXME: this should *likely* use `offset_from`, but more
344         // investigation is needed (including running tests in miri).
345         (r.addr() - l.addr()) / mem::size_of::<T>()
346     }
347 
348     loop {
349         // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
350         // some patch-up work in order to partition the remaining elements in between.
351         let is_done = width(l, r) <= 2 * BLOCK;
352 
353         if is_done {
354             // Number of remaining elements (still not compared to the pivot).
355             let mut rem = width(l, r);
356             if start_l < end_l || start_r < end_r {
357                 rem -= BLOCK;
358             }
359 
360             // Adjust block sizes so that the left and right block don't overlap, but get perfectly
361             // aligned to cover the whole remaining gap.
362             if start_l < end_l {
363                 block_r = rem;
364             } else if start_r < end_r {
365                 block_l = rem;
366             } else {
367                 // There were the same number of elements to switch on both blocks during the last
368                 // iteration, so there are no remaining elements on either block. Cover the remaining
369                 // items with roughly equally-sized blocks.
370                 block_l = rem / 2;
371                 block_r = rem - block_l;
372             }
373             debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
374             debug_assert!(width(l, r) == block_l + block_r);
375         }
376 
377         if start_l == end_l {
378             // Trace `block_l` elements from the left side.
379             start_l = MaybeUninit::slice_as_mut_ptr(&mut offsets_l);
380             end_l = start_l;
381             let mut elem = l;
382 
383             for i in 0..block_l {
384                 // SAFETY: The unsafety operations below involve the usage of the `offset`.
385                 //         According to the conditions required by the function, we satisfy them because:
386                 //         1. `offsets_l` is stack-allocated, and thus considered separate allocated object.
387                 //         2. The function `is_less` returns a `bool`.
388                 //            Casting a `bool` will never overflow `isize`.
389                 //         3. We have guaranteed that `block_l` will be `<= BLOCK`.
390                 //            Plus, `end_l` was initially set to the begin pointer of `offsets_` which was declared on the stack.
391                 //            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.
392                 //        Another unsafety operation here is dereferencing `elem`.
393                 //        However, `elem` was initially the begin pointer to the slice which is always valid.
394                 unsafe {
395                     // Branchless comparison.
396                     *end_l = i as u8;
397                     end_l = end_l.add(!is_less(&*elem, pivot) as usize);
398                     elem = elem.add(1);
399                 }
400             }
401         }
402 
403         if start_r == end_r {
404             // Trace `block_r` elements from the right side.
405             start_r = MaybeUninit::slice_as_mut_ptr(&mut offsets_r);
406             end_r = start_r;
407             let mut elem = r;
408 
409             for i in 0..block_r {
410                 // SAFETY: The unsafety operations below involve the usage of the `offset`.
411                 //         According to the conditions required by the function, we satisfy them because:
412                 //         1. `offsets_r` is stack-allocated, and thus considered separate allocated object.
413                 //         2. The function `is_less` returns a `bool`.
414                 //            Casting a `bool` will never overflow `isize`.
415                 //         3. We have guaranteed that `block_r` will be `<= BLOCK`.
416                 //            Plus, `end_r` was initially set to the begin pointer of `offsets_` which was declared on the stack.
417                 //            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.
418                 //        Another unsafety operation here is dereferencing `elem`.
419                 //        However, `elem` was initially `1 * sizeof(T)` past the end and we decrement it by `1 * sizeof(T)` before accessing it.
420                 //        Plus, `block_r` was asserted to be less than `BLOCK` and `elem` will therefore at most be pointing to the beginning of the slice.
421                 unsafe {
422                     // Branchless comparison.
423                     elem = elem.sub(1);
424                     *end_r = i as u8;
425                     end_r = end_r.add(is_less(&*elem, pivot) as usize);
426                 }
427             }
428         }
429 
430         // Number of out-of-order elements to swap between the left and right side.
431         let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
432 
433         if count > 0 {
434             macro_rules! left {
435                 () => {
436                     l.add(usize::from(*start_l))
437                 };
438             }
439             macro_rules! right {
440                 () => {
441                     r.sub(usize::from(*start_r) + 1)
442                 };
443             }
444 
445             // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
446             // permutation. This is not strictly equivalent to swapping, but produces a similar
447             // result using fewer memory operations.
448 
449             // SAFETY: The use of `ptr::read` is valid because there is at least one element in
450             // both `offsets_l` and `offsets_r`, so `left!` is a valid pointer to read from.
451             //
452             // The uses of `left!` involve calls to `offset` on `l`, which points to the
453             // beginning of `v`. All the offsets pointed-to by `start_l` are at most `block_l`, so
454             // these `offset` calls are safe as all reads are within the block. The same argument
455             // applies for the uses of `right!`.
456             //
457             // The calls to `start_l.offset` are valid because there are at most `count-1` of them,
458             // plus the final one at the end of the unsafe block, where `count` is the minimum number
459             // of collected offsets in `offsets_l` and `offsets_r`, so there is no risk of there not
460             // being enough elements. The same reasoning applies to the calls to `start_r.offset`.
461             //
462             // The calls to `copy_nonoverlapping` are safe because `left!` and `right!` are guaranteed
463             // not to overlap, and are valid because of the reasoning above.
464             unsafe {
465                 let tmp = ptr::read(left!());
466                 ptr::copy_nonoverlapping(right!(), left!(), 1);
467 
468                 for _ in 1..count {
469                     start_l = start_l.add(1);
470                     ptr::copy_nonoverlapping(left!(), right!(), 1);
471                     start_r = start_r.add(1);
472                     ptr::copy_nonoverlapping(right!(), left!(), 1);
473                 }
474 
475                 ptr::copy_nonoverlapping(&tmp, right!(), 1);
476                 mem::forget(tmp);
477                 start_l = start_l.add(1);
478                 start_r = start_r.add(1);
479             }
480         }
481 
482         if start_l == end_l {
483             // All out-of-order elements in the left block were moved. Move to the next block.
484 
485             // block-width-guarantee
486             // SAFETY: if `!is_done` then the slice width is guaranteed to be at least `2*BLOCK` wide. There
487             // are at most `BLOCK` elements in `offsets_l` because of its size, so the `offset` operation is
488             // safe. Otherwise, the debug assertions in the `is_done` case guarantee that
489             // `width(l, r) == block_l + block_r`, namely, that the block sizes have been adjusted to account
490             // for the smaller number of remaining elements.
491             l = unsafe { l.add(block_l) };
492         }
493 
494         if start_r == end_r {
495             // All out-of-order elements in the right block were moved. Move to the previous block.
496 
497             // SAFETY: Same argument as [block-width-guarantee]. Either this is a full block `2*BLOCK`-wide,
498             // or `block_r` has been adjusted for the last handful of elements.
499             r = unsafe { r.sub(block_r) };
500         }
501 
502         if is_done {
503             break;
504         }
505     }
506 
507     // All that remains now is at most one block (either the left or the right) with out-of-order
508     // elements that need to be moved. Such remaining elements can be simply shifted to the end
509     // within their block.
510 
511     if start_l < end_l {
512         // The left block remains.
513         // Move its remaining out-of-order elements to the far right.
514         debug_assert_eq!(width(l, r), block_l);
515         while start_l < end_l {
516             // remaining-elements-safety
517             // SAFETY: while the loop condition holds there are still elements in `offsets_l`, so it
518             // is safe to point `end_l` to the previous element.
519             //
520             // The `ptr::swap` is safe if both its arguments are valid for reads and writes:
521             //  - Per the debug assert above, the distance between `l` and `r` is `block_l`
522             //    elements, so there can be at most `block_l` remaining offsets between `start_l`
523             //    and `end_l`. This means `r` will be moved at most `block_l` steps back, which
524             //    makes the `r.offset` calls valid (at that point `l == r`).
525             //  - `offsets_l` contains valid offsets into `v` collected during the partitioning of
526             //    the last block, so the `l.offset` calls are valid.
527             unsafe {
528                 end_l = end_l.sub(1);
529                 ptr::swap(l.add(usize::from(*end_l)), r.sub(1));
530                 r = r.sub(1);
531             }
532         }
533         width(v.as_mut_ptr(), r)
534     } else if start_r < end_r {
535         // The right block remains.
536         // Move its remaining out-of-order elements to the far left.
537         debug_assert_eq!(width(l, r), block_r);
538         while start_r < end_r {
539             // SAFETY: See the reasoning in [remaining-elements-safety].
540             unsafe {
541                 end_r = end_r.sub(1);
542                 ptr::swap(l, r.sub(usize::from(*end_r) + 1));
543                 l = l.add(1);
544             }
545         }
546         width(v.as_mut_ptr(), l)
547     } else {
548         // Nothing else to do, we're done.
549         width(v.as_mut_ptr(), l)
550     }
551 }
552 
553 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
554 /// equal to `v[pivot]`.
555 ///
556 /// Returns a tuple of:
557 ///
558 /// 1. Number of elements smaller than `v[pivot]`.
559 /// 2. True if `v` was already partitioned.
partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool) where F: FnMut(&T, &T) -> bool,560 pub(super) fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
561 where
562     F: FnMut(&T, &T) -> bool,
563 {
564     let (mid, was_partitioned) = {
565         // Place the pivot at the beginning of slice.
566         v.swap(0, pivot);
567         let (pivot, v) = v.split_at_mut(1);
568         let pivot = &mut pivot[0];
569 
570         // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
571         // operation panics, the pivot will be automatically written back into the slice.
572 
573         // SAFETY: `pivot` is a reference to the first element of `v`, so `ptr::read` is safe.
574         let tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
575         let _pivot_guard = InsertionHole { src: &*tmp, dest: pivot };
576         let pivot = &*tmp;
577 
578         // Find the first pair of out-of-order elements.
579         let mut l = 0;
580         let mut r = v.len();
581 
582         // SAFETY: The unsafety below involves indexing an array.
583         // For the first one: We already do the bounds checking here with `l < r`.
584         // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
585         //                     From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
586         unsafe {
587             // Find the first element greater than or equal to the pivot.
588             while l < r && is_less(v.get_unchecked(l), pivot) {
589                 l += 1;
590             }
591 
592             // Find the last element smaller that the pivot.
593             while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
594                 r -= 1;
595             }
596         }
597 
598         (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
599 
600         // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
601         // variable) back into the slice where it originally was. This step is critical in ensuring
602         // safety!
603     };
604 
605     // Place the pivot between the two partitions.
606     v.swap(0, mid);
607 
608     (mid, was_partitioned)
609 }
610 
611 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
612 ///
613 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
614 /// elements smaller than the pivot.
partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize where F: FnMut(&T, &T) -> bool,615 pub(super) fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
616 where
617     F: FnMut(&T, &T) -> bool,
618 {
619     // Place the pivot at the beginning of slice.
620     v.swap(0, pivot);
621     let (pivot, v) = v.split_at_mut(1);
622     let pivot = &mut pivot[0];
623 
624     // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
625     // operation panics, the pivot will be automatically written back into the slice.
626     // SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
627     let tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
628     let _pivot_guard = InsertionHole { src: &*tmp, dest: pivot };
629     let pivot = &*tmp;
630 
631     // Now partition the slice.
632     let mut l = 0;
633     let mut r = v.len();
634     loop {
635         // SAFETY: The unsafety below involves indexing an array.
636         // For the first one: We already do the bounds checking here with `l < r`.
637         // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
638         //                     From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
639         unsafe {
640             // Find the first element greater than the pivot.
641             while l < r && !is_less(pivot, v.get_unchecked(l)) {
642                 l += 1;
643             }
644 
645             // Find the last element equal to the pivot.
646             while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
647                 r -= 1;
648             }
649 
650             // Are we done?
651             if l >= r {
652                 break;
653             }
654 
655             // Swap the found pair of out-of-order elements.
656             r -= 1;
657             let ptr = v.as_mut_ptr();
658             ptr::swap(ptr.add(l), ptr.add(r));
659             l += 1;
660         }
661     }
662 
663     // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
664     l + 1
665 
666     // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
667     // back into the slice where it originally was. This step is critical in ensuring safety!
668 }
669 
670 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
671 /// partitions in quicksort.
672 #[cold]
break_patterns<T>(v: &mut [T])673 pub(super) fn break_patterns<T>(v: &mut [T]) {
674     let len = v.len();
675     if len >= 8 {
676         let mut seed = len;
677         let mut gen_usize = || {
678             // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
679             if usize::BITS <= 32 {
680                 let mut r = seed as u32;
681                 r ^= r << 13;
682                 r ^= r >> 17;
683                 r ^= r << 5;
684                 seed = r as usize;
685                 seed
686             } else {
687                 let mut r = seed as u64;
688                 r ^= r << 13;
689                 r ^= r >> 7;
690                 r ^= r << 17;
691                 seed = r as usize;
692                 seed
693             }
694         };
695 
696         // Take random numbers modulo this number.
697         // The number fits into `usize` because `len` is not greater than `isize::MAX`.
698         let modulus = len.next_power_of_two();
699 
700         // Some pivot candidates will be in the nearby of this index. Let's randomize them.
701         let pos = len / 4 * 2;
702 
703         for i in 0..3 {
704             // Generate a random number modulo `len`. However, in order to avoid costly operations
705             // we first take it modulo a power of two, and then decrease by `len` until it fits
706             // into the range `[0, len - 1]`.
707             let mut other = gen_usize() & (modulus - 1);
708 
709             // `other` is guaranteed to be less than `2 * len`.
710             if other >= len {
711                 other -= len;
712             }
713 
714             v.swap(pos - 1 + i, other);
715         }
716     }
717 }
718 
719 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
720 ///
721 /// Elements in `v` might be reordered in the process.
choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool) where F: FnMut(&T, &T) -> bool,722 pub(super) fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
723 where
724     F: FnMut(&T, &T) -> bool,
725 {
726     // Minimum length to choose the median-of-medians method.
727     // Shorter slices use the simple median-of-three method.
728     const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
729     // Maximum number of swaps that can be performed in this function.
730     const MAX_SWAPS: usize = 4 * 3;
731 
732     let len = v.len();
733 
734     // Three indices near which we are going to choose a pivot.
735     let mut a = len / 4 * 1;
736     let mut b = len / 4 * 2;
737     let mut c = len / 4 * 3;
738 
739     // Counts the total number of swaps we are about to perform while sorting indices.
740     let mut swaps = 0;
741 
742     if len >= 8 {
743         // Swaps indices so that `v[a] <= v[b]`.
744         // SAFETY: `len >= 8` so there are at least two elements in the neighborhoods of
745         // `a`, `b` and `c`. This means the three calls to `sort_adjacent` result in
746         // corresponding calls to `sort3` with valid 3-item neighborhoods around each
747         // pointer, which in turn means the calls to `sort2` are done with valid
748         // references. Thus the `v.get_unchecked` calls are safe, as is the `ptr::swap`
749         // call.
750         let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
751             if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
752                 ptr::swap(a, b);
753                 swaps += 1;
754             }
755         };
756 
757         // Swaps indices so that `v[a] <= v[b] <= v[c]`.
758         let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
759             sort2(a, b);
760             sort2(b, c);
761             sort2(a, b);
762         };
763 
764         if len >= SHORTEST_MEDIAN_OF_MEDIANS {
765             // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
766             let mut sort_adjacent = |a: &mut usize| {
767                 let tmp = *a;
768                 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
769             };
770 
771             // Find medians in the neighborhoods of `a`, `b`, and `c`.
772             sort_adjacent(&mut a);
773             sort_adjacent(&mut b);
774             sort_adjacent(&mut c);
775         }
776 
777         // Find the median among `a`, `b`, and `c`.
778         sort3(&mut a, &mut b, &mut c);
779     }
780 
781     if swaps < MAX_SWAPS {
782         (b, swaps == 0)
783     } else {
784         // The maximum number of swaps was performed. Chances are the slice is descending or mostly
785         // descending, so reversing will probably help sort it faster.
786         v.reverse();
787         (len - 1 - b, true)
788     }
789 }
790 
791 /// Sorts `v` recursively.
792 ///
793 /// If the slice had a predecessor in the original array, it is specified as `pred`.
794 ///
795 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
796 /// this function will immediately switch to heapsort.
recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32) where F: FnMut(&T, &T) -> bool,797 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
798 where
799     F: FnMut(&T, &T) -> bool,
800 {
801     // Slices of up to this length get sorted using insertion sort.
802     const MAX_INSERTION: usize = 20;
803 
804     // True if the last partitioning was reasonably balanced.
805     let mut was_balanced = true;
806     // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
807     let mut was_partitioned = true;
808 
809     loop {
810         let len = v.len();
811 
812         // Very short slices get sorted using insertion sort.
813         if len <= MAX_INSERTION {
814             if len >= 2 {
815                 insertion_sort_shift_left(v, 1, is_less);
816             }
817             return;
818         }
819 
820         // If too many bad pivot choices were made, simply fall back to heapsort in order to
821         // guarantee `O(n * log(n))` worst-case.
822         if limit == 0 {
823             heapsort(v, is_less);
824             return;
825         }
826 
827         // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
828         // some elements around. Hopefully we'll choose a better pivot this time.
829         if !was_balanced {
830             break_patterns(v);
831             limit -= 1;
832         }
833 
834         // Choose a pivot and try guessing whether the slice is already sorted.
835         let (pivot, likely_sorted) = choose_pivot(v, is_less);
836 
837         // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
838         // selection predicts the slice is likely already sorted...
839         if was_balanced && was_partitioned && likely_sorted {
840             // Try identifying several out-of-order elements and shifting them to correct
841             // positions. If the slice ends up being completely sorted, we're done.
842             if partial_insertion_sort(v, is_less) {
843                 return;
844             }
845         }
846 
847         // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
848         // slice. Partition the slice into elements equal to and elements greater than the pivot.
849         // This case is usually hit when the slice contains many duplicate elements.
850         if let Some(p) = pred {
851             if !is_less(p, &v[pivot]) {
852                 let mid = partition_equal(v, pivot, is_less);
853 
854                 // Continue sorting elements greater than the pivot.
855                 v = &mut v[mid..];
856                 continue;
857             }
858         }
859 
860         // Partition the slice.
861         let (mid, was_p) = partition(v, pivot, is_less);
862         was_balanced = cmp::min(mid, len - mid) >= len / 8;
863         was_partitioned = was_p;
864 
865         // Split the slice into `left`, `pivot`, and `right`.
866         let (left, right) = v.split_at_mut(mid);
867         let (pivot, right) = right.split_at_mut(1);
868         let pivot = &pivot[0];
869 
870         // Recurse into the shorter side only in order to minimize the total number of recursive
871         // calls and consume less stack space. Then just continue with the longer side (this is
872         // akin to tail recursion).
873         if left.len() < right.len() {
874             recurse(left, is_less, pred, limit);
875             v = right;
876             pred = Some(pivot);
877         } else {
878             recurse(right, is_less, Some(pivot), limit);
879             v = left;
880         }
881     }
882 }
883 
884 /// Sorts `v` using pattern-defeating quicksort, which is *O*(*n* \* log(*n*)) worst-case.
quicksort<T, F>(v: &mut [T], mut is_less: F) where F: FnMut(&T, &T) -> bool,885 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
886 where
887     F: FnMut(&T, &T) -> bool,
888 {
889     // Sorting has no meaningful behavior on zero-sized types.
890     if T::IS_ZST {
891         return;
892     }
893 
894     // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
895     let limit = usize::BITS - v.len().leading_zeros();
896 
897     recurse(v, &mut is_less, None, limit);
898 }
899 
900 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
901 /// stores the result into `v[..]`.
902 ///
903 /// # Safety
904 ///
905 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
906 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F) where F: FnMut(&T, &T) -> bool,907 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
908 where
909     F: FnMut(&T, &T) -> bool,
910 {
911     let len = v.len();
912     let v = v.as_mut_ptr();
913 
914     // SAFETY: mid and len must be in-bounds of v.
915     let (v_mid, v_end) = unsafe { (v.add(mid), v.add(len)) };
916 
917     // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
918     // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
919     // copying the lesser (or greater) one into `v`.
920     //
921     // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
922     // consumed first, then we must copy whatever is left of the shorter run into the remaining
923     // hole in `v`.
924     //
925     // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
926     // 1. Protects integrity of `v` from panics in `is_less`.
927     // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
928     //
929     // Panic safety:
930     //
931     // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
932     // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
933     // object it initially held exactly once.
934     let mut hole;
935 
936     if mid <= len - mid {
937         // The left run is shorter.
938 
939         // SAFETY: buf must have enough capacity for `v[..mid]`.
940         unsafe {
941             ptr::copy_nonoverlapping(v, buf, mid);
942             hole = MergeHole { start: buf, end: buf.add(mid), dest: v };
943         }
944 
945         // Initially, these pointers point to the beginnings of their arrays.
946         let left = &mut hole.start;
947         let mut right = v_mid;
948         let out = &mut hole.dest;
949 
950         while *left < hole.end && right < v_end {
951             // Consume the lesser side.
952             // If equal, prefer the left run to maintain stability.
953 
954             // SAFETY: left and right must be valid and part of v same for out.
955             unsafe {
956                 let is_l = is_less(&*right, &**left);
957                 let to_copy = if is_l { right } else { *left };
958                 ptr::copy_nonoverlapping(to_copy, *out, 1);
959                 *out = out.add(1);
960                 right = right.add(is_l as usize);
961                 *left = left.add(!is_l as usize);
962             }
963         }
964     } else {
965         // The right run is shorter.
966 
967         // SAFETY: buf must have enough capacity for `v[mid..]`.
968         unsafe {
969             ptr::copy_nonoverlapping(v_mid, buf, len - mid);
970             hole = MergeHole { start: buf, end: buf.add(len - mid), dest: v_mid };
971         }
972 
973         // Initially, these pointers point past the ends of their arrays.
974         let left = &mut hole.dest;
975         let right = &mut hole.end;
976         let mut out = v_end;
977 
978         while v < *left && buf < *right {
979             // Consume the greater side.
980             // If equal, prefer the right run to maintain stability.
981 
982             // SAFETY: left and right must be valid and part of v same for out.
983             unsafe {
984                 let is_l = is_less(&*right.sub(1), &*left.sub(1));
985                 *left = left.sub(is_l as usize);
986                 *right = right.sub(!is_l as usize);
987                 let to_copy = if is_l { *left } else { *right };
988                 out = out.sub(1);
989                 ptr::copy_nonoverlapping(to_copy, out, 1);
990             }
991         }
992     }
993     // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
994     // it will now be copied into the hole in `v`.
995 
996     // When dropped, copies the range `start..end` into `dest..`.
997     struct MergeHole<T> {
998         start: *mut T,
999         end: *mut T,
1000         dest: *mut T,
1001     }
1002 
1003     impl<T> Drop for MergeHole<T> {
1004         fn drop(&mut self) {
1005             // SAFETY: `T` is not a zero-sized type, and these are pointers into a slice's elements.
1006             unsafe {
1007                 let len = self.end.sub_ptr(self.start);
1008                 ptr::copy_nonoverlapping(self.start, self.dest, len);
1009             }
1010         }
1011     }
1012 }
1013 
1014 /// This merge sort borrows some (but not all) ideas from TimSort, which used to be described in
1015 /// detail [here](https://github.com/python/cpython/blob/main/Objects/listsort.txt). However Python
1016 /// has switched to a Powersort based implementation.
1017 ///
1018 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1019 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1020 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1021 /// satisfied:
1022 ///
1023 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1024 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1025 ///
1026 /// The invariants ensure that the total running time is *O*(*n* \* log(*n*)) worst-case.
merge_sort<T, CmpF, ElemAllocF, ElemDeallocF, RunAllocF, RunDeallocF>( v: &mut [T], is_less: &mut CmpF, elem_alloc_fn: ElemAllocF, elem_dealloc_fn: ElemDeallocF, run_alloc_fn: RunAllocF, run_dealloc_fn: RunDeallocF, ) where CmpF: FnMut(&T, &T) -> bool, ElemAllocF: Fn(usize) -> *mut T, ElemDeallocF: Fn(*mut T, usize), RunAllocF: Fn(usize) -> *mut TimSortRun, RunDeallocF: Fn(*mut TimSortRun, usize),1027 pub fn merge_sort<T, CmpF, ElemAllocF, ElemDeallocF, RunAllocF, RunDeallocF>(
1028     v: &mut [T],
1029     is_less: &mut CmpF,
1030     elem_alloc_fn: ElemAllocF,
1031     elem_dealloc_fn: ElemDeallocF,
1032     run_alloc_fn: RunAllocF,
1033     run_dealloc_fn: RunDeallocF,
1034 ) where
1035     CmpF: FnMut(&T, &T) -> bool,
1036     ElemAllocF: Fn(usize) -> *mut T,
1037     ElemDeallocF: Fn(*mut T, usize),
1038     RunAllocF: Fn(usize) -> *mut TimSortRun,
1039     RunDeallocF: Fn(*mut TimSortRun, usize),
1040 {
1041     // Slices of up to this length get sorted using insertion sort.
1042     const MAX_INSERTION: usize = 20;
1043 
1044     // The caller should have already checked that.
1045     debug_assert!(!T::IS_ZST);
1046 
1047     let len = v.len();
1048 
1049     // Short arrays get sorted in-place via insertion sort to avoid allocations.
1050     if len <= MAX_INSERTION {
1051         if len >= 2 {
1052             insertion_sort_shift_left(v, 1, is_less);
1053         }
1054         return;
1055     }
1056 
1057     // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1058     // shallow copies of the contents of `v` without risking the dtors running on copies if
1059     // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1060     // which will always have length at most `len / 2`.
1061     let buf = BufGuard::new(len / 2, elem_alloc_fn, elem_dealloc_fn);
1062     let buf_ptr = buf.buf_ptr.as_ptr();
1063 
1064     let mut runs = RunVec::new(run_alloc_fn, run_dealloc_fn);
1065 
1066     let mut end = 0;
1067     let mut start = 0;
1068 
1069     // Scan forward. Memory pre-fetching prefers forward scanning vs backwards scanning, and the
1070     // code-gen is usually better. For the most sensitive types such as integers, these are merged
1071     // bidirectionally at once. So there is no benefit in scanning backwards.
1072     while end < len {
1073         let (streak_end, was_reversed) = find_streak(&v[start..], is_less);
1074         end += streak_end;
1075         if was_reversed {
1076             v[start..end].reverse();
1077         }
1078 
1079         // Insert some more elements into the run if it's too short. Insertion sort is faster than
1080         // merge sort on short sequences, so this significantly improves performance.
1081         end = provide_sorted_batch(v, start, end, is_less);
1082 
1083         // Push this run onto the stack.
1084         runs.push(TimSortRun { start, len: end - start });
1085         start = end;
1086 
1087         // Merge some pairs of adjacent runs to satisfy the invariants.
1088         while let Some(r) = collapse(runs.as_slice(), len) {
1089             let left = runs[r];
1090             let right = runs[r + 1];
1091             let merge_slice = &mut v[left.start..right.start + right.len];
1092             // SAFETY: `buf_ptr` must hold enough capacity for the shorter of the two sides, and
1093             // neither side may be on length 0.
1094             unsafe {
1095                 merge(merge_slice, left.len, buf_ptr, is_less);
1096             }
1097             runs[r + 1] = TimSortRun { start: left.start, len: left.len + right.len };
1098             runs.remove(r);
1099         }
1100     }
1101 
1102     // Finally, exactly one run must remain in the stack.
1103     debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
1104 
1105     // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1106     // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1107     // algorithm should continue building a new run instead, `None` is returned.
1108     //
1109     // TimSort is infamous for its buggy implementations, as described here:
1110     // http://envisage-project.eu/timsort-specification-and-verification/
1111     //
1112     // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1113     // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1114     // hold for *all* runs in the stack.
1115     //
1116     // This function correctly checks invariants for the top four runs. Additionally, if the top
1117     // run starts at index 0, it will always demand a merge operation until the stack is fully
1118     // collapsed, in order to complete the sort.
1119     #[inline]
1120     fn collapse(runs: &[TimSortRun], stop: usize) -> Option<usize> {
1121         let n = runs.len();
1122         if n >= 2
1123             && (runs[n - 1].start + runs[n - 1].len == stop
1124                 || runs[n - 2].len <= runs[n - 1].len
1125                 || (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len)
1126                 || (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len))
1127         {
1128             if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) }
1129         } else {
1130             None
1131         }
1132     }
1133 
1134     // Extremely basic versions of Vec.
1135     // Their use is super limited and by having the code here, it allows reuse between the sort
1136     // implementations.
1137     struct BufGuard<T, ElemDeallocF>
1138     where
1139         ElemDeallocF: Fn(*mut T, usize),
1140     {
1141         buf_ptr: ptr::NonNull<T>,
1142         capacity: usize,
1143         elem_dealloc_fn: ElemDeallocF,
1144     }
1145 
1146     impl<T, ElemDeallocF> BufGuard<T, ElemDeallocF>
1147     where
1148         ElemDeallocF: Fn(*mut T, usize),
1149     {
1150         fn new<ElemAllocF>(
1151             len: usize,
1152             elem_alloc_fn: ElemAllocF,
1153             elem_dealloc_fn: ElemDeallocF,
1154         ) -> Self
1155         where
1156             ElemAllocF: Fn(usize) -> *mut T,
1157         {
1158             Self {
1159                 buf_ptr: ptr::NonNull::new(elem_alloc_fn(len)).unwrap(),
1160                 capacity: len,
1161                 elem_dealloc_fn,
1162             }
1163         }
1164     }
1165 
1166     impl<T, ElemDeallocF> Drop for BufGuard<T, ElemDeallocF>
1167     where
1168         ElemDeallocF: Fn(*mut T, usize),
1169     {
1170         fn drop(&mut self) {
1171             (self.elem_dealloc_fn)(self.buf_ptr.as_ptr(), self.capacity);
1172         }
1173     }
1174 
1175     struct RunVec<RunAllocF, RunDeallocF>
1176     where
1177         RunAllocF: Fn(usize) -> *mut TimSortRun,
1178         RunDeallocF: Fn(*mut TimSortRun, usize),
1179     {
1180         buf_ptr: ptr::NonNull<TimSortRun>,
1181         capacity: usize,
1182         len: usize,
1183         run_alloc_fn: RunAllocF,
1184         run_dealloc_fn: RunDeallocF,
1185     }
1186 
1187     impl<RunAllocF, RunDeallocF> RunVec<RunAllocF, RunDeallocF>
1188     where
1189         RunAllocF: Fn(usize) -> *mut TimSortRun,
1190         RunDeallocF: Fn(*mut TimSortRun, usize),
1191     {
1192         fn new(run_alloc_fn: RunAllocF, run_dealloc_fn: RunDeallocF) -> Self {
1193             // Most slices can be sorted with at most 16 runs in-flight.
1194             const START_RUN_CAPACITY: usize = 16;
1195 
1196             Self {
1197                 buf_ptr: ptr::NonNull::new(run_alloc_fn(START_RUN_CAPACITY)).unwrap(),
1198                 capacity: START_RUN_CAPACITY,
1199                 len: 0,
1200                 run_alloc_fn,
1201                 run_dealloc_fn,
1202             }
1203         }
1204 
1205         fn push(&mut self, val: TimSortRun) {
1206             if self.len == self.capacity {
1207                 let old_capacity = self.capacity;
1208                 let old_buf_ptr = self.buf_ptr.as_ptr();
1209 
1210                 self.capacity = self.capacity * 2;
1211                 self.buf_ptr = ptr::NonNull::new((self.run_alloc_fn)(self.capacity)).unwrap();
1212 
1213                 // SAFETY: buf_ptr new and old were correctly allocated and old_buf_ptr has
1214                 // old_capacity valid elements.
1215                 unsafe {
1216                     ptr::copy_nonoverlapping(old_buf_ptr, self.buf_ptr.as_ptr(), old_capacity);
1217                 }
1218 
1219                 (self.run_dealloc_fn)(old_buf_ptr, old_capacity);
1220             }
1221 
1222             // SAFETY: The invariant was just checked.
1223             unsafe {
1224                 self.buf_ptr.as_ptr().add(self.len).write(val);
1225             }
1226             self.len += 1;
1227         }
1228 
1229         fn remove(&mut self, index: usize) {
1230             if index >= self.len {
1231                 panic!("Index out of bounds");
1232             }
1233 
1234             // SAFETY: buf_ptr needs to be valid and len invariant upheld.
1235             unsafe {
1236                 // the place we are taking from.
1237                 let ptr = self.buf_ptr.as_ptr().add(index);
1238 
1239                 // Shift everything down to fill in that spot.
1240                 ptr::copy(ptr.add(1), ptr, self.len - index - 1);
1241             }
1242             self.len -= 1;
1243         }
1244 
1245         fn as_slice(&self) -> &[TimSortRun] {
1246             // SAFETY: Safe as long as buf_ptr is valid and len invariant was upheld.
1247             unsafe { &*ptr::slice_from_raw_parts(self.buf_ptr.as_ptr(), self.len) }
1248         }
1249 
1250         fn len(&self) -> usize {
1251             self.len
1252         }
1253     }
1254 
1255     impl<RunAllocF, RunDeallocF> core::ops::Index<usize> for RunVec<RunAllocF, RunDeallocF>
1256     where
1257         RunAllocF: Fn(usize) -> *mut TimSortRun,
1258         RunDeallocF: Fn(*mut TimSortRun, usize),
1259     {
1260         type Output = TimSortRun;
1261 
1262         fn index(&self, index: usize) -> &Self::Output {
1263             if index < self.len {
1264                 // SAFETY: buf_ptr and len invariant must be upheld.
1265                 unsafe {
1266                     return &*(self.buf_ptr.as_ptr().add(index));
1267                 }
1268             }
1269 
1270             panic!("Index out of bounds");
1271         }
1272     }
1273 
1274     impl<RunAllocF, RunDeallocF> core::ops::IndexMut<usize> for RunVec<RunAllocF, RunDeallocF>
1275     where
1276         RunAllocF: Fn(usize) -> *mut TimSortRun,
1277         RunDeallocF: Fn(*mut TimSortRun, usize),
1278     {
1279         fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1280             if index < self.len {
1281                 // SAFETY: buf_ptr and len invariant must be upheld.
1282                 unsafe {
1283                     return &mut *(self.buf_ptr.as_ptr().add(index));
1284                 }
1285             }
1286 
1287             panic!("Index out of bounds");
1288         }
1289     }
1290 
1291     impl<RunAllocF, RunDeallocF> Drop for RunVec<RunAllocF, RunDeallocF>
1292     where
1293         RunAllocF: Fn(usize) -> *mut TimSortRun,
1294         RunDeallocF: Fn(*mut TimSortRun, usize),
1295     {
1296         fn drop(&mut self) {
1297             // As long as TimSortRun is Copy we don't need to drop them individually but just the
1298             // whole allocation.
1299             (self.run_dealloc_fn)(self.buf_ptr.as_ptr(), self.capacity);
1300         }
1301     }
1302 }
1303 
1304 /// Internal type used by merge_sort.
1305 #[derive(Clone, Copy, Debug)]
1306 pub struct TimSortRun {
1307     len: usize,
1308     start: usize,
1309 }
1310 
1311 /// Takes a range as denoted by start and end, that is already sorted and extends it to the right if
1312 /// necessary with sorts optimized for smaller ranges such as insertion sort.
provide_sorted_batch<T, F>(v: &mut [T], start: usize, mut end: usize, is_less: &mut F) -> usize where F: FnMut(&T, &T) -> bool,1313 fn provide_sorted_batch<T, F>(v: &mut [T], start: usize, mut end: usize, is_less: &mut F) -> usize
1314 where
1315     F: FnMut(&T, &T) -> bool,
1316 {
1317     let len = v.len();
1318     assert!(end >= start && end <= len);
1319 
1320     // This value is a balance between least comparisons and best performance, as
1321     // influenced by for example cache locality.
1322     const MIN_INSERTION_RUN: usize = 10;
1323 
1324     // Insert some more elements into the run if it's too short. Insertion sort is faster than
1325     // merge sort on short sequences, so this significantly improves performance.
1326     let start_end_diff = end - start;
1327 
1328     if start_end_diff < MIN_INSERTION_RUN && end < len {
1329         // v[start_found..end] are elements that are already sorted in the input. We want to extend
1330         // the sorted region to the left, so we push up MIN_INSERTION_RUN - 1 to the right. Which is
1331         // more efficient that trying to push those already sorted elements to the left.
1332         end = cmp::min(start + MIN_INSERTION_RUN, len);
1333         let presorted_start = cmp::max(start_end_diff, 1);
1334 
1335         insertion_sort_shift_left(&mut v[start..end], presorted_start, is_less);
1336     }
1337 
1338     end
1339 }
1340 
1341 /// Finds a streak of presorted elements starting at the beginning of the slice. Returns the first
1342 /// value that is not part of said streak, and a bool denoting whether the streak was reversed.
1343 /// Streaks can be increasing or decreasing.
find_streak<T, F>(v: &[T], is_less: &mut F) -> (usize, bool) where F: FnMut(&T, &T) -> bool,1344 fn find_streak<T, F>(v: &[T], is_less: &mut F) -> (usize, bool)
1345 where
1346     F: FnMut(&T, &T) -> bool,
1347 {
1348     let len = v.len();
1349 
1350     if len < 2 {
1351         return (len, false);
1352     }
1353 
1354     let mut end = 2;
1355 
1356     // SAFETY: See below specific.
1357     unsafe {
1358         // SAFETY: We checked that len >= 2, so 0 and 1 are valid indices.
1359         let assume_reverse = is_less(v.get_unchecked(1), v.get_unchecked(0));
1360 
1361         // SAFETY: We know end >= 2 and check end < len.
1362         // From that follows that accessing v at end and end - 1 is safe.
1363         if assume_reverse {
1364             while end < len && is_less(v.get_unchecked(end), v.get_unchecked(end - 1)) {
1365                 end += 1;
1366             }
1367 
1368             (end, true)
1369         } else {
1370             while end < len && !is_less(v.get_unchecked(end), v.get_unchecked(end - 1)) {
1371                 end += 1;
1372             }
1373             (end, false)
1374         }
1375     }
1376 }
1377