1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
use ;
use ;
use ;
use ;
/// Sorts a slice using drift sort.
///
/// Drift sort, designed by Orson Peters and Lukas Bergdoll in 2024 and the stable sort of
/// Rust's standard library since 1.81, drifts between merge sort and quick sort. It scans the
/// slice for natural runs, ascending or strictly descending, but keeps only those of at least
/// about `√n` elements (`min(n/2, 32)` below 4096 elements); everything else becomes chunks
/// that are left unsorted for now. Runs and chunks are combined in the order of a merge tree,
/// powersort's: two adjacent unsorted chunks are simply taken together, still unsorted, while
/// an unsorted chunk that meets a sorted run is first sorted by a stable quick sort and then
/// merged. Random input thus ends up as one big chunk for quick sort, which handles repeated
/// keys in `O(n log k)`, while input made of long runs is merged like Tim sort's, and anything
/// in between gets the cheaper of the two for each part.
///
/// Nine refinements keep the algorithm as cheap as drift sort can be. The ratios quoted are
/// measured on an Apple M4 Max with new input for every sort, the way a program sorts; where
/// sorting the same input again and again, which lets the processor learn every branch,
/// gives a different picture, that is said.
///
/// * **This crate's best parts.** Runs are merged by [`tim`](crate::sort::tim) sort's merge,
/// which skips the elements already in place, merges from both ends at once without
/// branching, gallops through runs that interleave in blocks and, once galloping has not
/// paid off, merges runs whose content interleaves finely as two merges at once (four
/// chains of comparisons the processor overlaps: 1.25–1.5 times faster on input made of
/// runs of random content); short parts are sorted by [`merge`](crate::sort::merge) sort's
/// branchless short-run sort (see below); a quick sort still partitioning after `2·log₂ n`
/// levels hands the part to merge sort, so the sort is `O(n log n)` on any input.
/// * **Pivot samples at several scales.** Pivots are chosen as in [`quick`](crate::sort::quick)
/// sort, from a median of 3 up to a pseudo-median of hundreds of samples, but quick sort's
/// ninther and evenly spaced pseudo-median sample at a single scale, which periodic input
/// whose period divides the spacing defeats: every sample shows the same key, each
/// partition peels off one key, and a sawtooth of 1000 elements cost 2.4 times the standard
/// library's time and even exhausted the quick sort limit. Here the samples lie in three
/// sections of an eighth of the width, centred at the middle and `3/8` of the width to
/// either side, recursively, so every level samples at its own scale: 9 samples at two
/// scales from 64 elements, 27 at three from 1024, three times as many for every 16 times
/// the length. The sawtooth of 1000 elements then costs 3.3–3.7 times less and random input
/// 1–2% fewer comparisons; integers are 1–2% slower on random input, and a sawtooth of 100
/// integers 1.12 times, whose exact median the old samples happened to hit. The layout is
/// symmetric, so sorted input still gets the middle element.
/// * **Branchless stable partitioning.** Each element is compared with the pivot and copied
/// into the buffer, to the front if it goes left and to the back otherwise, from an address
/// the comparison selects; then both parts are copied back, the back one reversed. Every
/// element is compared in place before it is copied, and the pivot is copied last, after
/// every comparison with it, so a comparison that panics or mutates its arguments leaves no
/// stale copy behind. A partition that moved nothing, because nothing or everything went
/// left, skips the copies back: 1.05–1.3 times faster for integers with 2 distinct keys, up
/// to 1.07 times with 16. Elements larger than 8 bytes, whose copies cost more than the
/// bookkeeping, are instead compacted in place as they go left, only the right part passing
/// through the buffer, in order, with the pivot moved out into a local for the scan, its
/// only live copy, and written back last; a guard restores every element exactly once if a
/// comparison panics. Measured: 1.2–1.3 times faster on random 64-byte elements, 1.2–1.5
/// times with repeated keys, 1.1–1.2 times on random strings from 10,000 elements; strings
/// up to 1000 gain nothing.
/// * **Repeated keys in one pass, without copying the pivot.** When a part's pivot is no
/// greater than the pivot of the partition that produced the part, which is no greater than
/// anything in it, every element equal to the pivot is taken out in one pass, and only the
/// rest is sorted further. The standard library compares against a bitwise copy of the
/// earlier pivot, which is only sound for types without interior mutability; here that
/// pivot is found in place instead, by counting during each partition how many elements
/// went left before it. Input with `k` distinct keys costs `O(n log k)`: 1.3–1.45 times
/// faster for integers with few distinct keys than without the check, 1.1–1.2 times for
/// strings and 64-byte elements. Counting splits the partition loop once more, so for
/// elements of at most 8 bytes only parts of 128 elements or more count, whose left part is
/// likely to be partitioned again: 1.04–1.07 times faster for random integers, and as fast
/// with few distinct keys. Where no earlier pivot bounds a part from below (at the top, and
/// after every such pass), a pivot that is the part's minimum would cost a partition that
/// moves nothing before the pass that takes out its equals, so such a part is first scanned
/// for a smaller element, a comparison or two on most input: another 1.08–1.25 times
/// faster for integers with 2 distinct keys, 1.03–1.1 times for strings with 2 or 16, and
/// nothing for 64-byte elements or on random input.
/// * **No per-element bookkeeping.** The partition loop is split at the pivot and at the
/// earlier pivot instead of checking for them at every element, and for elements of at most
/// 8 bytes it is unrolled by 4: 1.03–1.07 times faster for integers.
/// * **Short parts noted for order and merged in place.** A part of up to 32 elements of at
/// most 8 bytes is first scanned for descents, elements smaller than the one before, with
/// one comparison per element and no branch on the answers, into a mask of bits. Runs of 8
/// with no descent, and longer stretches of the merge tree without one, are left alone; the
/// other runs are sorted by merge sort's branchless short-run sort; and every merge reads
/// its halves where the level below left them, in the part or in the buffer, and writes the
/// other place, so no level is copied out before it is merged, and halves that come out in
/// order are not merged either. Larger elements, whose comparisons are calls, keep merge
/// sort's short-run sort for parts of up to 20 elements, and from 17 sort each half's first
/// 8 elements by it, insert the rest and merge once. The merges, like the partition, leave
/// no stale copy behind when a comparison mutates its arguments: a merge of up to 16
/// elements decides the order before it copies anything, and a longer one copies the few
/// elements compared after their copy was written once more (see
/// [`merge`](crate::sort::merge)), while a merge of larger elements stops as soon as a half
/// has run out; this costs integers 1.02–1.05 times on random input of 100 elements or more
/// and strings 1.03–1.06 times up to 1000, against merges that compare stale copies, which
/// are sound only for types without interior mutability.
/// The former scheme for integers, each half's first 8 elements sorted and the rest
/// inserted, is quick only on input sorted again and again, once the branch predictor has
/// learnt its insertions: with new input, the mask is 1.02–1.04 times faster on random
/// integers, 1.01–1.04 times on nearly sorted input, runs and `√n` distinct keys, but 1.2
/// times slower on a sawtooth of 100 elements, whose repeated runs of 10 the insertions
/// handled once learnt.
/// * **Short slices adapt too.** A slice of up to 64 elements of at most 8 bytes gets the same
/// scan for descents: none, and it is left alone; one at every element, and it is reversed;
/// at most one per 8 elements, and the elements after the first descent are inserted into
/// the sorted prefix, as Tim sort extends its runs; anything else is sorted with the
/// descents already found. Sorted and strictly descending input costs `n − 1` comparisons.
/// Against scanning for a prefix run and sorting the rest by merge sort (up to 32 elements)
/// or as chunks of 32 (33 to 64), with new input every time: 1.2–1.5 times faster on random
/// integers and with few distinct keys, 1.1–1.8 times on input made of runs, 1.3–2 times on
/// reverse-sorted input, 1.1–2.4 times on sorted input from 12 elements on, 1.1–2.9 times
/// on sorted input with elements appended from 16 elements on and 1.3–1.6 times on nearly
/// sorted input from 40 elements on, but 1.1–1.25 times slower on 8 to 28 nearly sorted
/// elements, and 1.2–2.9 times slower on a sawtooth of 8 to 64 elements or blocks of 8 to
/// 32, where the former entry's insertions were learnt (such input is periodic, so the
/// processor learns it even when it is new); with the same input again and again, the
/// learnt insertions are up to 1.3 times faster on 8 to 16 random elements and 1.1–1.9
/// times on 26 to 64 elements made of runs. Larger elements are scanned for a sorted or
/// strictly descending prefix and the rest inserted, which needs no buffer, up to 28
/// elements, or 40 for elements larger than 32 bytes, whose moves cost more than their
/// comparisons: 1.1–1.5 times faster than a chunk of 20 and the rest merged on random
/// strings of 24 to 28 elements, 1.3–2 times on nearly sorted or appended ones; 64-byte
/// elements gain 1.1–1.25 times on random input up to 40 elements and 1.3–1.9 times on
/// input with structure. Longer slices up to twice the small sort's length (40 elements
/// larger than 8 bytes) sort each chunk of that length the same way as soon as it is found,
/// its prefix being the run the scan just found, so no chunk is scanned twice, and merge
/// the chunks: 1.05–1.1 times faster on nearly sorted or block-wise sorted slices of 24–40
/// strings or 64-byte elements.
/// * **Runs cut by a chunk boundary are taken back.** A chunk ends where its length is up,
/// often inside a natural run, whose rest then falls short of the length a run must have.
/// A rest of at least half that length is probed with one or two comparisons and, if they
/// are in order, scanned backwards into the chunk, which gives the run back what it cut
/// off, the boundary moving with it, if that makes the run long enough: 1.05–1.2 times
/// faster on input made of runs of about `√n` elements, up to 1.04 times on nearly sorted
/// input below 4096 elements, and one comparison per chunk on sawtooth input, whose runs
/// stop just short.
/// * **No allocation for small slices or single runs.** The buffer lives on the stack while it
/// fits in 4 KiB, and is otherwise allocated when first needed; short slices of large
/// elements are insertion sorted and need none.
///
/// # Properties
///
/// * **Stable**: equal elements keep their relative order. Runs are reversed only if strictly
/// descending, both parts of a partition keep their order, and merges and the small sort
/// are stable.
/// * **Not in place**: a buffer of `n` elements (the standard library's drift sort makes do
/// with about `n/2` for large inputs, at the price of a top-level merge that costs it
/// 1.3–1.8 times on a million random strings), on the stack if it fits in 4 KiB and
/// allocated once otherwise.
/// * **Adaptive** to runs of `√n` elements or more, ascending or strictly descending, even
/// where a chunk boundary cuts them, and to repeated keys.
/// * **Sound for any `Ord`**: a comparison that panics, answers inconsistently or mutates its
/// arguments through interior mutability never leaves a stale copy, a duplicate or a hole
/// behind (see below).
///
/// | Case | Comparisons | Moves |
/// |-------------------------------------|------------------------------|--------------------|
/// | Best (sorted, strictly descending) | `n − 1` | `0` (`n` reversed) |
/// | `k` distinct keys | `O(n log k)` | `O(n log k)` |
/// | Average (random) | `≈ (1.06–1.12)·n·log₂ n` | `O(n log n)` |
/// | Worst | `O(n log n)` | `O(n log n)` |
///
/// For `n = 1000`: 999 comparisons on sorted or strictly descending input, about 11,200 on
/// random input, 5,700 with 16 distinct keys and 2,800 with 2 (Tim sort: 10,560, 9,390 and
/// 7,050 for elements of at most 8 bytes, 11,800, 10,380 and 5,290 for larger ones), about
/// 2,050 with 10 random pairs swapped and 7,100 on a sawtooth (the standard
/// library: 10,600, 5,660, 3,100, 6,600 and 8,900). Elements of at most 8 bytes trade about
/// 4% more comparisons on random input, and 6–13% on slices of up to 64 elements, for fewer
/// mispredicted branches.
///
/// Against [`slice::sort`], the standard library's drift sort, with new input for every sort:
/// 1.3–3 times faster on 8 to 64 random integers (it insertion sorts up to 20 elements and
/// merges chunks up to 64, which the processor only learns when the input repeats), 1.03–1.06
/// times slower on 100 to a million; 1.07–1.08 times slower on random strings of 100 to 1000
/// elements, as fast at 10,000 and 1.06–1.75 times faster beyond; 1.1–1.15 times slower on
/// random 64-byte elements up to 100, 1.06–1.25 times faster from 1000; 1.05–1.9 times
/// faster with few or `√n` distinct keys from 1000 elements on (integers with 16 keys within
/// 1.06 either way) and 1.25–1.65 times on a sawtooth of 1000 (3 times on one of a million
/// integers or strings); and 1.1–8 times faster on input with structure from 24 elements on:
/// nearly sorted, sorted with elements appended, made of runs of `√n` elements (from 10,000;
/// as fast below) or of interleaved blocks. Up to 20 nearly sorted elements its insertion
/// sort is 1.2–1.5 times faster. Against this crate's Tim sort: 1.05–1.3 times faster on
/// random integers from 1000 elements on and 1.4–1.65 times on random strings (1.2–1.3 times
/// on 64-byte elements), 1.6–9.3 times with few distinct keys (3.4–9.3 times for integers)
/// and 1.25–2.55 times on sawtooth input up to 100,000 elements, but 1.1–1.4 times slower on
/// nearly sorted integers (1.15–2 times for strings) and 1.05–1.4 times slower on input made
/// of runs of `√n` elements, which Tim sort keeps whole.
///
/// Prefer [`slice::sort`] for real workloads.
///
/// # Panics
///
/// Panics only if allocating the buffer fails. If the [`Ord`] implementation of `T` panics,
/// the panic is propagated and `arr` is left in an unspecified order, but it still holds every
/// original element exactly once: nothing is dropped twice or leaked. An [`Ord`] that is not a
/// total order leaves `arr` in an unspecified order with every element exactly once as well,
/// and one that mutates its arguments through interior mutability sees every mutation kept:
/// no element is ever compared through a copy whose twin is live, nor compared with itself.
///
/// # Examples
///
/// ```
/// use a::sort::drift;
///
/// let mut v = [5, 1, 4, 2, 8, 0, 3, 9, 7, 6];
/// drift(&mut v);
/// assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
///
/// // Many repeated keys are taken out a key at a time.
/// let mut v: Vec<u8> = (0..1000).map(|i| (i * 7 % 3) as u8).collect();
/// drift(&mut v);
/// assert!(v.windows(2).all(|w| w[0] <= w[1]));
///
/// // Equal keys keep their order: cards are compared by rank only.
/// #[derive(Debug, PartialEq, Eq)]
/// struct Card(u8, char);
/// impl Ord for Card {
/// fn cmp(&self, other: &Self) -> std::cmp::Ordering {
/// self.0.cmp(&other.0)
/// }
/// }
/// impl PartialOrd for Card {
/// fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
/// Some(self.cmp(other))
/// }
/// }
/// let mut cards: Vec<Card> = "abcdefghij".chars().zip([3, 1, 3, 0, 1, 3, 0, 2, 1, 0])
/// .map(|(c, rank)| Card(rank, c))
/// .collect();
/// drift(&mut cards);
/// let order: String = cards.iter().map(|c| c.1).collect();
/// assert_eq!(order, "dgjbeihacf");
/// ```
/// Slices of at most this many elements of at most [`SMALL_MAX_SIZE`] bytes are sorted by
/// [`sort_short`]: as many as the descents of a slice that fit in a `u64`. Measured against
/// sorting 33 to 64 elements as two chunks and a merge, with new input every time: 1.2–1.45
/// times faster on random integers and with few distinct keys, 1.1–1.8 times on input made
/// of runs, 1.3–1.6 times on nearly sorted input and 1.9–3.2 times on sorted, reverse-sorted
/// or appended input; with the same input again and again, 1.1–1.3 times slower on integers
/// made of runs. Quick sorting 33 to 64 random integers at once, which a count of descents
/// told from input with order, was 1.1–1.3 times faster than the chunks but 1.2–1.35 times
/// slower than this.
const SHORT_MAX: usize = PINGPONG_MAX;
/// Sorts `arr`, at most [`SHORT_MAX`] elements of at most [`SMALL_MAX_SIZE`] bytes, with
/// `buf`, which has room for all of it. One pass of `len − 1` comparisons, with no branch on
/// their outcome, notes every descent: none means the slice is sorted, one at every element
/// that it is strictly descending and is reversed, at most `len / DESCENTS_DIV` that a few
/// elements are out of place and are inserted into the sorted prefix, and anything else goes
/// to the small sort with the descents it found, which spares it a scan of its own.
/// The descents of a strictly descending slice of `2 <= len <= 64` elements: every bit from
/// 1 to `len − 1`.
/// A short slice with at most `len / DESCENTS_DIV` descents (elements smaller than the one
/// before) has its elements after the first inserted into the sorted prefix, which moves
/// little on such input; one with more goes to the small sort, whose branchless merges cost
/// the same whatever the order. Measured against inserting never: 2.3–4 times faster on
/// sorted integers with one appended and 1.3–1.5 times on nearly sorted ones, at 16 to 32
/// elements; and against inserting from 2 descents on however short the slice: 1.3–1.6 times
/// faster on 8 random integers, with few distinct keys or made of runs.
const DESCENTS_DIV: usize = 8;
/// The largest element size, in bytes, for which parts are sorted by [`small_sort`] from 32
/// elements down instead of 20, partitioning is unrolled, short parts and slices are checked
/// for order without branching (see [`sort_short`] and [`small_sort`]), and parts shorter
/// than [`track_min`] do not follow the ancestor pivot into their left part.
///
/// Measured: for integers, small parts of up to 32 elements make random input 1.05–1.1 times
/// faster than up to 20, and unrolling the partition loop by 4 another 1.03–1.07 times. For
/// strings and 64-byte elements, 32 is up to 1.2 times slower on short slices with few
/// distinct keys, and unrolling 1.2–1.35 times slower: their comparisons are calls, and the
/// longer loop only adds code. Insertion sort instead of merge sort's short-run sort would be
/// 1.1–1.5 times slower on random input for them.
const SMALL_MAX_SIZE: usize = 8;
/// Parts of at most this many elements are sorted by [`small_sort`], and chunks of this many
/// elements are sorted as they are found (see [`create_run`]).
const
/// Slices of at most this many elements of more than [`SMALL_MAX_SIZE`] bytes are sorted
/// whole, the way Tim sort builds a short run: scanned for a sorted or strictly descending
/// prefix and the rest inserted into it, in place and without a buffer, instead of chunk by
/// chunk (see [`create_run`]): up to [`INSERTION_LEN`] elements, or twice [`small_sort_len`]
/// for elements larger than [`LARGE_INSERTION_SIZE`] bytes.
const
/// See [`short_slice_len`]: how many elements of 9 to [`LARGE_INSERTION_SIZE`] bytes are insertion
/// sorted whole rather than as a chunk of [`small_sort_len`] and the rest, merged.
///
/// Measured for strings on slices of 21–28 elements: 1.03–1.5 times faster than the chunks on
/// random input and with few distinct keys, 1.3–2 times on nearly sorted or appended input,
/// whether the input is new to the branch predictor or not. From 30 elements on the
/// insertions lose on random input, few distinct keys or runs whenever the same data is
/// sorted repeatedly, up to 1.08 times at 30–32 and 1.3 times at 40 (and still win 1.02–1.1
/// times on new input), so the bound stops at 28. Elements larger than 32 bytes, whose moves
/// cost more than their comparisons unless they compare by a heap-allocated key, win up to 40
/// elements in both regimes: 1.02–1.2 times on random input and 1.1–2 times on input with
/// structure for 40-, 48- and 64-byte elements.
const INSERTION_LEN: usize = 28;
/// See [`short_slice_len`]: elements larger than this many bytes, whose moves cost more than
/// their comparisons unless they compare by a heap-allocated key, are insertion sorted whole
/// up to twice [`small_sort_len`] elements.
const LARGE_INSERTION_SIZE: usize = 32;
/// Parts of this many elements up to [`HALVES_MAX`], of more than [`SMALL_MAX_SIZE`] bytes,
/// are sorted by [`small_sort`] as two halves of at least 8 elements.
const HALVES_MIN: usize = 17;
/// See [`HALVES_MIN`]: every part [`small_sort`] gets for such elements.
const HALVES_MAX: usize = 20;
/// Parts shorter than this do not follow the ancestor pivot into their left part: counting
/// where it goes splits the partition loop once more, which for elements of at most
/// [`SMALL_MAX_SIZE`] bytes costs more than it saves when the left part is likely short enough
/// for [`small_sort`]. Measured for integers: 1.04–1.07 times faster on random input, and the
/// same with few distinct keys. Strings and 64-byte elements, whose comparisons dominate, lose
/// up to 1.06 times with few distinct keys without it, and follow it in every part.
const
/// Below `MIN_SQRT_RUN² = 4096` elements, a natural run must be `min(len / 2, 32)` elements
/// long to be kept; from there on, about `√len`.
const MIN_SQRT_RUN: usize = 64;
const MIN_MERGE_RUN: usize = 32;
/// A natural run that falls short of the length a run must have reaches back into the
/// unsorted chunk before it only if it has at least `1 / STEAL_DIV` of that length, which is
/// the most the chunk can have cut off a run worth keeping, see [`steal`]. Measured against
/// 4: the same.
const STEAL_DIV: usize = 2;
/// How many elements of at most [`SMALL_MAX_SIZE`] bytes [`stable_partition`] compares per
/// round of its loop.
const UNROLL: usize = 4;
/// Room on the run stack: the depths of the boundaries between runs on it strictly increase
/// and lie between 0 and 64.
const MAX_RUNS: usize = 66;
/// A stretch of the slice waiting to be merged: its length and whether it is sorted yet.
/// Sorts `v` (more than [`small_sort_len`] elements) with `buf`, which has room for all of it.
/// If `eager`, every chunk is sorted as soon as it is found.
/// `⌊√n⌋`, roughly: `2^⌈log₂(n) / 2⌉` refined by one step of Newton's method.
/// Finds the run at `v[scan..]`: a sorted run if a natural one of at least `min_good_run`
/// elements is there (reversed if strictly descending), and otherwise the next chunk, a chunk
/// of `eager_len` elements sorted now if that is not 0 and a chunk of `min_good_run` elements
/// left unsorted otherwise. `prev` is the run before `scan`: a natural run that falls short of
/// `min_good_run` but goes on backwards into `prev`, if that is an unsorted chunk, takes those
/// elements from it (see [`steal`]). The second value returned is how many, by which `prev`
/// shrinks and the run starts before `scan`.
/// Extends the natural run of `run` elements at `v[scan..]`, strictly descending if
/// `descending`, backwards over the elements before `scan` that continue it, if at least
/// `need` of them do (`need` is at least 1 and at most `stealable`, which is less than
/// `scan`): the chunk before the run cut them off it. Takes at most `stealable` of them and
/// returns how many, 0 if fewer than `need` continue the run, which is then left alone. A
/// descending run is reversed as a whole, stolen elements included.
///
/// An ascending run takes an element equal to its first, so equal elements keep their order;
/// a descending one only takes strictly greater elements, so reversing it cannot swap equal
/// elements. Every comparison is made in place, between two different elements.
/// Returns the length of the run at the start of `v` (at least 2 elements long), the longest
/// prefix that is ascending or strictly descending, and whether it descends.
/// Combines the adjacent runs `left` and `right`, which make up `v`. Two unsorted runs are
/// simply taken together, unsorted; otherwise an unsorted one is sorted first and the two are
/// merged.
/// Sorts `v` stably by quick sort through `buf`, falling back to merge sort once `limit` more
/// levels of partitioning have not finished the job. `ancestor`, if set, is the index of an
/// element of `v` no greater than any other: the pivot of an enclosing partition.
/// Whether no element of `v` is smaller than `v[pivot]`: every element is compared in place,
/// up to the first smaller one, and the pivot is not compared with itself.
/// `buf` as a slice of `len` slots, for a part of that many elements. The slice, unlike the
/// raw pointer, tells the compiler that nothing written through it aliases the part, which
/// lets a partition keep the pivot in a register (it reloaded it for every element otherwise).
/// Below this length the pivot is the median of three elements, at `len/4`, `len/2` and
/// `3·len/4`; from here on a pseudo-median of 9 samples at two scales (see [`pseudo_median`]).
const NINTHER: usize = 64;
/// From this length on, the pivot is the pseudo-median of 27 samples at three scales, and of
/// three times as many, one scale deeper, for every 16 times the length (81 from 16,384
/// elements, 243 from 262,144, 729 from 4,194,304).
///
/// Measured: 27 samples from 512 elements, the standard library's count, save about 1% of
/// the comparisons on random integers from 10,000 elements but no time, and cost 3–5% with
/// 16 distinct keys at 1000–10,000 elements, where partitions are cheap and few; 27 from
/// 4096, as before, leaves sizes below that with two scales only, which a sawtooth whose
/// period divides both offsets still defeats (`3.7·n·log₂ n` comparisons at 65,535 elements
/// with a period of 128).
const PSEUDO_MEDIAN: usize = 1024;
/// Returns the index of the pivot for partitioning `v`: the median of three samples below
/// [`NINTHER`] elements, and from there on a pseudo-median of `3^depth` samples laid out at
/// `depth − 1` scales (see [`pseudo_median`]), 9 from 64 elements, 27 from [`PSEUDO_MEDIAN`]
/// and three times as many for every 16 times the length.
///
/// Not [`quick`](crate::sort::quick) sort's: its ninther samples `len/4`, `len/2` and
/// `3·len/4`, each `± len/8`, and its pseudo-median an evenly spaced grid, both at a single
/// scale. A periodic input whose period divides that spacing (a sawtooth of 1000 elements
/// with a period of 31, say: `125 ≡ 1 (mod 31)`, so the samples at `k·125` are the keys 1 to
/// 7) then shows every sample about the same key, each partition peels off a key, and the
/// sort costs 2–4 times what it should, or even exhausts the quick sort limit.
/// The offset of a section's outer samples from its centre, `3/8` of its `width` (see
/// [`pseudo_median`]), computed so that it cannot overflow.
const
/// Returns the index of the pseudo-median of 9 samples of `v` at two scales, the median of
/// the medians of three sections of `width / 8` elements centred at `mid` and `mid ± off`,
/// each sampled at its centre and `3/8` of its width to either side: [`pseudo_median`] at
/// depth 2, written out so that it costs no calls, which for parts of 64 to 1023 elements is
/// most of what the pivot costs (measured for integers against the recursion: 1.03–1.07
/// times faster on random input and with 16 or `√n` keys at 1000–10,000 elements, with
/// fresh input for every sort).
/// Returns the index of the pseudo-median of `3^depth` samples of `v` spread over `width`
/// elements around `mid`: at depth 1, the median of the elements at `mid − off`, `mid` and
/// `mid + off`, where `off = 3·width/8`; deeper, the median of the pseudo-medians, one level
/// shallower, of three sections of `width/8` elements centred there (at depth 2, the
/// [`ninther`]).
///
/// Every level samples at its own scale (offsets of `3/8`, `3/64`, `3/512`, … of the width),
/// so the samples are not an arithmetic progression: a periodic input whose period divides
/// one level's offset is still spread by the other levels. Counted over every length from
/// 64 to a million elements with a sawtooth of period `√n`, or of 8 to 4096, the worst
/// length costs `1.6·n·log₂ n` comparisons (random input: about `1.1·n·log₂ n`), against
/// `3.9·n·log₂ n` with samples at a single scale. The layout is symmetric around `mid`, so
/// on sorted input the pivot is the middle element; the standard library's `0`, `n/2`,
/// `7n/8` costs 1.08 times as many comparisons on nearly sorted input.
///
/// Bounds: each offset is at most `3/8` of its level's width, and widths shrink 8 times per
/// level, so the farthest sample lies within `(3/8)·(1 + 1/8 + 1/64 + …)·width < 3·width/7`
/// of `mid` (rounding down only shrinks offsets), and so does every section's centre; with
/// `mid = len/2` and `width = len` every index lies in `[len/14 − 1, 13·len/14]`, inside `v`,
/// and no subtraction underflows. Sections at one level are `3·width/8` apart and reach less
/// than `3·width/56` from their centres, so they do not overlap, and the depth grows only
/// every 16 times the length while sections shrink 8 times, so the finest width is at least
/// 8 and the finest offset at least 3: the samples are all distinct.
/// Returns whichever of `a`, `b` and `c` indexes the median of the three elements, with two or
/// three comparisons. Two equal indices name the same element, which is the median then and
/// is not compared with itself (an `Ord` that borrows both arguments mutably would panic): a
/// safeguard, since the sample layouts keep every sample distinct.
/// What [`stable_partition`] found: how many elements went left, and how many of those were
/// before the pivot and before the tracked element.
/// Partitions `v` stably around the element at `pivot`: the elements for which
/// `goes_left(element, pivot)` holds come first, in their original order, then the others, in
/// their original order; the pivot itself goes left if `pivot_goes_left`. Returns how many go
/// left, and how many of those were before the pivot and before `tracked`. `scratch` has room
/// for all of `v`.
///
/// Every element is compared in place and copied into `scratch`, the ones going left to the
/// front and the others to the back, from where they are copied back in reverse; the pivot is
/// copied last, after every comparison with it. A partition that moved nothing, because
/// nothing or everything went left, skips the copies back: `v`, only read so far, already is
/// the partition. Elements larger than [`SMALL_MAX_SIZE`] bytes are partitioned by
/// [`stable_partition_inplace`] instead.
/// The progress of [`stable_partition_inplace`], which writes into `v` while comparisons that
/// may panic remain, kept so that `v` can be restored with every element exactly once. The
/// pivot was moved out into `pivot` before the scan, which leaves its slot `pivot_pos` of `v`
/// stale. `state` is `(i, left)`: of the first `i` elements, `left` went left and sit in
/// `v[..left]`, the others in `scratch[..i − left]`, both in order; `v[left..i]` is stale and
/// `v[i..]` unread. Once `i > pivot_pos`, the pivot's slot is only reserved: at
/// `v[left_before_pivot]` if it goes left (it is counted in `left` then), else at
/// `scratch[pivot_pos − left_before_pivot]`, a gap among the elements that went right.
/// [`stable_partition`] for elements larger than [`SMALL_MAX_SIZE`] bytes, whose copies cost
/// more than the bookkeeping: the elements going left are compacted in place, into
/// `v[..left]`, the others copied in order into `scratch`, and only those are copied back, in
/// one block, so each element is copied once or twice instead of twice and the right part is
/// never reversed. Elements of at most 8 bytes gain nothing: their scan, whose stores are
/// the limit, would be slower and their copies back are cheap. Measured for a partition
/// alone, 1.3 times faster for random 64-byte elements, 1.05–1.13 times for strings.
///
/// The pivot is moved out into a local for the whole scan, the only live copy of it: the
/// comparisons read it there, which also lets the compiler keep it in registers while the
/// scan writes into `v`, and it is written into its final slot last, after every comparison.
/// Element `i` goes to `v[left]` (`left ≤ i`, a slot already read) or to `scratch[i − left]`;
/// the pivot's final slot is only reserved at its turn. Since `v` is written while
/// comparisons remain, an [`InplaceGuard`] records the progress before each comparison and
/// restores `v`, every element exactly once, if one panics; for comparisons that cannot
/// unwind the compiler drops those stores.
/// Sorts `v`, at most [`small_sort_len`] elements, stably. Elements of at most
/// [`SMALL_MAX_SIZE`] bytes go to merge sort's short-run sort in its ping-pong form (see
/// [`sort_pingpong`]), which notes the descents of the part by one pass of `len − 1`
/// comparisons with no branch on their outcome, leaves the runs and stretches without one
/// alone, sorts the other runs without branching and merges every level in place of the one
/// below instead of copying it out first. Larger elements go to merge sort's short-run sort
/// as it is, and from [`HALVES_MIN`] elements up to [`HALVES_MAX`] as two halves, each of
/// whose first 8 elements are sorted by it and the rest inserted, merged once: merge sort
/// alone would split 17 to 20 elements into runs of 4 to 5 and merge three times.