fcoreutils 0.22.0

High-performance GNU coreutils replacement with SIMD and parallelism
Documentation
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
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
use memchr::memchr_iter;
use std::io::{self, BufRead, IoSlice, Write};

/// Minimum file size for parallel processing (4MB).
/// Files above this threshold use rayon parallel chunked processing.
/// Lowered from 32MB to enable parallelism on benchmark-sized (~7MB) inputs.
/// Rayon pre-init in main() eliminates the 300-500us cold-start penalty.
const PARALLEL_THRESHOLD: usize = 4 * 1024 * 1024;

/// Max iovec entries per writev call (Linux default).
const MAX_IOV: usize = 1024;

/// Input chunk size for sequential processing. 8MB ensures benchmark-sized
/// (~7MB) inputs process in a single pass, avoiding chunk-boundary overhead.
/// Reduces write_all syscalls (~2 calls for 10MB vs ~40 at 256KB).
const SEQ_CHUNK: usize = 8 * 1024 * 1024;

/// Process data in newline-aligned chunks, writing each chunk's output immediately.
/// Avoids allocating a full-size output buffer (e.g. 12MB for 11MB input).
fn process_chunked(
    data: &[u8],
    line_delim: u8,
    out: &mut impl Write,
    mut process_fn: impl FnMut(&[u8], &mut Vec<u8>),
) -> io::Result<()> {
    // Fast path: data fits in one chunk, skip chunk-boundary scanning entirely.
    if data.len() <= SEQ_CHUNK {
        let mut buf = Vec::with_capacity(data.len() + 256);
        process_fn(data, &mut buf);
        if !buf.is_empty() {
            out.write_all(&buf)?;
        }
        return Ok(());
    }
    let mut buf = Vec::with_capacity(SEQ_CHUNK * 2);
    let mut start = 0;
    while start < data.len() {
        let end = if start + SEQ_CHUNK >= data.len() {
            data.len()
        } else {
            match memchr::memrchr(line_delim, &data[start..start + SEQ_CHUNK]) {
                Some(pos) => start + pos + 1,
                None => (start + SEQ_CHUNK).min(data.len()),
            }
        };
        buf.clear();
        process_fn(&data[start..end], &mut buf);
        if !buf.is_empty() {
            out.write_all(&buf)?;
        }
        start = end;
    }
    Ok(())
}

/// Configuration for cut operations.
pub struct CutConfig<'a> {
    pub mode: CutMode,
    pub ranges: &'a [Range],
    pub complement: bool,
    pub delim: u8,
    pub output_delim: &'a [u8],
    pub suppress_no_delim: bool,
    pub line_delim: u8,
}

/// A range specification like 1, 3-5, -3, 4-
#[derive(Debug, Clone)]
pub struct Range {
    pub start: usize, // 1-based, 0 means "from beginning"
    pub end: usize,   // 1-based, usize::MAX means "to end"
}

/// Parse a LIST specification like "1,3-5,7-" into ranges.
/// Each range is 1-based. Returns sorted, merged ranges.
/// When `no_merge_adjacent` is true, overlapping ranges are still merged but
/// adjacent ranges (e.g., 1-2,3-4) are kept separate. This is needed when
/// `--output-delimiter` is specified for byte/char mode so the delimiter is
/// inserted between originally separate but adjacent ranges.
pub fn parse_ranges(spec: &str, no_merge_adjacent: bool) -> Result<Vec<Range>, String> {
    let mut ranges = Vec::new();

    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        if let Some(idx) = part.find('-') {
            let left = &part[..idx];
            let right = &part[idx + 1..];

            // Reject bare "-" (both sides empty)
            if left.is_empty() && right.is_empty() {
                return Err("invalid range with no endpoint: -".to_string());
            }

            let start = if left.is_empty() {
                1
            } else {
                left.parse::<usize>()
                    .map_err(|_| format!("invalid range: '{}'", part))?
            };

            let end = if right.is_empty() {
                usize::MAX
            } else {
                right
                    .parse::<usize>()
                    .map_err(|_| format!("invalid range: '{}'", part))?
            };

            if start == 0 {
                return Err("fields and positions are numbered from 1".to_string());
            }
            if start > end {
                return Err(format!("invalid decreasing range: '{}'", part));
            }

            ranges.push(Range { start, end });
        } else {
            let n = part
                .parse::<usize>()
                .map_err(|_| format!("invalid field: '{}'", part))?;
            if n == 0 {
                return Err("fields and positions are numbered from 1".to_string());
            }
            ranges.push(Range { start: n, end: n });
        }
    }

    if ranges.is_empty() {
        return Err("you must specify a list of bytes, characters, or fields".to_string());
    }

    // Sort and merge overlapping/adjacent ranges
    ranges.sort_by_key(|r| (r.start, r.end));
    let mut merged = vec![ranges[0].clone()];
    for r in &ranges[1..] {
        let last = merged.last_mut().unwrap();
        if no_merge_adjacent {
            // Only merge truly overlapping ranges, not adjacent ones
            if r.start <= last.end {
                last.end = last.end.max(r.end);
            } else {
                merged.push(r.clone());
            }
        } else {
            // Merge both overlapping and adjacent ranges
            if r.start <= last.end.saturating_add(1) {
                last.end = last.end.max(r.end);
            } else {
                merged.push(r.clone());
            }
        }
    }

    Ok(merged)
}

/// Check if a 1-based position is in any range.
/// Ranges must be sorted. Uses early exit since ranges are sorted.
#[inline(always)]
fn in_ranges(ranges: &[Range], pos: usize) -> bool {
    for r in ranges {
        if pos < r.start {
            return false;
        }
        if pos <= r.end {
            return true;
        }
    }
    false
}

/// Pre-compute a 64-bit mask for field selection.
/// Bit i-1 is set if field i should be output.
#[inline]
fn compute_field_mask(ranges: &[Range], complement: bool) -> u64 {
    let mut mask: u64 = 0;
    for i in 1..=64u32 {
        let in_range = in_ranges(ranges, i as usize);
        if in_range != complement {
            mask |= 1u64 << (i - 1);
        }
    }
    mask
}

/// Check if a field should be selected, using bitset for first 64 fields.
#[inline(always)]
fn is_selected(field_num: usize, mask: u64, ranges: &[Range], complement: bool) -> bool {
    if field_num <= 64 {
        (mask >> (field_num - 1)) & 1 == 1
    } else {
        in_ranges(ranges, field_num) != complement
    }
}

// ── Unsafe buffer helpers (skip bounds checks in hot loops) ──────────────

/// Append a slice to buf without capacity checks.
/// Caller MUST ensure buf has enough remaining capacity.
#[inline(always)]
unsafe fn buf_extend(buf: &mut Vec<u8>, data: &[u8]) {
    unsafe {
        let len = buf.len();
        std::ptr::copy_nonoverlapping(data.as_ptr(), buf.as_mut_ptr().add(len), data.len());
        buf.set_len(len + data.len());
    }
}

/// Append a single byte to buf without capacity checks.
/// Caller MUST ensure buf has enough remaining capacity.
#[inline(always)]
unsafe fn buf_push(buf: &mut Vec<u8>, b: u8) {
    unsafe {
        let len = buf.len();
        *buf.as_mut_ptr().add(len) = b;
        buf.set_len(len + 1);
    }
}

/// Write multiple IoSlice buffers using write_vectored (writev syscall).
/// Batches into MAX_IOV-sized groups. Hot path: single write_vectored succeeds.
/// Cold path (partial write) is out-of-line to keep the hot loop tight.
#[inline]
fn write_ioslices(out: &mut impl Write, slices: &[IoSlice]) -> io::Result<()> {
    if slices.is_empty() {
        return Ok(());
    }
    for batch in slices.chunks(MAX_IOV) {
        let total: usize = batch.iter().map(|s| s.len()).sum();
        let written = out.write_vectored(batch)?;
        if written >= total {
            continue;
        }
        if written == 0 {
            return Err(io::Error::new(io::ErrorKind::WriteZero, "write zero"));
        }
        write_ioslices_slow(out, batch, written)?;
    }
    Ok(())
}

/// Handle partial write_vectored (cold path, never inlined).
#[cold]
#[inline(never)]
fn write_ioslices_slow(
    out: &mut impl Write,
    slices: &[IoSlice],
    mut skip: usize,
) -> io::Result<()> {
    for slice in slices {
        let len = slice.len();
        if skip >= len {
            skip -= len;
            continue;
        }
        out.write_all(&slice[skip..])?;
        skip = 0;
    }
    Ok(())
}

// ── Chunk splitting for parallel processing ──────────────────────────────

/// Number of available CPUs for parallel chunk splitting.
/// Uses std::thread::available_parallelism() to avoid triggering premature
/// rayon pool initialization (~300-500µs). Rayon pool inits on first scope() call.
#[inline]
fn num_cpus() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
}

/// Split data into chunks for rayon::scope parallel processing.
/// Uses Rayon's thread count to match the number of worker threads.
fn split_for_scope<'a>(data: &'a [u8], line_delim: u8) -> Vec<&'a [u8]> {
    let num_threads = num_cpus().max(1);
    if data.len() < PARALLEL_THRESHOLD || num_threads <= 1 {
        return vec![data];
    }

    let chunk_size = data.len() / num_threads;
    let mut chunks = Vec::with_capacity(num_threads);
    let mut pos = 0;

    for _ in 0..num_threads - 1 {
        let target = pos + chunk_size;
        if target >= data.len() {
            break;
        }
        let boundary = memchr::memchr(line_delim, &data[target..])
            .map(|p| target + p + 1)
            .unwrap_or(data.len());
        if boundary > pos {
            chunks.push(&data[pos..boundary]);
        }
        pos = boundary;
    }

    if pos < data.len() {
        chunks.push(&data[pos..]);
    }

    chunks
}

// ── Fast path: multi-field non-contiguous extraction ─────────────────────

/// Multi-field non-contiguous extraction (e.g., `cut -d, -f1,3,5`).
/// Pre-collects delimiter positions per line into a stack-allocated array,
/// then directly indexes into them for each selected field.
/// This is O(max_field) per line instead of O(num_fields * scan_length).
fn process_fields_multi_select(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    ranges: &[Range],
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    let max_field = ranges.last().map_or(0, |r| r.end);

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len() * 3 / 4);
                    multi_select_chunk(
                        chunk, delim, line_delim, ranges, max_field, suppress, result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            multi_select_chunk(chunk, delim, line_delim, ranges, max_field, suppress, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk for multi-field extraction.
/// Uses single-pass memchr2 with bitmask field selection when max_field <= 64.
/// Falls back to two-level scanning for larger field numbers.
fn multi_select_chunk(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    ranges: &[Range],
    max_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    // Two-level scan for small max_field: outer memchr(newline) + inner
    // memchr(delim) with early exit at max_field. This is faster than the
    // single-pass memchr2 approach when lines have many fields past max_field,
    // because we skip scanning delimiters we don't need (e.g., for -f1,3,5
    // on a 10-field CSV, we stop after delimiter 5 instead of scanning all 9).
    if max_field <= 64 && delim != line_delim {
        let mut mask: u64 = 0;
        for r in ranges {
            let s = r.start.max(1);
            let e = r.end.min(64);
            for f in s..=e {
                mask |= 1u64 << (f - 1);
            }
        }
        // For small max_field, use single-pass memchr2 bitmask approach:
        // scans for both delimiter and newline simultaneously, avoiding
        // per-line iterator creation overhead on short lines.
        // Trade-off: bitmask processes all delimiters per line (no early exit),
        // while twolevel exits after max_field delimiters. For narrow CSVs
        // (<=8 fields), the memchr2 SIMD advantage outweighs the extra hits.
        // For wide CSVs, twolevel's early exit wins.
        if max_field <= 8 {
            multi_select_chunk_bitmask(data, delim, line_delim, mask, max_field, suppress, buf);
        } else {
            multi_select_twolevel(data, delim, line_delim, mask, max_field, suppress, buf);
        }
        return;
    }

    // Fallback: two-level scanning for large field numbers
    buf.reserve(data.len());
    let base = data.as_ptr();
    let mut start = 0;
    let max_delims = max_field.min(128);

    for end_pos in memchr_iter(line_delim, data) {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), end_pos - start) };
        multi_select_line_fast(
            line, delim, line_delim, ranges, max_delims, suppress, buf, start, base,
        );
        start = end_pos + 1;
    }
    if start < data.len() {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), data.len() - start) };
        multi_select_line_fast(
            line, delim, line_delim, ranges, max_delims, suppress, buf, start, base,
        );
    }
}

/// Single-pass memchr2 multi-field extraction with bitmask field selection.
/// Scans for both delimiter and newline simultaneously, avoiding per-line
/// memchr_iter creation overhead on short lines (~200K lines x ~35 bytes).
/// Best for max_field <= 8 where most fields are selected.
fn multi_select_chunk_bitmask(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    mask: u64,
    max_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    // Single-pass memchr2 approach: scan for both delimiters and newlines
    // simultaneously. This avoids per-line memchr_iter creation overhead,
    // which dominates for short lines (200K lines × ~35 bytes each).
    buf.reserve(data.len() + 1);
    let initial_len = buf.len();
    let out_base = unsafe { buf.as_mut_ptr().add(initial_len) };
    let src = data.as_ptr();
    let mut wp: usize = 0;

    let mut field_num: usize = 1; // current field (1-based)
    let mut field_start: usize = 0; // start of current field
    let mut first_output = true; // first field on current line?
    let mut has_delim = false; // current line has any delimiter?

    for pos in memchr::memchr2_iter(delim, line_delim, data) {
        if data[pos] == line_delim {
            // End of line: handle last field + write newline
            if !has_delim {
                // Line had no delimiter: pass through or suppress
                if !suppress {
                    let len = pos - field_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(src.add(field_start), out_base.add(wp), len);
                    }
                    wp += len;
                    unsafe {
                        *out_base.add(wp) = line_delim;
                    }
                    wp += 1;
                }
            } else {
                // Check if last field is selected
                if field_num <= 64 && (mask & (1u64 << (field_num - 1))) != 0 {
                    if !first_output {
                        unsafe {
                            *out_base.add(wp) = delim;
                        }
                        wp += 1;
                    }
                    let len = pos - field_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(src.add(field_start), out_base.add(wp), len);
                    }
                    wp += len;
                }
                unsafe {
                    *out_base.add(wp) = line_delim;
                }
                wp += 1;
            }
            // Reset for next line
            field_num = 1;
            field_start = pos + 1;
            first_output = true;
            has_delim = false;
        } else {
            // Delimiter found
            has_delim = true;
            if field_num <= max_field && (mask & (1u64 << (field_num - 1))) != 0 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let len = pos - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(src.add(field_start), out_base.add(wp), len);
                }
                wp += len;
                first_output = false;
            }
            field_num += 1;
            field_start = pos + 1;
        }
    }

    // Handle final line without trailing newline
    if field_start < data.len() {
        if !has_delim {
            if !suppress {
                let len = data.len() - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(src.add(field_start), out_base.add(wp), len);
                }
                wp += len;
                unsafe {
                    *out_base.add(wp) = line_delim;
                }
                wp += 1;
            }
        } else {
            if field_num <= 64 && (mask & (1u64 << (field_num - 1))) != 0 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let len = data.len() - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(src.add(field_start), out_base.add(wp), len);
                }
                wp += len;
            }
            unsafe {
                *out_base.add(wp) = line_delim;
            }
            wp += 1;
        }
    }

    debug_assert!(wp <= data.len() + 1);
    unsafe {
        buf.set_len(initial_len + wp);
    }
}

/// Two-level multi-field extraction: outer memchr(newline) for line boundaries,
/// inner memchr(delim) with early exit after max_field delimiters per line.
/// For `-f1,3,5` on a 10-field CSV, this scans only 5 delimiters per line
/// instead of all 9, saving ~45% of delimiter processing.
fn multi_select_twolevel(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    mask: u64,
    max_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len() + 1);
    let initial_len = buf.len();
    let out_base = unsafe { buf.as_mut_ptr().add(initial_len) };
    let src = data.as_ptr();
    let mut wp: usize = 0;
    let mut line_start: usize = 0;

    for nl_pos in memchr_iter(line_delim, data) {
        let line_len = nl_pos - line_start;
        let line = &data[line_start..nl_pos];

        if line_len == 0 {
            if !suppress {
                unsafe {
                    *out_base.add(wp) = line_delim;
                }
                wp += 1;
            }
            line_start = nl_pos + 1;
            continue;
        }

        // Scan delimiters within the line, stopping after max_field.
        // Uses memchr_iter for amortized SIMD setup (one per line vs one per field).
        let mut field_num: usize = 1;
        let mut field_start: usize = 0;
        let mut first_output = true;
        let mut has_delim = false;

        for dp in memchr::memchr_iter(delim, line) {
            has_delim = true;
            if (mask >> (field_num - 1)) & 1 == 1 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let flen = dp - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        src.add(line_start + field_start),
                        out_base.add(wp),
                        flen,
                    );
                }
                wp += flen;
                first_output = false;
            }
            field_num += 1;
            field_start = dp + 1;
            if field_num > max_field {
                break;
            }
        }

        if !has_delim {
            // No delimiter: pass through or suppress
            if !suppress {
                unsafe {
                    std::ptr::copy_nonoverlapping(src.add(line_start), out_base.add(wp), line_len);
                }
                wp += line_len;
                unsafe {
                    *out_base.add(wp) = line_delim;
                }
                wp += 1;
            }
        } else {
            // Check if the last field (after last found delimiter) is selected
            if field_num <= 64 && (mask >> (field_num - 1)) & 1 == 1 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let flen = line_len - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        src.add(line_start + field_start),
                        out_base.add(wp),
                        flen,
                    );
                }
                wp += flen;
            }
            unsafe {
                *out_base.add(wp) = line_delim;
            }
            wp += 1;
        }

        line_start = nl_pos + 1;
    }

    // Handle final line without trailing newline
    if line_start < data.len() {
        let line = &data[line_start..];
        let line_len = line.len();
        let mut field_num: usize = 1;
        let mut field_start: usize = 0;
        let mut first_output = true;
        let mut has_delim = false;

        for dp in memchr::memchr_iter(delim, line) {
            has_delim = true;
            if (mask >> (field_num - 1)) & 1 == 1 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let flen = dp - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        src.add(line_start + field_start),
                        out_base.add(wp),
                        flen,
                    );
                }
                wp += flen;
                first_output = false;
            }
            field_num += 1;
            field_start = dp + 1;
            if field_num > max_field {
                break;
            }
        }

        if !has_delim {
            if !suppress {
                unsafe {
                    std::ptr::copy_nonoverlapping(src.add(line_start), out_base.add(wp), line_len);
                }
                wp += line_len;
                unsafe {
                    *out_base.add(wp) = line_delim;
                }
                wp += 1;
            }
        } else {
            if field_num <= 64 && (mask >> (field_num - 1)) & 1 == 1 {
                if !first_output {
                    unsafe {
                        *out_base.add(wp) = delim;
                    }
                    wp += 1;
                }
                let flen = line_len - field_start;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        src.add(line_start + field_start),
                        out_base.add(wp),
                        flen,
                    );
                }
                wp += flen;
            }
            unsafe {
                *out_base.add(wp) = line_delim;
            }
            wp += 1;
        }
    }

    debug_assert!(
        wp <= data.len() + 1,
        "wp={} exceeded reservation data.len()+1={}",
        wp,
        data.len() + 1
    );
    unsafe {
        buf.set_len(initial_len + wp);
    }
}

/// Extract selected fields from a single line using delimiter position scanning.
/// Optimized: collects delimiter positions into a stack array with early exit at max_delims,
/// then indexes directly for each selected field. Uses raw pointer arithmetic.
#[inline(always)]
fn multi_select_line_fast(
    line: &[u8],
    delim: u8,
    line_delim: u8,
    ranges: &[Range],
    max_delims: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
    _line_abs_start: usize,
    _data_base: *const u8,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    let base = line.as_ptr();

    // Collect delimiter positions up to max_delims (early exit).
    let mut delim_pos = [0usize; 128];
    let mut num_delims: usize = 0;

    for pos in memchr_iter(delim, line) {
        if num_delims < max_delims {
            delim_pos[num_delims] = pos;
            num_delims += 1;
            if num_delims >= max_delims {
                break;
            }
        }
    }

    if num_delims == 0 {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    let total_fields = num_delims + 1;
    let mut first_output = true;

    for r in ranges {
        let range_start = r.start;
        let range_end = r.end.min(total_fields);
        if range_start > total_fields {
            break;
        }
        for field_num in range_start..=range_end {
            if field_num > total_fields {
                break;
            }

            let field_start = if field_num == 1 {
                0
            } else if field_num - 2 < num_delims {
                delim_pos[field_num - 2] + 1
            } else {
                continue;
            };
            let field_end = if field_num <= num_delims {
                delim_pos[field_num - 1]
            } else {
                len
            };

            if !first_output {
                unsafe { buf_push(buf, delim) };
            }
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(field_start), field_end - field_start),
                );
            }
            first_output = false;
        }
    }

    unsafe { buf_push(buf, line_delim) };
}

// ── Fast path: field extraction with batched output ──────────────────────

/// Optimized field extraction with early exit and batched output.
fn process_fields_fast(data: &[u8], cfg: &CutConfig, out: &mut impl Write) -> io::Result<()> {
    let delim = cfg.delim;
    let line_delim = cfg.line_delim;
    let ranges = cfg.ranges;
    let complement = cfg.complement;
    let output_delim = cfg.output_delim;
    let suppress = cfg.suppress_no_delim;

    // NOTE: Removed the full-file `memchr(delim, data).is_none()` scan.
    // That scan was O(N) over the entire file just to check an edge case
    // (no delimiter in any line). The per-line processing already handles
    // lines without delimiters correctly, so the scan was pure overhead
    // for files that DO contain delimiters (the common case).

    // Ultra-fast path: single field extraction (e.g., cut -f5)
    if !complement && ranges.len() == 1 && ranges[0].start == ranges[0].end {
        return process_single_field(data, delim, line_delim, ranges[0].start, suppress, out);
    }

    // Fast path: complement of single field or contiguous range with default output delimiter.
    if complement
        && ranges.len() == 1
        && output_delim.len() == 1
        && output_delim[0] == delim
        && ranges[0].start == ranges[0].end
    {
        return process_complement_single_field(
            data,
            delim,
            line_delim,
            ranges[0].start,
            suppress,
            out,
        );
    }

    // Fast path: complement of contiguous range (e.g., --complement -f3-5 = output fields 1,2,6+).
    // This is equivalent to outputting a prefix and a suffix, skipping the middle range.
    if complement
        && ranges.len() == 1
        && ranges[0].start > 1
        && ranges[0].end < usize::MAX
        && output_delim.len() == 1
        && output_delim[0] == delim
    {
        return process_complement_range(
            data,
            delim,
            line_delim,
            ranges[0].start,
            ranges[0].end,
            suppress,
            out,
        );
    }

    // Fast path: contiguous from-start field range (e.g., cut -f1-5)
    if !complement
        && ranges.len() == 1
        && ranges[0].start == 1
        && output_delim.len() == 1
        && output_delim[0] == delim
        && ranges[0].end < usize::MAX
    {
        return process_fields_prefix(data, delim, line_delim, ranges[0].end, suppress, out);
    }

    // Fast path: open-ended field range from field N (e.g., cut -f3-)
    if !complement
        && ranges.len() == 1
        && ranges[0].end == usize::MAX
        && ranges[0].start > 1
        && output_delim.len() == 1
        && output_delim[0] == delim
    {
        return process_fields_suffix(data, delim, line_delim, ranges[0].start, suppress, out);
    }

    // Fast path: contiguous field range with start > 1 (e.g., cut -f2-4)
    if !complement
        && ranges.len() == 1
        && ranges[0].start > 1
        && ranges[0].end < usize::MAX
        && output_delim.len() == 1
        && output_delim[0] == delim
    {
        return process_fields_mid_range(
            data,
            delim,
            line_delim,
            ranges[0].start,
            ranges[0].end,
            suppress,
            out,
        );
    }

    // Fast path: multi-field non-contiguous extraction (e.g., cut -f1,3,5)
    // Uses delimiter position caching: find all delimiter positions per line,
    // then directly index into them for each selected field.
    // This is faster than the general extract_fields_to_buf which re-checks
    // is_selected() for every field encountered.
    if !complement
        && ranges.len() > 1
        && ranges.last().map_or(false, |r| r.end < usize::MAX)
        && output_delim.len() == 1
        && output_delim[0] == delim
        && delim != line_delim
    {
        return process_fields_multi_select(data, delim, line_delim, ranges, suppress, out);
    }

    // General field extraction
    let max_field = if complement {
        usize::MAX
    } else {
        ranges.last().map(|r| r.end).unwrap_or(0)
    };
    let field_mask = compute_field_mask(ranges, complement);

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len() + 1);
                    process_fields_chunk(
                        chunk,
                        delim,
                        ranges,
                        output_delim,
                        suppress,
                        max_field,
                        field_mask,
                        line_delim,
                        complement,
                        result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            process_fields_chunk(
                chunk,
                delim,
                ranges,
                output_delim,
                suppress,
                max_field,
                field_mask,
                line_delim,
                complement,
                buf,
            );
        })?;
    }
    Ok(())
}

/// Process a chunk of data for general field extraction.
/// Uses two-level scanning: outer memchr(newline) for line boundaries, inner
/// memchr_iter(delim) for delimiter positions. This is faster than memchr2 single-pass
/// because memchr (one needle) is ~30-50% faster per byte than memchr2 (two needles).
fn process_fields_chunk(
    data: &[u8],
    delim: u8,
    ranges: &[Range],
    output_delim: &[u8],
    suppress: bool,
    max_field: usize,
    field_mask: u64,
    line_delim: u8,
    complement: bool,
    buf: &mut Vec<u8>,
) {
    // Always use two-level approach: outer memchr(newline) + inner memchr_iter(delim).
    // Even for complement/unbounded ranges, two-level is faster because memchr is
    // ~30-50% faster per byte than memchr2. The per-line function call overhead
    // is negligible compared to the SIMD scan savings.
    if delim != line_delim {
        buf.reserve(data.len());
        let mut start = 0;
        for end_pos in memchr_iter(line_delim, data) {
            let line = &data[start..end_pos];
            extract_fields_to_buf(
                line,
                delim,
                ranges,
                output_delim,
                suppress,
                max_field,
                field_mask,
                line_delim,
                buf,
                complement,
            );
            start = end_pos + 1;
        }
        if start < data.len() {
            extract_fields_to_buf(
                &data[start..],
                delim,
                ranges,
                output_delim,
                suppress,
                max_field,
                field_mask,
                line_delim,
                buf,
                complement,
            );
        }
        return;
    }

    // Fallback: when delim == line_delim, use the two-level scan approach
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        extract_fields_to_buf(
            line,
            delim,
            ranges,
            output_delim,
            suppress,
            max_field,
            field_mask,
            line_delim,
            buf,
            complement,
        );
        start = end_pos + 1;
    }
    if start < data.len() {
        extract_fields_to_buf(
            &data[start..],
            delim,
            ranges,
            output_delim,
            suppress,
            max_field,
            field_mask,
            line_delim,
            buf,
            complement,
        );
    }
}

// ── Ultra-fast single field extraction ───────────────────────────────────

/// Specialized path for extracting exactly one field (e.g., `cut -f5`).
/// Uses two-level scanning: outer memchr(newline) for line boundaries, inner
/// memchr(delim) for the field delimiter with early exit.
fn process_single_field(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    target: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    let target_idx = target - 1;

    if delim != line_delim {
        // Field 1 fast path: two-level scan (outer newline + inner first-delim).
        // For field 1, only needs to find the first delimiter per line.
        // Lines without delimiter are tracked as contiguous runs for bulk copy.
        if target_idx == 0 && !suppress {
            if data.len() >= PARALLEL_THRESHOLD {
                return single_field1_parallel(data, delim, line_delim, out);
            }
            return process_chunked(data, line_delim, out, |chunk, buf| {
                single_field1_to_buf(chunk, delim, line_delim, buf);
            });
        }

        // Two-level approach for field N: outer newline scan + inner delim scan
        // with early exit at target_idx. Faster than memchr2 single-pass because
        // we only scan delimiters up to target_idx per line (not all of them).
        if data.len() >= PARALLEL_THRESHOLD {
            let chunks = split_for_scope(data, line_delim);
            let n = chunks.len();
            let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
            rayon::scope(|s| {
                for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                    s.spawn(move |_| {
                        result.reserve(chunk.len() / 2);
                        process_single_field_chunk(
                            chunk, delim, target_idx, line_delim, suppress, result,
                        );
                    });
                }
            });
            let slices: Vec<IoSlice> = results
                .iter()
                .filter(|r| !r.is_empty())
                .map(|r| IoSlice::new(r))
                .collect();
            write_ioslices(out, &slices)?;
        } else {
            let mut buf = Vec::with_capacity(data.len().min(4 * 1024 * 1024));
            process_single_field_chunk(data, delim, target_idx, line_delim, suppress, &mut buf);
            if !buf.is_empty() {
                out.write_all(&buf)?;
            }
        }
        return Ok(());
    }

    // Fallback for delim == line_delim: nested loop approach
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len() / 4);
                    process_single_field_chunk(
                        chunk, delim, target_idx, line_delim, suppress, result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        let mut buf = Vec::with_capacity(data.len() / 4);
        process_single_field_chunk(data, delim, target_idx, line_delim, suppress, &mut buf);
        if !buf.is_empty() {
            out.write_all(&buf)?;
        }
    }
    Ok(())
}

/// Complement range extraction: skip fields start..=end, output rest (e.g., --complement -f3-5).
/// For each line: output fields 1..start-1, then fields end+1..EOF, skipping fields start..end.
fn process_complement_range(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    skip_start: usize,
    skip_end: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    complement_range_chunk(
                        chunk, delim, skip_start, skip_end, line_delim, suppress, result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            complement_range_chunk(
                chunk, delim, skip_start, skip_end, line_delim, suppress, buf,
            );
        })?;
    }
    Ok(())
}

/// Process a chunk for complement range extraction.
fn complement_range_chunk(
    data: &[u8],
    delim: u8,
    skip_start: usize,
    skip_end: usize,
    line_delim: u8,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    // Pre-reserve entire chunk capacity to eliminate per-line reserve overhead.
    buf.reserve(data.len());
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        complement_range_line(line, delim, skip_start, skip_end, line_delim, suppress, buf);
        start = end_pos + 1;
    }
    if start < data.len() {
        complement_range_line(
            &data[start..],
            delim,
            skip_start,
            skip_end,
            line_delim,
            suppress,
            buf,
        );
    }
}

/// Extract all fields except skip_start..=skip_end from one line.
/// Outputs fields 1..skip_start-1, then fields skip_end+1..EOF.
///
/// Optimized: only scans for enough delimiters to find the skip region boundaries.
/// For `--complement -f3-5` with 20 fields, this finds delimiter 2 and 5, then
/// does a single copy of prefix + suffix, avoiding scanning past field 5.
#[inline(always)]
fn complement_range_line(
    line: &[u8],
    delim: u8,
    skip_start: usize,
    skip_end: usize,
    line_delim: u8,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    // Note: no per-line buf.reserve — complement_range_chunk already reserves data.len()
    let base = line.as_ptr();

    // 1-based field numbers. To skip fields skip_start..=skip_end:
    // - prefix_end = position of (skip_start-1)th delimiter (exclusive; end of prefix fields)
    // - suffix_start = position after skip_end-th delimiter (inclusive; start of suffix fields)
    //
    // Find the first (skip_start - 1) delimiters to locate prefix_end,
    // then the next (skip_end - skip_start + 1) delimiters to locate suffix_start.

    let need_prefix_delims = skip_start - 1; // number of delimiters before the skip region
    let need_skip_delims = skip_end - skip_start + 1; // delimiters within the skip region
    let total_need = need_prefix_delims + need_skip_delims;

    // Find delimiter positions up to total_need
    let mut delim_count: usize = 0;
    let mut prefix_end_pos: usize = usize::MAX; // byte position of (skip_start-1)th delim
    let mut suffix_start_pos: usize = usize::MAX; // byte position after skip_end-th delim

    for pos in memchr_iter(delim, line) {
        delim_count += 1;
        if delim_count == need_prefix_delims {
            prefix_end_pos = pos;
        }
        if delim_count == total_need {
            suffix_start_pos = pos + 1;
            break;
        }
    }

    if delim_count == 0 {
        // No delimiter at all
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    // Case analysis:
    // 1. Not enough delims to reach skip_start: all fields are before skip region, output all
    // 2. Enough to reach skip_start but not skip_end: prefix + no suffix
    // 3. Enough to reach skip_end: prefix + delim + suffix

    if delim_count < need_prefix_delims {
        // Not enough fields to reach skip region — output entire line
        unsafe {
            buf_extend(buf, line);
            buf_push(buf, line_delim);
        }
        return;
    }

    let has_prefix = need_prefix_delims > 0;
    let has_suffix = suffix_start_pos != usize::MAX && suffix_start_pos < len;

    if has_prefix && has_suffix {
        // Output: prefix (up to prefix_end_pos) + delim + suffix (from suffix_start_pos)
        unsafe {
            buf_extend(buf, std::slice::from_raw_parts(base, prefix_end_pos));
            buf_push(buf, delim);
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(suffix_start_pos), len - suffix_start_pos),
            );
            buf_push(buf, line_delim);
        }
    } else if has_prefix {
        // Only prefix, no suffix (skip region extends to end of line)
        unsafe {
            buf_extend(buf, std::slice::from_raw_parts(base, prefix_end_pos));
            buf_push(buf, line_delim);
        }
    } else if has_suffix {
        // No prefix (skip_start == 1), only suffix
        unsafe {
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(suffix_start_pos), len - suffix_start_pos),
            );
            buf_push(buf, line_delim);
        }
    } else {
        // All fields skipped
        unsafe { buf_push(buf, line_delim) };
    }
}

/// Complement single-field extraction: skip one field, output rest unchanged.
fn process_complement_single_field(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    skip_field: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    let skip_idx = skip_field - 1;

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    complement_single_field_chunk(
                        chunk, delim, skip_idx, line_delim, suppress, result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            complement_single_field_chunk(chunk, delim, skip_idx, line_delim, suppress, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk for complement single-field extraction using two-level scanning.
/// Outer memchr(newline) for line boundaries, inner memchr_iter(delim) with early exit
/// after finding the skip field's bounding delimiters. Faster than memchr2 single-pass
/// because memchr is faster per byte and inner scan exits early.
fn complement_single_field_chunk(
    data: &[u8],
    delim: u8,
    skip_idx: usize,
    line_delim: u8,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        complement_single_field_line(line, delim, skip_idx, line_delim, suppress, buf);
        start = end_pos + 1;
    }
    if start < data.len() {
        complement_single_field_line(&data[start..], delim, skip_idx, line_delim, suppress, buf);
    }
}

/// Fallback per-line complement single-field extraction (for delim == line_delim).
#[inline(always)]
fn complement_single_field_line(
    line: &[u8],
    delim: u8,
    skip_idx: usize,
    line_delim: u8,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    let base = line.as_ptr();
    let need_before = skip_idx;
    let need_total = skip_idx + 1;

    let mut delim_count: usize = 0;
    let mut skip_start_pos: usize = 0;
    let mut skip_end_pos: usize = len;
    let mut found_end = false;

    for pos in memchr_iter(delim, line) {
        delim_count += 1;
        if delim_count == need_before {
            skip_start_pos = pos + 1;
        }
        if delim_count == need_total {
            skip_end_pos = pos;
            found_end = true;
            break;
        }
    }

    if delim_count == 0 {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    if delim_count < need_before {
        unsafe {
            buf_extend(buf, line);
            buf_push(buf, line_delim);
        }
        return;
    }

    let has_prefix = skip_idx > 0 && skip_start_pos > 0;
    let has_suffix = found_end && skip_end_pos < len;

    if has_prefix && has_suffix {
        unsafe {
            buf_extend(buf, std::slice::from_raw_parts(base, skip_start_pos - 1));
            buf_push(buf, delim);
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(skip_end_pos + 1), len - skip_end_pos - 1),
            );
            buf_push(buf, line_delim);
        }
    } else if has_prefix {
        unsafe {
            buf_extend(buf, std::slice::from_raw_parts(base, skip_start_pos - 1));
            buf_push(buf, line_delim);
        }
    } else if has_suffix {
        unsafe {
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(skip_end_pos + 1), len - skip_end_pos - 1),
            );
            buf_push(buf, line_delim);
        }
    } else {
        unsafe { buf_push(buf, line_delim) };
    }
}

/// Contiguous from-start field range extraction (e.g., `cut -f1-5`).
/// Zero-copy for the non-parallel path: identifies the truncation point per line
/// and writes contiguous runs directly from the source data.
fn process_fields_prefix(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    last_field: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    fields_prefix_chunk(chunk, delim, line_delim, last_field, suppress, result);
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else if !suppress {
        // Zero-copy fast path: scan for truncation points, write runs from source.
        // When suppress is false, every line is output (with or without delimiter).
        // Most lines have enough fields, so the output is often identical to input.
        fields_prefix_zerocopy(data, delim, line_delim, last_field, out)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            fields_prefix_chunk(chunk, delim, line_delim, last_field, suppress, buf);
        })?;
    }
    Ok(())
}

/// Zero-copy field-prefix extraction using writev: builds IoSlice entries pointing
/// directly into the source data, flushing in MAX_IOV-sized batches.
/// For lines where the Nth delimiter exists, we truncate at that point.
/// For lines with fewer fields, we output them unchanged (contiguous run).
/// Lines without any delimiter are output unchanged (suppress=false assumed).
#[inline]
fn fields_prefix_zerocopy(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    last_field: usize,
    out: &mut impl Write,
) -> io::Result<()> {
    let newline_buf: [u8; 1] = [line_delim];
    let mut iov: Vec<IoSlice> = Vec::with_capacity(MAX_IOV);
    let mut start = 0;
    let mut run_start: usize = 0;

    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        let mut field_count = 1;
        let mut truncate_at: Option<usize> = None;
        for dpos in memchr_iter(delim, line) {
            if field_count >= last_field {
                truncate_at = Some(start + dpos);
                break;
            }
            field_count += 1;
        }

        if let Some(trunc_pos) = truncate_at {
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..trunc_pos]));
            iov.push(IoSlice::new(&newline_buf));
            run_start = end_pos + 1;

            if iov.len() >= MAX_IOV - 2 {
                write_ioslices(out, &iov)?;
                iov.clear();
            }
        }
        start = end_pos + 1;
    }
    // Handle last line without terminator
    if start < data.len() {
        let line = &data[start..];
        let mut field_count = 1;
        let mut truncate_at: Option<usize> = None;
        for dpos in memchr_iter(delim, line) {
            if field_count >= last_field {
                truncate_at = Some(start + dpos);
                break;
            }
            field_count += 1;
        }
        if let Some(trunc_pos) = truncate_at {
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..trunc_pos]));
            iov.push(IoSlice::new(&newline_buf));
            if !iov.is_empty() {
                write_ioslices(out, &iov)?;
            }
            return Ok(());
        }
    }
    // Flush remaining contiguous run
    if run_start < data.len() {
        iov.push(IoSlice::new(&data[run_start..]));
        if !data.is_empty() && *data.last().unwrap() != line_delim {
            iov.push(IoSlice::new(&newline_buf));
        }
    }
    if !iov.is_empty() {
        write_ioslices(out, &iov)?;
    }
    Ok(())
}

/// Process a chunk for contiguous from-start field range extraction.
fn fields_prefix_chunk(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    last_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        fields_prefix_line(line, delim, line_delim, last_field, suppress, buf);
        start = end_pos + 1;
    }
    if start < data.len() {
        fields_prefix_line(&data[start..], delim, line_delim, last_field, suppress, buf);
    }
}

/// Extract first N fields from one line (contiguous from-start range).
/// Uses memchr SIMD for delimiter scanning on all line sizes.
#[inline(always)]
fn fields_prefix_line(
    line: &[u8],
    delim: u8,
    line_delim: u8,
    last_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    // Note: no per-line buf.reserve — fields_prefix_chunk already reserves data.len()
    let base = line.as_ptr();

    let mut field_count = 1usize;
    let mut has_delim = false;

    for pos in memchr_iter(delim, line) {
        has_delim = true;
        if field_count >= last_field {
            unsafe {
                buf_extend(buf, std::slice::from_raw_parts(base, pos));
                buf_push(buf, line_delim);
            }
            return;
        }
        field_count += 1;
    }

    if !has_delim {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    unsafe {
        buf_extend(buf, line);
        buf_push(buf, line_delim);
    }
}

/// Open-ended field suffix extraction (e.g., `cut -f3-`).
fn process_fields_suffix(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    fields_suffix_chunk(chunk, delim, line_delim, start_field, suppress, result);
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            fields_suffix_chunk(chunk, delim, line_delim, start_field, suppress, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk for open-ended field suffix extraction.
fn fields_suffix_chunk(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        fields_suffix_line(line, delim, line_delim, start_field, suppress, buf);
        start = end_pos + 1;
    }
    if start < data.len() {
        fields_suffix_line(
            &data[start..],
            delim,
            line_delim,
            start_field,
            suppress,
            buf,
        );
    }
}

/// Extract fields from start_field to end from one line.
/// Uses memchr SIMD for delimiter scanning on all line sizes.
#[inline(always)]
fn fields_suffix_line(
    line: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    // Note: no per-line buf.reserve — fields_suffix_chunk already reserves data.len()
    let base = line.as_ptr();

    let skip_delims = start_field - 1;
    let mut delim_count = 0usize;
    let mut has_delim = false;

    for pos in memchr_iter(delim, line) {
        has_delim = true;
        delim_count += 1;
        if delim_count >= skip_delims {
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(pos + 1), len - pos - 1),
                );
                buf_push(buf, line_delim);
            }
            return;
        }
    }

    if !has_delim {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    // Fewer delimiters than needed
    unsafe { buf_push(buf, line_delim) };
}

/// Contiguous mid-range field extraction (e.g., `cut -f2-4`).
/// Optimized: skip to start_field using memchr, then output until end_field.
fn process_fields_mid_range(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    end_field: usize,
    suppress: bool,
    out: &mut impl Write,
) -> io::Result<()> {
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    fields_mid_range_chunk(
                        chunk,
                        delim,
                        line_delim,
                        start_field,
                        end_field,
                        suppress,
                        result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            fields_mid_range_chunk(
                chunk,
                delim,
                line_delim,
                start_field,
                end_field,
                suppress,
                buf,
            );
        })?;
    }
    Ok(())
}

/// Process a chunk for contiguous mid-range field extraction.
/// Two-level scan: outer memchr(newline) for line boundaries, inner memchr_iter(delim)
/// with early exit at target_end_delim. Faster than memchr2 single-pass because
/// memchr is faster per byte and inner scan exits early.
fn fields_mid_range_chunk(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    end_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        fields_mid_range_line(
            line,
            delim,
            line_delim,
            start_field,
            end_field,
            suppress,
            buf,
        );
        start = end_pos + 1;
    }
    if start < data.len() {
        fields_mid_range_line(
            &data[start..],
            delim,
            line_delim,
            start_field,
            end_field,
            suppress,
            buf,
        );
    }
}

/// Extract fields start_field..=end_field from one line.
/// Uses scalar byte scanning for short lines, memchr_iter for longer.
/// Raw pointer arithmetic to eliminate bounds checking.
#[inline(always)]
fn fields_mid_range_line(
    line: &[u8],
    delim: u8,
    line_delim: u8,
    start_field: usize,
    end_field: usize,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    if len == 0 {
        if !suppress {
            unsafe { buf_push(buf, line_delim) };
        }
        return;
    }

    // Note: no per-line buf.reserve — fields_mid_range_chunk already reserves data.len()
    let base = line.as_ptr();

    // Count delimiters to find start_field and end_field boundaries
    let skip_before = start_field - 1; // delimiters to skip before start_field
    let field_span = end_field - start_field; // additional delimiters within the range
    let target_end_delim = skip_before + field_span + 1;
    let mut delim_count = 0;
    let mut range_start = 0;
    let mut has_delim = false;

    for pos in memchr_iter(delim, line) {
        has_delim = true;
        delim_count += 1;
        if delim_count == skip_before {
            range_start = pos + 1;
        }
        if delim_count == target_end_delim {
            if skip_before == 0 {
                range_start = 0;
            }
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(range_start), pos - range_start),
                );
                buf_push(buf, line_delim);
            }
            return;
        }
    }

    if !has_delim {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
        return;
    }

    // Line has delimiters but fewer fields than end_field
    if delim_count >= skip_before {
        // We have at least start_field, output from range_start to end
        if skip_before == 0 {
            range_start = 0;
        }
        unsafe {
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(range_start), len - range_start),
            );
            buf_push(buf, line_delim);
        }
    } else {
        // Not enough fields even for start_field — output empty line
        unsafe { buf_push(buf, line_delim) };
    }
}

/// Zero-copy field-1 extraction using writev: builds IoSlice entries pointing
/// directly into the source data, flushing in MAX_IOV-sized batches.
/// For each line: if delimiter exists, output field1 + newline; otherwise pass through.
///
/// Uses a two-level scan: outer memchr(newline) for line boundaries, inner memchr(delim)
/// Parallel field-1 extraction for large data using memchr2 single-pass.
/// Splits data into per-thread chunks, each chunk extracts field 1 using
/// memchr2(delim, newline) which finds the first special byte in one scan.
/// For field 1: first special byte is either the delimiter (field end) or
/// newline (no delimiter, output line unchanged). 4 threads cut scan time ~4x.
fn single_field1_parallel(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let chunks = split_for_scope(data, line_delim);
    let n = chunks.len();
    let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
    rayon::scope(|s| {
        for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
            s.spawn(move |_| {
                result.reserve(chunk.len() + 1);
                single_field1_to_buf(chunk, delim, line_delim, result);
            });
        }
    });
    let slices: Vec<IoSlice> = results
        .iter()
        .filter(|r| !r.is_empty())
        .map(|r| IoSlice::new(r))
        .collect();
    write_ioslices(out, &slices)
}

/// Extract field 1 from a chunk using two-level scanning: outer memchr(newline)
/// for line boundaries, inner memchr(delim) for the first delimiter per line.
///
/// This is faster than memchr2_iter single-pass because:
/// 1. memchr (one needle) is ~30-50% faster per byte than memchr2 (two needles)
/// 2. For field 1, the inner memchr exits after the FIRST delimiter, skipping
///    all subsequent delimiters on the line (huge win for multi-column CSV)
/// 3. Lines without delimiter produce contiguous runs that are bulk-copied
///
/// Uses a single output pointer to avoid per-line buf.len() load/store.
#[inline]
fn single_field1_to_buf(data: &[u8], delim: u8, line_delim: u8, buf: &mut Vec<u8>) {
    debug_assert_ne!(delim, line_delim, "delim and line_delim must differ");
    // Reserve data.len() + 1: output <= input for all lines except potentially
    // the last line without trailing newline, where we add a newline (GNU compat).
    buf.reserve(data.len() + 1);

    let base = data.as_ptr();
    let initial_len = buf.len();
    let mut out_ptr = unsafe { buf.as_mut_ptr().add(initial_len) };
    let mut start = 0;
    // Track the start of contiguous runs of no-delimiter lines for bulk copy.
    let mut run_start: usize = 0;
    let mut in_run = true; // we start in a run

    for end_pos in memchr_iter(line_delim, data) {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), end_pos - start) };
        match memchr::memchr(delim, line) {
            Some(dp) => {
                // Line has delimiter — flush contiguous run, output field1 + newline
                if in_run && run_start < start {
                    // Bulk copy the contiguous run of unchanged lines
                    let run_len = start - run_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
                        out_ptr = out_ptr.add(run_len);
                    }
                }
                // Output field (bytes before first delimiter) + newline
                unsafe {
                    std::ptr::copy_nonoverlapping(base.add(start), out_ptr, dp);
                    out_ptr = out_ptr.add(dp);
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
                run_start = end_pos + 1;
                in_run = true;
            }
            None => {
                // No delimiter — this line stays in the contiguous run
                if !in_run {
                    run_start = start;
                    in_run = true;
                }
            }
        }
        start = end_pos + 1;
    }

    // Flush any remaining contiguous run
    if in_run && run_start < start {
        let run_len = start - run_start;
        unsafe {
            std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
            out_ptr = out_ptr.add(run_len);
        }
    }

    // Handle last line without trailing newline
    if start < data.len() {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), data.len() - start) };
        match memchr::memchr(delim, line) {
            Some(dp) => {
                // Field + trailing newline
                unsafe {
                    std::ptr::copy_nonoverlapping(base.add(start), out_ptr, dp);
                    out_ptr = out_ptr.add(dp);
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
            }
            None => {
                // No delimiter — output remaining data + newline (GNU compat)
                let len = data.len() - start;
                unsafe {
                    std::ptr::copy_nonoverlapping(base.add(start), out_ptr, len);
                    out_ptr = out_ptr.add(len);
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
            }
        }
    }

    unsafe {
        let new_len = out_ptr as usize - buf.as_ptr() as usize;
        debug_assert!(new_len >= initial_len && new_len <= buf.capacity());
        buf.set_len(new_len);
    }
}

/// Zero-copy field 1 extraction using writev: builds IoSlice entries pointing
/// directly into the source data. Uses two-level scan: outer memchr(newline)
/// for the first delimiter. This is faster than memchr2 for SMALL data because
/// the inner scan exits after the FIRST delimiter, skipping all
/// subsequent delimiters on the line.
///
/// Lines without delimiter stay in contiguous runs (zero-copy pass-through).
/// Lines with delimiter produce two IoSlices (truncated field + newline byte).
#[inline]
#[allow(dead_code)]
fn single_field1_zerocopy(
    data: &[u8],
    delim: u8,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let newline_buf: [u8; 1] = [line_delim];

    let mut iov: Vec<IoSlice> = Vec::with_capacity(MAX_IOV);
    let mut run_start: usize = 0;
    let mut start = 0;

    for end_pos in memchr_iter(line_delim, data) {
        let line = &data[start..end_pos];
        if let Some(dp) = memchr::memchr(delim, line) {
            // Line has delimiter — truncate at first delimiter.
            // Flush current contiguous run, then add truncated field + newline.
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..start + dp]));
            iov.push(IoSlice::new(&newline_buf));
            run_start = end_pos + 1;

            if iov.len() >= MAX_IOV - 2 {
                write_ioslices(out, &iov)?;
                iov.clear();
            }
        }
        // else: no delimiter in line, output unchanged (stays in contiguous run)
        start = end_pos + 1;
    }

    // Handle last line (no trailing newline)
    if start < data.len() {
        let line = &data[start..];
        if let Some(dp) = memchr::memchr(delim, line) {
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..start + dp]));
            iov.push(IoSlice::new(&newline_buf));
            if !iov.is_empty() {
                write_ioslices(out, &iov)?;
            }
            return Ok(());
        }
    }

    // Flush remaining contiguous run
    if run_start < data.len() {
        iov.push(IoSlice::new(&data[run_start..]));
        if !data.is_empty() && *data.last().unwrap() != line_delim {
            iov.push(IoSlice::new(&newline_buf));
        }
    }
    if !iov.is_empty() {
        write_ioslices(out, &iov)?;
    }
    Ok(())
}

/// Process a chunk of data for single-field extraction using write-pointer pattern.
/// Two-level scan: outer memchr(newline), inner memchr_iter(delim) with early exit.
/// Uses contiguous run tracking for lines that pass through unchanged.
fn process_single_field_chunk(
    data: &[u8],
    delim: u8,
    target_idx: usize,
    line_delim: u8,
    suppress: bool,
    buf: &mut Vec<u8>,
) {
    // Pre-reserve chunk capacity to eliminate per-line reserve overhead.
    buf.reserve(data.len() + 1);

    let base = data.as_ptr();
    let initial_len = buf.len();
    let mut out_ptr = unsafe { buf.as_mut_ptr().add(initial_len) };
    let mut start = 0;
    // Track contiguous runs of lines that output unchanged
    let mut run_start: usize = 0;
    let mut in_run = !suppress; // if suppress, no line passes through without delimiter

    for end_pos in memchr_iter(line_delim, data) {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), end_pos - start) };
        let line_len = end_pos - start;

        if line_len == 0 {
            if !suppress {
                // Empty line passes through in the run
                if !in_run {
                    run_start = start;
                    in_run = true;
                }
            }
            start = end_pos + 1;
            continue;
        }

        // Count delimiters up to target_idx to find the target field
        let mut field_start_offset = 0;
        let mut field_idx = 0;
        let mut found = false;
        let mut has_delim = false;

        for pos in memchr_iter(delim, line) {
            has_delim = true;
            if field_idx == target_idx {
                // Found the target field: line[field_start_offset..pos]
                // Flush run, output field + newline
                if in_run && run_start < start {
                    let run_len = start - run_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
                        out_ptr = out_ptr.add(run_len);
                    }
                }
                let field_len = pos - field_start_offset;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        base.add(start + field_start_offset),
                        out_ptr,
                        field_len,
                    );
                    out_ptr = out_ptr.add(field_len);
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
                run_start = end_pos + 1;
                in_run = true;
                found = true;
                break;
            }
            field_idx += 1;
            field_start_offset = pos + 1;
        }

        if !found {
            if !has_delim {
                // No delimiter in line
                if !suppress {
                    // Line passes through unchanged — stays in run
                    if !in_run {
                        run_start = start;
                        in_run = true;
                    }
                } else {
                    // Suppress: flush run, skip this line
                    if in_run && run_start < start {
                        let run_len = start - run_start;
                        unsafe {
                            std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
                            out_ptr = out_ptr.add(run_len);
                        }
                    }
                    in_run = false;
                    run_start = end_pos + 1;
                }
            } else if field_idx == target_idx {
                // Last field is the target: line[field_start_offset..]
                if in_run && run_start < start {
                    let run_len = start - run_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
                        out_ptr = out_ptr.add(run_len);
                    }
                }
                let field_len = line_len - field_start_offset;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        base.add(start + field_start_offset),
                        out_ptr,
                        field_len,
                    );
                    out_ptr = out_ptr.add(field_len);
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
                run_start = end_pos + 1;
                in_run = true;
            } else {
                // Not enough fields for target — output empty line
                if in_run && run_start < start {
                    let run_len = start - run_start;
                    unsafe {
                        std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
                        out_ptr = out_ptr.add(run_len);
                    }
                }
                unsafe {
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
                run_start = end_pos + 1;
                in_run = true;
            }
        }

        start = end_pos + 1;
    }

    // Flush remaining contiguous run
    if in_run && run_start < start {
        let run_len = start - run_start;
        unsafe {
            std::ptr::copy_nonoverlapping(base.add(run_start), out_ptr, run_len);
            out_ptr = out_ptr.add(run_len);
        }
    }

    // Handle last line without trailing newline
    if start < data.len() {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), data.len() - start) };
        let line_len = data.len() - start;

        if line_len == 0 {
            if !suppress {
                unsafe {
                    *out_ptr = line_delim;
                    out_ptr = out_ptr.add(1);
                }
            }
        } else {
            let mut field_start_offset = 0;
            let mut field_idx = 0;
            let mut found = false;
            let mut has_delim = false;

            for pos in memchr_iter(delim, line) {
                has_delim = true;
                if field_idx == target_idx {
                    let field_len = pos - field_start_offset;
                    unsafe {
                        std::ptr::copy_nonoverlapping(
                            base.add(start + field_start_offset),
                            out_ptr,
                            field_len,
                        );
                        out_ptr = out_ptr.add(field_len);
                        *out_ptr = line_delim;
                        out_ptr = out_ptr.add(1);
                    }
                    found = true;
                    break;
                }
                field_idx += 1;
                field_start_offset = pos + 1;
            }

            if !found {
                if !has_delim {
                    if !suppress {
                        unsafe {
                            std::ptr::copy_nonoverlapping(base.add(start), out_ptr, line_len);
                            out_ptr = out_ptr.add(line_len);
                            *out_ptr = line_delim;
                            out_ptr = out_ptr.add(1);
                        }
                    }
                } else if field_idx == target_idx {
                    let field_len = line_len - field_start_offset;
                    unsafe {
                        std::ptr::copy_nonoverlapping(
                            base.add(start + field_start_offset),
                            out_ptr,
                            field_len,
                        );
                        out_ptr = out_ptr.add(field_len);
                        *out_ptr = line_delim;
                        out_ptr = out_ptr.add(1);
                    }
                } else {
                    unsafe {
                        *out_ptr = line_delim;
                        out_ptr = out_ptr.add(1);
                    }
                }
            }
        }
    }

    unsafe {
        let new_len = out_ptr as usize - buf.as_ptr() as usize;
        debug_assert!(new_len >= initial_len && new_len <= buf.capacity());
        buf.set_len(new_len);
    }
}

/// Extract fields from a single line into the output buffer.
/// Uses unsafe buf helpers with pre-reserved capacity for zero bounds-check overhead.
/// Raw pointer arithmetic eliminates per-field bounds checking.
#[inline(always)]
fn extract_fields_to_buf(
    line: &[u8],
    delim: u8,
    ranges: &[Range],
    output_delim: &[u8],
    suppress: bool,
    max_field: usize,
    field_mask: u64,
    line_delim: u8,
    buf: &mut Vec<u8>,
    complement: bool,
) {
    let len = line.len();

    if len == 0 {
        if !suppress {
            buf.push(line_delim);
        }
        return;
    }

    // Only reserve if remaining capacity is insufficient. The caller pre-sizes the
    // buffer to data.len(), so this check avoids redundant reserve() calls per line.
    let needed = len + output_delim.len() * 16 + 1;
    if buf.capacity() - buf.len() < needed {
        buf.reserve(needed);
    }

    let base = line.as_ptr();
    let mut field_num: usize = 1;
    let mut field_start: usize = 0;
    let mut first_output = true;
    let mut has_delim = false;

    // Use memchr SIMD for all line sizes
    for delim_pos in memchr_iter(delim, line) {
        has_delim = true;

        if is_selected(field_num, field_mask, ranges, complement) {
            if !first_output {
                unsafe { buf_extend(buf, output_delim) };
            }
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(field_start), delim_pos - field_start),
                )
            };
            first_output = false;
        }

        field_num += 1;
        field_start = delim_pos + 1;

        if field_num > max_field {
            break;
        }
    }

    // Last field
    if (field_num <= max_field || complement)
        && has_delim
        && is_selected(field_num, field_mask, ranges, complement)
    {
        if !first_output {
            unsafe { buf_extend(buf, output_delim) };
        }
        unsafe {
            buf_extend(
                buf,
                std::slice::from_raw_parts(base.add(field_start), len - field_start),
            )
        };
        first_output = false;
    }

    if !first_output {
        unsafe { buf_push(buf, line_delim) };
    } else if !has_delim {
        if !suppress {
            unsafe {
                buf_extend(buf, line);
                buf_push(buf, line_delim);
            }
        }
    } else {
        unsafe { buf_push(buf, line_delim) };
    }
}

// ── Fast path: byte/char extraction with batched output ──────────────────

/// Ultra-fast path for `cut -b1-N`: single from-start byte range.
/// Zero-copy: writes directly from the source data using output runs.
/// For lines shorter than max_bytes, the output is identical to the input,
/// so we emit contiguous runs directly. Only lines exceeding max_bytes need truncation.
fn process_bytes_from_start(
    data: &[u8],
    max_bytes: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    // For data under 64MB: check if all lines fit for zero-copy passthrough.
    // When all lines fit, output = input (single write_all, no per-line processing).
    // The sequential scan (~1.7ms for 10MB at memchr speed) is cheaper than
    // per-line truncation + buffer assembly even with parallelism.
    // 64MB limit is independent of PARALLEL_THRESHOLD to preserve this fast path
    // even when parallel threshold is lowered.
    //
    // When all_fit=false, the scan breaks early at the first long line, so the
    // overhead is bounded by the position of that line (not the full file size).
    if data.len() < 64 * 1024 * 1024 && max_bytes > 0 && max_bytes < usize::MAX {
        let mut start = 0;
        let mut all_fit = true;
        for pos in memchr_iter(line_delim, data) {
            if pos - start > max_bytes {
                all_fit = false;
                break;
            }
            start = pos + 1;
        }
        // Check last line (no trailing delimiter)
        if all_fit && start < data.len() && data.len() - start > max_bytes {
            all_fit = false;
        }
        if all_fit {
            // All lines fit: output = input. Handle missing trailing delimiter.
            if !data.is_empty() && data[data.len() - 1] == line_delim {
                return out.write_all(data);
            } else if !data.is_empty() {
                out.write_all(data)?;
                return out.write_all(&[line_delim]);
            }
            return Ok(());
        }
    }

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    // Output can be up to input size (when all lines fit).
                    // Reserve full chunk size to avoid reallocation.
                    result.reserve(chunk.len());
                    bytes_from_start_chunk(chunk, max_bytes, line_delim, result);
                });
            }
        });
        // Use write_vectored (writev) to batch N writes into fewer syscalls
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        // For moderate max_bytes, the buffer path is faster than writev zero-copy
        // because every line gets truncated, creating 3 IoSlice entries per line.
        // Copying max_bytes+1 bytes into a contiguous buffer is cheaper than
        // managing millions of IoSlice entries through the kernel.
        // Threshold at 512 covers common byte-range benchmarks like -b1-100.
        if max_bytes <= 512 {
            // Estimate output size without scanning: output <= data.len(),
            // typically ~data.len()/4 for short max_bytes on longer lines.
            let est_out = (data.len() / 4).max(max_bytes + 2);
            let mut buf = Vec::with_capacity(est_out.min(data.len()));
            bytes_from_start_chunk(data, max_bytes, line_delim, &mut buf);
            if !buf.is_empty() {
                out.write_all(&buf)?;
            }
        } else {
            // Zero-copy path: track contiguous output runs and write directly from source.
            // For lines <= max_bytes, we include them as-is (no copy needed).
            // For lines > max_bytes, we flush the run, write the truncated line, start new run.
            bytes_from_start_zerocopy(data, max_bytes, line_delim, out)?;
        }
    }
    Ok(())
}

/// Zero-copy byte-prefix extraction using writev: builds IoSlice entries pointing
/// directly into the source data, flushing in MAX_IOV-sized batches.
/// Lines shorter than max_bytes stay in contiguous runs. Lines needing truncation
/// produce two IoSlices (truncated data + newline).
#[inline]
fn bytes_from_start_zerocopy(
    data: &[u8],
    max_bytes: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let newline_buf: [u8; 1] = [line_delim];
    let mut iov: Vec<IoSlice> = Vec::with_capacity(MAX_IOV);
    let mut start = 0;
    let mut run_start: usize = 0;

    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        if line_len > max_bytes {
            // This line needs truncation
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..start + max_bytes]));
            iov.push(IoSlice::new(&newline_buf));
            run_start = pos + 1;

            if iov.len() >= MAX_IOV - 2 {
                write_ioslices(out, &iov)?;
                iov.clear();
            }
        }
        start = pos + 1;
    }
    // Handle last line without terminator
    if start < data.len() {
        let line_len = data.len() - start;
        if line_len > max_bytes {
            if run_start < start {
                iov.push(IoSlice::new(&data[run_start..start]));
            }
            iov.push(IoSlice::new(&data[start..start + max_bytes]));
            iov.push(IoSlice::new(&newline_buf));
            if !iov.is_empty() {
                write_ioslices(out, &iov)?;
            }
            return Ok(());
        }
    }
    // Flush remaining contiguous run
    if run_start < data.len() {
        iov.push(IoSlice::new(&data[run_start..]));
        if !data.is_empty() && *data.last().unwrap() != line_delim {
            iov.push(IoSlice::new(&newline_buf));
        }
    }
    if !iov.is_empty() {
        write_ioslices(out, &iov)?;
    }
    Ok(())
}

/// Process a chunk for from-start byte range extraction (parallel path).
/// Uses unsafe appends to eliminate bounds checking in the hot loop.
/// Pre-reserves data.len() (output never exceeds input), then uses a single
/// write pointer with deferred set_len — no per-line capacity checks.
#[inline]
fn bytes_from_start_chunk(data: &[u8], max_bytes: usize, line_delim: u8, buf: &mut Vec<u8>) {
    // Output is always <= input size (we only truncate, never expand).
    // Single reserve eliminates ALL per-line capacity checks.
    buf.reserve(data.len());

    let src = data.as_ptr();
    let dst_base = buf.as_mut_ptr();
    let mut wp = buf.len();
    let mut start = 0;

    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        let take = line_len.min(max_bytes);
        unsafe {
            std::ptr::copy_nonoverlapping(src.add(start), dst_base.add(wp), take);
            *dst_base.add(wp + take) = line_delim;
        }
        wp += take + 1;
        start = pos + 1;
    }
    // Handle last line without terminator
    if start < data.len() {
        let line_len = data.len() - start;
        let take = line_len.min(max_bytes);
        unsafe {
            std::ptr::copy_nonoverlapping(src.add(start), dst_base.add(wp), take);
            *dst_base.add(wp + take) = line_delim;
        }
        wp += take + 1;
    }
    unsafe { buf.set_len(wp) };
}

/// Fast path for `cut -bN-`: skip first N-1 bytes per line.
fn process_bytes_from_offset(
    data: &[u8],
    skip_bytes: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    bytes_from_offset_chunk(chunk, skip_bytes, line_delim, result);
                });
            }
        });
        // Use write_vectored (writev) to batch N writes into fewer syscalls
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        // Zero-copy: write suffix of each line directly from source
        bytes_from_offset_zerocopy(data, skip_bytes, line_delim, out)?;
    }
    Ok(())
}

/// Zero-copy byte-offset extraction: writes suffix of each line directly from source data.
/// Collects IoSlice pairs (data + delimiter) and flushes with write_vectored in batches,
/// reducing syscall overhead from 2 write_all calls per line to batched writev.
#[inline]
fn bytes_from_offset_zerocopy(
    data: &[u8],
    skip_bytes: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let delim_buf = [line_delim];
    let mut iov: Vec<IoSlice> = Vec::with_capacity(256);

    let mut start = 0;
    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        if line_len > skip_bytes {
            iov.push(IoSlice::new(&data[start + skip_bytes..pos]));
        }
        iov.push(IoSlice::new(&delim_buf));
        // Flush when approaching MAX_IOV to avoid oversized writev
        if iov.len() >= MAX_IOV - 1 {
            write_ioslices(out, &iov)?;
            iov.clear();
        }
        start = pos + 1;
    }
    if start < data.len() {
        let line_len = data.len() - start;
        if line_len > skip_bytes {
            iov.push(IoSlice::new(&data[start + skip_bytes..data.len()]));
        }
        iov.push(IoSlice::new(&delim_buf));
    }
    if !iov.is_empty() {
        write_ioslices(out, &iov)?;
    }
    Ok(())
}

/// Process a chunk for from-offset byte range extraction.
/// Single reserve + deferred set_len for zero per-line overhead.
#[inline]
fn bytes_from_offset_chunk(data: &[u8], skip_bytes: usize, line_delim: u8, buf: &mut Vec<u8>) {
    buf.reserve(data.len());

    let src = data.as_ptr();
    let dst_base = buf.as_mut_ptr();
    let mut wp = buf.len();
    let mut start = 0;

    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        if line_len > skip_bytes {
            let take = line_len - skip_bytes;
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start + skip_bytes), dst_base.add(wp), take);
            }
            wp += take;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
        start = pos + 1;
    }
    if start < data.len() {
        let line_len = data.len() - start;
        if line_len > skip_bytes {
            let take = line_len - skip_bytes;
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start + skip_bytes), dst_base.add(wp), take);
            }
            wp += take;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
    }
    unsafe { buf.set_len(wp) };
}

/// Fast path for `cut -bN-M` where N > 1 and M < MAX: extract bytes N through M per line.
fn process_bytes_mid_range(
    data: &[u8],
    start_byte: usize,
    end_byte: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let skip = start_byte.saturating_sub(1);

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    bytes_mid_range_chunk(chunk, skip, end_byte, line_delim, result);
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            bytes_mid_range_chunk(chunk, skip, end_byte, line_delim, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk for mid-range byte extraction.
/// For each line, output bytes skip..min(line_len, end_byte).
/// Single reserve + deferred set_len.
#[inline]
fn bytes_mid_range_chunk(
    data: &[u8],
    skip: usize,
    end_byte: usize,
    line_delim: u8,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());

    let src = data.as_ptr();
    let dst_base = buf.as_mut_ptr();
    let mut wp = buf.len();
    let mut start = 0;

    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        if line_len > skip {
            let take_end = line_len.min(end_byte);
            let take = take_end - skip;
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start + skip), dst_base.add(wp), take);
            }
            wp += take;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
        start = pos + 1;
    }
    if start < data.len() {
        let line_len = data.len() - start;
        if line_len > skip {
            let take_end = line_len.min(end_byte);
            let take = take_end - skip;
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start + skip), dst_base.add(wp), take);
            }
            wp += take;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
    }
    unsafe { buf.set_len(wp) };
}

/// Fast path for `--complement -bN-M`: output bytes 1..N-1 and M+1..end per line.
fn process_bytes_complement_mid(
    data: &[u8],
    skip_start: usize,
    skip_end: usize,
    line_delim: u8,
    out: &mut impl Write,
) -> io::Result<()> {
    let prefix_bytes = skip_start - 1; // bytes before the skip region
    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len());
                    bytes_complement_mid_chunk(chunk, prefix_bytes, skip_end, line_delim, result);
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            bytes_complement_mid_chunk(chunk, prefix_bytes, skip_end, line_delim, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk for complement mid-range byte extraction.
/// For each line: output bytes 0..prefix_bytes, then bytes skip_end..line_len.
#[inline]
fn bytes_complement_mid_chunk(
    data: &[u8],
    prefix_bytes: usize,
    skip_end: usize,
    line_delim: u8,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());

    let src = data.as_ptr();
    let dst_base = buf.as_mut_ptr();
    let mut wp = buf.len();
    let mut start = 0;

    for pos in memchr_iter(line_delim, data) {
        let line_len = pos - start;
        // Copy prefix (bytes before skip region)
        let take_prefix = prefix_bytes.min(line_len);
        if take_prefix > 0 {
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start), dst_base.add(wp), take_prefix);
            }
            wp += take_prefix;
        }
        // Copy suffix (bytes after skip region)
        if line_len > skip_end {
            let suffix_len = line_len - skip_end;
            unsafe {
                std::ptr::copy_nonoverlapping(
                    src.add(start + skip_end),
                    dst_base.add(wp),
                    suffix_len,
                );
            }
            wp += suffix_len;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
        start = pos + 1;
    }
    if start < data.len() {
        let line_len = data.len() - start;
        let take_prefix = prefix_bytes.min(line_len);
        if take_prefix > 0 {
            unsafe {
                std::ptr::copy_nonoverlapping(src.add(start), dst_base.add(wp), take_prefix);
            }
            wp += take_prefix;
        }
        if line_len > skip_end {
            let suffix_len = line_len - skip_end;
            unsafe {
                std::ptr::copy_nonoverlapping(
                    src.add(start + skip_end),
                    dst_base.add(wp),
                    suffix_len,
                );
            }
            wp += suffix_len;
        }
        unsafe {
            *dst_base.add(wp) = line_delim;
        }
        wp += 1;
    }
    unsafe { buf.set_len(wp) };
}

/// Optimized byte/char extraction with batched output and parallel processing.
fn process_bytes_fast(data: &[u8], cfg: &CutConfig, out: &mut impl Write) -> io::Result<()> {
    let line_delim = cfg.line_delim;
    let ranges = cfg.ranges;
    let complement = cfg.complement;
    let output_delim = cfg.output_delim;

    // Ultra-fast path: single range from byte 1 (e.g., cut -b1-10, cut -b-20)
    if !complement && ranges.len() == 1 && ranges[0].start == 1 && output_delim.is_empty() {
        let max_bytes = ranges[0].end;
        if max_bytes < usize::MAX {
            return process_bytes_from_start(data, max_bytes, line_delim, out);
        }
    }

    // Fast path: single open-ended range from byte N (e.g., cut -b5-)
    if !complement && ranges.len() == 1 && ranges[0].end == usize::MAX && output_delim.is_empty() {
        let skip_bytes = ranges[0].start.saturating_sub(1);
        if skip_bytes > 0 {
            return process_bytes_from_offset(data, skip_bytes, line_delim, out);
        }
    }

    // Fast path: single mid-range (e.g., cut -b5-100)
    if !complement
        && ranges.len() == 1
        && ranges[0].start > 1
        && ranges[0].end < usize::MAX
        && output_delim.is_empty()
    {
        return process_bytes_mid_range(data, ranges[0].start, ranges[0].end, line_delim, out);
    }

    // Fast path: complement of single from-start range (e.g., --complement -b1-100 = output bytes 101+)
    if complement
        && ranges.len() == 1
        && ranges[0].start == 1
        && ranges[0].end < usize::MAX
        && output_delim.is_empty()
    {
        return process_bytes_from_offset(data, ranges[0].end, line_delim, out);
    }

    // Fast path: complement of single from-offset range (e.g., --complement -b5- = output bytes 1-4)
    if complement
        && ranges.len() == 1
        && ranges[0].end == usize::MAX
        && ranges[0].start > 1
        && output_delim.is_empty()
    {
        let max_bytes = ranges[0].start - 1;
        return process_bytes_from_start(data, max_bytes, line_delim, out);
    }

    // Fast path: complement of single mid-range (e.g., --complement -b5-100 = bytes 1-4,101+)
    if complement
        && ranges.len() == 1
        && ranges[0].start > 1
        && ranges[0].end < usize::MAX
        && output_delim.is_empty()
    {
        return process_bytes_complement_mid(data, ranges[0].start, ranges[0].end, line_delim, out);
    }

    if data.len() >= PARALLEL_THRESHOLD {
        let chunks = split_for_scope(data, line_delim);
        let n = chunks.len();
        let mut results: Vec<Vec<u8>> = (0..n).map(|_| Vec::new()).collect();
        rayon::scope(|s| {
            for (chunk, result) in chunks.iter().zip(results.iter_mut()) {
                s.spawn(move |_| {
                    result.reserve(chunk.len() + 1);
                    process_bytes_chunk(
                        chunk,
                        ranges,
                        complement,
                        output_delim,
                        line_delim,
                        result,
                    );
                });
            }
        });
        let slices: Vec<IoSlice> = results
            .iter()
            .filter(|r| !r.is_empty())
            .map(|r| IoSlice::new(r))
            .collect();
        write_ioslices(out, &slices)?;
    } else {
        process_chunked(data, line_delim, out, |chunk, buf| {
            process_bytes_chunk(chunk, ranges, complement, output_delim, line_delim, buf);
        })?;
    }
    Ok(())
}

/// Process a chunk of data for byte/char extraction.
/// Uses raw pointer arithmetic for the newline scan.
/// Complement single-range fast path: compute complement ranges once, then use
/// the non-complement multi-range path which is more cache-friendly.
fn process_bytes_chunk(
    data: &[u8],
    ranges: &[Range],
    complement: bool,
    output_delim: &[u8],
    line_delim: u8,
    buf: &mut Vec<u8>,
) {
    buf.reserve(data.len());
    let base = data.as_ptr();
    let mut start = 0;
    for end_pos in memchr_iter(line_delim, data) {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), end_pos - start) };
        cut_bytes_to_buf(line, ranges, complement, output_delim, buf);
        unsafe { buf_push(buf, line_delim) };
        start = end_pos + 1;
    }
    if start < data.len() {
        let line = unsafe { std::slice::from_raw_parts(base.add(start), data.len() - start) };
        cut_bytes_to_buf(line, ranges, complement, output_delim, buf);
        unsafe { buf_push(buf, line_delim) };
    }
}

/// Extract byte ranges from a line into the output buffer.
/// Uses unsafe buf helpers for zero bounds-check overhead in hot loops.
/// Raw pointer arithmetic eliminates per-range bounds checking.
#[inline(always)]
fn cut_bytes_to_buf(
    line: &[u8],
    ranges: &[Range],
    complement: bool,
    output_delim: &[u8],
    buf: &mut Vec<u8>,
) {
    let len = line.len();
    let base = line.as_ptr();
    let mut first_range = true;

    // Reserve worst case: full line + delimiters between ranges
    let needed = len + output_delim.len() * ranges.len() + 1;
    if buf.capacity() - buf.len() < needed {
        buf.reserve(needed);
    }

    if complement {
        let mut pos: usize = 1;
        for r in ranges {
            let rs = r.start;
            let re = r.end.min(len);
            if pos < rs {
                if !first_range && !output_delim.is_empty() {
                    unsafe { buf_extend(buf, output_delim) };
                }
                unsafe { buf_extend(buf, std::slice::from_raw_parts(base.add(pos - 1), rs - pos)) };
                first_range = false;
            }
            pos = re + 1;
            if pos > len {
                break;
            }
        }
        if pos <= len {
            if !first_range && !output_delim.is_empty() {
                unsafe { buf_extend(buf, output_delim) };
            }
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(pos - 1), len - pos + 1),
                )
            };
        }
    } else if output_delim.is_empty() && ranges.len() == 1 {
        // Ultra-fast path: single range, no output delimiter
        let start = ranges[0].start.saturating_sub(1);
        let end = ranges[0].end.min(len);
        if start < len {
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(start), end - start),
                )
            };
        }
    } else {
        for r in ranges {
            let start = r.start.saturating_sub(1);
            let end = r.end.min(len);
            if start >= len {
                break;
            }
            if !first_range && !output_delim.is_empty() {
                unsafe { buf_extend(buf, output_delim) };
            }
            unsafe {
                buf_extend(
                    buf,
                    std::slice::from_raw_parts(base.add(start), end - start),
                )
            };
            first_range = false;
        }
    }
}

// ── Public API ───────────────────────────────────────────────────────────

/// Cut fields from a line using a delimiter. Writes to `out`.
#[inline]
pub fn cut_fields(
    line: &[u8],
    delim: u8,
    ranges: &[Range],
    complement: bool,
    output_delim: &[u8],
    suppress_no_delim: bool,
    out: &mut impl Write,
) -> io::Result<bool> {
    if memchr::memchr(delim, line).is_none() {
        if !suppress_no_delim {
            out.write_all(line)?;
            return Ok(true);
        }
        return Ok(false);
    }

    let mut field_num: usize = 1;
    let mut field_start: usize = 0;
    let mut first_output = true;

    for delim_pos in memchr_iter(delim, line) {
        let selected = in_ranges(ranges, field_num) != complement;
        if selected {
            if !first_output {
                out.write_all(output_delim)?;
            }
            out.write_all(&line[field_start..delim_pos])?;
            first_output = false;
        }
        field_start = delim_pos + 1;
        field_num += 1;
    }

    let selected = in_ranges(ranges, field_num) != complement;
    if selected {
        if !first_output {
            out.write_all(output_delim)?;
        }
        out.write_all(&line[field_start..])?;
    }

    Ok(true)
}

/// Cut bytes/chars from a line. Writes selected bytes to `out`.
#[inline]
pub fn cut_bytes(
    line: &[u8],
    ranges: &[Range],
    complement: bool,
    output_delim: &[u8],
    out: &mut impl Write,
) -> io::Result<bool> {
    let mut first_range = true;

    if complement {
        let len = line.len();
        let mut comp_ranges = Vec::new();
        let mut pos: usize = 1;
        for r in ranges {
            let rs = r.start;
            let re = r.end.min(len);
            if pos < rs {
                comp_ranges.push((pos, rs - 1));
            }
            pos = re + 1;
            if pos > len {
                break;
            }
        }
        if pos <= len {
            comp_ranges.push((pos, len));
        }
        for &(s, e) in &comp_ranges {
            if !first_range && !output_delim.is_empty() {
                out.write_all(output_delim)?;
            }
            out.write_all(&line[s - 1..e])?;
            first_range = false;
        }
    } else {
        for r in ranges {
            let start = r.start.saturating_sub(1);
            let end = r.end.min(line.len());
            if start >= line.len() {
                break;
            }
            if !first_range && !output_delim.is_empty() {
                out.write_all(output_delim)?;
            }
            out.write_all(&line[start..end])?;
            first_range = false;
        }
    }
    Ok(true)
}

/// In-place field 1 extraction: modifies `data` buffer directly, returns new length.
/// Output is always <= input (we remove everything after first delimiter per line).
/// Avoids intermediate Vec allocation + BufWriter copy, saving ~10MB of memory
/// bandwidth for 10MB input. Requires owned mutable data (not mmap).
///
/// Lines without delimiter pass through unchanged (unless suppress=true).
/// Lines with delimiter: keep bytes before delimiter + newline.
pub fn cut_field1_inplace(data: &mut [u8], delim: u8, line_delim: u8, suppress: bool) -> usize {
    let len = data.len();
    let mut wp: usize = 0;
    let mut rp: usize = 0;

    while rp < len {
        match memchr::memchr2(delim, line_delim, &data[rp..]) {
            None => {
                // Rest is partial line, no delimiter
                if suppress {
                    // suppress: skip lines without delimiter
                    break;
                }
                let remaining = len - rp;
                if wp != rp {
                    data.copy_within(rp..len, wp);
                }
                wp += remaining;
                break;
            }
            Some(offset) => {
                let actual = rp + offset;
                if data[actual] == line_delim {
                    // No delimiter on this line
                    if suppress {
                        // Skip this line entirely
                        rp = actual + 1;
                    } else {
                        // Output entire line including newline
                        let chunk_len = actual + 1 - rp;
                        if wp != rp {
                            data.copy_within(rp..actual + 1, wp);
                        }
                        wp += chunk_len;
                        rp = actual + 1;
                    }
                } else {
                    // Delimiter found: output field 1 (up to delimiter) + newline
                    let field_len = actual - rp;
                    if wp != rp && field_len > 0 {
                        data.copy_within(rp..actual, wp);
                    }
                    wp += field_len;
                    data[wp] = line_delim;
                    wp += 1;
                    // Skip to next newline
                    match memchr::memchr(line_delim, &data[actual + 1..]) {
                        None => {
                            rp = len;
                        }
                        Some(nl_off) => {
                            rp = actual + 1 + nl_off + 1;
                        }
                    }
                }
            }
        }
    }
    wp
}

/// Process a full data buffer (from mmap or read) with cut operation.
pub fn process_cut_data(data: &[u8], cfg: &CutConfig, out: &mut impl Write) -> io::Result<()> {
    match cfg.mode {
        CutMode::Fields => process_fields_fast(data, cfg, out),
        CutMode::Bytes | CutMode::Characters => process_bytes_fast(data, cfg, out),
    }
}

/// Process input from a reader (for stdin).
/// Uses batch reading: reads large chunks (16MB), then processes them in batch
/// using the fast mmap-based paths, avoiding per-line read_until syscall overhead.
/// 16MB chunks mean a 10MB piped input is consumed in a single batch.
pub fn process_cut_reader<R: BufRead>(
    mut reader: R,
    cfg: &CutConfig,
    out: &mut impl Write,
) -> io::Result<()> {
    const CHUNK_SIZE: usize = 16 * 1024 * 1024; // 16MB read chunks
    let line_delim = cfg.line_delim;

    // Read large chunks and process in batch.
    // We keep a buffer; after processing complete lines, we shift leftover to the front.
    let mut buf = Vec::with_capacity(CHUNK_SIZE + 4096);

    loop {
        // Read up to CHUNK_SIZE bytes
        buf.reserve(CHUNK_SIZE);
        let read_start = buf.len();
        unsafe { buf.set_len(read_start + CHUNK_SIZE) };
        let n = read_fully(&mut reader, &mut buf[read_start..])?;
        buf.truncate(read_start + n);

        if buf.is_empty() {
            break;
        }

        if n == 0 {
            // EOF with leftover data (last line without terminator)
            process_cut_data(&buf, cfg, out)?;
            break;
        }

        // Find the last line delimiter in the buffer so we process complete lines
        let process_end = match memchr::memrchr(line_delim, &buf) {
            Some(pos) => pos + 1,
            None => {
                // No line delimiter found — keep accumulating
                continue;
            }
        };

        // Process the complete lines using the fast batch path
        process_cut_data(&buf[..process_end], cfg, out)?;

        // Shift leftover to the front for next iteration
        let leftover_len = buf.len() - process_end;
        if leftover_len > 0 {
            buf.copy_within(process_end.., 0);
        }
        buf.truncate(leftover_len);
    }

    Ok(())
}

/// Read as many bytes as possible into buf, retrying on partial reads.
#[inline]
fn read_fully<R: BufRead>(reader: &mut R, buf: &mut [u8]) -> io::Result<usize> {
    let n = reader.read(buf)?;
    if n == buf.len() || n == 0 {
        return Ok(n);
    }
    // Slow path: partial read — retry to fill buffer
    let mut total = n;
    while total < buf.len() {
        match reader.read(&mut buf[total..]) {
            Ok(0) => break,
            Ok(n) => total += n,
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        }
    }
    Ok(total)
}

/// In-place cut processing for mutable data buffers.
/// Returns Some(new_length) if in-place processing succeeded, None if not supported
/// for the given configuration (caller should fall back to regular processing).
///
/// In-place avoids allocating intermediate output buffers — the result is written
/// directly into the input buffer (output is always <= input for non-complement modes
/// with default output delimiter).
///
/// Note: if the input does not end with line_delim, we fall back to the regular
/// path because GNU cut always adds a trailing line delimiter, and the in-place
/// buffer cannot grow beyond the input size.
pub fn process_cut_data_mut(data: &mut [u8], cfg: &CutConfig) -> Option<usize> {
    if cfg.complement {
        return None;
    }
    // If input doesn't end with line_delim, the output may need an extra byte
    // (GNU cut always terminates the last line). In-place can't grow the buffer,
    // so fall back to the regular allocating path.
    if data.is_empty() || data[data.len() - 1] != cfg.line_delim {
        return None;
    }

    match cfg.mode {
        CutMode::Fields => {
            // Only handle when output delimiter matches input (single-byte)
            if cfg.output_delim.len() != 1 || cfg.output_delim[0] != cfg.delim {
                return None;
            }
            if cfg.delim == cfg.line_delim {
                return None;
            }
            Some(cut_fields_inplace_general(
                data,
                cfg.delim,
                cfg.line_delim,
                cfg.ranges,
                cfg.suppress_no_delim,
            ))
        }
        CutMode::Bytes | CutMode::Characters => {
            if !cfg.output_delim.is_empty() {
                return None;
            }
            Some(cut_bytes_inplace_general(data, cfg.line_delim, cfg.ranges))
        }
    }
}

/// In-place generalized field extraction.
/// Handles single fields, contiguous ranges, and non-contiguous multi-field patterns.
fn cut_fields_inplace_general(
    data: &mut [u8],
    delim: u8,
    line_delim: u8,
    ranges: &[Range],
    suppress: bool,
) -> usize {
    // Special case: field 1 only (existing optimized path)
    if ranges.len() == 1 && ranges[0].start == 1 && ranges[0].end == 1 {
        return cut_field1_inplace(data, delim, line_delim, suppress);
    }

    let len = data.len();
    if len == 0 {
        return 0;
    }

    let max_field = ranges.last().map_or(0, |r| r.end);
    let max_delims = max_field.min(128);
    let mut wp: usize = 0;
    let mut rp: usize = 0;

    while rp < len {
        let line_end = memchr::memchr(line_delim, &data[rp..])
            .map(|p| rp + p)
            .unwrap_or(len);
        let line_len = line_end - rp;

        // Collect delimiter positions (relative to line start)
        let mut delim_pos = [0usize; 128];
        let mut num_delims: usize = 0;

        for pos in memchr_iter(delim, &data[rp..line_end]) {
            if num_delims < max_delims {
                delim_pos[num_delims] = pos;
                num_delims += 1;
                if num_delims >= max_delims {
                    break;
                }
            }
        }

        if num_delims == 0 {
            // No delimiter in line
            if !suppress {
                if wp != rp {
                    data.copy_within(rp..line_end, wp);
                }
                wp += line_len;
                if line_end < len {
                    data[wp] = line_delim;
                    wp += 1;
                }
            }
        } else {
            let total_fields = num_delims + 1;
            let mut first_output = true;

            for r in ranges {
                let range_start = r.start;
                let range_end = r.end.min(total_fields);
                if range_start > total_fields {
                    break;
                }
                for field_num in range_start..=range_end {
                    if field_num > total_fields {
                        break;
                    }

                    let field_start = if field_num == 1 {
                        0
                    } else if field_num - 2 < num_delims {
                        delim_pos[field_num - 2] + 1
                    } else {
                        continue;
                    };
                    let field_end = if field_num <= num_delims {
                        delim_pos[field_num - 1]
                    } else {
                        line_len
                    };

                    if !first_output {
                        data[wp] = delim;
                        wp += 1;
                    }
                    let flen = field_end - field_start;
                    if flen > 0 {
                        data.copy_within(rp + field_start..rp + field_start + flen, wp);
                        wp += flen;
                    }
                    first_output = false;
                }
            }

            if !first_output && line_end < len {
                data[wp] = line_delim;
                wp += 1;
            } else if first_output && line_end < len {
                // No fields selected but line had delimiters — output empty line
                data[wp] = line_delim;
                wp += 1;
            }
        }

        rp = if line_end < len { line_end + 1 } else { len };
    }

    wp
}

/// In-place byte/char range extraction.
fn cut_bytes_inplace_general(data: &mut [u8], line_delim: u8, ranges: &[Range]) -> usize {
    let len = data.len();
    if len == 0 {
        return 0;
    }

    // Quick check: single range from byte 1 to end = no-op
    if ranges.len() == 1 && ranges[0].start == 1 && ranges[0].end == usize::MAX {
        return len;
    }

    // Single range from byte 1: fast truncation path
    if ranges.len() == 1 && ranges[0].start == 1 && ranges[0].end < usize::MAX {
        return cut_bytes_from_start_inplace(data, line_delim, ranges[0].end);
    }

    let mut wp: usize = 0;
    let mut rp: usize = 0;

    while rp < len {
        let line_end = memchr::memchr(line_delim, &data[rp..])
            .map(|p| rp + p)
            .unwrap_or(len);
        let line_len = line_end - rp;

        for r in ranges {
            let start = r.start.saturating_sub(1);
            let end = r.end.min(line_len);
            if start >= line_len {
                break;
            }
            let flen = end - start;
            if flen > 0 {
                data.copy_within(rp + start..rp + start + flen, wp);
                wp += flen;
            }
        }

        if line_end < len {
            data[wp] = line_delim;
            wp += 1;
        }

        rp = if line_end < len { line_end + 1 } else { len };
    }

    wp
}

/// In-place truncation for -b1-N: truncate each line to at most max_bytes.
fn cut_bytes_from_start_inplace(data: &mut [u8], line_delim: u8, max_bytes: usize) -> usize {
    let len = data.len();

    // Quick check: see if all lines fit within max_bytes (common case)
    let mut all_fit = true;
    let mut start = 0;
    for pos in memchr_iter(line_delim, data) {
        if pos - start > max_bytes {
            all_fit = false;
            break;
        }
        start = pos + 1;
    }
    if all_fit && start < len && len - start > max_bytes {
        all_fit = false;
    }
    if all_fit {
        return len;
    }

    // Some lines need truncation
    let mut wp: usize = 0;
    let mut rp: usize = 0;

    while rp < len {
        let line_end = memchr::memchr(line_delim, &data[rp..])
            .map(|p| rp + p)
            .unwrap_or(len);
        let line_len = line_end - rp;

        let take = line_len.min(max_bytes);
        if take > 0 && wp != rp {
            data.copy_within(rp..rp + take, wp);
        }
        wp += take;

        if line_end < len {
            data[wp] = line_delim;
            wp += 1;
        }

        rp = if line_end < len { line_end + 1 } else { len };
    }

    wp
}

/// Cut operation mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CutMode {
    Bytes,
    Characters,
    Fields,
}