fastmash 0.2.0

Fast command-line statistics on text data, compatible with GNU datamash
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
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
//! Stable sorting with projected text or original numerical record payloads.
use super::{
    command_output::CommandOutput,
    intake::{self, Intake},
    *,
};
use std::{cmp::Ordering, io::BufRead};
#[path = "projected_batch.rs"]
mod batch;
#[path = "csv_sort.rs"]
mod decoded;
pub(super) use decoded::Sorting as DecodedSorting;
pub(super) use decoded::calculate as calculate_decoded;
#[cfg(test)]
pub(super) use decoded::{RunFault, fail_run};
#[path = "projected_hash.rs"]
mod hash;
pub(super) use hash::{Setting as Grouping, eligible as hash_eligible, setting as grouping};
#[path = "projected_memory.rs"]
mod memory;
#[path = "projected_spill.rs"]
mod spill;
#[path = "projected_storage.rs"]
mod storage;
#[cfg(test)]
use storage::{Build, Keys};
use storage::{Original, Packed, Storage};

fn allocation() -> Failure {
    unsupported("projected sort memory allocation failed")
}

/// Check an active native route's explicit resource setting before input.
pub(super) fn admit_memory(setting: Option<&std::ffi::OsStr>) -> Result<(), Failure> {
    memory::target(setting).map(|_| ())
}

/// Marks a key layout that the eight-byte prefix cannot fully encode.
const LONG_KEY: u8 = 9;

/// A record's key cache (`key_cache`): its key prefix and key length.
type KeyCache = (u64, u8);

/// The sort's key cache: the first key's first eight bytes, zero-padded, and
/// the key's length when that prefix holds the whole key layout (one key of
/// at most eight bytes), else `LONG_KEY`.
fn key_cache(first: Option<&[u8]>, key_count: usize) -> KeyCache {
    let mut prefix = [0; 8];
    let mut short_key_len = LONG_KEY;
    if let Some(key) = first {
        let count = key.len().min(prefix.len());
        prefix[..count].copy_from_slice(&key[..count]);
        if key_count == 1 && key.len() <= prefix.len() {
            short_key_len = key.len() as u8;
        }
    }
    (u64::from_be_bytes(prefix), short_key_len)
}

struct Record<S: Storage> {
    data: S,
    prefix: u64,
    fields: u64,
    sequence: u64,
    short_key_len: u8,
}
impl<S: Storage> Record<S> {
    fn key_cache(data: &S) -> KeyCache {
        let count = data.key_count();
        key_cache((count != 0).then(|| data.segment(0)), count)
    }
    fn new(data: S, fields: u64, sequence: u64) -> Self {
        let (prefix, short_key_len) = Self::key_cache(&data);
        Self {
            prefix,
            short_key_len,
            data,
            fields,
            sequence,
        }
    }
    fn segment(&self, at: usize) -> &[u8] {
        self.data.segment(at)
    }
    fn key_count(&self) -> usize {
        self.data.key_count()
    }
    fn original(&self) -> Option<&[u8]> {
        self.data.original()
    }
    fn compare(&self, other: &Self) -> Ordering {
        self.prefix.cmp(&other.prefix).then_with(|| {
            let keys = if self.short_key_len < LONG_KEY && other.short_key_len < LONG_KEY {
                self.short_key_len.cmp(&other.short_key_len)
            } else {
                self.data.compare_keys(&other.data)
            };
            keys.then(self.sequence.cmp(&other.sequence))
        })
    }
    fn field<'a>(
        &'a self,
        layout: &[u64],
        field: u64,
        line: u64,
        input: records::Separator,
    ) -> Result<&'a [u8], Failure> {
        self.indexed_field(
            layout,
            &mut records::FieldIndex::default(),
            field,
            line,
            input,
        )
    }
    /// [`Record::field`], locating the fields of an original record through
    /// `fields`, its index.
    fn indexed_field<'a>(
        &'a self,
        layout: &[u64],
        fields: &mut records::FieldIndex,
        field: u64,
        line: u64,
        input: records::Separator,
    ) -> Result<&'a [u8], Failure> {
        if field > self.fields {
            return Err(missing_field(field, line, self.fields));
        }
        if let Some(bytes) = self.original() {
            let span = indexed_field(bytes, fields, field, line, input)?;
            Ok(&bytes[span.start..span.start + span.length])
        } else {
            Ok(self.segment(
                self.key_count()
                    + layout
                        .binary_search(&field)
                        .expect("selected field in projection"),
            ))
        }
    }
}

fn last_selected<S: Storage>(layout: &[u64], keys: &[u64]) -> u64 {
    keys.iter()
        .chain(if S::ORIGINAL { &[][..] } else { layout })
        .copied()
        .max()
        .unwrap_or(0)
}

/// The positions of `keys` in field order (request order among equal
/// keys), so a projection finds every key in one pass over the fields.
fn key_order(keys: &[u64]) -> Result<Vec<usize>, Failure> {
    let mut order = Vec::new();
    order
        .try_reserve_exact(keys.len())
        .map_err(|_| allocation())?;
    order.extend(0..keys.len());
    order.sort_unstable_by_key(|&at| (keys[at], at));
    Ok(order)
}

#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn project<S: Build>(
    bytes: &[u8],
    layout: &[u64],
    keys: &[u64],
    input: records::Separator,
    sequence: u64,
    vnlog: bool,
    ignore_case: bool,
    last_selected: u64,
) -> Result<Record<S>, Failure> {
    project_with_scratch::<S>(
        bytes,
        layout,
        keys,
        input,
        sequence,
        vnlog,
        ignore_case,
        last_selected,
        &mut Vec::new(),
    )
}

#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn project_with_scratch<S: Build>(
    bytes: &[u8],
    layout: &[u64],
    keys: &[u64],
    input: records::Separator,
    sequence: u64,
    vnlog: bool,
    ignore_case: bool,
    last_selected: u64,
    spans: &mut Vec<std::ops::Range<usize>>,
) -> Result<Record<S>, Failure> {
    let data = if vnlog { annotated::data(bytes) } else { bytes };
    let count = project_spans::<S>(
        bytes,
        layout,
        keys,
        &key_order(keys)?,
        input,
        vnlog,
        false,
        last_selected,
        spans,
        None,
    )?;
    Ok(Record::new(
        S::build(bytes, data, spans, keys.len(), ignore_case)?,
        count,
        sequence,
    ))
}

/// Fills `spans` with the projected spans of `bytes`: each key's, then (for
/// packed storage) each layout field's. With `identities`, which must hold one
/// empty span per key, also each key's field span within the data, without the
/// leading blanks or annotation spans that key spans may include. With
/// `zero_terminated` blank-separated records that hold a newline, key spans
/// and identities are the fields `sort -z` finds ([`sort_fields`]) instead.
/// `order` is the keys' [`key_order`]. Returns the record's field count.
#[allow(clippy::too_many_arguments)]
fn project_spans<S: Storage>(
    bytes: &[u8],
    layout: &[u64],
    keys: &[u64],
    order: &[usize],
    input: records::Separator,
    vnlog: bool,
    zero_terminated: bool,
    last_selected: u64,
    spans: &mut Vec<std::ops::Range<usize>>,
    mut identities: Option<&mut [std::ops::Range<usize>]>,
) -> Result<u64, Failure> {
    let data = if vnlog { annotated::data(bytes) } else { bytes };
    let count = keys
        .len()
        .checked_add(if S::ORIGINAL { 0 } else { layout.len() })
        .ok_or_else(allocation)?;
    spans.clear();
    spans.try_reserve_exact(count).map_err(|_| allocation())?;
    spans.resize(count, 0..0);
    let mut count = 0u64;
    let mut previous_end = 0;
    // The next key in field order; keys before the first field (0 for an
    // unresolved name) match no field.
    let mut next = order.partition_point(|&at| keys[at] == 0);
    for span in records::fields(data, input) {
        count = count.checked_add(1).ok_or_else(allocation)?;
        if !S::ORIGINAL
            && let Ok(at) = layout.binary_search(&count)
        {
            spans[keys.len() + at] = span.start..span.start + span.length;
        }
        let start = if input == records::Separator::Whitespace {
            previous_end
        } else {
            span.start
        };
        while let Some(&at) = order.get(next)
            && keys[at] == count
        {
            if !vnlog {
                spans[at] = start..span.start + span.length;
            }
            if let Some(identities) = identities.as_deref_mut() {
                identities[at] = span.start..span.start + span.length;
            }
            next += 1;
        }
        previous_end = span.start + span.length;
        if !vnlog
            && count >= last_selected
            && let records::Separator::Literal(delimiter) = input
        {
            // Remaining delimiters each introduce one field, including a final
            // empty field. No remaining ranges are needed by this projection.
            let remaining = memchr::memchr_iter(delimiter, &data[previous_end..]).count();
            count = count
                .checked_add(u64::try_from(remaining).map_err(|_| allocation())?)
                .ok_or_else(allocation)?;
            break;
        }
    }
    // With `-z`, GNU sort also splits blank-separated keys at a newline
    // (`sort -z` without `-t`), where datamash's fields do not.
    let newline_blanks = zero_terminated && input == records::Separator::Whitespace;
    if vnlog || (newline_blanks && memchr::memchr(b'\n', data).is_some()) {
        // Raw input determines sort keys; annotations are removed only from data.
        let source = if vnlog { bytes } else { data };
        let mut next = order.partition_point(|&at| keys[at] == 0);
        if newline_blanks {
            // A field of newlines alone joins the next sort field, so a key
            // can lie past the last one: its sort key is then empty.
            let end = source.len();
            for &at in &order[next..] {
                spans[at] = end..end;
                if !vnlog && let Some(identities) = identities.as_deref_mut() {
                    identities[at] = end..end;
                }
            }
        }
        let mut place = |index: usize, span: std::ops::Range<usize>| {
            while let Some(&at) = order.get(next)
                && keys[at] == index as u64 + 1
            {
                // A language key's identity is then its sort field, as its
                // field is otherwise: without the blanks before it.
                if !vnlog && let Some(identities) = identities.as_deref_mut() {
                    let blanks = source[span.clone()]
                        .iter()
                        .take_while(|&&b| matches!(b, b' ' | b'\t' | b'\n'))
                        .count();
                    identities[at] = span.start + blanks..span.end;
                }
                spans[at] = span.clone();
                next += 1;
            }
        };
        if newline_blanks {
            for (index, span) in sort_fields(source).enumerate() {
                place(index, span);
            }
        } else {
            let mut previous_end = 0;
            for (index, span) in records::fields(source, input).enumerate() {
                place(index, previous_end..span.start + span.length);
                previous_end = span.start + span.length;
            }
        }
    }
    Ok(count)
}

/// The fields of blank-separated `record` as `sort -z` finds them, each with
/// the blanks before it: a newline is a blank there too.
fn sort_fields(record: &[u8]) -> impl Iterator<Item = std::ops::Range<usize>> + '_ {
    let blank = |b: &u8| matches!(b, b' ' | b'\t' | b'\n');
    let mut end = 0;
    std::iter::from_fn(move || {
        if end == record.len() {
            return None;
        }
        let start = end;
        end += record[end..].iter().take_while(|b| blank(b)).count();
        end += record[end..].iter().take_while(|b| !blank(b)).count();
        Some(start..end)
    })
}

/// The first key field, in field order, that language sorting cannot read.
fn identity_error(
    data: &[u8],
    keys: &[u64],
    identities: &[std::ops::Range<usize>],
) -> Option<Failure> {
    let mut first: Option<(u64, usize, Failure)> = None;
    for (at, span) in identities.iter().enumerate() {
        if first.as_ref().is_some_and(|(key, _, _)| *key <= keys[at]) {
            continue;
        }
        if let Err(error) = locale::text(&data[span.clone()]) {
            first = Some((keys[at], at, error));
        }
    }
    first.map(|(_, _, error)| error)
}

/// A raw Record's language key segments, in `scratch.language` (`bytes`
/// split at `ends`; [`storage::language_segments`]): each key is sorted by
/// its projected key span and identified by its field. Invalid keys are
/// refused in field order. Returns the record's field count.
fn language_keys(
    bytes: &[u8],
    keys: &[u64],
    order: &[usize],
    options: &options::Options,
    collator: &locale::Collator,
    last_selected: u64,
    scratch: &mut batch::Scratch,
) -> Result<u64, Failure> {
    let batch::Scratch {
        spans,
        sort_keys,
        language,
    } = scratch;
    let storage::LanguageScratch {
        identities,
        bytes: out,
        ends,
        text,
    } = language;
    let data = if options.vnlog {
        annotated::data(bytes)
    } else {
        bytes
    };
    identities.clear();
    identities
        .try_reserve_exact(keys.len())
        .map_err(|_| allocation())?;
    identities.resize(keys.len(), 0..0);
    let fields = project_spans::<Original>(
        bytes,
        &[],
        keys,
        order,
        options.input,
        options.vnlog,
        options.record_end == 0,
        last_selected,
        spans,
        Some(identities),
    )?;
    // Annotated key spans come from the raw record, so they are checked
    // separately after the fields. Otherwise a key span is its field, possibly
    // after ASCII blanks, and is valid exactly when the field is.
    if options.vnlog
        && let Some(error) = identity_error(data, keys, identities)
    {
        return Err(error);
    }
    let identities = &*identities;
    storage::language_segments(
        keys.len(),
        |at| match locale::text(&bytes[spans[at].clone()]) {
            Ok(text) => Ok(text),
            Err(error) if options.vnlog => Err(error),
            Err(error) => Err(identity_error(data, keys, identities).unwrap_or(error)),
        },
        |at| &data[identities[at].clone()],
        options.ignore_case,
        collator,
        sort_keys,
        text,
        out,
        ends,
    )?;
    Ok(fields)
}

/// Projects a raw Record for a language sort as the record storage built it
/// (`Build::language`): its key segments (`language_keys`), then the data.
#[cfg(test)]
fn project_language<S: Build>(
    bytes: &[u8],
    keys: &[u64],
    options: &options::Options,
    collator: &locale::Collator,
    last_selected: u64,
    sequence: u64,
    scratch: &mut batch::Scratch,
) -> Result<Record<S>, Failure> {
    let order = key_order(keys)?;
    let fields = language_keys(
        bytes,
        keys,
        &order,
        options,
        collator,
        last_selected,
        scratch,
    )?;
    let data = if options.vnlog {
        annotated::data(bytes)
    } else {
        bytes
    };
    let language = &scratch.language;
    Ok(Record::new(
        S::language(&language.bytes, &language.ends, data)?,
        fields,
        sequence,
    ))
}

/// Which bytes a sorted record keeps whole.
#[derive(Clone, Copy)]
enum Kept {
    /// The data: the record without a vnlog annotation.
    Data,
    /// The raw record, annotation and all (rmdup hands it on).
    Raw,
}

/// Projects a raw Record for a language sort into a chunk body (`spill::encode`):
/// its key segments (`language_keys`), then the kept bytes. Returns its key
/// cache.
#[allow(clippy::too_many_arguments)]
fn language_body(
    bytes: &[u8],
    keys: &[u64],
    order: &[usize],
    options: &options::Options,
    collator: &locale::Collator,
    last_selected: u64,
    kept: Kept,
    scratch: &mut batch::Scratch,
    out: &mut Vec<u8>,
) -> Result<KeyCache, Failure> {
    let fields = language_keys(
        bytes,
        keys,
        order,
        options,
        collator,
        last_selected,
        scratch,
    )?;
    let kept = match kept {
        Kept::Raw => bytes,
        Kept::Data if options.vnlog => annotated::data(bytes),
        Kept::Data => bytes,
    };
    let storage::LanguageScratch {
        bytes: segments,
        ends,
        ..
    } = &scratch.language;
    let payload = segments
        .len()
        .checked_add(kept.len())
        .ok_or_else(allocation)?;
    spill::encode(
        out,
        fields,
        (ends.len() + 1, payload),
        (ends.len(), 0),
        |at| match at.checked_sub(1) {
            _ if at == ends.len() => kept,
            None => &segments[..ends[0]],
            Some(previous) => &segments[ends[previous]..ends[at]],
        },
    )
}

/// Projects a raw Record for a byte-order sort of original records into a
/// chunk body: its key segments (ASCII-uppercased with `-i`) and the kept
/// bytes. Returns its key cache.
#[allow(clippy::too_many_arguments)]
fn bytes_body(
    bytes: &[u8],
    keys: &[u64],
    order: &[usize],
    options: &options::Options,
    last_selected: u64,
    kept: Kept,
    scratch: &mut batch::Scratch,
    out: &mut Vec<u8>,
) -> Result<KeyCache, Failure> {
    let spans = &mut scratch.spans;
    let fields = project_spans::<Original>(
        bytes,
        &[],
        keys,
        order,
        options.input,
        options.vnlog,
        options.record_end == 0,
        last_selected,
        spans,
        None,
    )?;
    let kept = match kept {
        Kept::Raw => bytes,
        Kept::Data if options.vnlog => annotated::data(bytes),
        Kept::Data => bytes,
    };
    let segment = |at: usize| -> &[u8] {
        if at == keys.len() {
            kept
        } else {
            &bytes[spans[at].clone()]
        }
    };
    let mut payload = 0usize;
    for at in 0..=keys.len() {
        payload = payload
            .checked_add(segment(at).len())
            .ok_or_else(allocation)?;
    }
    let fold = if options.ignore_case { keys.len() } else { 0 };
    spill::encode(
        out,
        fields,
        (keys.len() + 1, payload),
        (keys.len(), fold),
        segment,
    )
}

/// Sorts the Records `intake` accepts and hands them on raw, each in turn in
/// the same buffer: rmdup reads a second Input header from them, as GNU does
/// from its sort pipe.
pub(super) fn sorted_rows(
    reader: &mut impl BufRead,
    intake: Intake<'_>,
    options: &options::Options,
    keys: &[u64],
    mut consume: impl FnMut(&mut Vec<u8>) -> Result<(), Failure>,
) -> Result<(), Failure> {
    let mut bytes = Vec::new();
    sorted_records(reader, intake, options, keys, |record, _, phase| {
        if phase == RecordPhase::Consume {
            bytes.clear();
            bytes.try_reserve(record.len()).map_err(|_| allocation())?;
            bytes.extend_from_slice(record);
            consume(&mut bytes)?;
        }
        Ok(())
    })
}

/// Source observation happens before sorting; sorted consumption keeps each
/// Record's original accepted ordinal, including a previously read header.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RecordPhase {
    ObserveSource,
    Consume,
}

pub(super) fn sorted_records(
    reader: &mut (impl BufRead + ?Sized),
    mut intake: Intake<'_>,
    options: &options::Options,
    keys: &[u64],
    mut visit: impl FnMut(&[u8], u64, RecordPhase) -> Result<(), Failure>,
) -> Result<(), Failure> {
    let preceding = intake.line();
    let collator = options.locale.collator()?;
    let target = memory::target(options.sort_memory.as_deref())?;
    let mut bytes = Vec::new();
    let last = last_selected::<Original>(&[], keys);
    let order = key_order(keys)?;
    let order = &order[..];
    let (shape, threads) = match collator {
        Some(_) => (
            spill::Shape::language(keys.len())?,
            fastmash_sort_process::sort_threads() as usize,
        ),
        None => (spill::Shape::original(keys.len())?, 1),
    };
    let mut sorter = sorter::<Original>(target, threads);
    let project =
        |raw: &[u8], scratch: &mut batch::Scratch, out: &mut Vec<u8>| match collator.as_ref() {
            Some(collator) => language_body(
                raw,
                keys,
                order,
                options,
                collator,
                last,
                Kept::Raw,
                scratch,
                out,
            ),
            None => bytes_body(raw, keys, order, options, last, Kept::Raw, scratch, out),
        };
    let mut batch = batch::Batch::new(threads, target.bytes);
    let mut accept = |record: batch::Projected<'_>| sorter.push_body(record, shape);
    while let Some(record) = intake.next(reader, &mut bytes)? {
        visit(record.data(), intake.line(), RecordPhase::ObserveSource)?;
        batch.push(record.raw(), &project, &mut accept)?;
    }
    batch.finish(&project, &mut accept)?;
    // Like the system sort, a sort whose input failed yields no records.
    if intake.read_error().is_some() {
        return intake.finish();
    }
    drop(batch);
    drop(bytes);
    let mut sorted = sorter.finish();
    sorted.emit(|record| {
        let ordinal = preceding
            .checked_add(record.sequence)
            .and_then(|n| n.checked_add(1))
            .ok_or_else(|| unsupported("record count exceeds u64 limit"))?;
        let original = record.data.original().unwrap_or_default();
        visit(original, ordinal, RecordPhase::Consume)
    })
}

fn equal_group<S: Storage>(
    a: &mut Sorted<'_, S>,
    b: &mut Sorted<'_, S>,
    keys: &[u64],
    line: u64,
    options: &options::Options,
) -> Result<bool, Failure> {
    // Byte-order literal keys already retain exactly these field bytes (possibly
    // ASCII-folded). Whitespace, annotations and language keys have other spans
    // or representations, so they must still select the original fields.
    let stored = matches!(options.input, records::Separator::Literal(_))
        && !options.vnlog
        && options.locale.collation == locale::Collation::Bytes;
    for (at, &key) in keys.iter().enumerate() {
        let (a, b) = if stored && key != 0 && key <= a.record.fields && key <= b.record.fields {
            (a.record.segment(at), b.record.segment(at))
        } else {
            // Preserve request-order diagnostics, including the earlier-key
            // mismatch that makes later missing keys irrelevant here.
            (
                a.record
                    .indexed_field(a.layout, &mut a.fields, key, line, options.input)?,
                b.record
                    .indexed_field(b.layout, &mut b.fields, key, line, options.input)?,
            )
        };
        if !text_order::same_group(a, b, options.ignore_case) {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Whether numeric Operations can read packed fields, which hold each field
/// alone. GNU reads a number from the field's start on through the rest of
/// the record (`decimal::number`): an ASCII letter or digit, or the radix
/// point, as the separator continues many numbers into the next field. Any
/// other separator continues only a rare few (`runs_on`), whose numbers the
/// intake reads from the whole record (`Crossings`).
fn packs_numbers(options: &options::Options) -> bool {
    match options.input {
        records::Separator::Whitespace => true,
        records::Separator::Literal(byte) => {
            !byte.is_ascii_alphanumeric() && byte != options.presentation.profile.radix()
        }
    }
}

/// Whether GNU's parse of numeric field `part` might run on past its end into
/// `separator`, one that [`packs_numbers`] admits: a blank or sign separator
/// after a field of blanks (skipped as leading space), a sign after an
/// exponent letter, `(` after `nan`, or `)` or `_` inside `nan(...)`.
fn runs_on(part: &[u8], separator: u8) -> bool {
    let blanks = || {
        !part.is_empty()
            && part
                .iter()
                .all(|&b| matches!(b, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r'))
    };
    match separator {
        b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r' => blanks(),
        b'+' | b'-' => blanks() || matches!(part.last(), Some(b'e' | b'E' | b'p' | b'P')),
        b'(' => matches!(part.last(), Some(b'n' | b'N')),
        b')' | b'_' => part.contains(&b'('),
        _ => false,
    }
}

/// The numbers GNU reads differently from packed fields than from the field
/// alone, by record sequence and field: their outcome as the whole record
/// gives it. Only [`runs_on`] fields can be among them.
type Crossings = std::collections::HashMap<
    (u64, u64),
    Result<Option<numerics::Value>, decimal::NumberError>,
    random::TableState,
>;

/// Records in `crossings` how GNU reads the numeric fields of one record
/// (`data`, sequence `sequence`) whose packed `spans` (at `positions`, by
/// field) it could read differently alone.
fn record_crossings(
    data: &[u8],
    spans: &[std::ops::Range<usize>],
    positions: &[(u64, usize)],
    separator: u8,
    sequence: u64,
    options: &options::Options,
    crossings: &mut Crossings,
) -> Result<(), Failure> {
    for &(field, at) in positions {
        let span = spans[at].clone();
        let part = &data[span.clone()];
        if !runs_on(part, separator) {
            continue;
        }
        let (narm, profile) = (options.narm, options.presentation.profile);
        let whole = decimal::number(
            data,
            field_policy::FieldRange {
                start: span.start,
                length: span.len(),
            },
            narm,
            profile,
        );
        let alone = decimal::number(
            part,
            field_policy::FieldRange {
                start: 0,
                length: part.len(),
            },
            narm,
            profile,
        );
        let same = match (&whole, &alone) {
            (Ok(_), Ok(_)) => true,
            (Err(a), Err(b)) => a.same(b),
            _ => false,
        };
        if !same {
            crossings.try_reserve(1).map_err(|_| allocation())?;
            crossings.insert((sequence, field), whole);
        }
    }
    Ok(())
}

/// A packed record's fields as the Operations read them: numbers from the
/// field alone, except those in `crossings`.
struct Projected<'a, S: Storage> {
    record: &'a Record<S>,
    layout: &'a [u64],
    crossings: &'a Crossings,
    separator: Option<u8>,
}

impl<'a, S: Storage> operation_set::Fields<'a> for Projected<'a, S> {
    #[inline]
    fn text(
        &mut self,
        field: u64,
        line: u64,
        options: &options::Options,
    ) -> Result<&'a [u8], Failure> {
        self.record.field(self.layout, field, line, options.input)
    }
    #[inline]
    fn number(
        &mut self,
        field: u64,
        line: u64,
        options: &options::Options,
    ) -> Result<Option<numerics::Value>, Failure> {
        let part = self.text(field, line, options)?;
        if !self.crossings.is_empty()
            && let Some(separator) = self.separator
            && runs_on(part, separator)
            && let Some(outcome) = self.crossings.get(&(self.record.sequence, field))
        {
            return outcome
                .clone()
                .map_err(|error| error.report(part, field, line));
        }
        decimal::field(
            part,
            field_policy::FieldRange {
                start: 0,
                length: part.len(),
            },
            field,
            line,
            options.narm,
            options.presentation.profile,
        )
    }
}

/// A sorted record with the layout its projected fields follow, the index
/// of an original record's fields, and the numbers GNU would read on past a
/// packed field (`Crossings`).
struct Sorted<'l, S: Storage> {
    record: Record<S>,
    layout: &'l [u64],
    fields: records::FieldIndex,
    crossings: &'l Crossings,
    /// Whether every Operation reads one field's text (`NativeSort::Packed`).
    texts: bool,
}

impl<S: Storage> grouping::GroupRecord for Sorted<'_, S> {
    fn field(&mut self, key: u64, line: u64, options: &options::Options) -> Result<&[u8], Failure> {
        self.record
            .indexed_field(self.layout, &mut self.fields, key, line, options.input)
    }
    fn field_pair(
        &mut self,
        first: u64,
        second: u64,
        line: u64,
        options: &options::Options,
    ) -> Result<(&[u8], &[u8]), Failure> {
        let a =
            self.record
                .indexed_field(self.layout, &mut self.fields, first, line, options.input)?;
        let b = self.record.indexed_field(
            self.layout,
            &mut self.fields,
            second,
            line,
            options.input,
        )?;
        Ok((a, b))
    }
    fn same_group(
        &mut self,
        previous: &mut Self,
        keys: &[u64],
        line: u64,
        options: &options::Options,
    ) -> Result<bool, Failure> {
        equal_group(self, previous, keys, line, options)
    }
    fn original(&self) -> Option<&[u8]> {
        self.record.original()
    }
    fn collect(
        &mut self,
        operations: &mut OperationSet,
        line: u64,
        options: &options::Options,
        arithmetic: &mut numerics::Numerics,
        random: Option<&mut random::RandomState>,
    ) -> Result<bool, Failure> {
        if let Some(bytes) = self.record.original() {
            return operations.collect(bytes, &mut self.fields, line, options, arithmetic, random);
        }
        let separator = match options.input {
            records::Separator::Literal(byte) => Some(byte),
            records::Separator::Whitespace => None,
        };
        operations.collect_fields(
            &mut Projected {
                record: &self.record,
                layout: self.layout,
                crossings: self.crossings,
                separator,
            },
            self.texts,
            line,
            options,
            arithmetic,
        )
    }
}

/// The generated Output header of the first sorted record, which checks each
/// selected field of the original record as it names it.
fn generated_header<W: Write, S: Storage>(
    record: &Record<S>,
    layout: &[u64],
    keys: &[u64],
    operations: &OperationSet,
    options: &options::Options,
    output: &mut command_output::Results<'_, W>,
) -> Result<(), Failure> {
    // Original records (every --full sort among them) render as usual.
    if let Some(bytes) = record.original() {
        return output.first(bytes, operations, keys);
    }
    output.first_projected(
        |field| record.field(layout, field, 1, options.input),
        operations,
        keys,
    )
}

/// Hash grouping of sorted Groups (`-s -g`) with `setting`, for a Command it
/// is eligible for ([`hash_eligible`]): the status of the Command when it
/// wrote the Groups, or `None` when it gave up, having set standard input
/// back to where it started and written nothing, so that the sort runs as if
/// it had not.
pub(super) fn group_by_hash(
    reader: &mut impl replay::Rewind,
    transport: &mut impl command_output::Transport,
    options: &options::Options,
    binding: &mut binding::Binding<'_>,
    arithmetic: &mut numerics::Numerics,
    setting: Grouping,
    report: &mut impl FnMut(&Failure) -> bool,
) -> Result<Option<i32>, Failure> {
    // Settings the sort route reports on its own are left to it.
    let (Ok(target), Ok(collator)) = (
        memory::target(options.sort_memory.as_deref()),
        options.locale.collator(),
    ) else {
        return Ok(None);
    };
    let Some(mark) = reader.mark() else {
        return Ok(None);
    };
    let remaining = reader.length().map(|length| length.saturating_sub(mark));
    let (capacity, line_buffered) = transport.buffering();
    let buffer = buffered_stdout::BufferedStdout::new(transport, capacity, line_buffered)
        .map_err(|e| os_failure(&e, false))?;
    let mut output = command_output::Results::new(buffer, options);
    let result = hash::calculate(
        reader,
        options,
        binding,
        collator.as_ref(),
        arithmetic,
        &mut output,
        target,
        setting,
        remaining,
    );
    if let Ok(hash::Outcome::Restart(_)) = result {
        drop(output);
        // The sort follows; give back what the classes took.
        malloc_arenas::trim();
        reader
            .rewind(mark)
            .map_err(|error| intake::read_failure(&error))?;
        return Ok(None);
    }
    Ok(Some(command_output::complete(
        output.buffer,
        result.map(drop),
        command_output::Transport::close,
        report,
    )))
}

/// Sorts in process, keeping only the selected fields of each record where
/// `packed` ([`packed`]), and runs the Command over the sorted records. The
/// sort's memory leaves room for what the reader still holds (`unread`).
#[allow(clippy::too_many_arguments)]
pub(super) fn run(
    reader: &mut impl BufRead,
    transport: &mut impl command_output::Transport,
    options: &options::Options,
    binding: binding::Binding<'_>,
    arithmetic: &mut numerics::Numerics,
    random: Option<&mut random::RandomState>,
    packed: bool,
    unread: replay::Unread,
    report: &mut impl FnMut(&Failure) -> bool,
) -> Result<i32, Failure> {
    let (capacity, line_buffered) = transport.buffering();
    let buffer = buffered_stdout::BufferedStdout::new(transport, capacity, line_buffered)
        .map_err(|e| os_failure(&e, false))?;
    let mut output = command_output::Results::new(buffer, options);
    let result = if packed {
        calculate_records::<_, Packed>(
            reader,
            options,
            binding,
            arithmetic,
            random,
            unread,
            &mut output,
        )
    } else {
        calculate_records::<_, Original>(
            reader,
            options,
            binding,
            arithmetic,
            random,
            unread,
            &mut output,
        )
    };
    Ok(command_output::complete(
        output.buffer,
        result,
        command_output::Transport::close,
        report,
    ))
}

/// The sorter of a sort of memory target `target` on `threads` projection
/// threads, whose chunk grows as its memory target allows.
fn sorter<S: spill::Codec>(target: memory::Target, threads: usize) -> spill::Sorter<S> {
    spill::Sorter::with_target(target, batch::share(threads, target.bytes))
}

/// Whether a sort keeps only the selected fields (Packed storage): not with
/// --full, which prints whole records, nor in a language locale, whose sorter
/// keeps original records, and for numbers only where [`packs_numbers`].
pub(crate) fn packed(options: &options::Options, native: operation_set::NativeSort) -> bool {
    !options.full
        && !options.locale.language()
        && match native {
            operation_set::NativeSort::Packed => true,
            operation_set::NativeSort::Original => packs_numbers(options),
            operation_set::NativeSort::Unsupported => false,
        }
}
fn calculate_records<W: Write, S: spill::Codec>(
    reader: &mut impl BufRead,
    options: &options::Options,
    mut binding: binding::Binding<'_>,
    arithmetic: &mut numerics::Numerics,
    mut random: Option<&mut random::RandomState>,
    unread: replay::Unread,
    output: &mut command_output::Results<'_, W>,
) -> Result<(), Failure> {
    let target = memory::target(options.sort_memory.as_deref())?;
    let collator = options.locale.collator()?;
    let mut bytes = Vec::new();
    let mut intake =
        Intake::new(options, intake::Header::of(options)).warn_full(options, binding.program);
    if !options.header_in {
        binding.numbered()?;
    }
    // Weighted mean has no calculation domain before the first data Record,
    // even when a requested header never arrives. Only clean EOF can use the
    // ordinary empty pipeline; failed reads retain their intake diagnostic.
    if intake.header(reader, &mut bytes, |header| binding.header(header, options))? {
        output.first(&bytes, &binding.operations, &binding.keys)?;
    } else if options.header_in
        && binding.unresolved_keys()
        && !(binding.operations.has_weighted_mean() && intake.read_error().is_none())
    {
        // An input failure takes precedence over an unresolved named key.
        intake.finish()?;
        return Err(failure(
            b"missing input header for named grouping key\n".to_vec(),
        ));
    }
    let binding::Binding {
        mut operations,
        keys,
        ..
    } = binding;
    let mut layout = Vec::new();
    layout
        .try_reserve_exact(
            keys.len()
                .checked_add(operations.len())
                .ok_or_else(allocation)?,
        )
        .map_err(|_| allocation())?;
    layout.extend_from_slice(&keys);
    for (_, selector) in operations.requests() {
        match selector {
            Selector::Single(field) => layout.push(field),
            Selector::Pair { left, right } => {
                layout.try_reserve(2).map_err(|_| allocation())?;
                layout.extend([left, right]);
            }
        }
    }
    layout.sort_unstable();
    layout.dedup();
    let order = key_order(&keys)?;
    // Original records' fields are looked up for keys and Operations.
    let index = records::FieldIndex::selecting(layout.iter().copied());
    // Language sorts project on several threads: collation keys make that
    // worth its batches.
    let threads = if collator.is_some() {
        fastmash_sort_process::sort_threads() as usize
    } else {
        1
    };
    let mut sorter = sorter::<S>(target, threads);
    sorter.leave_room(unread);
    let mut crossings = Crossings::default();
    let texts = operations.native_sort() == operation_set::NativeSort::Packed;
    match collator.as_ref() {
        // Byte-order sorts: records go straight from the intake into the
        // chunk.
        None => {
            let last = last_selected::<S>(&layout, &keys);
            // Packed numeric fields that GNU could read on past: by field,
            // their positions among a record's spans.
            let mut positions = Vec::new();
            let separator = match options.input {
                records::Separator::Literal(byte) if !S::ORIGINAL => {
                    for field in operations.numeric_fields() {
                        let at = layout
                            .binary_search(&field)
                            .expect("numeric field in projection");
                        positions.try_reserve(1).map_err(|_| allocation())?;
                        positions.push((field, keys.len() + at));
                    }
                    (!positions.is_empty()).then_some(byte)
                }
                _ => None,
            };
            let mut spans = Vec::new();
            let mut sequence = 0u64;
            // Skipped Records never reach key projection.
            while let Some(record) = intake.next(reader, &mut bytes)? {
                let raw = record.raw();
                let data = if options.vnlog {
                    annotated::data(raw)
                } else {
                    raw
                };
                let fields = project_spans::<S>(
                    raw,
                    &layout,
                    &keys,
                    &order,
                    options.input,
                    options.vnlog,
                    options.record_end == 0,
                    last,
                    &mut spans,
                    None,
                )?;
                if let Some(separator) = separator {
                    record_crossings(
                        data,
                        &spans,
                        &positions,
                        separator,
                        sequence,
                        options,
                        &mut crossings,
                    )?;
                }
                sorter.push(
                    raw,
                    data,
                    &spans,
                    keys.len(),
                    options.ignore_case,
                    fields,
                    sequence,
                )?;
                sequence = sequence.checked_add(1).ok_or_else(allocation)?;
            }
        }
        // Language sorts: batches of records are projected on `threads`
        // threads.
        Some(collator) => {
            if !S::ORIGINAL {
                return Err(unsupported(
                    "internal language sorter requires original records",
                ));
            }
            let shape = spill::Shape::language(keys.len())?;
            let last = last_selected::<S>(&layout, &keys);
            let project = |raw: &[u8], scratch: &mut batch::Scratch, out: &mut Vec<u8>| {
                language_body(
                    raw,
                    &keys,
                    &order,
                    options,
                    collator,
                    last,
                    Kept::Data,
                    scratch,
                    out,
                )
            };
            let mut batch = batch::Batch::new(threads, target.bytes);
            let mut accept = |record: batch::Projected<'_>| sorter.push_body(record, shape);
            // Skipped Records never reach key projection.
            while let Some(record) = intake.next(reader, &mut bytes)? {
                batch.push(record.raw(), &project, &mut accept)?;
            }
            batch.finish(&project, &mut accept)?;
        }
    }
    drop(bytes);
    let mut sorted = sorter.finish();
    let mut calculation = grouping::Calculation::new(&keys, options);
    // Line numbers follow the sorted order, as GNU counts the Records it reads
    // back from its sort pipe, so the intake's count (input order) would name
    // the wrong Record; only the Input header keeps its place.
    let mut line = u64::from(options.header_in);
    // The field index for the next record: that of a record grouping no
    // longer holds, else a fresh one.
    let mut spare = None;
    // Like the system sort, a sort whose input failed yields no records.
    if intake.read_error().is_none() {
        sorted.emit(|record| {
            line = line.checked_add(1).ok_or_else(allocation)?;
            if line == 1 && options.header_out && !options.header_in {
                generated_header(&record, &layout, &keys, &operations, options, output)?;
            }
            let mut context = grouping::Context::new(
                &mut operations,
                &keys,
                options,
                arithmetic,
                random.as_deref_mut(),
                output,
            );
            let mut fields = spare.take().unwrap_or_else(|| index.fresh());
            fields.clear();
            let sorted = Sorted {
                record,
                layout: &layout,
                fields,
                crossings: &crossings,
                texts,
            };
            if let Some(unused) = calculation.push(sorted, line, &mut context)? {
                spare = Some(unused.fields);
            }
            Ok(())
        })?;
    }
    let mut context =
        grouping::Context::new(&mut operations, &keys, options, arithmetic, None, output);
    calculation.finish(line, &mut context)?;
    intake.finish()
}

#[cfg(test)]
mod compact_tests {
    use super::*;

    #[test]
    fn native_named_key_failures_finalize_output_and_preserve_read_error_priority() {
        use crate::command_test_support::{Input, Output, command_in};

        struct Closing(Output, Option<i32>);
        impl Write for Closing {
            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
                self.0.write(bytes)
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        impl command_output::Transport for Closing {
            fn buffering(&self) -> (usize, bool) {
                (1, false)
            }
            fn close(&mut self) -> io::Result<()> {
                self.0.closed = true;
                self.1
                    .map_or(Ok(()), |code| Err(io::Error::from_raw_os_error(code)))
            }
        }

        for locale in ["C", "en_US.UTF-8"] {
            for requests in [
                &["-gkey", "sum", "value"][..],
                &["-gkey", "wmean", "value:weight"],
                &["-gkey", "wmean", "value:weight", "dotprod", "value:weight"],
                &["rmdup", "key"],
            ] {
                // C-locale rmdup still has an external route in this slice;
                // the standalone executable checks its native fallback.
                if locale == "C" && requests[0] == "rmdup" {
                    continue;
                }
                let weighted = requests.contains(&"wmean");
                for bytes in [b"".as_slice(), b"#skip\n ;skip\n"] {
                    for read_error in [None, Some(5), Some(9), Some(21)] {
                        for close_error in [None, Some(9), Some(28), Some(5)] {
                            let mut input = Input {
                                bytes,
                                segment: 1,
                                error: read_error,
                            };
                            let mut output = Closing(
                                Output {
                                    bytes: Vec::new(),
                                    error: None,
                                    closed: false,
                                },
                                close_error,
                            );
                            let mut args = vec!["-sCH"];
                            args.extend_from_slice(requests);
                            let environment = Environment {
                                locale: locale::Policy::resolve(|key| {
                                    (key == "LC_ALL").then(|| locale.into())
                                }),
                                posixly_correct: false,
                                grouping: Some("sort".into()),
                                sort_memory: Some("1".into()),
                                pipe_grouping: None,
                                terminal: Default::default(),
                            };
                            let (status, diagnostics) =
                                command_in(&mut input, &mut output, &args, environment);
                            let mut expected = Vec::new();
                            match read_error {
                                Some(5) => {
                                    expected.push(b"read error: Input/output error\n".to_vec())
                                }
                                Some(9) => {
                                    expected.push(b"read error: Bad file descriptor\n".to_vec())
                                }
                                Some(21) => expected.push(b"read error: Is a directory\n".to_vec()),
                                None if !weighted => expected.push(
                                    b"missing input header for named grouping key\n".to_vec(),
                                ),
                                _ => {}
                            }
                            match close_error {
                                Some(28) => expected
                                    .push(b"write error: No space left on device\n".to_vec()),
                                Some(5) => {
                                    expected.push(b"unsupported output I/O error\n".to_vec())
                                }
                                _ => {}
                            }
                            assert_eq!(
                                diagnostics, expected,
                                "{locale}, {args:?}, read {read_error:?}, close {close_error:?}"
                            );
                            assert_eq!(
                                status,
                                if close_error == Some(5) {
                                    77
                                } else {
                                    i32::from(!expected.is_empty())
                                }
                            );
                            assert!(output.0.bytes.is_empty());
                            assert!(output.0.closed);
                        }
                    }
                }
            }
        }
    }

    fn calculation_options() -> Box<options::Options> {
        let options::Action::Calculate(options) =
            options::parse(&["count".into(), "1".into()], b"fastmash", false)
                .ok()
                .unwrap()
        else {
            panic!("calculation")
        };
        options
    }
    fn language_record(
        bytes: &[u8],
        keys: &[u64],
        options: &options::Options,
        collator: &locale::Collator,
        scratch: &mut batch::Scratch,
    ) -> Result<Record<Original>, Failure> {
        project_language::<Original>(
            bytes,
            keys,
            options,
            collator,
            last_selected::<Original>(&[], keys),
            3,
            scratch,
        )
    }
    /// A sorted record's sequence, field count and segments.
    fn described<T: Storage>(record: &Record<T>, segments: usize) -> (u64, u64, Vec<Vec<u8>>) {
        (
            record.sequence,
            record.fields,
            (0..segments)
                .map(|at| record.data.segment(at).to_vec())
                .collect(),
        )
    }
    /// Language records projected in batches on any thread count into chunks
    /// at any target emit the order of the record comparator (stable sort)
    /// over independently built language records.
    #[test]
    fn language_chunks_emit_the_record_comparator_order() {
        let words: &[&str] = &[
            "apple",
            "Apple",
            "APPLE",
            "\u{e9}clair",
            "Eclair",
            "e\u{301}clair",
            "stra\u{df}e",
            "Strasse",
            "\u{f6}lfeld",
            "Olfeld",
            "a-b",
            "ab",
            "a b",
            "",
            "k01",
            "k1",
            "angstrom",
            "\u{c5}ngstr\u{f6}m",
            "caf\u{e9}",
            "cafe",
            "\u{1f600}",
        ];
        let mut state = 7u64;
        let mut next = |bound: usize| {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (state >> 33) as usize % bound
        };
        let long = "x".repeat(70);
        let rows: Vec<Vec<u8>> = (0..1200)
            .map(|at| {
                // Dates share long collation key prefixes, in groups large
                // enough for word rounds.
                let date = format!("2026-09-{:02}", 1 + next(28));
                let key = if at % 97 == 0 {
                    long.as_str()
                } else if at % 3 == 0 {
                    date.as_str()
                } else {
                    words[next(words.len())]
                };
                format!("{key}\t{}\t{}", next(9), words[next(words.len())]).into_bytes()
            })
            .collect();
        let mut options = calculation_options();
        for tag in ["en-US", "de-DE"] {
            options.locale.collation = locale::Collation::Language(tag);
            let collator = options.locale.collator().ok().unwrap().unwrap();
            for fold in [false, true] {
                options.ignore_case = fold;
                for keys in [&[1u64][..], &[3, 1][..]] {
                    let last = last_selected::<Original>(&[], keys);
                    let shape = spill::Shape::language(keys.len()).ok().unwrap();
                    let segments = 2 * keys.len() + 1;
                    let mut scratch = batch::Scratch::default();
                    let mut records: Vec<Record<Original>> = rows
                        .iter()
                        .enumerate()
                        .map(|(sequence, row)| {
                            project_language::<Original>(
                                row,
                                keys,
                                &options,
                                &collator,
                                last,
                                sequence as u64,
                                &mut scratch,
                            )
                            .ok()
                            .unwrap()
                        })
                        .collect();
                    records.sort_by(Record::compare);
                    let expected: Vec<_> =
                        records.iter().map(|row| described(row, segments)).collect();
                    for target in [usize::MAX, 1 << 16, 4096, 1] {
                        for threads in [1, 3] {
                            let mut sorter = spill::Sorter::<Original>::new(
                                target,
                                batch::share(threads, target),
                            );
                            let order = key_order(keys).ok().unwrap();
                            let project =
                                |raw: &[u8], scratch: &mut batch::Scratch, out: &mut Vec<u8>| {
                                    language_body(
                                        raw,
                                        keys,
                                        &order,
                                        &options,
                                        &collator,
                                        last,
                                        Kept::Data,
                                        scratch,
                                        out,
                                    )
                                };
                            let mut accept =
                                |record: batch::Projected<'_>| sorter.push_body(record, shape);
                            let mut batch = batch::Batch::new(threads, target);
                            for row in &rows {
                                batch.push(row, &project, &mut accept).ok().unwrap();
                            }
                            batch.finish(&project, &mut accept).ok().unwrap();
                            let mut actual = Vec::new();
                            sorter
                                .finish()
                                .emit(|record| {
                                    actual.push(described(&record, segments));
                                    Ok(())
                                })
                                .ok()
                                .unwrap();
                            assert!(
                                actual == expected,
                                "{tag} fold {fold} keys {keys:?} target {target} threads {threads}"
                            );
                            // Every chunk of several records spilled within
                            // its part of the target, beside the batches'
                            // share and the run buffers.
                            let part = spill::chunk_memory(target, batch::share(threads, target));
                            assert!(spill::spilled_memory() <= part);
                        }
                    }
                }
            }
        }
    }
    #[test]
    fn language_records_do_not_keep_the_byte_key_cache() {
        let mut options = calculation_options();
        options.locale.collation = locale::Collation::Language("en-US");
        let collator = options.locale.collator().ok().unwrap().unwrap();
        let mut rows = Vec::new();
        for bytes in [b"a".as_slice(), b"A", b"ab", b"a-b"] {
            let row = language_record(
                bytes,
                &[1],
                &options,
                &collator,
                &mut batch::Scratch::default(),
            )
            .ok()
            .unwrap();
            assert_eq!(row.key_count(), 2);
            assert_eq!(row.short_key_len, 9);
            rows.push(row);
        }
        for a in &rows {
            for b in &rows {
                assert_eq!(a.compare(b), a.data.compare_keys(&b.data));
            }
        }
    }
    /// Language key segments as the former two-step build made them: a byte
    /// projection, then identity fields checked and copied in field order,
    /// then each key segment's text checked and its sort key computed, each
    /// followed by its identity.
    fn former_language_segments(
        bytes: &[u8],
        keys: &[u64],
        options: &options::Options,
        collator: &locale::Collator,
    ) -> Result<(Vec<Vec<u8>>, u64), Failure> {
        let record = project::<Original>(
            bytes,
            &[],
            keys,
            options.input,
            0,
            options.vnlog,
            options.ignore_case,
            last_selected::<Original>(&[], keys),
        )?;
        let data = if options.vnlog {
            annotated::data(bytes)
        } else {
            bytes
        };
        let mut identity = vec![Vec::new(); keys.len()];
        for (index, span) in records::fields(data, options.input).enumerate() {
            for (at, key) in keys.iter().enumerate() {
                if *key == index as u64 + 1 {
                    let field = &data[span.start..span.start + span.length];
                    locale::text(field)?;
                    identity[at] = field.to_vec();
                    if options.ignore_case {
                        identity[at].make_ascii_lowercase();
                    }
                }
            }
        }
        let composed = |text: &str| {
            let mut out = String::new();
            locale::compose(text, &mut out).ok().unwrap().then_some(out)
        };
        let mut segments = Vec::new();
        assert_eq!(identity.len(), record.key_count());
        for (at, field) in identity.iter().enumerate() {
            let text = locale::text(record.segment(at))?;
            let text = composed(text).unwrap_or_else(|| text.to_owned());
            let mut key = Vec::new();
            assert!(collator.write_key(&text, &mut key).is_ok());
            segments.push(key);
            // The identity is read uppercased with -i, composed, placed and
            // lowercased.
            let mut read = std::str::from_utf8(field).unwrap().to_owned();
            if options.ignore_case {
                read.make_ascii_uppercase();
            }
            if let Some(read_composed) = composed(&read) {
                read = read_composed;
            }
            let mut written = Vec::new();
            if !collator.write_identity(&read, &mut written).ok().unwrap() {
                written = read.into_bytes();
            }
            if options.ignore_case {
                written.make_ascii_lowercase();
            }
            segments.push(written);
        }
        segments.push(record.original().unwrap().to_vec());
        Ok((segments, record.fields))
    }
    #[test]
    fn language_records_equal_the_former_two_step_build() {
        let pieces: &[&[u8]] = &[
            b"a",
            b"A",
            b"b",
            b"k01",
            b"\xc3\xa9",
            b"E\xcc\x81",
            b"\xc3\x9f",
            b"-",
            b" ",
            b"\t",
            b",",
            b"#",
            b"\0",
            b"\xff",
            b"\xc3",
            b"\xf0\x9f\x98\x80",
            b"z",
            b"Z",
            "\u{438}\u{306}".as_bytes(),
            "\u{439}".as_bytes(),
            "L\u{b7}".as_bytes(),
            "l\u{b7}".as_bytes(),
            "\u{401}".as_bytes(),
            "\u{415}\u{308}".as_bytes(),
            "\u{ed}".as_bytes(),
            "i\u{301}".as_bytes(),
        ];
        let key_sets: &[&[u64]] = &[&[1], &[2], &[2, 1], &[1, 3, 1], &[4], &[3, 2]];
        let mut state = 143u64;
        let mut next = |bound: usize| {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (state >> 33) as usize % bound
        };
        let mut options = calculation_options();
        let mut scratch = batch::Scratch::default();
        let (mut accepted, mut refused) = (0, 0);
        for tag in ["en-US", "de-DE"] {
            options.locale.collation = locale::Collation::Language(tag);
            let collator = options.locale.collator().ok().unwrap().unwrap();
            for _ in 0..6000 {
                let mut bytes = Vec::new();
                for _ in 0..next(12) {
                    bytes.extend_from_slice(pieces[next(pieces.len())]);
                }
                options.input = [
                    records::Separator::Literal(b'\t'),
                    records::Separator::Literal(b','),
                    records::Separator::Whitespace,
                ][next(3)];
                options.vnlog = next(4) == 0;
                options.ignore_case = next(2) == 0;
                let keys = key_sets[next(key_sets.len())];
                let expected = former_language_segments(&bytes, keys, &options, &collator);
                let observed = language_record(&bytes, keys, &options, &collator, &mut scratch);
                match (expected, observed) {
                    (Ok((segments, fields)), Ok(record)) => {
                        accepted += 1;
                        let stored = record.data.segments.count();
                        assert_eq!(stored, segments.len(), "{bytes:?}");
                        for (at, segment) in segments.iter().enumerate() {
                            assert_eq!(record.segment(at), segment, "{bytes:?} {at}");
                        }
                        assert_eq!(record.fields, fields);
                        assert_eq!(
                            (record.prefix, record.short_key_len),
                            Record::key_cache(&record.data)
                        );
                    }
                    (Err(expected), Err(observed)) => {
                        refused += 1;
                        assert_eq!(expected.message, observed.message, "{bytes:?} {keys:?}");
                    }
                    (expected, observed) => panic!(
                        "{bytes:?} {keys:?}: {:?} vs {:?}",
                        expected.map(|_| ()).map_err(|e| e.message),
                        observed.map(|_| ()).map_err(|e| e.message)
                    ),
                }
            }
        }
        assert!(accepted > 2000 && refused > 2000, "{accepted} {refused}");
    }
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn short_key_cache_preserves_record_footprint() {
        assert_eq!(std::mem::size_of::<Record<Original>>(), 64);
        assert_eq!(std::mem::size_of::<Record<Packed>>(), 72);
    }
    fn stored_group_equivalence<S: Build>() {
        let options::Action::Calculate(mut options) =
            options::parse(&["count".into(), "1".into()], b"fastmash", false)
                .ok()
                .unwrap()
        else {
            panic!("calculation")
        };
        let inputs: &[&[u8]] = &[
            b"",
            b"a",
            b"A",
            b"a\tb\t",
            b"A\tb\t",
            b"z\tc",
            b"a\0x\tb",
            b"a\0y\tb",
            b"a\0yy\tb",
            b"\xff\t\xfe",
        ];
        for delimiter in [0, b'\t', b'.', 0xff] {
            options.input = records::Separator::Literal(delimiter);
            for fold in [false, true] {
                options.ignore_case = fold;
                for keys in [vec![1], vec![2, 1, 2], vec![1, 3], vec![3, 1]] {
                    let layout = vec![1, 2, 3];
                    for &left in inputs {
                        for &right in inputs {
                            let make = |bytes| {
                                project::<S>(
                                    bytes,
                                    &layout,
                                    &keys,
                                    options.input,
                                    0,
                                    false,
                                    fold,
                                    last_selected::<S>(&layout, &keys),
                                )
                                .ok()
                                .unwrap()
                            };
                            let a = make(left);
                            let b = make(right);
                            let old = || -> Result<bool, Failure> {
                                for &key in &keys {
                                    if !text_order::same_group(
                                        a.field(&layout, key, 7, options.input)?,
                                        b.field(&layout, key, 7, options.input)?,
                                        fold,
                                    ) {
                                        return Ok(false);
                                    }
                                }
                                Ok(true)
                            };
                            let expected = old().map_err(|e| e.message);
                            let crossings = Crossings::default();
                            for keep in [false, true] {
                                let sorted = |bytes| Sorted {
                                    record: make(bytes),
                                    layout: &layout,
                                    fields: if keep {
                                        records::FieldIndex::always_keeping(layout.iter().copied())
                                    } else {
                                        records::FieldIndex::default()
                                    },
                                    crossings: &crossings,
                                    texts: false,
                                };
                                let (mut a, mut b) = (sorted(left), sorted(right));
                                assert_eq!(
                                    equal_group(&mut a, &mut b, &keys, 7, &options)
                                        .map_err(|e| e.message),
                                    expected
                                );
                            }
                        }
                    }
                }
            }
        }
    }
    #[test]
    fn stored_group_keys_preserve_raw_comparison_and_missing_error_order() {
        stored_group_equivalence::<Original>();
        stored_group_equivalence::<Packed>();
    }
    fn tail_counts<S: Build>() {
        for delimiter in [0, b'\t', b',', b' ', 0xff] {
            let input = records::Separator::Literal(delimiter);
            for length in [0, 1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 4097] {
                let mut raw = vec![b'x'; length];
                for at in (0..length).step_by(3) {
                    raw[at] = delimiter;
                }
                for (layout, keys) in [
                    (vec![1, 2], vec![1]),
                    (vec![1, 2, 4], vec![3, 1, 3]),
                    (vec![1, 2, 9000], vec![1]),
                    (vec![2], vec![9000]),
                    (vec![2], vec![]),
                ] {
                    let optimized = project::<S>(
                        &raw,
                        &layout,
                        &keys,
                        input,
                        0,
                        false,
                        false,
                        last_selected::<S>(&layout, &keys),
                    )
                    .ok()
                    .unwrap();
                    // An unreachable selected index forces the existing full
                    // field walk, independently of delimiter counting.
                    let full = project::<S>(&raw, &layout, &keys, input, 0, false, false, u64::MAX)
                        .ok()
                        .unwrap();
                    assert_eq!(optimized.fields, full.fields);
                    assert_eq!(optimized.compare(&full), Ordering::Equal);
                    assert_eq!(optimized.original(), full.original());
                    for field in layout.iter().copied().chain([9001]) {
                        let observed = optimized
                            .field(&layout, field, 7, input)
                            .map_err(|e| (e.status, e.message));
                        let expected = full
                            .field(&layout, field, 7, input)
                            .map_err(|e| (e.status, e.message));
                        assert_eq!(observed, expected);
                    }
                }
            }
        }
    }
    #[test]
    fn unused_tail_keeps_fields_keys_payloads_and_missing_field_errors() {
        tail_counts::<Packed>();
        tail_counts::<Original>();
    }

    fn boundaries<S: Build>() {
        let layout = [1, 2, 3, 4];
        let input = records::Separator::Literal(b'\t');
        let row = project::<S>(
            b"aB\t\t\0\xff",
            &layout,
            &[3, 1, 3, 4],
            input,
            7,
            false,
            true,
            last_selected::<S>(&layout, &[3, 1, 3, 4]),
        )
        .ok()
        .unwrap();
        assert_eq!(row.segment(0), b"\0\xff");
        assert_eq!(row.segment(1), b"AB");
        assert_eq!(row.segment(2), b"\0\xff");
        assert_eq!(row.segment(3), b"");
        assert_eq!(row.field(&layout, 1, 8, input).ok().unwrap(), b"aB");
        assert_eq!(row.field(&layout, 2, 8, input).ok().unwrap(), b"");
        assert!(row.field(&layout, 4, 8, input).is_err());
        if S::ORIGINAL {
            assert_eq!(row.original(), Some(b"aB\t\t\0\xff".as_slice()));
        }
        let make = |raw: &[u8], keys: &[u64], sequence| {
            project::<S>(
                raw,
                &[1, 2],
                keys,
                input,
                sequence,
                false,
                false,
                last_selected::<S>(&[1, 2], keys),
            )
            .ok()
            .unwrap()
        };
        let a = make(b"a\tbc", &[1, 2], 1);
        let b = make(b"ab\tc", &[1, 2], 0);
        let short = make(b"a\tbc", &[1], 9);
        let tied = make(b"a\tbc", &[1, 2], 2);
        assert_eq!(a.compare(&b), Ordering::Less);
        assert_eq!(short.compare(&a), Ordering::Less);
        assert_eq!(a.compare(&tied), Ordering::Less);
        assert_eq!(a.compare(&a), Ordering::Equal);
        assert_eq!(b.compare(&a), Ordering::Greater);
    }
    #[test]
    fn projection_preserves_distinct_keys_and_raw_payloads() {
        boundaries::<Packed>();
        boundaries::<Original>();
    }
    fn annotated<S: Build>() {
        let row = project::<S>(
            b"  aB  cD # note",
            &[1, 2, 3],
            &[2, 3, 1],
            records::Separator::Whitespace,
            0,
            true,
            true,
            last_selected::<S>(&[1, 2, 3], &[2, 3, 1]),
        )
        .ok()
        .unwrap();
        assert_eq!(row.segment(0), b"  CD");
        assert_eq!(row.segment(1), b" #");
        assert_eq!(row.segment(2), b"  AB");
        assert_eq!(row.fields, 2);
        assert_eq!(
            row.field(&[1, 2, 3], 2, 1, records::Separator::Whitespace)
                .ok()
                .unwrap(),
            b"cD"
        );
        if S::ORIGINAL {
            assert_eq!(row.original(), Some(b"  aB  cD".as_slice()));
        }
    }
    #[test]
    fn whitespace_and_vnlog_keep_raw_keys_separate() {
        annotated::<Packed>();
        annotated::<Original>();
    }
    fn reusable_projection<S: spill::Codec + Build>() {
        let mut scratch = Vec::new();
        let keys = [3, 1, 3, 4];
        let layout = [1, 2, 3, 4];
        let mut rows = Vec::new();
        for (sequence, bytes) in [b"b\t2\tx".as_slice(), b"a", b"\t\t\t"]
            .into_iter()
            .enumerate()
        {
            rows.push(
                project_with_scratch::<S>(
                    bytes,
                    &layout,
                    &keys,
                    records::Separator::Literal(b'\t'),
                    sequence as u64,
                    false,
                    true,
                    last_selected::<S>(&layout, &keys),
                    &mut scratch,
                )
                .ok()
                .unwrap(),
            );
        }
        assert_eq!(
            (
                rows[0].segment(0),
                rows[0].segment(1),
                rows[0].segment(2),
                rows[0].segment(3)
            ),
            (
                b"X".as_slice(),
                b"B".as_slice(),
                b"X".as_slice(),
                b"".as_slice()
            )
        );
        assert_eq!(
            (rows[1].segment(0), rows[1].segment(1), rows[1].segment(2)),
            (b"".as_slice(), b"A".as_slice(), b"".as_slice())
        );
        assert!((0..4).all(|at| rows[2].segment(at).is_empty()));
        assert_eq!(
            rows[0]
                .field(&layout, 3, 1, records::Separator::Literal(b'\t'))
                .ok()
                .unwrap(),
            b"x"
        );
        assert!(
            rows[1]
                .field(&layout, 3, 2, records::Separator::Literal(b'\t'))
                .is_err()
        );
        // Reconstruct the established spill payload independently of storage.
        let segments: Vec<&[u8]> = if S::ORIGINAL {
            vec![b"X", b"B", b"X", b"", b"b\t2\tx"]
        } else {
            vec![b"X", b"B", b"X", b"", b"b", b"2", b"x", b""]
        };
        // Storage, key and segment counts; sequence delta 0, three fields; the
        // one-byte lengths; the concatenated segments.
        let mut expected = vec![u8::from(S::ORIGINAL), 4, segments.len() as u8, 0, 3];
        expected.extend(segments.iter().map(|value| value.len() as u8));
        for value in &segments {
            expected.extend_from_slice(value);
        }
        assert_eq!(spill::encode_one(&rows[0]), expected);
        let decoded = spill::decode_one::<S>(&expected).ok().unwrap();
        for (at, bytes) in segments.iter().enumerate() {
            assert_eq!(decoded.segment(at), *bytes);
        }
    }
    #[test]
    fn projection_scratch_does_not_leak_fields_or_change_spill_payloads() {
        reusable_projection::<Original>();
        reusable_projection::<Packed>();
    }
    /// Key and identity spans as the former projection found them: every
    /// key compared with every field.
    fn former_key_spans(
        bytes: &[u8],
        keys: &[u64],
        input: records::Separator,
        vnlog: bool,
    ) -> (Vec<std::ops::Range<usize>>, Vec<std::ops::Range<usize>>) {
        let data = if vnlog { annotated::data(bytes) } else { bytes };
        let (mut spans, mut identities) = (vec![0..0; keys.len()], vec![0..0; keys.len()]);
        let mut previous_end = 0;
        for (index, span) in records::fields(data, input).enumerate() {
            let start = if input == records::Separator::Whitespace {
                previous_end
            } else {
                span.start
            };
            for (at, &key) in keys.iter().enumerate() {
                if key == index as u64 + 1 {
                    if !vnlog {
                        spans[at] = start..span.start + span.length;
                    }
                    identities[at] = span.start..span.start + span.length;
                }
            }
            previous_end = span.start + span.length;
        }
        if vnlog {
            let mut previous_end = 0;
            for (index, span) in records::fields(bytes, input).enumerate() {
                for (at, &key) in keys.iter().enumerate() {
                    if key == index as u64 + 1 {
                        spans[at] = previous_end..span.start + span.length;
                    }
                }
                previous_end = span.start + span.length;
            }
        }
        (spans, identities)
    }
    #[test]
    fn keys_in_any_order_project_as_every_key_against_every_field() {
        let mut state = 147u64;
        let mut next = |bound: usize| {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (state >> 33) as usize % bound
        };
        for input in [
            records::Separator::Literal(b'\t'),
            records::Separator::Whitespace,
        ] {
            for vnlog in [false, true] {
                for _ in 0..3000 {
                    let mut bytes = Vec::new();
                    for at in 0..next(14) {
                        let blanks = [" ", "  ", "\t", " \t"][next(4)];
                        match input {
                            records::Separator::Literal(_) if at > 0 => bytes.push(b'\t'),
                            records::Separator::Whitespace if at > 0 || next(2) == 0 => {
                                bytes.extend_from_slice(blanks.as_bytes())
                            }
                            _ => {}
                        }
                        bytes.extend_from_slice(format!("f{}", next(100)).as_bytes());
                    }
                    if vnlog && next(2) == 0 {
                        bytes.extend_from_slice(b" # note");
                    }
                    let keys: Vec<u64> = (0..next(8)).map(|_| next(16) as u64).collect();
                    let order = key_order(&keys).ok().unwrap();
                    let (mut spans, mut identities) = (Vec::new(), vec![0..0; keys.len()]);
                    let last = last_selected::<Original>(&[], &keys);
                    let fields = project_spans::<Original>(
                        &bytes,
                        &[],
                        &keys,
                        &order,
                        input,
                        vnlog,
                        false,
                        last,
                        &mut spans,
                        Some(&mut identities),
                    )
                    .ok()
                    .unwrap();
                    let data = if vnlog {
                        annotated::data(&bytes)
                    } else {
                        &bytes
                    };
                    assert_eq!(fields, records::fields(data, input).count() as u64);
                    assert_eq!(
                        (spans, identities),
                        former_key_spans(&bytes, &keys, input, vnlog),
                        "{bytes:?} {keys:?} {vnlog}"
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod packed_number_tests {
    use super::*;
    use operation_set::{Fields, NativeSort, Whole};

    fn options(separator: u8, narm: bool) -> Box<options::Options> {
        let options::Action::Calculate(mut options) =
            options::parse(&["sum".into(), "2".into()], b"fastmash", false)
                .ok()
                .unwrap()
        else {
            panic!("calculation")
        };
        options.input = records::Separator::Literal(separator);
        options.narm = narm;
        options
    }

    fn outcome(result: Result<Option<numerics::Value>, Failure>) -> String {
        match result {
            Ok(value) => format!("ok {value:?}"),
            Err(error) => format!(
                "err {} {}",
                error.status,
                String::from_utf8_lossy(&error.message)
            ),
        }
    }

    #[test]
    fn numbers_pack_unless_the_separator_can_continue_them() {
        for (separator, packs) in [
            (b'\t', true),
            (b' ', true),
            (b',', true),
            (b'+', true),
            (b'(', true),
            (b'e', false),
            (b'X', false),
            (b'1', false),
            (b'.', false),
        ] {
            let mut options = options(separator, false);
            assert_eq!(packed(&options, NativeSort::Original), packs, "{separator}");
            assert!(packed(&options, NativeSort::Packed));
            assert!(!packed(&options, NativeSort::Unsupported));
            options.full = true;
            assert!(!packed(&options, NativeSort::Original));
            assert!(!packed(&options, NativeSort::Packed));
        }
    }

    /// A number read from its packed field, with the intake's crossings, is
    /// the one GNU reads on from the field through the whole record, for every
    /// separator that packs numbers and fields its parse might run on past.
    #[test]
    fn packed_numbers_read_as_whole_records_do() {
        let blanks = " ".repeat(600);
        let blanks_exponent = format!("{}1e", " ".repeat(510));
        let long_nan = format!("nan({}", "a".repeat(600));
        let parts: [&[u8]; 33] = [
            b"",
            b" ",
            b"\t",
            b"\r",
            b"\x0b\x0c",
            blanks.as_bytes(),
            blanks_exponent.as_bytes(),
            b"1",
            b"-2.5",
            b"1e",
            b"1E",
            b"0x1p",
            b"0x1P",
            b"12e",
            b"nan",
            b"NaN",
            b"-nan",
            b"nan(",
            b"nan(ab",
            long_nan.as_bytes(),
            b"inf",
            b"NA",
            b"N/A",
            b"+",
            b"-",
            b"  7",
            b"7  ",
            b"1.5",
            b"1,5",
            b"99999999999999999999999",
            b"1e99999",
            b"5x",
            b"0x",
        ];
        let rests: [&[u8]; 13] = [
            b"", b"5", b"+5", b"-5", b"1e99999", b"(abc)", b"abc)", b"_d)", b" 7", b"\t8", b"e5",
            b")", b"  \t  6",
        ];
        let keys = [1u64];
        let layout = [1u64, 2];
        let order = key_order(&keys).ok().unwrap();
        let last = last_selected::<Packed>(&layout, &keys);
        let mut checked = 0usize;
        for separator in 1u8..=u8::MAX {
            if separator == b'\n' || !packs_numbers(&options(separator, false)) {
                continue;
            }
            for narm in [false, true] {
                let options = options(separator, narm);
                for part in parts {
                    if part.contains(&separator) {
                        continue;
                    }
                    for rest in rests {
                        let mut record = b"k".to_vec();
                        record.push(separator);
                        record.extend_from_slice(part);
                        record.push(separator);
                        record.extend_from_slice(rest);
                        let whole = Whole {
                            record: &record,
                            index: &mut records::FieldIndex::selecting([1, 2].into_iter()),
                        }
                        .number(2, 1, &options);
                        let mut spans = Vec::new();
                        let fields = project_spans::<Packed>(
                            &record,
                            &layout,
                            &keys,
                            &order,
                            options.input,
                            false,
                            false,
                            last,
                            &mut spans,
                            None,
                        )
                        .ok()
                        .unwrap();
                        let mut crossings = Crossings::default();
                        record_crossings(
                            &record,
                            &spans,
                            &[(2, keys.len() + 1)],
                            separator,
                            7,
                            &options,
                            &mut crossings,
                        )
                        .ok()
                        .unwrap();
                        let packed = project::<Packed>(
                            &record,
                            &layout,
                            &keys,
                            options.input,
                            7,
                            false,
                            false,
                            last,
                        )
                        .ok()
                        .unwrap();
                        assert_eq!(packed.fields, fields);
                        let got = Projected {
                            record: &packed,
                            layout: &layout,
                            crossings: &crossings,
                            separator: Some(separator),
                        }
                        .number(2, 1, &options);
                        assert_eq!(
                            outcome(got),
                            outcome(whole),
                            "separator {separator:#04x}, narm {narm}, field {:?}, rest {:?}",
                            String::from_utf8_lossy(part),
                            String::from_utf8_lossy(rest)
                        );
                        checked += 1;
                    }
                }
            }
        }
        assert!(checked > 100_000, "{checked}");
    }
}