structured-zstd 0.2.2

Pure-Rust Zstandard (zstd) compression and decompression: all levels, streaming, dictionaries, no_std and WebAssembly ready — no FFI, no cmake
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
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
//! `zstd` command-line interface with upstream-compatible flag dispatch.
//!
//! The argument model mirrors upstream zstd v1.5.7: mode + level FLAGS (not
//! subcommands), `argv[0]` dispatch (`unzstd` / `zstdcat` change the default
//! mode), stdin/stdout streaming, `-r` / `--filelist` / `--output-dir-*` file
//! selection, the `ZSTD_CLEVEL` / `ZSTD_NBTHREADS` environment, the `-q` /
//! `-v` display levels, and the conventional `-o`/`-f`/`-k`/`-D` file flags.
//! Compression/decompression run through the streaming codec, so peak memory
//! stays O(window), not O(file). Exit status is 0, 1 when any input failed,
//! and 2 when interrupted, as the reference command's is.

use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, ErrorKind, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};

use structured_zstd::encoding::{
    CompressionContext, CompressionLevel, CompressionParameters, LevelParameters,
    LiteralCompressionMode, Strategy, StreamingEncoder,
};

/// Error type for the tool: a boxed message, which is all a command-line
/// program does with an error — print it and exit non-zero. Written against
/// `std` rather than an error library so the tool adds no dependency to the
/// crate that hosts it.
type Error = Box<dyn std::error::Error + Send + Sync>;

/// The tool's result alias, shadowing `std::result::Result`'s second parameter.
type Result<T, E = Error> = core::result::Result<T, E>;

/// Build an [`Error`] from a format string.
macro_rules! eyre {
    ($($arg:tt)*) => {
        <$crate::Error as From<String>>::from(format!($($arg)*))
    };
}

/// Return early with a formatted [`Error`].
macro_rules! bail {
    ($($arg:tt)*) => {
        return Err(eyre!($($arg)*))
    };
}

/// Attach context to an error, the way `wrap_err` does: the message, then the
/// cause. Kept under the same names so every call site reads unchanged.
trait WrapErr<T> {
    /// Prefix the error with `msg`.
    fn wrap_err(self, msg: impl core::fmt::Display) -> Result<T>;
    /// Prefix the error with a message built only when there is an error.
    fn wrap_err_with<D: core::fmt::Display, F: FnOnce() -> D>(self, msg: F) -> Result<T>;
}

impl<T, E: core::fmt::Display> WrapErr<T> for core::result::Result<T, E> {
    fn wrap_err(self, msg: impl core::fmt::Display) -> Result<T> {
        self.map_err(|source| eyre!("{msg}: {source}"))
    }

    fn wrap_err_with<D: core::fmt::Display, F: FnOnce() -> D>(self, msg: F) -> Result<T> {
        self.map_err(|source| eyre!("{}: {source}", msg()))
    }
}
/// Say something on stderr when `$verbosity` reaches `$level`: `1` carries
/// errors, `2` results and warnings, `3` progress, `4` detail. A tool this
/// size does not need a tracing subscriber; a macro keeps every call site a
/// line.
macro_rules! display {
    ($verbosity:expr, $level:expr, $($arg:tt)*) => {
        if $verbosity >= $level {
            eprintln!($($arg)*);
        }
    };
}

mod display;
mod identity;
mod inputs;
mod interrupt;
mod priority;
mod progress;
mod synthetic;
mod trace;

use display::{DEFAULT_LEVEL, HumanSize, Progress, confirm};
use inputs::Selection;
use progress::ProgressMonitor;

const ZSTD_SUFFIX: &str = ".zst";

/// Suffixes a decompressed name is derived from, each with what replaces it:
/// `.zst` and `.zstd` are dropped, `.tzst` becomes `.tar`, as the reference
/// command's suffix list has it.
const DECOMPRESS_SUFFIXES: [(&str, &str); 3] = [("zst", ""), ("zstd", ""), ("tzst", "tar")];

/// The reference command version whose command line this tool follows.
const UPSTREAM_VERSION: &str = "1.5.7";

/// [`UPSTREAM_VERSION`] as `ZSTD_VERSION_NUMBER` spells it
/// (`major * 10000 + minor * 100 + release`), the version a trace line carries.
const UPSTREAM_VERSION_NUMBER: u32 = 10507;

/// How the reference command names stdout in a summary line.
const STDOUT_MARK: &str = "/*stdout*\\";

/// Highest level the CLI compresses at when `--ultra` was not given (upstream
/// `ZSTDCLI_CLEVEL_MAX`). Asking for more without naming `--ultra` reduces to
/// this with a warning rather than failing.
const CLI_MAX_LEVEL_WITHOUT_ULTRA: i32 = 19;

/// Operation selected by mode flags / `argv[0]`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
    Compress,
    Decompress,
    Test,
    List,
    Train,
}

/// The standard streams a run treats as terminals whatever they are
/// (`--fake-stdin-is-console` and its siblings), so the rules that depend on a
/// terminal can be exercised from a script.
#[derive(Clone, Copy, Default)]
struct FakeConsole {
    stdin: bool,
    stdout: bool,
    stderr: bool,
}

impl FakeConsole {
    fn stdin(self) -> bool {
        self.stdin || io::stdin().is_terminal()
    }

    fn stdout(self) -> bool {
        self.stdout || io::stdout().is_terminal()
    }

    fn stderr(self) -> bool {
        self.stderr || io::stderr().is_terminal()
    }
}

/// Parsed command line.
struct Options {
    mode: Mode,
    /// Numeric compression level (zstd scale).
    level: i32,
    /// Raw dictionary blob path (`-D`), applied to both compress and decompress.
    dict: Option<PathBuf>,
    /// Force output to stdout (`-c` / `zstdcat` / a `-` input).
    to_stdout: bool,
    /// Explicit output path (`-o`); at most one input is allowed with it.
    output: Option<PathBuf>,
    force: bool,
    keep: bool,
    /// Remove source files after a successful (de)compression (`--rm`; implied
    /// by upstream's default when not `-k`/stdout, but we keep the input unless
    /// `--rm` is given — safer default for a young tool).
    remove_source: bool,
    /// Positional inputs; empty or a lone `-` means stdin. Held as paths
    /// rather than text: a filename is bytes and need not be UTF-8.
    inputs: Vec<PathBuf>,
    /// Target dictionary size for `--train` (`--maxdict`, upstream default 112640).
    max_dict: usize,
    /// Explicit dictionary ID for `--train` (`--dictID`).
    dict_id: Option<u32>,
    /// Benchmark mode (`-b`); benchmarks `bench_start..=bench_end`. The start
    /// is the compression level, as the reference command takes it.
    bench: bool,
    bench_start: i32,
    bench_end: i32,
    /// Per-level benchmark time budget in seconds (`-i`, default 1). Zero
    /// measures one pass.
    bench_secs: f64,
    /// `-p#`: a number the benchmark's `-q` lines carry as `(param=#)`, to
    /// tell runs of a parameter sweep apart.
    bench_param: Option<u32>,
    /// `-P#`: with no input named, benchmark generated data of this
    /// compressibility in percent instead of lorem ipsum text.
    bench_compressibility: Option<u32>,
    /// `-p`: wait for Enter before exiting.
    pause: bool,
    /// `--priority=rt`: the benchmark measures at real-time scheduling.
    bench_realtime: bool,
    /// Which standard streams count as terminals; see [`FakeConsole`].
    console: FakeConsole,
    /// `--trace FILE`: where one CSV line per frame is appended.
    trace: Option<PathBuf>,
    /// The widest window decoding takes; see [`decode_window_ceiling`]. Set
    /// once the command line is settled.
    decode_window: u64,
    /// A patch lifted the decode window to its widest, and no `-M` (`-M0`
    /// included) came after to set a limit of its own.
    patch_window_lifted: bool,
    /// Measure each input on its own (`-S`) instead of as one stream, so the
    /// reported ratio and throughput describe a file rather than a mixture.
    bench_separately: bool,
    /// `-B#`: the benchmark cuts every input into independent frames of this
    /// many bytes (below [`MIN_BENCH_BLOCK_SIZE`] it cuts nothing, as the
    /// reference's benchmark ignores such a size).
    block_size: Option<u64>,
    /// Long-distance matching (`--long`), enabled on the encoder via the
    /// compression-parameters API.
    long: bool,
    /// Back-reference window from `--long=N`. Bare `--long` leaves it unset, so
    /// the level's own window applies.
    long_window_log: Option<u32>,
    /// Decompression memory ceiling from `-M` / `--memory`, in bytes. Kept
    /// rather than checked and dropped, so the `-D` dictionary can be weighed
    /// against it once its size is known.
    memory_limit: Option<u64>,
    /// Block-size target from `--target-compressed-block-size`. A soft target,
    /// as upstream documents it: it bounds what goes into a block, so blocks
    /// flush sooner and stay near the requested size.
    target_block_size: Option<u32>,
    /// Exact input length from `--stream-size`. Recorded in the frame header,
    /// so the stream must actually be this long — a wrong value is an error,
    /// not a worse ratio.
    pledged_size: Option<u64>,
    /// Estimated input length from `--size-hint`. Steers the encoder's window
    /// and table sizing only; being wrong costs ratio, never correctness, so
    /// it must NOT reach the header.
    size_hint: Option<u64>,
    /// Display level: `-v` raises it, `-q` lowers it (see [`display!`]).
    verbosity: i32,
    /// Whether frames carry a content checksum (`-C` / `--[no-]check`), and
    /// whether decoding verifies one. On by default, as the reference
    /// command's is.
    checksum: bool,
    /// Whether a known input length is written into the frame header
    /// (`--[no-]content-size`).
    content_size_flag: bool,
    /// Whether a dictionary frame records the dictionary's ID
    /// (`--no-dictID`).
    dict_id_flag: bool,
    /// Copy input that is not a zstd stream through unchanged when
    /// decompressing (`--[no-]pass-through`). `None` is the reference
    /// command's default: on only when forced and writing to stdout, which
    /// is what `zstdcat` does.
    pass_through: Option<bool>,
    /// Skip inputs whose extension says they are already compressed
    /// (`--exclude-compressed`).
    exclude_compressed: bool,
    /// Replace directories among the inputs by the files beneath them (`-r`).
    recursive: bool,
    /// Report a directory `-r` cannot open and go on without counting it as a
    /// failed input (`--ignore-read-errors`), which is the reference command's
    /// exit status. Off by default: a run that left part of a tree out fails.
    ignore_read_errors: bool,
    /// Process symbolic links rather than skipping them; part of `-f`.
    follow_links: bool,
    /// Read stdin even when it is a terminal; part of `-f`.
    force_stdin: bool,
    /// Files naming further inputs, one per line (`--filelist`).
    filelists: Vec<PathBuf>,
    /// Directory every output is written into, by file name
    /// (`--output-dir-flat`).
    output_dir: Option<PathBuf>,
    /// Root under which each input's directory is replayed for its output
    /// (`--output-dir-mirror`). Wins over `output_dir` when both are given.
    output_dir_mirror: Option<PathBuf>,
    /// Whether the progress counter is drawn (`--[no-]progress`).
    progress: Progress,
    /// Per-knob compression parameters from `--zstd=...`.
    advanced: AdvancedParams,
    /// Whether literals are entropy-coded (`--[no-]compress-literals`).
    literals: LiteralCompressionMode,
    /// Reference file for `--patch-from`: raw-content dictionary compression
    /// with the window sized to the input, so the whole reference is
    /// reachable.
    patch_from: Option<PathBuf>,
    /// Print the parameters the level selects for each input before
    /// compressing it (`--show-default-cparams`).
    show_default_cparams: bool,
    /// Which dictionary trainer `--train*` runs.
    trainer: Trainer,
    /// The trainer's tuning from `--train-fastcover=...` / `--train-cover=...`.
    trainer_params: TrainerParams,
    /// The legacy trainer's selectivity from `-s#` or `--train-legacy=s=#`;
    /// zero is its default.
    selectivity: u32,
    /// Highest instruction set the kernels may use (`--cpu=LEVEL`); `None`
    /// lets the CPU's own features decide.
    cpu: Option<structured_zstd::CpuLevel>,
}

/// The dictionary trainers `--train` selects between.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Trainer {
    /// `--train` / `--train-fastcover`: FastCOVER, the reference default.
    FastCover,
    /// `--train-cover`: the segment-scoring COVER trainer.
    Cover,
    /// `--train-legacy`: the reference's original suffix-array trainer.
    Legacy,
}

/// Tuning from `--train-fastcover=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]`
/// and `--train-cover=k=#,d=#,steps=#,split=#,shrink[=#]`, each knob `None`
/// until given a value other than zero.
///
/// As in the reference command, a listed tuning starts from zero in every
/// knob, and zero asks the trainer for its own default or a search; only the
/// bare flag starts from the command's defaults (`d` of 8, four steps).
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
struct TrainerParams {
    /// Whether the flag carried a `=` list at all.
    listed: bool,
    k: Option<u32>,
    d: Option<u32>,
    f: Option<u32>,
    steps: Option<u32>,
    split_percent: Option<u32>,
    accel: Option<u32>,
    /// `shrink[=#]`: the regression the shrinking search allows, in percent.
    shrink: Option<u32>,
}

/// Per-knob compression parameters from `--zstd=wlog=#,clog=#,...`
/// (upstream `parseCompressionParameters`). Every knob is optional and
/// overrides the level's own value when set; zero, as there, means "the
/// level's value".
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
struct AdvancedParams {
    window_log: Option<u32>,
    chain_log: Option<u32>,
    hash_log: Option<u32>,
    search_log: Option<u32>,
    min_match: Option<u32>,
    target_length: Option<u32>,
    strategy: Option<Strategy>,
    ldm_hash_log: Option<u32>,
    ldm_min_match: Option<u32>,
    ldm_bucket_size_log: Option<u32>,
    ldm_hash_rate_log: Option<u32>,
}

impl AdvancedParams {
    /// Whether any knob overrides the level.
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

/// Upstream `zstd --maxdict` default (110 KiB).
const DEFAULT_MAX_DICT: usize = 112_640;

/// Least time `-b` measures each level for (upstream `BMK_TIMETEST_DEFAULT_S`).
const DEFAULT_BENCH_SECONDS: f64 = 3.0;

/// Smallest `-B` block the benchmark cuts its inputs into; a smaller one leaves
/// each input whole (`benchzstd.c`, `BMK_benchMemAdvancedNoAlloc`:
/// `adv->blockSize >= 32`).
const MIN_BENCH_BLOCK_SIZE: u64 = 32;

/// Window log a bare `--long` selects, as upstream documents (128 MiB).
const DEFAULT_LONG_WINDOW_LOG: u32 = 27;

/// Which spellings of a size suffix [`read_leading_number`] reads.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SuffixCase {
    /// `K`, `M`, `G` and `B` only, as the reference reads them. Required where
    /// the number is followed by more text: in `-19k` the `k` is the next flag,
    /// and in `--fast=3k` a tail the option drops.
    Upper,
    /// Lower case as well. Only for a value that must be a number and nothing
    /// else, where `4kb` cannot mean anything but four kibibytes. The
    /// reference refuses it; reading it is a superset of its grammar that no
    /// valid command line changes meaning under, and these options took lower
    /// case here before they took the reference's other spellings.
    Any,
}

/// Read the leading number of `text` the way upstream's argument readers do
/// (`readU32FromCharChecked` and `readSizeTFromCharChecked`, zstdcli.c:355-460):
/// a run of decimal digits, then an optional `K`, `M` or `G` multiplier, which
/// may be followed by `i` and then `B`. The multipliers are powers of two
/// whatever the spelling, so `KB`, `K` and `KiB` are all 1024. `max` is the
/// widest value the destination holds. Reading stops after the suffix and the
/// rest is handed back; an empty digit run reads as zero.
fn read_leading_number(text: &str, max: u64, case: SuffixCase) -> Result<(u64, &str)> {
    let overflow = || {
        eyre!(
            "numeric value `{text}` overflows {} bits",
            64 - max.leading_zeros()
        )
    };
    let bytes = text.as_bytes();
    let mut at = 0;
    let mut value: u64 = 0;
    while let Some(&digit) = bytes.get(at).filter(|b| b.is_ascii_digit()) {
        value = value
            .checked_mul(10)
            .and_then(|v| v.checked_add(u64::from(digit - b'0')))
            .filter(|&v| v <= max)
            .ok_or_else(overflow)?;
        at += 1;
    }
    let fold = |byte: &u8| match case {
        SuffixCase::Upper => *byte,
        SuffixCase::Any => byte.to_ascii_uppercase(),
    };
    let shift = match bytes.get(at).map(fold) {
        Some(b'K') => 10,
        Some(b'M') => 20,
        Some(b'G') => 30,
        _ => return Ok((value, &text[at..])),
    };
    value = value
        .checked_mul(1 << shift)
        .filter(|&v| v <= max)
        .ok_or_else(overflow)?;
    at += 1;
    at += usize::from(bytes.get(at) == Some(&b'i'));
    at += usize::from(bytes.get(at).map(fold) == Some(b'B'));
    Ok((value, &text[at..]))
}

/// A whole option value that is a number: the leading number and nothing
/// after it, as upstream's `NEXT_UINT32` / `NEXT_TSIZE` require. An empty value
/// is refused, where the reference reads it as zero: `--size-hint=$UNSET` is a
/// script that lost its value, not one asking for nothing.
fn parse_number(text: &str, max: u64) -> Result<u64> {
    if !text.starts_with(|c: char| c.is_ascii_digit()) {
        bail!("`{text}`: expected a number");
    }
    let (value, rest) = read_leading_number(text, max, SuffixCase::Any)?;
    if !rest.is_empty() {
        bail!(
            "`{text}`: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed"
        );
    }
    Ok(value)
}

/// A size option (`NEXT_TSIZE`): as wide as the platform's `size_t`.
fn parse_size(text: &str) -> Result<u64> {
    parse_number(text, usize::MAX as u64)
}

/// A count option (`NEXT_UINT32`).
fn parse_u32(text: &str) -> Result<u32> {
    let value = parse_number(text, u64::from(u32::MAX))?;
    Ok(u32::try_from(value).expect("parse_number caps the value at u32::MAX"))
}

/// The number that starts at `chars[at]` inside a short-option cluster
/// (`-e19`, `-B64K`), suffix included, and the index where the cluster carries
/// on after it. The reference reads such a number and then goes on with the
/// cluster (`zstdcli.c:1205-1345`), so `-b1e10i0` is `-b`, `-1`, `-e10`,
/// `-i0`. No digit there reads as zero, as `readU32FromChar` reads it.
fn cluster_u32(chars: &[char], at: usize) -> Result<(u32, usize)> {
    let rest: String = chars[at..].iter().collect();
    let (value, tail) = read_leading_u32(&rest)?;
    Ok((value, chars.len() - tail.chars().count()))
}

/// [`read_leading_number`] into a `u32`, for the short options and the
/// sub-options that read a number and then look at what follows it.
fn read_leading_u32(text: &str) -> Result<(u32, &str)> {
    let (value, rest) = read_leading_number(text, u64::from(u32::MAX), SuffixCase::Upper)?;
    Ok((
        u32::try_from(value).expect("read_leading_number caps the value at u32::MAX"),
        rest,
    ))
}

/// Parse a `-M` / `--memory` value into bytes, or `None` for "the default".
///
/// The default unit is MiB, as upstream documents, so `-M256` is 256 MiB. A
/// suffix means what it says and is not multiplied again: `-M1M` is one
/// mebibyte, a limit far below what decompression needs, and has to be refused
/// as such rather than read as a terabyte that trivially passes.
///
/// Zero asks for no custom ceiling at all: the parameter contract says "value 0
/// means use default maximum windowLog" (`zstd.h`, `ZSTD_d_windowLogMax`), and
/// the default is what this build enforces anyway. Read as a limit of zero
/// bytes it would refuse every run, turning an explicit request for the default
/// into an error.
fn parse_memory_limit(text: &str) -> Result<Option<u64>> {
    let value = parse_size(text)?;
    let bytes = if text.trim().ends_with(|c: char| c.is_ascii_digit()) {
        value
            .checked_mul(1 << 20)
            .ok_or_else(|| eyre!("memory limit `{text}` MiB does not fit in 64 bits"))?
    } else {
        value
    };
    Ok((bytes != 0).then_some(bytes))
}

/// What the decoder holds BESIDES the window, rounded well up: the literal and
/// block buffers (a block is capped at 128 KiB each), the sequence storage,
/// the Huffman and FSE tables, and the tool's own I/O buffers. A limit that
/// cannot cover these and the default window together is refused up front.
const DECODER_AUXILIARY_BYTES: u64 = 1 << 20;

/// The widest window this run decodes, handed to the decoder as its ceiling.
///
/// Under `-M` the window is the limit, as the reference sets it
/// (`ZSTD_DCtx_setMaxWindowSize(dctx, memLimit)`, fileio.c): scripts written
/// for it decode a 2^29 window under `--memory=512MB`, which a limit counting
/// the other buffers too would refuse. `-M` comes first because a patch keeps
/// it too: `--patch-apply` drops a `-M` given before it, so one still set came after,
/// and replaces the lifted limit as a later `-M` replaces it in the reference
/// command. Otherwise a patch whose window no later `-M` (`-M0` included) has
/// limited again reaches back across its whole reference, so it is decoded
/// with the widest window any decode takes, as upstream's development branch
/// raises its limit for `--patch-apply`. Failing both, `--zstd=wlog=N` or
/// `--long=N` raises it, the former first as it wins when compressing; and
/// failing those the decoder's default stands. A log below the default does
/// not lower it: the reference would then refuse frames its own default
/// accepts, which serves nobody.
fn decode_window_ceiling(opts: &Options) -> u64 {
    use structured_zstd::decoding::{MAX_DECODER_WINDOW_SIZE, MAXIMUM_ALLOWED_WINDOW_SIZE};

    if let Some(limit) = opts.memory_limit {
        return limit.clamp(MAXIMUM_ALLOWED_WINDOW_SIZE, MAX_DECODER_WINDOW_SIZE);
    }
    if opts.patch_window_lifted {
        return MAX_DECODER_WINDOW_SIZE;
    }
    // The reference derives a missing limit from the compression window
    // whatever set it (zstdcli.c:1572-1577), `--max` included, which sets
    // `windowLog` to its maximum (zstdcli.c:644): so `-d --max` raises the
    // ceiling there, and here, rather than being read as compression-only.
    match opts.advanced.window_log.or(opts.long_window_log) {
        Some(log) => (1u64 << log).clamp(MAXIMUM_ALLOWED_WINDOW_SIZE, MAX_DECODER_WINDOW_SIZE),
        None => MAXIMUM_ALLOWED_WINDOW_SIZE,
    }
}

/// Check a requested decompression memory ceiling against the one this build
/// actually enforces.
///
/// `-M` is a safety promise about untrusted input, not a performance hint, so
/// it is either kept or refused. The decoder rejects any frame whose window
/// exceeds a fixed ceiling, which makes a request at or above that ceiling
/// already satisfied — we are the stricter of the two. A request BELOW it is a
/// promise this build cannot make, and saying nothing would leave the caller
/// believing a bound that is not there.
///
/// `whole_file_bytes` is what this run holds in full rather than streams, and
/// `copies` is how many forms of it exist at once: the `-D` dictionary is held
/// as read and again as parsed, a benchmark holds its input, the compressed
/// frame and the decompressed copy. Any of them can break the promise alone, so
/// they are weighed from the file sizes before anything is loaded.
fn check_memory_limit(requested: u64, whole_file_bytes: u64, copies: u64) -> Result<()> {
    /// Window ceiling the decoder refuses to exceed by default.
    const WINDOW: u64 = structured_zstd::decoding::MAXIMUM_ALLOWED_WINDOW_SIZE;
    const AUXILIARY: u64 = DECODER_AUXILIARY_BYTES;
    // A size here is what a directory entry claims, not what was allocated, and
    // a sparse file can claim more than memory could ever hold. Arithmetic that
    // leaves the type is therefore a real input, not a theoretical one: a
    // wrapped total would accept a limit nothing could keep. Nothing that
    // overflows fits under any limit, so the failure is the ordinary refusal.
    let buffers = whole_file_bytes
        .checked_mul(copies)
        .and_then(|buffers| buffers.checked_add(WINDOW + AUXILIARY));
    let Some(floor) = buffers else {
        bail!(
            "requested memory limit {requested} B cannot cover this run: the files it \
             would hold add up to more than any machine can address."
        );
    };
    if requested < floor {
        if floor > WINDOW + AUXILIARY {
            // A caller that holds one thing in several forms says how many, and
            // the count is worth naming: it is usually the surprise. One that
            // has already added its buffers up passes 1, and then the count
            // says nothing worth reading.
            let held = if copies == 1 {
                String::new()
            } else {
                format!(", each held in {copies} forms at once")
            };
            bail!(
                "requested memory limit {requested} B does not cover this run: a {} MiB \
                 window, about {} MiB of literal, block, sequence and table buffers, and \
                 {} MiB of whole-file buffers{held}.",
                WINDOW / (1 << 20),
                AUXILIARY / (1 << 20),
                (floor - WINDOW - AUXILIARY) / (1 << 20),
            );
        }
        bail!(
            "requested memory limit {requested} B is below what decompression can need \
             here: a {} MiB window plus about {} MiB of literal, block, sequence and \
             table buffers. This build cannot be tightened below that.",
            WINDOW / (1 << 20),
            AUXILIARY / (1 << 20),
        );
    }
    Ok(())
}

/// Check a `--long=N` or `--zstd=wlog=N` window log once the mode is known:
/// against what this build both writes and reads back when the run
/// compresses, against the widest window the decoder takes when it only
/// decodes. Validated at parse time rather than at the first frame, so a wrong
/// value is reported before any output is written. A window past the
/// decoder's default ceiling is fine: decoding such a frame takes `--long=N`
/// or `--memory`, as it does with the reference command.
fn check_window_log(log: u32, compressing: bool) -> Result<()> {
    use structured_zstd::encoding::CParameter;

    let bounds = CParameter::WindowLog.bounds();
    let upper = i64::from(if compressing {
        max_window_log()
    } else {
        structured_zstd::decoding::MAX_DECODER_WINDOW_SIZE.ilog2()
    });
    if i64::from(log) < bounds.lower_bound || i64::from(log) > upper {
        bail!(
            "window log {log} is outside the supported range {}..={upper}",
            bounds.lower_bound,
        );
    }
    Ok(())
}

/// The largest window this build both writes and reads back: the encoder's
/// ceiling or the largest window any decode accepts, whichever is lower.
fn max_window_log() -> u32 {
    use structured_zstd::encoding::CParameter;

    let encodable = u32::try_from(CParameter::WindowLog.bounds().upper_bound)
        .expect("the window-log bound is a small positive number");
    let decodable = structured_zstd::decoding::MAX_DECODER_WINDOW_SIZE.ilog2();
    encodable.min(decodable)
}

/// Every knob at the end of its range that compresses hardest, as the
/// reference command's `--max` sets them (`zstdcli.c`, `setMaxCompression`).
/// One departure: the window stops at [`max_window_log`] rather than at 31,
/// the widest the encoder writes. The
/// long-distance hash rate is left to derive from the rest, which is what the
/// reference's 0 there asks for.
fn max_compression_params() -> AdvancedParams {
    use structured_zstd::encoding::CParameter;

    let upper = |parameter: CParameter| {
        u32::try_from(parameter.bounds().upper_bound)
            .expect("every compression-parameter bound is a small positive number")
    };
    let lower = |parameter: CParameter| {
        u32::try_from(parameter.bounds().lower_bound)
            .expect("every compression-parameter bound is a small positive number")
    };
    AdvancedParams {
        window_log: Some(max_window_log()),
        chain_log: Some(upper(CParameter::ChainLog)),
        hash_log: Some(upper(CParameter::HashLog)),
        search_log: Some(upper(CParameter::SearchLog)),
        min_match: Some(lower(CParameter::MinMatch)),
        target_length: Some(upper(CParameter::TargetLength)),
        strategy: Some(Strategy::Btultra2),
        ldm_hash_log: Some(upper(CParameter::LdmHashLog)),
        // The reference's heuristic value, not a bound.
        ldm_min_match: Some(16),
        ldm_bucket_size_log: Some(upper(CParameter::LdmBucketSizeLog)),
        ldm_hash_rate_log: None,
    }
}

/// Validate the parameter list of `--adapt=min=N,max=N`.
///
/// The bounds have no effect here — the level does not vary — but a command
/// line that misspells a key or passes a non-number is broken whether or not
/// this build acts on it, and reporting that is the whole difference between
/// ignoring a flag and hiding a mistake.
fn parse_adapt_params(params: &str) -> Result<()> {
    if params.is_empty() {
        bail!("--adapt= needs parameters, e.g. --adapt=min=1,max=9");
    }
    for field in params.split(',') {
        let (key, value) = field
            .split_once('=')
            .ok_or_else(|| eyre!("--adapt parameter `{field}` is not `key=value`"))?;
        if key != "min" && key != "max" {
            bail!("--adapt has no `{key}` parameter; expected `min` or `max`");
        }
        value
            .parse::<i32>()
            .map_err(|_| eyre!("--adapt {key} must be a number, got `{value}`"))?;
    }
    Ok(())
}

/// Parse `--zstd=wlog=#,clog=#,hlog=#,slog=#,mml=#,tlen=#,strat=#,...` the
/// way the reference command does (`zstdcli.c`, `parseCompressionParameters`):
/// each key in its long or short spelling, a value read as a leading number
/// with an optional `K` / `M`, commas between. `overlapLog` / `ovlog` is a
/// multi-threading knob, accepted and without effect. Zero leaves the knob at
/// the level's value, as it does there.
///
/// Written into `params`, which earlier `--zstd=` lists already filled: as the
/// reference command writes every list into one set of parameters, keys a list
/// does not name keep their values and keys it names again take the new one.
fn apply_advanced_params(text: &str, params: &mut AdvancedParams) -> Result<()> {
    if text.is_empty() {
        return Ok(());
    }
    for field in text.split(',') {
        let (key, value) = field
            .split_once('=')
            .ok_or_else(|| eyre!("--zstd parameter `{field}` is not `key=value`"))?;
        let (number, tail) = read_leading_u32(value)
            .wrap_err_with(|| format!("--zstd parameter `{key}` has an invalid value"))?;
        if !tail.is_empty() {
            bail!("--zstd parameter `{key}` has an invalid value `{value}`");
        }
        // Zero, an empty value (`wlog=`) included, leaves the knob to the
        // level, as the reference reads it: `readU32FromChar` of nothing is 0,
        // and 0 is "default" for every compression parameter.
        let set = (number != 0).then_some(number);
        match key {
            "windowLog" | "wlog" => params.window_log = set,
            "chainLog" | "clog" => params.chain_log = set,
            "hashLog" | "hlog" => params.hash_log = set,
            "searchLog" | "slog" => params.search_log = set,
            "minMatch" | "mml" => params.min_match = set,
            "targetLength" | "tlen" => params.target_length = set,
            "strategy" | "strat" => {
                params.strategy = match set {
                    None => None,
                    Some(ordinal) => {
                        Some(Strategy::from_ordinal(ordinal).ok_or_else(|| {
                            eyre!("--zstd strategy {ordinal} is out of range 1..=9")
                        })?)
                    }
                }
            }
            "overlapLog" | "ovlog" => {}
            "ldmHashLog" | "lhlog" => params.ldm_hash_log = set,
            "ldmMinMatch" | "lmml" => params.ldm_min_match = set,
            "ldmBucketSizeLog" | "lblog" => params.ldm_bucket_size_log = set,
            "ldmHashRateLog" | "lhrlog" => params.ldm_hash_rate_log = set,
            _ => bail!("--zstd has no `{key}` parameter"),
        }
    }
    Ok(())
}

/// One `--zstd=` list on its own (for tests).
#[cfg(test)]
fn parse_advanced_params(text: &str) -> Result<AdvancedParams> {
    let mut params = AdvancedParams::default();
    apply_advanced_params(text, &mut params)?;
    Ok(params)
}

/// Parse the tuning of `--train-fastcover=...` (`fastcover` true: `f=` and
/// `accel=` are accepted as well) or `--train-cover=...`, the way the
/// reference command's `parseFastCoverParameters` / `parseCoverParameters`
/// read them. `shrink` takes an optional `=#` regression bound.
fn parse_trainer_params(text: &str, fastcover: bool) -> Result<TrainerParams> {
    let flag = if fastcover {
        "--train-fastcover"
    } else {
        "--train-cover"
    };
    let mut params = TrainerParams {
        listed: true,
        ..TrainerParams::default()
    };
    for field in text.split(',') {
        if field == "shrink" || field.starts_with("shrink=") {
            // The reference's default bound (`kDefaultRegression`, zstdcli.c).
            let mut bound = 1;
            if let Some(text) = field.strip_prefix("shrink=") {
                let (value, tail) = read_leading_u32(text)
                    .wrap_err_with(|| format!("{flag} shrink bound `{text}` is invalid"))?;
                if !tail.is_empty() {
                    bail!("{flag} shrink bound `{text}` is invalid");
                }
                bound = value;
            }
            params.shrink = Some(bound);
            continue;
        }
        let (key, value) = field
            .split_once('=')
            .ok_or_else(|| eyre!("{flag} parameter `{field}` is not `key=value`"))?;
        let (number, tail) = read_leading_u32(value)
            .wrap_err_with(|| format!("{flag} parameter `{key}` has an invalid value"))?;
        if !tail.is_empty() {
            bail!("{flag} parameter `{key}` has an invalid value `{value}`");
        }
        let set = (number != 0).then_some(number);
        match key {
            "k" => params.k = set,
            "d" => params.d = set,
            "steps" => params.steps = set,
            "split" => params.split_percent = set,
            "f" if fastcover => params.f = set,
            "accel" if fastcover => params.accel = set,
            _ => bail!("{flag} has no `{key}` parameter"),
        }
    }
    Ok(params)
}

/// Refuse to compress stdin into a terminal nobody asked to write to.
///
/// The reference command's own check (`zstdcli.c`, "stdout is a console"):
/// stdin among the inputs, no `-o` file, stdout a terminal, neither `-c` nor
/// `-f`, and an operation that writes a frame. `-c` asks for stdout "even if
/// it is a console", as the help says, and a terminal is what `ssh -t` and
/// `docker run -t` hand the command on the far side of a redirect. Decompression
/// is exempt, since plaintext on a terminal is what the user asked to see.
/// Taken before any input is read, so a run that would paint a frame into the
/// session never starts.
fn refuse_console_stdout(opts: &Options, stdout_is_terminal: bool) -> Result<()> {
    // Several inputs without `-o` count too, since `-` among them streams to
    // stdout, and the reference command asks the same question of a missing
    // output name.
    if opts.mode == Mode::Compress
        && !opts.bench
        && opts.output.is_none()
        && !opts.to_stdout
        && reads_stdin(&opts.inputs)
        && stdout_is_terminal
        && !opts.force
    {
        bail!("stdout is a console, aborting");
    }
    Ok(())
}

/// Outcome of argument parsing: either run with `Options`, or a terminal
/// message already handled (help / version).
enum Parsed {
    /// Boxed: the options are a few hundred bytes, and the other variant is
    /// nothing at all.
    Run(Box<Options>),
    /// `pause` is whether a `-p` came before the option that was handled.
    Handled { pause: bool },
}

/// A command line that could not be parsed, with the display level the
/// flags before the mistake had reached: `-q --bogus` reports the mistake
/// alone, where the default level adds the short usage under it. `pause` is
/// likewise whether a `-p` came before it.
struct ParseFailure {
    error: Error,
    verbosity: i32,
    pause: bool,
}

/// `-p`: hold the window open before exiting, as the reference does at its
/// common exit (`waitEnter`). Whatever `stdin` holds, or its end, lets the
/// program go.
fn wait_for_enter(stdin: &mut impl Read) {
    eprintln!("Press enter to continue... ");
    let mut byte = [0u8; 1];
    // A failed read ends the wait just as Enter would.
    drop(stdin.read(&mut byte));
}

fn main() {
    // `args_os`, not `args`: the latter panics on an argument that is not
    // UTF-8, which on Unix is a legitimate filename rather than a mistake.
    let raw: Vec<OsString> = std::env::args_os().collect();
    std::process::exit(run_command(&raw, &mut io::stdin()));
}

/// The whole command for `raw` (`argv`, program name first): its exit status,
/// returned once `-p` has had its wait on `stdin`. The one exit every outcome
/// passes through, as the reference's `_end` is.
fn run_command(raw: &[OsString], stdin: &mut impl Read) -> i32 {
    let mut pause = false;
    let status = command_status(raw, &mut pause);
    if pause {
        wait_for_enter(stdin);
    }
    status
}

/// [`run_command`] up to the exit: the status, with `pause` set when the
/// command line asked for `-p`.
fn command_status(raw: &[OsString], pause: &mut bool) -> i32 {
    let prog = raw
        .first()
        .map(|arg| arg.to_string_lossy().into_owned())
        .unwrap_or_else(|| "zstd".to_string());
    let preset = program_preset(&prog);
    // The environment is read before the command line, at the default
    // level: `-q` further along cannot silence a warning about a variable
    // that was already applied when it was met.
    let default_level = level_from_env(std::env::var_os("ZSTD_CLEVEL").as_deref(), DEFAULT_LEVEL);
    check_threads_env(std::env::var_os("ZSTD_NBTHREADS").as_deref(), DEFAULT_LEVEL);

    let args = raw.get(1..).unwrap_or_default();
    let options = match parse_args(args, &preset, default_level) {
        Ok(Parsed::Run(options)) => *options,
        Ok(Parsed::Handled { pause: asked }) => {
            *pause = asked;
            return 0;
        }
        Err(failure) => {
            *pause = failure.pause;
            display!(failure.verbosity, 1, "zstd: {}", failure.error);
            if failure.verbosity >= DEFAULT_LEVEL {
                let mut stderr = io::stderr().lock();
                let _ = write_short_usage(&mut stderr, &preset.name);
            }
            return 1;
        }
    };
    let verbosity = options.verbosity;
    *pause = options.pause;
    // Before anything that compresses or decompresses: the first such call
    // chooses the kernels, and they stay chosen for the process.
    if let Some(level) = options.cpu
        && let Err(err) = structured_zstd::set_cpu_ceiling(level)
    {
        display!(verbosity, 1, "zstd: --cpu={level}: {err}");
        return 1;
    }
    display!(
        verbosity,
        4,
        "kernels: entropy {}, match finding {}",
        structured_zstd::active_cpu_kernel_name(),
        structured_zstd::active_match_kernel_name()
    );
    // Status goes to stderr through `display!`, so it never contaminates a
    // `-c` stdout data stream.
    match run(options) {
        Ok(0) => 0,
        Ok(_failed_inputs) => 1,
        Err(err) => {
            display!(verbosity, 1, "zstd: {err}");
            1
        }
    }
}

/// What `argv[0]` presets before any flag is read: the conventional symlink
/// dispatch. `unzstd` decompresses; `zstdcat` and `zcat` decompress to
/// stdout, overwriting, passing non-zstd input through, and quietly, as the
/// reference command sets them up; `zstdmt` compresses like `zstd` (its
/// worker count has no effect here).
struct ProgramPreset {
    /// The name the tool was invoked by, as the usage text shows it.
    name: String,
    mode: Mode,
    to_stdout: bool,
    force: bool,
    pass_through: Option<bool>,
    verbosity: i32,
}

fn program_preset(prog: &str) -> ProgramPreset {
    let name = Path::new(prog)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(prog);
    // Strip a trailing `.exe` for Windows symlink names.
    let stem = name.strip_suffix(".exe").unwrap_or(name);
    let plain = ProgramPreset {
        name: name.to_string(),
        mode: Mode::Compress,
        to_stdout: false,
        force: false,
        pass_through: None,
        verbosity: DEFAULT_LEVEL,
    };
    match stem {
        "unzstd" => ProgramPreset {
            mode: Mode::Decompress,
            ..plain
        },
        "zstdcat" | "zcat" => ProgramPreset {
            mode: Mode::Decompress,
            to_stdout: true,
            force: true,
            pass_through: Some(true),
            verbosity: 1,
            ..plain
        },
        // "zstd", "zstdmt", anything else: compress by default.
        _ => plain,
    }
}

/// The default compression level, from `ZSTD_CLEVEL` when it is set.
///
/// Read the way the reference command reads it: an optional sign, then the
/// leading unsigned number with its `K`/`M` multiplier. A value that is not
/// that is ignored with a warning rather than failing the run, since an
/// environment variable is set far from the command that trips over it. The
/// variable replaces the DEFAULT only; `-#` on the command line still wins.
fn level_from_env(value: Option<&OsStr>, verbosity: i32) -> i32 {
    let Some(value) = value else {
        return CompressionLevel::DEFAULT_LEVEL;
    };
    let text = value.to_string_lossy();
    let (sign, digits) = match text.strip_prefix('-') {
        Some(rest) => (-1, rest),
        None => (1, text.strip_prefix('+').unwrap_or(&text)),
    };
    if digits.starts_with(|c: char| c.is_ascii_digit()) {
        match read_leading_u32(digits) {
            Ok((magnitude, "")) => {
                // The scale runs from `MIN_LEVEL` up; the library clamps a
                // value below it, and the command line's own ceiling reduces
                // one above 19 with the usual warning later.
                return i32::try_from(magnitude)
                    .map(|magnitude| sign * magnitude)
                    .unwrap_or(if sign < 0 { i32::MIN } else { i32::MAX })
                    .max(CompressionLevel::MIN_LEVEL);
            }
            Err(_) => {
                display!(
                    verbosity,
                    2,
                    "Ignore environment variable setting ZSTD_CLEVEL={text}: numeric value too large"
                );
                return CompressionLevel::DEFAULT_LEVEL;
            }
            Ok(_) => {}
        }
    }
    display!(
        verbosity,
        2,
        "Ignore environment variable setting ZSTD_CLEVEL={text}: not a valid integer value"
    );
    CompressionLevel::DEFAULT_LEVEL
}

/// Validate `ZSTD_NBTHREADS` the way the reference command does, warning
/// about a value that is not an unsigned number. The count itself has no
/// effect here: compression runs single-threaded, which is also what the
/// reference command does when built without threads.
fn check_threads_env(value: Option<&OsStr>, verbosity: i32) {
    let Some(value) = value else {
        return;
    };
    let text = value.to_string_lossy();
    if text.starts_with(|c: char| c.is_ascii_digit()) {
        match read_leading_u32(&text) {
            Ok((_, "")) => return,
            Err(_) => {
                display!(
                    verbosity,
                    2,
                    "Ignore environment variable setting ZSTD_NBTHREADS={text}: numeric value too large"
                );
                return;
            }
            Ok(_) => {}
        }
    }
    display!(
        verbosity,
        2,
        "Ignore environment variable setting ZSTD_NBTHREADS={text}: not a valid unsigned value"
    );
}

/// The value of a long option that takes one, given attached
/// (`--name=value`) or as the next argument (`--name value`), the way the
/// reference command's `NEXT_FIELD` reads it. `None` when `long` is not this
/// option at all. The next argument may not start with `-`: an option there
/// means the value was left out, and reading the option as the value would
/// hide the mistake.
fn option_value<'a>(
    long: &str,
    name: &str,
    arg_os: &OsStr,
    rest: &mut impl Iterator<Item = (usize, &'a OsString)>,
) -> Result<Option<PathBuf>> {
    if long == name {
        let Some((_, value)) = rest.next() else {
            bail!("error: missing command argument for --{name}");
        };
        if value.to_string_lossy().starts_with('-') {
            bail!("error: command cannot be separated from its argument by another command");
        }
        return Ok(Some(PathBuf::from(value)));
    }
    if long.len() > name.len() && long.starts_with(name) && long.as_bytes()[name.len()] == b'=' {
        // Past `--`, the name and the `=`, all ASCII.
        return Ok(Some(attached_path(arg_os, 2 + name.len() + 1)));
    }
    Ok(None)
}

/// [`option_value`] for an option whose value is a number or a word rather
/// than a path.
fn option_text<'a>(
    long: &str,
    name: &str,
    arg_os: &OsStr,
    rest: &mut impl Iterator<Item = (usize, &'a OsString)>,
) -> Result<Option<String>> {
    Ok(option_value(long, name, arg_os, rest)?
        .map(|value| value.as_os_str().to_string_lossy().into_owned()))
}

/// [`option_text`] for an option spelled several ways (`--memory`,
/// `--memlimit`): the first spelling that matches supplies the value.
fn first_option_text<'a>(
    long: &str,
    names: &[&str],
    arg_os: &OsStr,
    rest: &mut impl Iterator<Item = (usize, &'a OsString)>,
) -> Result<Option<String>> {
    for name in names {
        if let Some(value) = option_text(long, name, arg_os, rest)? {
            return Ok(Some(value));
        }
    }
    Ok(None)
}

/// Manual upstream-style parse: bare `-N` is a level, short flags combine
/// (`-dc`), `-o`/`-D` take a value, `--long-opts` are matched whole. `clap`'s
/// derive cannot model bare numeric levels, so we parse argv directly.
/// `default_level` is what `-#` overrides: the built-in default, or
/// `ZSTD_CLEVEL`.
fn parse_args(
    args: &[OsString],
    preset: &ProgramPreset,
    default_level: i32,
) -> Result<Parsed, ParseFailure> {
    let mut verbosity = preset.verbosity;
    let mut pause = false;
    parse_args_into(args, preset, default_level, &mut verbosity, &mut pause).map_err(|error| {
        ParseFailure {
            error,
            verbosity,
            pause,
        }
    })
}

fn parse_args_into(
    args: &[OsString],
    preset: &ProgramPreset,
    default_level: i32,
    verbosity: &mut i32,
    pause: &mut bool,
) -> Result<Parsed> {
    let mut opts = Options {
        mode: preset.mode,
        level: default_level,
        dict: None,
        to_stdout: preset.to_stdout,
        output: None,
        force: preset.force,
        keep: false,
        remove_source: false,
        inputs: Vec::new(),
        max_dict: DEFAULT_MAX_DICT,
        dict_id: None,
        bench: false,
        bench_start: default_level,
        bench_end: default_level,
        bench_secs: DEFAULT_BENCH_SECONDS,
        bench_param: None,
        bench_compressibility: None,
        pause: false,
        bench_realtime: false,
        console: FakeConsole::default(),
        trace: None,
        decode_window: structured_zstd::decoding::MAXIMUM_ALLOWED_WINDOW_SIZE,
        patch_window_lifted: false,
        bench_separately: false,
        block_size: None,
        long: false,
        long_window_log: None,
        memory_limit: None,
        target_block_size: None,
        pledged_size: None,
        size_hint: None,
        verbosity: preset.verbosity,
        checksum: true,
        content_size_flag: true,
        dict_id_flag: true,
        pass_through: preset.pass_through,
        exclude_compressed: false,
        recursive: false,
        ignore_read_errors: false,
        follow_links: preset.force,
        // `zstdcat` / `zcat` read a terminal on stdin the way `cat` does. The
        // reference command's preset forces only the output side
        // (`zstdcli.c` sets `forceStdout`, not `forceStdin`) and refuses the
        // terminal; that refusal protects nothing a script relies on, so the
        // preset's force covers both sides here.
        force_stdin: preset.force,
        filelists: Vec::new(),
        output_dir: None,
        output_dir_mirror: None,
        progress: Progress::Auto,
        advanced: AdvancedParams::default(),
        literals: LiteralCompressionMode::Auto,
        patch_from: None,
        show_default_cparams: false,
        trainer: Trainer::FastCover,
        trainer_params: TrainerParams::default(),
        selectivity: 0,
        cpu: None,
    };
    let mut ultra = false;
    // `-e`, when typed. Without it the benchmark ends where it starts, so no
    // value can stand in for it: the start may come from `ZSTD_CLEVEL` and be
    // negative, below any fixed default end.
    let mut bench_end = None;
    let mut iter = args.iter().enumerate().peekable();
    let mut positional_only = false;

    while let Some((idx, arg_os)) = iter.next() {
        // Option spellings and their numeric values are text; a filename is
        // bytes. Matching happens on a lossy view, while anything kept as a
        // path keeps the argument itself, so a name that is not UTF-8 reaches
        // the filesystem as it was given.
        let arg = arg_os.to_string_lossy();
        let arg = arg.as_ref();
        if positional_only || arg == "-" || !arg.starts_with('-') {
            opts.inputs.push(PathBuf::from(arg_os));
            continue;
        }
        if arg == "--" {
            positional_only = true;
            continue;
        }
        if let Some(long) = arg.strip_prefix("--") {
            match long {
                "compress" => select_mode(&mut opts, Mode::Compress),
                "decompress" | "uncompress" => select_mode(&mut opts, Mode::Decompress),
                "test" => select_mode(&mut opts, Mode::Test),
                "list" => select_mode(&mut opts, Mode::List),
                // `--train` selects the mode and leaves the trainer alone, as
                // upstream's does (`zstdcli.c` sets only the operation): the
                // trainer is FastCOVER until a `--train-cover` /
                // `--train-fastcover` names one, in whichever order the two
                // flags come, so `--train-cover --train` still trains COVER.
                // Bare `--train-fastcover` resets the tuning, as upstream's does.
                "train" => select_mode(&mut opts, Mode::Train),
                "train-fastcover" => {
                    select_mode(&mut opts, Mode::Train);
                    opts.trainer = Trainer::FastCover;
                    opts.trainer_params = TrainerParams::default();
                }
                "train-cover" => {
                    select_mode(&mut opts, Mode::Train);
                    opts.trainer = Trainer::Cover;
                    opts.trainer_params = TrainerParams::default();
                }
                "train-legacy" => {
                    select_mode(&mut opts, Mode::Train);
                    opts.trainer = Trainer::Legacy;
                }
                // `-c` and `-o` name competing destinations, so each clears the
                // other and the later one on the command line wins, as upstream
                // does. Setting only one of them lets `-c -o f` ignore the `-o`.
                "stdout" | "to-stdout" => {
                    opts.to_stdout = true;
                    opts.output = None;
                }
                // `-f` disables every input and output check at once, as the
                // reference command's does: overwriting, a terminal on either
                // end, and symbolic links.
                "force" => {
                    opts.force = true;
                    opts.force_stdin = true;
                    opts.follow_links = true;
                }
                "keep" => opts.keep = true,
                "rm" => opts.remove_source = true,
                "ultra" => ultra = true,
                // Replaces every knob at once, as the reference command's does,
                // so a `--zstd=` before it is overwritten and one after it
                // adjusts the maximum. Its tables at their widest do not fit a
                // 32-bit address space, which the reference refuses the same way.
                "max" => {
                    if usize::BITS < 64 {
                        bail!("--max is incompatible with 32-bit mode");
                    }
                    ultra = true;
                    opts.long = true;
                    opts.advanced = max_compression_params();
                }
                "quiet" => *verbosity -= 1,
                "verbose" => *verbosity += 1,
                // The wire-format switches: the checksum, the
                // Frame_Content_Size field, the Dictionary_ID. Each reaches
                // the encoder, so the frame that comes out is the one asked
                // for.
                "check" => opts.checksum = true,
                "no-check" => opts.checksum = false,
                "content-size" => opts.content_size_flag = true,
                "no-content-size" => opts.content_size_flag = false,
                "no-dictID" => opts.dict_id_flag = false,
                "pass-through" => opts.pass_through = Some(true),
                "no-pass-through" => opts.pass_through = Some(false),
                "exclude-compressed" => opts.exclude_compressed = true,
                "ignore-read-errors" => opts.ignore_read_errors = true,
                "show-default-cparams" => opts.show_default_cparams = true,
                "progress" => opts.progress = Progress::Always,
                "no-progress" => opts.progress = Progress::Never,
                "version" => {
                    print_version(*verbosity);
                    return Ok(Parsed::Handled { pause: *pause });
                }
                "help" => {
                    print_help(*verbosity, &preset.name);
                    return Ok(Parsed::Handled { pause: *pause });
                }
                // Flags that steer HOW the work is done, not what comes out:
                // thread counts, IO strategy, matcher hints. We are
                // single-threaded and pick our own limits, so accepting them
                // yields the same valid stream. Upstream takes them, so a
                // script that passes them must not fail here: that is the
                // whole drop-in contract.
                "single-thread"
                | "adapt"
                | "sparse"
                | "no-sparse"
                | "asyncio"
                | "no-asyncio"
                | "mmap-dict"
                | "no-mmap-dict"
                | "row-match-finder"
                | "no-row-match-finder" => {}
                // The reference prints a trace of its own file-system helpers
                // by their C names (`UTIL_stat`, `UTIL_isLink`, ...). There is
                // nothing of ours that output would describe, and taking the
                // option silently would leave a script waiting for a trace
                // that never comes.
                "trace-file-stat" => bail!(
                    "--trace-file-stat traces the reference implementation's own file-system \
                     calls; this build has none to trace"
                ),
                "priority=rt" => opts.bench_realtime = true,
                "fake-stdin-is-console" => opts.console.stdin = true,
                "fake-stdout-is-console" => opts.console.stdout = true,
                "fake-stderr-is-console" => opts.console.stderr = true,
                "compress-literals" => opts.literals = LiteralCompressionMode::Enable,
                "no-compress-literals" => opts.literals = LiteralCompressionMode::Disable,
                _ => {
                    if long == "fast" {
                        // `--fast` is the level -1 alias.
                        opts.level = -1;
                    } else if let Some(v) = long.strip_prefix("fast=") {
                        // `--fast=N` is level -N (upstream zstd,
                        // zstdcli.c:1133-1153). The factor is the LEADING
                        // number only, so `--fast=3.5` is level -3 and the tail
                        // is dropped; a factor past the minimum level clamps
                        // rather than failing; only a zero factor is an error.
                        // Exact-match the prefix so a typo like `--faster`
                        // falls through to unknown-option.
                        let (n, _tail) = read_leading_u32(v).wrap_err("invalid --fast level")?;
                        // Zero would negate to level 0, which is the ordinary
                        // default rather than a fast one.
                        if n == 0 {
                            bail!("--fast level must be at least 1, got 0");
                        }
                        let capped = n.min(CompressionLevel::MIN_LEVEL.unsigned_abs());
                        opts.level = -i32::try_from(capped)
                            .expect("capped at |MIN_LEVEL|, which is an i32 magnitude");
                    } else if long.starts_with("use-dict=") {
                        opts.dict = Some(attached_path(arg_os, "--use-dict=".len()));
                    } else if let Some(v) = option_text(long, "maxdict", arg_os, &mut iter)? {
                        opts.max_dict =
                            usize::try_from(parse_u32(&v).wrap_err("invalid --maxdict size")?)
                                .expect("a u32 fits in usize on the platforms this builds for");
                    } else if let Some(v) = option_text(long, "dictID", arg_os, &mut iter)? {
                        // Zero is how the dictionary API spells "choose one for
                        // me", so it selects the default rather than being
                        // carried through as an id the trainer would refuse.
                        let id = parse_u32(&v).wrap_err("invalid --dictID")?;
                        opts.dict_id = (id != 0).then_some(id);
                    } else if let Some(v) = option_text(long, "stream-size", arg_os, &mut iter)? {
                        // An exact pledge: it goes into the frame header, so a
                        // stream of a different length is an error.
                        opts.pledged_size = Some(parse_size(&v).wrap_err("invalid --stream-size")?);
                    } else if let Some(v) = option_text(long, "size-hint", arg_os, &mut iter)? {
                        // An estimate: it sizes the encoder and nothing else,
                        // so a wrong guess costs ratio rather than failing.
                        opts.size_hint = Some(parse_size(&v).wrap_err("invalid --size-hint")?);
                    } else if let Some(v) = first_option_text(
                        long,
                        &["memory", "memlimit", "memlimit-decompress"],
                        arg_os,
                        &mut iter,
                    )? {
                        // Recorded now, checked once the mode is final: the
                        // ceiling describes decoding, and a later flag can
                        // still decide this run does none. Zero included, it
                        // replaces the window a patch lifted.
                        opts.memory_limit =
                            parse_memory_limit(&v).wrap_err("invalid memory limit")?;
                        opts.patch_window_lifted = false;
                    } else if let Some(params) = long.strip_prefix("adapt=") {
                        // Parameterised form (`--adapt=min=1,max=9`). We do not
                        // vary the level, so the bounds change nothing, but a
                        // misspelled key or a non-numeric bound is still a
                        // broken command line, and the contract is that ignored
                        // options validate what they are given.
                        parse_adapt_params(params)?;
                    } else if let Some(v) = option_text(long, "auto-threads", arg_os, &mut iter)? {
                        // Single-threaded: the choice has no effect, but a bad
                        // value is still a bad command line.
                        if v != "physical" && v != "logical" {
                            bail!("--auto-threads must be `physical` or `logical`, got `{v}`");
                        }
                    } else if let Some(v) =
                        option_text(long, "target-compressed-block-size", arg_os, &mut iter)?
                    {
                        let target =
                            parse_size(&v).wrap_err("invalid --target-compressed-block-size")?;
                        opts.target_block_size = Some(u32::try_from(target).map_err(|_| {
                            eyre!("--target-compressed-block-size={v} is too large")
                        })?);
                    } else if let Some(v) = option_text(long, "threads", arg_os, &mut iter)? {
                        parse_u32(&v).wrap_err("invalid --threads")?;
                    } else if let Some(v) = first_option_text(
                        long,
                        &["block-size", "split", "jobsize"],
                        arg_os,
                        &mut iter,
                    )? {
                        // The long spellings of `-B#`: the reference reads all
                        // of them into one setting (zstdcli.c:1108-1110,
                        // `chunkSize`), which cuts the benchmark's frames and
                        // the training samples, and is a multi-threaded job
                        // size otherwise.
                        let size = parse_size(&v).wrap_err("invalid --block-size")?;
                        opts.block_size = (size != 0).then_some(size);
                    } else if let Some(list) = option_value(long, "filelist", arg_os, &mut iter)? {
                        opts.filelists.push(list);
                    } else if let Some(dir) =
                        option_value(long, "output-dir-flat", arg_os, &mut iter)?
                    {
                        if dir.as_os_str().is_empty() {
                            bail!(
                                "error: output dir cannot be empty string (did you mean to pass '.' instead?)"
                            );
                        }
                        opts.output_dir = Some(dir);
                    } else if let Some(dir) =
                        option_value(long, "output-dir-mirror", arg_os, &mut iter)?
                    {
                        if dir.as_os_str().is_empty() {
                            bail!(
                                "error: output dir cannot be empty string (did you mean to pass '.' instead?)"
                            );
                        }
                        opts.output_dir_mirror = Some(dir);
                    } else if let Some(v) = long.strip_prefix("format=") {
                        // Anything but zstd would hand back a file the caller
                        // did not ask for, so it fails rather than silently
                        // producing a `.zst` under a `.gz` name.
                        if v != "zstd" {
                            bail!("--format={v} is not supported; this build only writes zstd");
                        }
                    } else if let Some(v) = long.strip_prefix("zstd=") {
                        apply_advanced_params(v, &mut opts.advanced)?;
                    } else if let Some(v) = long.strip_prefix("cpu=") {
                        opts.cpu = Some(v.parse().map_err(|err| eyre!("--cpu={v}: {err}"))?);
                    } else if let Some(v) = long.strip_prefix("train-cover=") {
                        select_mode(&mut opts, Mode::Train);
                        opts.trainer = Trainer::Cover;
                        opts.trainer_params = parse_trainer_params(v, false)?;
                    } else if let Some(v) = long.strip_prefix("train-fastcover=") {
                        select_mode(&mut opts, Mode::Train);
                        opts.trainer = Trainer::FastCover;
                        opts.trainer_params = parse_trainer_params(v, true)?;
                    } else if let Some(v) = long.strip_prefix("train-legacy=") {
                        // `s=#` or `selectivity=#`, as `parseLegacyParameters`
                        // reads it.
                        select_mode(&mut opts, Mode::Train);
                        opts.trainer = Trainer::Legacy;
                        let value = v
                            .strip_prefix("selectivity=")
                            .or_else(|| v.strip_prefix("s="))
                            .ok_or_else(|| {
                                eyre!("--train-legacy takes `s=#` or `selectivity=#`, got `{v}`")
                            })?;
                        let (selectivity, tail) = read_leading_u32(value)
                            .wrap_err("invalid --train-legacy selectivity")?;
                        if !tail.is_empty() {
                            bail!("invalid --train-legacy selectivity `{value}`");
                        }
                        opts.selectivity = selectivity;
                    } else if let Some(reference) =
                        option_value(long, "patch-from", arg_os, &mut iter)?
                    {
                        // A patch needs the levels that reach far back, so the
                        // reference command unlocks the ultra levels with it.
                        opts.patch_from = Some(reference);
                        opts.patch_window_lifted = true;
                        ultra = true;
                    } else if let Some(reference) =
                        option_value(long, "patch-apply", arg_os, &mut iter)?
                    {
                        // Decompression against a `--patch-from` reference. The
                        // reference command (its development branch; 1.5.7 has
                        // no such option) lifts its memory ceiling to the
                        // largest window here, since a patch
                        // reaches back across the whole reference. A `-M` given
                        // earlier is dropped the same way; one given later
                        // stands (see `decode_window_ceiling`).
                        select_mode(&mut opts, Mode::Decompress);
                        opts.patch_from = Some(reference);
                        opts.patch_window_lifted = true;
                        opts.memory_limit = None;
                    } else if let Some(path) = option_value(long, "trace", arg_os, &mut iter)? {
                        // The file one CSV line per compressed and decompressed
                        // frame is appended to, as a reference build with library
                        // tracing writes it (`programs/zstdcli_trace.c`).
                        opts.trace = Some(path);
                    } else if long == "rsyncable" {
                        // Synchronisation points are cut between the jobs of a
                        // multi-threaded run, which this build does not have;
                        // the reference command refuses the pair too.
                        bail!("--rsyncable is not compatible with single-thread mode");
                    } else if long == "long" {
                        // Bare `--long` is `--long=27` upstream. The window is
                        // the point of the flag, so leaving the level's own one
                        // would reach back nowhere near the asked-for distance.
                        opts.long = true;
                        opts.long_window_log = Some(DEFAULT_LONG_WINDOW_LOG);
                    } else if let Some(v) = long.strip_prefix("long=") {
                        // `--long=N` names the back-reference window, so the N is
                        // carried through to the encoder rather than dropped.
                        // Reject `--long=` / `--long=abc` instead of treating
                        // them as a silent no-op. Exact-match so `--longer` is an
                        // unknown option.
                        // Checked once the mode is final, as a decode-only run
                        // takes a wider window than one that compresses.
                        let log: u32 = v.parse().wrap_err("invalid --long window log")?;
                        opts.long = true;
                        opts.long_window_log = Some(log);
                    } else {
                        bail!("unknown option: --{long}");
                    }
                }
            }
            continue;
        }
        // Short flag cluster, e.g. `-dcf`, `-19`, `-D dict`, `-o out`.
        let chars: Vec<char> = arg[1..].chars().collect();
        let mut ci = 0;
        while ci < chars.len() {
            let c = chars[ci];
            match c {
                'd' => select_mode(&mut opts, Mode::Decompress),
                'z' => select_mode(&mut opts, Mode::Compress),
                't' => select_mode(&mut opts, Mode::Test),
                'l' => select_mode(&mut opts, Mode::List),
                // `-b` benchmarks; the digits after it are the level it starts
                // at, read by the level arm (`-b19`).
                'b' => opts.bench = true,
                // `-p` takes a benchmark parameter only when a digit follows;
                // otherwise it is the pause, and the cluster goes on
                // (zstdcli.c:1322-1329).
                'p' if !chars.get(ci + 1).is_some_and(char::is_ascii_digit) => *pause = true,
                'e' | 'i' | 'p' | 'P' | 'B' | 'T' | 's' => {
                    // A flag with a number attached; the cluster goes on after
                    // the number, so `-b1e10i0` is `-b -1 -e10 -i0`.
                    let (value, next) = cluster_u32(&chars, ci + 1)
                        .wrap_err_with(|| format!("invalid -{c} value (in {arg})"))?;
                    match c {
                        // End of the benchmarked level range.
                        'e' => {
                            bench_end = Some(
                                i32::try_from(value)
                                    .wrap_err_with(|| format!("invalid -e level `{value}`"))?,
                            );
                        }
                        // Per-level benchmark time budget in seconds. A bare
                        // `-i` is zero, one pass, as the reference reads it
                        // (`readU32FromChar` of nothing is 0).
                        'i' => opts.bench_secs = f64::from(value),
                        // `-p` with digits: a benchmark parameter.
                        'p' => opts.bench_param = Some(value),
                        'P' => opts.bench_compressibility = Some(value),
                        // `-B#` cuts the benchmark's inputs into independent
                        // frames and a training sample into several samples.
                        // When compressing it is the job size of a
                        // multi-threaded run, which this build does not have,
                        // so it is kept and has no effect there.
                        'B' => opts.block_size = (value != 0).then_some(u64::from(value)),
                        // The thread count: single-threaded here, so it steers
                        // nothing, but it is read like every other number.
                        'T' => {}
                        // `-s#`, the legacy trainer's selectivity: the one flag
                        // of this arm left.
                        _ => {
                            debug_assert_eq!(c, 's');
                            opts.selectivity = value;
                        }
                    }
                    ci = next;
                    continue;
                }
                // Gzip's "do not store the name": nothing is stored to begin
                // with, so accepted and ignored, as the reference does.
                'n' => {}
                'c' => {
                    // Clears `-o`; see the `--stdout` arm for why.
                    opts.to_stdout = true;
                    opts.output = None;
                }
                'f' => {
                    opts.force = true;
                    opts.force_stdin = true;
                    opts.follow_links = true;
                }
                'k' => opts.keep = true,
                // `-S` measures each input on its own.
                'S' => opts.bench_separately = true,
                'q' => *verbosity -= 1,
                'v' => *verbosity += 1,
                'C' => opts.checksum = true,
                'r' => opts.recursive = true,
                'M' => {
                    // `-M[N]` is a decompression memory ceiling — a safety
                    // promise, so it is checked against the one this build
                    // enforces rather than swallowed.
                    //
                    // A bare `-M` sets no ceiling, which is what upstream does
                    // with it: the value is attached or it is nothing, and the
                    // next argument stays a filename (`zstd -d -M 8 f.zst`
                    // reads `8` as a file). Erroring here would refuse a
                    // command line the reference tool accepts.
                    let (_, next) = cluster_u32(&chars, ci + 1)
                        .wrap_err_with(|| format!("invalid -M memory limit (in {arg})"))?;
                    let number: String = chars[ci + 1..next].iter().collect();
                    if !number.is_empty() {
                        opts.memory_limit =
                            parse_memory_limit(&number).wrap_err("invalid -M memory limit")?;
                        opts.patch_window_lifted = false;
                    }
                    ci = next;
                    continue;
                }
                'V' => {
                    print_version(*verbosity);
                    return Ok(Parsed::Handled { pause: *pause });
                }
                'H' => {
                    print_help(*verbosity, &preset.name);
                    return Ok(Parsed::Handled { pause: *pause });
                }
                'h' => {
                    let mut stdout = io::stdout().lock();
                    write_short_usage(&mut stdout, &preset.name)
                        .wrap_err("failed to write usage")?;
                    return Ok(Parsed::Handled { pause: *pause });
                }
                'D' | 'o' => {
                    // Value is the rest of this token, or the next argument.
                    // Either way it comes off the original argument, so a path
                    // that is not UTF-8 reaches the filesystem as given. The
                    // flags scanned so far are all ASCII, one byte each, so the
                    // value starts at `ci + 2`: the leading `-` plus them.
                    let value = if ci + 1 == chars.len() {
                        iter.next()
                            .map(|(_, v)| PathBuf::from(v))
                            .ok_or_else(|| eyre!("option -{c} requires a value"))?
                    } else {
                        attached_path(arg_os, ci + 2)
                    };
                    if c == 'D' {
                        opts.dict = Some(value);
                    } else {
                        // Clears `-c`, so the later of the two wins.
                        opts.output = Some(value);
                        opts.to_stdout = false;
                    }
                    ci = chars.len();
                    continue;
                }
                '0'..='9' => {
                    // The level, and the cluster goes on after it (`-19c`).
                    let (level, next) = cluster_u32(&chars, ci)
                        .wrap_err_with(|| format!("invalid level (in {arg})"))?;
                    opts.level = i32::try_from(level)
                        .wrap_err_with(|| format!("invalid level `{level}`"))?;
                    ci = next;
                    continue;
                }
                _ => bail!("unknown flag: -{c} (in {arg})"),
            }
            ci += 1;
        }
        let _ = idx;
    }
    opts.verbosity = *verbosity;
    opts.pause = *pause;

    // `-M` bounds decompression, so it is weighed only on the runs that decode.
    // Compressing, listing or training allocates no decoder, and upstream takes
    // the flag there without complaint. A mode flag may follow the limit, which
    // is why this waits for the whole command line. The `-D` dictionary is
    // weighed on top in `run`, once its size is known.
    if let Some(limit) = opts.memory_limit
        && decodes(&opts)
    {
        check_memory_limit(limit, 0, 0)?;
    }
    validate_level(opts.level)?;
    // The benchmark starts at the compression level, however it was given
    // (`-b19`, `-19 -b`, `ZSTD_CLEVEL`), as the reference starts at `cLevel`.
    opts.bench_start = opts.level;
    // An end below the start is raised to it, as upstream raises `cLevelLast`.
    opts.bench_end = bench_end.map_or(opts.bench_start, |end: i32| end.max(opts.bench_start));
    // The levels 20-22 are expensive enough that upstream asks for them by
    // name. Benchmarking compresses the range `-b`/`-e` give rather than the
    // level `-N` set, so the gate reads the range's top when there is one —
    // `-b20` reaches an ultra level as surely as `-20` does.
    let (lowest_level, highest_level) = if opts.bench {
        (
            opts.bench_start.min(opts.bench_end),
            opts.bench_start.max(opts.bench_end),
        )
    } else {
        (opts.level, opts.level)
    };
    // Both ends run, so both are checked here rather than at the level that
    // reaches them: a range starting below the scale would otherwise stat and
    // read every input before the first pass refused it.
    validate_level(lowest_level)?;
    validate_level(highest_level)?;
    // Unnamed, an ultra level is not refused but reduced, with a warning, the
    // way upstream reduces it — a script that runs `zstd -22` compresses at 19
    // rather than failing, and refusing here is what would break it.
    if !ultra && highest_level > CLI_MAX_LEVEL_WITHOUT_ULTRA {
        display!(
            *verbosity,
            2,
            "Warning : compression level higher than max, reduced to {CLI_MAX_LEVEL_WITHOUT_ULTRA}"
        );
        opts.level = opts.level.min(CLI_MAX_LEVEL_WITHOUT_ULTRA);
        opts.bench_start = opts.bench_start.min(CLI_MAX_LEVEL_WITHOUT_ULTRA);
        opts.bench_end = opts.bench_end.min(CLI_MAX_LEVEL_WITHOUT_ULTRA);
    }
    // Window logs are validated here, before any file is opened, against the
    // mode the whole command line settled on; a knob out of its range is a
    // broken command line.
    for log in [opts.long_window_log, opts.advanced.window_log]
        .into_iter()
        .flatten()
    {
        check_window_log(log, compresses(&opts))?;
    }
    if compresses(&opts) {
        frame_parameters(
            CompressionLevel::from_level(opts.level),
            &FrameSettings::from_options(&opts),
        )?;
    }
    if opts.patch_from.is_some() && opts.dict.is_some() {
        bail!("error : can't use -D and --patch-from=# at the same time");
    }
    Ok(Parsed::Run(Box::new(opts)))
}

/// The part of `arg` from byte `at`, as the bytes it was given in.
///
/// An attached path — `-Dname`, `--use-dict=name` — is the same filename as one
/// passed separately and has to survive the same way, so it comes off the
/// original argument rather than off the lossy view the option spelling was
/// matched against. `at` must land after ASCII only, which every option
/// spelling is: a lossy conversion replaces non-ASCII sequences alone, so a
/// prefix that matched there is byte-for-byte the same at the front of `arg`.
fn attached_path(arg: &std::ffi::OsStr, at: usize) -> PathBuf {
    let bytes = arg.as_encoded_bytes();
    debug_assert!(
        bytes[..at].is_ascii(),
        "the split point must follow ASCII, or it is not a boundary"
    );
    // SAFETY: `bytes` came from an `OsStr` and is split at the end of an ASCII
    // run, so the remainder is a valid encoded `OsStr` — exactly the
    // precondition `from_encoded_bytes_unchecked` documents.
    let rest = unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(&bytes[at..]) };
    PathBuf::from(rest)
}

/// Select the operation, replacing whatever was chosen before it.
///
/// Benchmarking is a mode like any other from the command line's point of view,
/// even though it is carried in its own field, so naming an operation after
/// `-b` has to turn the benchmark off — the last flag typed is the one that
/// runs, which is how every other operation flag here behaves.
fn select_mode(opts: &mut Options, mode: Mode) {
    opts.mode = mode;
    opts.bench = false;
}

/// Whether this run will decode anything, and so whether `-M` binds it.
///
/// Not the same question as the mode: benchmarking keeps `Mode::Compress` and
/// still decompresses at every level it measures.
fn decodes(opts: &Options) -> bool {
    opts.bench || matches!(opts.mode, Mode::Decompress | Mode::Test)
}

/// Whether this run will compress anything, and so whether the encoder's own
/// flags have to hold. Benchmarking compresses whatever mode was asked for.
fn compresses(opts: &Options) -> bool {
    opts.bench || matches!(opts.mode, Mode::Compress)
}

fn validate_level(level: i32) -> Result<()> {
    let (min, max) = (CompressionLevel::MIN_LEVEL, CompressionLevel::MAX_LEVEL);
    if !(min..=max).contains(&level) {
        bail!("compression level {level} out of range [{min}, {max}]");
    }
    Ok(())
}

/// `--version`: the reference command version this tool follows, and this
/// build's own. Below the default display level (`-qV`) only the bare
/// version number is printed, for a script to read; at `-vV` the supported
/// formats follow, as they do there.
fn print_version(verbosity: i32) {
    if verbosity < DEFAULT_LEVEL {
        println!("{UPSTREAM_VERSION}");
        return;
    }
    println!(
        "zstd version {UPSTREAM_VERSION} (structured-zstd v{})",
        env!("CARGO_PKG_VERSION")
    );
    if verbosity >= 3 {
        println!("*** supports: zstd");
    }
}

/// The short usage: `-h`, and what a mistaken command line gets under its
/// error. Laid out as the reference command lays it out.
fn write_short_usage(out: &mut impl Write, program: &str) -> io::Result<()> {
    writeln!(
        out,
        "Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided.\n"
    )?;
    writeln!(
        out,
        "Usage: {program} [OPTIONS...] [INPUT... | -] [-o OUTPUT]\n"
    )?;
    writeln!(out, "Options:")?;
    writeln!(
        out,
        "  -o OUTPUT                     Write output to a single file, OUTPUT."
    )?;
    writeln!(
        out,
        "  -k, --keep                    Preserve INPUT file(s). [Default]"
    )?;
    writeln!(
        out,
        "  --rm                          Remove INPUT file(s) after successful (de)compression.\n"
    )?;
    writeln!(
        out,
        "  -#                            Desired compression level, where `#` is a number between 1 and {CLI_MAX_LEVEL_WITHOUT_ULTRA};"
    )?;
    writeln!(
        out,
        "                                lower numbers provide faster compression, higher numbers yield"
    )?;
    writeln!(
        out,
        "                                better compression ratios. [Default: {}]\n",
        CompressionLevel::DEFAULT_LEVEL
    )?;
    writeln!(
        out,
        "  -d, --decompress              Perform decompression."
    )?;
    writeln!(
        out,
        "  -D DICT                       Use DICT as the dictionary for compression or decompression.\n"
    )?;
    writeln!(
        out,
        "  -f, --force                   Disable input and output checks. Allows overwriting existing files,"
    )?;
    writeln!(
        out,
        "                                receiving input from the console, printing output to STDOUT, and"
    )?;
    writeln!(
        out,
        "                                operating on links, block devices, etc. Unrecognized formats will be"
    )?;
    writeln!(
        out,
        "                                passed through as-is.\n"
    )?;
    writeln!(
        out,
        "  -h                            Display short usage and exit."
    )?;
    writeln!(
        out,
        "  -H, --help                    Display full help and exit."
    )?;
    writeln!(
        out,
        "  -V, --version                 Display the program version and exit.\n"
    )
}

/// The full help (`-H`, `--help`): the short usage, then every option this
/// build honours, then the ones it accepts without effect and the ones it
/// refuses, so a reader is not surprised by either.
fn print_help(verbosity: i32, program: &str) {
    print_version(verbosity.max(DEFAULT_LEVEL));
    println!();
    let mut stdout = io::stdout().lock();
    let _ = write_short_usage(&mut stdout, program);
    let _ = stdout.write_all(HELP_ADVANCED.as_bytes());
}

/// The part of the full help below the short usage.
const HELP_ADVANCED: &str = "\
Advanced options:
  -c, --stdout                  Write to STDOUT (even if it is a console) and keep the INPUT file(s).

  -v, --verbose                 Enable verbose output; pass multiple times to increase verbosity.
  -q, --quiet                   Suppress warnings; pass twice to suppress errors.
  --trace LOG                   Log tracing information to LOG.

  --[no-]progress               Forcibly show/hide the progress counter. NOTE: Any (de)compressed
                                output to terminal will mix with progress counter text.

  -r                            Operate recursively on directories.
  --ignore-read-errors          With -r, report a directory that cannot be opened and go on
                                without failing the run (exit 0, as upstream zstd).
  --filelist LIST               Read a list of files to operate on from LIST.
  --output-dir-flat DIR         Store processed files in DIR.
  --output-dir-mirror DIR       Store processed files in DIR, respecting original directory structure.

  --[no-]check                  Add XXH64 integrity checksums during compression. [Default: Add, Validate]
                                If `-d` is present, ignore/validate checksums during decompression.

  --                            Treat remaining arguments after `--` as files.

  --cpu=LEVEL                   Use kernels up to LEVEL only: scalar, sse2, sse4.2, bmi2, avx2, avx512
                                (x86) or neon, sve (aarch64). [Default: all the CPU supports]

Advanced compression options:
  --ultra                       Enable levels beyond 19, up to 22; requires more memory.
  --max                         Compress with every parameter at its maximum; the window stops at 30,
                                the widest this build writes. Requires a lot of memory.
  --fast[=#]                    Use to very fast compression levels. [Default: 1]
  --long[=#]                    Enable long distance matching with window log #. [Default: 27]
                                Available from level 16 up (or with --zstd=strat=7..9), where
                                long-distance matching runs; up to 30 when compressing. When
                                decompressing, admits windows up to 2^#.
  --patch-from=REF              Use REF as the reference point for Zstandard's diff engine.
  --zstd=wlog=#,clog=#,hlog=#,slog=#,mml=#,tlen=#,strat=#[,lhlog=#,lmml=#,lblog=#,lhrlog=#]
                                Override the level's compression parameters knob by knob.
  --exclude-compressed          Only compress files that are not already compressed.
  --show-default-cparams        Print the parameters the level selects for each input.

  --stream-size=#               Specify size of streaming input from STDIN.
  --size-hint=#                 Optimize compression parameters for streaming input of approximately size #.
  --target-compressed-block-size=#
                                Generate compressed blocks of approximately # size.

  --no-dictID                   Don't write `dictID` into the header (dictionary compression only).
  --[no-]content-size           Write the input size into the frame header when it is known. [Default: Write]
  --[no-]compress-literals      Force (un)compressed literals.

  --format=zstd                 Compress files to the `.zst` format. [Default]

Advanced decompression options:
  -l                            Print information about Zstandard-compressed files.
  --test                        Test compressed file integrity.
  -M#                           Set the memory usage limit to # megabytes.
  --[no-]pass-through           Pass through uncompressed files as-is. [Default: Disabled; Enabled for zstdcat]

Dictionary builder:
  --train                       Create a dictionary from a training set of files.

  --train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]]
                                Use the cover algorithm (with optional arguments).
  --train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]]
                                Use the fast cover algorithm (with optional arguments).

  --train-legacy[=s=#]          Use the legacy algorithm with selectivity #. [Default: 9]
  -B#                           Cut each file into samples of size #; otherwise each file
                                is one sample of up to 128 KiB. At least 5 samples are needed.
  -o NAME                      Use NAME as dictionary name. [Default: dictionary]
  --maxdict=#                   Limit dictionary to specified size #. [Default: 112640]
  --dictID=#                    Force dictionary ID to #. [Default: Random]

Benchmark options:
  -b#                           Perform benchmarking with compression level #. [Default: 3]
  -e#                           Test all compression levels up to #; starting level is `-b#`. [Default: 1]
  -i#                           Set the minimum evaluation to time # seconds. [Default: 3]
  -B#                           Cut file into independent chunks of size #. [Default: No chunking]
  -S                            Output one benchmark result per input file. [Default: Consolidated result]
  -D dictionary                 Benchmark using dictionary

Environment: ZSTD_CLEVEL sets the default compression level; ZSTD_NBTHREADS is read and validated.

Accepted for compatibility, with no effect here: -T#/--threads=#, --single-thread,
--auto-threads, -B# and --block-size=# when compressing (the job size of a
multi-threaded run), --adapt, --zstd=ovlog=#, --[no-]sparse,
--[no-]asyncio, --[no-]mmap-dict, --[no-]row-match-finder (compression runs
single-threaded).

Rejected rather than ignored, because they would change the result: --format=
other than zstd, --rsyncable (needs worker threads), and -M/--memory below the
enforced ceiling when decoding.
Trainer shrink[=#] takes effect: the smallest dictionary within # percent
(default 1) of the full one is kept.
A new output file keeps its source's permissions.
";

/// Upstream's names for the nine strategies, in ordinal order from 1
/// (`zstdcli.c`, `ZSTD_strategyMap`).
const STRATEGY_NAMES: [&str; 9] = [
    "ZSTD_fast",
    "ZSTD_dfast",
    "ZSTD_greedy",
    "ZSTD_lazy",
    "ZSTD_lazy2",
    "ZSTD_btlazy2",
    "ZSTD_btopt",
    "ZSTD_btultra",
    "ZSTD_btultra2",
];

/// Write what `--show-default-cparams` reports for one input: the parameters
/// `level` selects for it, in the reference command's layout
/// (`zstdcli.c`, `printDefaultCParams`).
///
/// `size` is the input's length when it has one (`None` for stdin or anything
/// not a regular file). A length of zero is printed as such but sized as an
/// unknown source, because `ZSTD_getCParams`, which the reference calls here,
/// reads zero as "unknown".
fn write_default_cparams(
    out: &mut impl Write,
    name: &str,
    size: Option<u64>,
    dictionary_size: usize,
    level: i32,
) -> io::Result<()> {
    match size {
        Some(bytes) => writeln!(out, "{name} ({bytes} bytes)")?,
        None => writeln!(out, "{name} (src size unknown)")?,
    }
    let params =
        LevelParameters::for_level(level, size.filter(|&bytes| bytes != 0), dictionary_size);
    let ordinal = params.strategy.ordinal();
    // `ordinal` is 1..=9 by construction of `Strategy`.
    let strategy = STRATEGY_NAMES[ordinal as usize - 1];
    writeln!(out, " - windowLog     : {}", params.window_log)?;
    writeln!(out, " - chainLog      : {}", params.chain_log)?;
    writeln!(out, " - hashLog       : {}", params.hash_log)?;
    writeln!(out, " - searchLog     : {}", params.search_log)?;
    writeln!(out, " - minMatch      : {}", params.min_match)?;
    writeln!(out, " - targetLength  : {}", params.target_length)?;
    writeln!(out, " - strategy      : {strategy} ({ordinal})")
}

/// Print `--show-default-cparams` for every input of a compressing run, on
/// stderr and whatever the verbosity, as the reference command does.
fn show_default_cparams(opts: &Options) -> Result<()> {
    let dictionary_size = match dictionary_path(opts) {
        Some(path) => fs::metadata(path)
            .wrap_err_with(|| format!("failed to inspect dictionary file {}", path.display()))?
            .len(),
        None => 0,
    };
    let dictionary_size = usize::try_from(dictionary_size)
        .map_err(|_| eyre!("dictionary of {dictionary_size} bytes does not fit in memory"))?;
    let mut err = io::stderr().lock();
    let stdin = [PathBuf::from("-")];
    let inputs: &[PathBuf] = if opts.inputs.is_empty() {
        &stdin
    } else {
        &opts.inputs
    };
    for input in inputs {
        let (name, size) = if input == Path::new("-") {
            (STDIN_MARK.to_string(), None)
        } else {
            let size = fs::metadata(input)
                .ok()
                .filter(fs::Metadata::is_file)
                .map(|metadata| metadata.len());
            (input.display().to_string(), size)
        };
        write_default_cparams(&mut err, &name, size, dictionary_size, opts.level)
            .wrap_err("failed to write the default parameters")?;
    }
    Ok(())
}

/// The file the run's dictionary comes from: `-D`, or the `--patch-from`
/// reference, which is a dictionary by another name. The command line refuses
/// both at once, so at most one is set.
fn dictionary_path(opts: &Options) -> Option<&Path> {
    opts.dict.as_deref().or(opts.patch_from.as_deref())
}

/// The window a `--patch-from` compression runs with: wide enough to reach
/// back over the whole input (`highbit(size) + 1`, as the reference command
/// sizes it), within what this build both writes and reads back. A larger
/// input cannot be patched here.
fn patch_window_log(source_size: u64) -> Result<u32> {
    use structured_zstd::encoding::CParameter;

    let file_window_log = u64::BITS - source_size.max(1).leading_zeros();
    let lower = u32::try_from(CParameter::WindowLog.bounds().lower_bound)
        .expect("the window log lower bound is a small positive number");
    let upper = max_window_log();
    if file_window_log > upper {
        bail!(
            "Can't handle files larger than {} MiB with --patch-from: the patch would \
             need a window past the largest this build writes and reads back",
            (1u64 << upper) >> 20
        );
    }
    Ok(file_window_log.max(lower))
}

/// Whether a `--patch-from` compression of `source_size` bytes against a
/// `reference_size`-byte reference needs long-distance matching to reach the
/// reference: when the file's window outgrows what the match finder cycles
/// through, by the reference command's rule (`FIO_adjustParamsForPatchFromMode`,
/// `fileWindowLog > ZSTD_cycleLog(chainLog, strategy)`, the binary-tree
/// strategies cycling one log short of their chain). The chain and strategy
/// are the ones the frame runs, the level's for those sizes under any
/// `--zstd=` override; the reference command reads the bare level's and
/// leaves an overridden short chain without long mode.
fn patch_needs_long_distance(
    level: i32,
    advanced: &AdvancedParams,
    source_size: u64,
    reference_size: u64,
) -> bool {
    let file_window_log = u64::BITS - source_size.max(1).leading_zeros();
    // A reference past the address space cannot have been read to get here.
    let reference_size = usize::try_from(reference_size).unwrap_or(usize::MAX);
    let params = LevelParameters::for_level(level, Some(source_size), reference_size);
    let chain_log = advanced.chain_log.unwrap_or(params.chain_log);
    let strategy = advanced.strategy.unwrap_or(params.strategy);
    let cycle_log = chain_log - u32::from(strategy >= Strategy::Btlazy2);
    file_window_log > cycle_log
}

/// Whether a level this run compresses at needs long-distance matching for the
/// patch (see [`patch_needs_long_distance`]). A benchmark compresses every
/// level of its `-b`/`-e` range under one setting, so one level that cannot
/// cycle the input turns it on for all.
fn patch_run_needs_long_distance(opts: &Options, source_size: u64, reference_size: u64) -> bool {
    let levels = if opts.bench {
        opts.bench_start..=opts.bench_end
    } else {
        opts.level..=opts.level
    };
    levels
        .into_iter()
        .any(|level| patch_needs_long_distance(level, &opts.advanced, source_size, reference_size))
}

/// Whether the run reads the `-D` / `--patch-from` file it names. Listing
/// walks frame headers and training builds a dictionary from its samples;
/// neither consults that one. Reading it anyway would fail a listing over a
/// missing file that has nothing to do with it, and spend time and memory on
/// a large one nothing looks at.
fn reads_dictionary(opts: &Options) -> bool {
    opts.bench || !matches!(opts.mode, Mode::List | Mode::Train)
}

/// Read the `-D` dictionary, if there is one, without breaking `-M` to do it.
///
/// The limit was already weighed against what decoding alone needs; the
/// dictionary is the other half of that promise. Its size comes from the
/// directory entry, so an oversized one is refused before it is read rather
/// than after the allocation the limit was supposed to prevent. The read is
/// then bounded by that same size, and a file that grew in between is an error
/// rather than a silent truncation, which would corrupt the dictionary.
fn load_dictionary(opts: &Options) -> Result<Option<Vec<u8>>> {
    let Some(path) = dictionary_path(opts) else {
        return Ok(None);
    };
    if !reads_dictionary(opts) {
        return Ok(None);
    }
    // Asked of the path first, because opening a FIFO blocks until a writer
    // turns up and the point of the check is not to wait for one. Everything
    // the read depends on is then re-asked of the OPEN FILE below, since a path
    // is only a name: between this answer and the open it can be made to name
    // something else, and it is the thing actually read whose type and length
    // have to hold. (A swap to a FIFO inside that window still blocks in the
    // open; refusing to wait would need a non-blocking open, which needs a
    // platform flag this crate has no dependency to name.)
    let named = fs::metadata(path)
        .wrap_err_with(|| format!("failed to inspect dictionary file {}", path.display()))?;
    if !named.is_file() {
        bail!("-D needs a regular file: {} is not one", path.display());
    }
    // What the read will cost, answerable from a size alone. Asked of the name
    // before the file is opened — a dictionary that cannot fit the promise is
    // refused without spending a descriptor on it — and asked again below of
    // the file that was actually opened.
    let weigh = |size: u64| -> Result<usize> {
        // The size bounds the read, so it has to be a count of bytes this
        // machine can hold: a 64-bit length cast to a pointer-sized one
        // truncates on a 32-bit target, where 4 GiB would become a capacity of
        // zero that the read then grows into an allocation which aborts rather
        // than refuses.
        let capacity = usize::try_from(size).map_err(|_| {
            eyre!(
                "dictionary file {} is {size} bytes, more than this machine can address",
                path.display()
            )
        })?;
        if let Some(limit) = opts.memory_limit
            && decodes(opts)
        {
            // As read and again as parsed.
            check_memory_limit(limit, size, 2)?;
        }
        Ok(capacity)
    };
    weigh(named.len())?;

    let file = File::open(path)
        .wrap_err_with(|| format!("failed to open dictionary file {}", path.display()))?;
    // And asked again of the FILE, because a path is only a name: between the
    // answer above and this open it can be made to name something else, and it
    // is the thing actually read whose type and length have to hold. (A swap to
    // a FIFO inside that window still blocks in the open; refusing to wait
    // would need a non-blocking open, which needs a platform flag this crate
    // has no dependency to name.)
    let opened = file
        .metadata()
        .wrap_err_with(|| format!("failed to inspect dictionary file {}", path.display()))?;
    if !opened.is_file() {
        bail!("-D needs a regular file: {} is not one", path.display());
    }
    let size = opened.len();
    let capacity = weigh(size)?;

    let mut bytes = Vec::with_capacity(capacity);
    // One byte past the size the check cleared: reading it means the file grew.
    file.take(size + 1)
        .read_to_end(&mut bytes)
        .wrap_err_with(|| format!("failed to read dictionary file {}", path.display()))?;
    if bytes.len() as u64 > size {
        bail!("{} grew while it was being read; run again", path.display());
    }
    Ok(Some(bytes))
}

/// What the run compresses and decodes with, built once and used by every
/// frame: the `-D` dictionary in the forms the two codecs take, and the
/// compression context the frames share, as the reference command keeps one
/// set of resources for a run (`fileio.c`, `FIO_createCResources`).
///
/// Parsing the blob or building a context per frame would put that setup
/// inside every frame and, under `-b`, inside the measurement, where for a
/// large dictionary over a small input it is most of what the number would be.
#[derive(Default)]
struct Codecs {
    encoder: Option<structured_zstd::encoding::EncoderDictionary>,
    decoder: Option<structured_zstd::decoding::DictionaryHandle>,
    /// The context frames are compressed with and the settings it was built
    /// for; absent before the first frame, and again after one fails.
    compressor: Option<(FrameSettings, CompressionContext)>,
    /// The decoder every frame is decoded with, its buffers allocated by the
    /// first frame and reused by the rest.
    decompressor: structured_zstd::decoding::FrameDecoder,
    /// What the decoder fills before each write, [`IO_CHUNK`] once the first
    /// frame allocates it, and kept for the rest of the run.
    chunk: Vec<u8>,
    /// Length of the `-D` / `--patch-from` blob, the dictionary size a trace
    /// line reports either way (upstream's `dictContentSize` and
    /// `ZSTD_DDict_dictSize`, both the whole buffer).
    dictionary_size: u64,
    /// `--trace`: the file every frame is recorded in, once it is open.
    trace: Option<trace::Trace>,
}

impl Codecs {
    /// Open `--trace` for this run, if it was asked for. A file that cannot be
    /// opened is reported and the run goes on untraced, as the reference goes
    /// on when its `fopen` fails.
    ///
    /// # Errors
    ///
    /// The trace names a file the run reads or writes. Appending to an input
    /// or the dictionary would change it, and opening an output ahead of its
    /// own overwrite check would make the run refuse its own output, or with
    /// `-f` rename the output over the trace. The reference opens the trace
    /// without asking; refusing first leaves every file as it was.
    fn open_trace(&mut self, opts: &Options, single_pass: bool) -> Result<()> {
        let Some(path) = &opts.trace else {
            return Ok(());
        };
        refuse_trace_alias(opts, path)?;
        match trace::Trace::open(path, UPSTREAM_VERSION_NUMBER, single_pass) {
            Ok(mut trace) => {
                trace.reports_failures = opts.verbosity >= 1;
                self.trace = Some(trace);
            }
            Err(err) => display!(
                opts.verbosity,
                2,
                "zstd: --trace {}: {err}; nothing is traced",
                path.display()
            ),
        }
        Ok(())
    }
}

/// Refuse a `--trace` path that names a file of the run: an input, a file
/// list, the dictionary, the `-o` output, an output derived from an input, or
/// the file standard output is when the run writes its data there. Compared
/// as files, as the output checks compare them: another spelling, a symlink
/// or a hard link is the same file.
fn refuse_trace_alias(opts: &Options, trace: &Path) -> Result<()> {
    // Opening a dangling link creates the file it points at, so that file is
    // the one compared. Files that exist are compared by identity; names of
    // files still to be created are compared as spelled, so two spellings a
    // case-insensitive filesystem would merge are not told apart. Knowing that
    // takes each filesystem's own case rules, which no portable call reads.
    let trace = &dangling_link_target(trace);
    let names = |other: &Path| -> Result<bool> {
        // A dangling link among the run's files leads to the file opening it
        // would create as well, which opening the trace may create first.
        let other = &dangling_link_target(other);
        Ok(names_the_same_file(trace, other)?
            || (trace.exists() && other.exists() && paths_point_to_same_file(trace, other)?))
    };
    let refuse = |role: &str, other: &Path| -> Result<()> {
        if names(other)? {
            bail!(
                "--trace {} is also {role} {}",
                trace.display(),
                other.display()
            );
        }
        Ok(())
    };
    if let Some(dictionary) = dictionary_path(opts)
        && reads_dictionary(opts)
    {
        refuse("the dictionary", dictionary)?;
    }
    for input in opts.inputs.iter().filter(|input| *input != Path::new("-")) {
        refuse("the input", input)?;
    }
    for list in &opts.filelists {
        refuse("the file list", list)?;
    }
    // Stdin is read through a descriptor rather than a name, and not only by
    // the codec: a confirmation or `-p` reads it too, so no trace goes there.
    if is_stdin(trace) {
        bail!(
            "--trace {} is also standard input, which this run reads",
            trace.display()
        );
    }
    // What the run sends to stdout would interleave with the trace's lines
    // there. A run writing to a file leaves stdout free for the trace.
    if writes_to_stdout(opts) && is_stdout(trace) {
        bail!(
            "--trace {} is also standard output, which this run writes to",
            trace.display()
        );
    }
    // Errors, summaries and progress go to stderr unless `-qq` silences it;
    // `--show-default-cparams`, `-p`'s prompt and `--progress` go there
    // whatever it is.
    if (opts.verbosity >= 1
        || opts.show_default_cparams
        || opts.pause
        || opts.progress == Progress::Always)
        && is_stderr(trace)
    {
        bail!(
            "--trace {} is also standard error, which this run writes to",
            trace.display()
        );
    }
    // A benchmark and `-t` write nothing, `--list` writes its table to stdout
    // whatever `-o` says, and stdout is no file.
    if opts.bench || opts.to_stdout || matches!(opts.mode, Mode::Test | Mode::List) {
        return Ok(());
    }
    if opts.mode == Mode::Train {
        return refuse("the dictionary being trained", &training_output(opts));
    }
    if let Some(output) = &opts.output {
        // Every input skipped as already compressed leaves `-o` unwritten.
        let writes_output = opts.inputs.is_empty()
            || opts
                .inputs
                .iter()
                .any(|input| !skips_as_compressed(opts, input));
        return if writes_output {
            refuse("the output", output)
        } else {
            Ok(())
        };
    }
    if matches!(opts.mode, Mode::Compress | Mode::Decompress) {
        for input in opts.inputs.iter().filter(|input| *input != Path::new("-")) {
            // An input skipped as already compressed, or whose output cannot
            // be derived, writes nothing.
            if skips_as_compressed(opts, input) {
                continue;
            }
            if let Ok(output) = derive_output_path(opts, input) {
                refuse("the output", &output)?;
                // A directory the run has to create on the way to it, as
                // `--output-dir-mirror` does: a trace opened there first
                // would be a file where the directory has to go.
                for directory in output.ancestors().skip(1) {
                    if directory.as_os_str().is_empty() || directory.exists() {
                        break;
                    }
                    refuse("the output directory", directory)?;
                }
            }
        }
    }
    Ok(())
}

/// Whether the run writes to standard output: (de)compressed data under `-c`
/// or from stdin without `-o`, a benchmark's results unless `-qq` silences
/// them, or `--list`'s table. `-o -` is a file named `-`, as the output is
/// written everywhere else.
fn writes_to_stdout(opts: &Options) -> bool {
    if opts.bench {
        return opts.verbosity >= 1;
    }
    match opts.mode {
        Mode::List => true,
        Mode::Compress | Mode::Decompress => {
            opts.to_stdout
                || (opts.output.is_none()
                    && (opts.inputs.is_empty()
                        || opts.inputs.iter().any(|input| input == Path::new("-"))))
        }
        Mode::Test | Mode::Train => false,
    }
}

/// Whether `input` is one `--exclude-compressed` leaves alone: compression
/// skips a name with a compressed extension, and writes nothing for it.
fn skips_as_compressed(opts: &Options, input: &Path) -> bool {
    compresses(opts) && opts.exclude_compressed && inputs::has_compressed_extension(input)
}

/// Whether `path` is the file this process's standard output writes to: by
/// identity, or by one of the names Unix gives it, which reach it whatever
/// it is (macOS gives a pipe under `/dev/fd` an identity of its own).
fn is_stdout(path: &Path) -> bool {
    names_stream(path, &["/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"])
        || identity::of_stdout().is_some_and(|stdout| identity::of_path(path) == Some(stdout))
}

/// Whether `path` is the file this process's standard error writes to, as
/// [`is_stdout`] tells standard output.
fn is_stderr(path: &Path) -> bool {
    names_stream(path, &["/dev/stderr", "/dev/fd/2", "/proc/self/fd/2"])
        || identity::of_stderr().is_some_and(|stderr| identity::of_path(path) == Some(stderr))
}

/// Whether `path` is the file this process's standard input reads: by one
/// of its Unix names, or by identity when it is a regular file or a named
/// pipe, the kinds a trace written to would feed into the input. A device is
/// left out: `/dev/null` as stdin and as a trace is two discards, not a
/// collision.
fn is_stdin(path: &Path) -> bool {
    names_stream(path, &["/dev/stdin", "/dev/fd/0", "/proc/self/fd/0"])
        || (fs::metadata(path)
            .is_ok_and(|metadata| metadata.is_file() || is_fifo_type(&metadata.file_type()))
            && identity::of_stdin().is_some_and(|stdin| identity::of_path(path) == Some(stdin)))
}

/// Whether `path` is spelled as one of a standard stream's Unix `names`.
fn names_stream(path: &Path, names: &[&str]) -> bool {
    cfg!(unix) && names.iter().any(|name| path == Path::new(name))
}

/// Where `--train` writes the dictionary: `-o`, or `dictionary` as the
/// reference command names it.
fn training_output(opts: &Options) -> PathBuf {
    opts.output
        .clone()
        .unwrap_or_else(|| PathBuf::from("dictionary"))
}

/// The file a dangling symlink at `path` would create when opened for
/// writing, following a chain of them; `path` itself when it is not one. A
/// relative target is read against the link's own directory. The chain is
/// cut at 40 links, as the kernel cuts it (`SYMLOOP_MAX` on Linux), and the
/// path reached there is returned.
fn dangling_link_target(path: &Path) -> PathBuf {
    let mut current = path.to_path_buf();
    for _ in 0..40 {
        if current.exists() {
            break;
        }
        // A path that is not there and is no link reads no link either.
        let Ok(target) = fs::read_link(&current) else {
            break;
        };
        current = match current.parent() {
            Some(parent) if target.is_relative() => parent.join(target),
            _ => target,
        };
    }
    current
}

/// Append `frame` to `trace`, if one is open. A trace that cannot be written
/// is reported once and closed; the work it describes goes on.
fn trace_frame(trace: &mut Option<trace::Trace>, frame: &trace::Frame) {
    if let Some(open) = trace.as_mut()
        && let Err(err) = open.record(frame)
    {
        if open.reports_failures {
            eprintln!("zstd: --trace: {err}; no further frames are traced");
        }
        *trace = None;
    }
}

/// The piece the command reads and writes at a time: one block, the size of
/// upstream's `ZSTD_DStreamOutSize()` and `ZSTD_CStreamInSize()`. Each piece is
/// one system call, so a smaller one multiplies the calls the data costs.
const IO_CHUNK: usize = 128 * 1024;

impl Codecs {
    /// Parse the blob into the forms this run will use, and no others: a run
    /// that only compresses has no use for the decoder's tables. `-b` asks for
    /// both, since it measures the two directions in turn.
    ///
    /// An empty file is no dictionary rather than a broken one — loading a
    /// zero-size dictionary returns to no-dictionary mode — so `-D` on an empty
    /// file compresses plainly instead of failing.
    ///
    /// `raw_content` is `--patch-from`: the reference is content whatever it
    /// starts with, the way `ZSTD_CCtx_refPrefix` takes it, so a reference that
    /// happens to begin with the dictionary magic is not parsed as one.
    fn prepare(
        raw: Option<&[u8]>,
        raw_content: bool,
        for_compression: bool,
        for_decoding: bool,
    ) -> Result<Self> {
        use structured_zstd::decoding::{Dictionary, DictionaryHandle};
        use structured_zstd::encoding::EncoderDictionary;

        let Some(raw) = raw.filter(|raw| !raw.is_empty()) else {
            return Ok(Self::default());
        };
        let mut prepared = Self {
            dictionary_size: raw.len() as u64,
            ..Self::default()
        };
        if for_compression {
            // Through the constructor that keeps the blob's own length, since
            // that is what the compression-parameter tier is chosen by —
            // parsing first and handing over the content would key it on the
            // wrong size. Whatever `-D` was pointed at: a trained dictionary,
            // or any file at all, taken as raw content the way upstream does.
            // Raw content has no tables, so its content length is its length.
            let dictionary = if raw_content {
                Dictionary::from_raw_content(0, raw.to_vec())
                    .map(EncoderDictionary::from_dictionary)
            } else {
                EncoderDictionary::from_serialized_or_raw_content(raw)
            };
            prepared.encoder =
                Some(dictionary.map_err(|err| eyre!("invalid dictionary: {err:?}"))?);
        }
        if for_decoding {
            let dictionary = if raw_content {
                Dictionary::from_raw_content(0, raw.to_vec())
            } else {
                Dictionary::from_serialized_or_raw_content(raw)
            };
            prepared.decoder = Some(DictionaryHandle::from_dictionary(
                dictionary.map_err(|err| eyre!("failed to parse dictionary: {err:?}"))?,
            ));
        }
        Ok(prepared)
    }

    /// The context a frame under `settings` is compressed with: the previous
    /// frame's when it was built for the same settings, else a new one. Only
    /// the pledge changes from frame to frame, and it is set per frame.
    fn compressor(&mut self, settings: &FrameSettings) -> Result<&mut CompressionContext> {
        let key = FrameSettings {
            pledged_size: None,
            ..*settings
        };
        if self
            .compressor
            .as_ref()
            .is_none_or(|(built_for, _)| *built_for != key)
        {
            // The outgoing context is released first, so two are never held
            // at once.
            self.compressor = None;
            self.compressor = Some((key, new_compressor(&key, self.encoder.as_ref())?));
        }
        let (_, context) = self
            .compressor
            .as_mut()
            .expect("a context for these settings is in place");
        Ok(context)
    }
}

/// How the reference command names stdin in a summary line.
const STDIN_MARK: &str = "/*stdin*\\";

/// Whether the run reads stdin: no input named, or `-` among them.
fn reads_stdin(inputs: &[PathBuf]) -> bool {
    inputs.is_empty() || inputs.iter().any(|input| input == Path::new("-"))
}

/// Whether the run's data goes to stdout: `-c`, or stdin in and no `-o` out.
/// The reference command's `hasStdout`, which silences the result summary
/// and disables `--rm`.
fn writes_stdout(opts: &Options) -> bool {
    opts.to_stdout
        || (opts.output.is_none() && opts.inputs.iter().all(|input| input == Path::new("-")))
}

/// Run the command line. The count of inputs that failed comes back; the
/// exit status is 1 when it is not zero, as the reference command's is,
/// while an error that ends the run early is returned outright.
///
/// A directory `-r` could not open counts as a failed input unless
/// `--ignore-read-errors` is given. The reference command reports it and exits
/// 0, which lets `zstd -r dir && rm -r dir` delete files that were never
/// compressed; the readable rest of the tree is still processed either way.
fn run(mut opts: Options) -> Result<usize> {
    let Selection {
        files,
        explicit,
        unreadable_dirs,
    } = inputs::select_inputs(
        std::mem::take(&mut opts.inputs),
        &opts.filelists,
        opts.recursive,
        opts.follow_links,
        opts.verbosity,
    )?;
    let skipped = if opts.ignore_read_errors {
        0
    } else {
        unreadable_dirs
    };
    // Listing, training and benchmarking take named files only and refuse
    // stdin with their own reasons; the streaming modes read it.
    let streams =
        matches!(opts.mode, Mode::Compress | Mode::Decompress | Mode::Test) && !opts.bench;
    if files.is_empty() && explicit && streams {
        // Pointed at empty directories or an empty list: nothing to do, and not
        // a request to read stdin. The reference command says so for empty
        // directories and exits 0; for an empty list it reads stdin, which
        // would compress data the caller never pointed it at. The file-only
        // modes go on to their own refusal of an empty input list instead, as
        // the reference command's training and listing do, rather than report
        // a dictionary or a measurement that was never made.
        display!(
            opts.verbosity,
            1,
            "please provide correct input file(s) or non-empty directories -- ignored"
        );
        return Ok(skipped);
    }
    // A benchmark with no input named measures generated data. Inputs that were
    // named and came to nothing are a different request: measuring lorem ipsum
    // in their place would report a result for files never read.
    if files.is_empty() && explicit && opts.bench {
        bail!("-b requires one or more regular input files to benchmark");
    }
    opts.inputs = files;
    // The count is exact: at most one per directory walked, each its own input.
    Ok(run_selected(opts)? + skipped)
}

/// The run over the inputs [`run`] selected. The count of inputs that failed
/// comes back, as from [`run`].
fn run_selected(mut opts: Options) -> Result<usize> {
    let streams =
        matches!(opts.mode, Mode::Compress | Mode::Decompress | Mode::Test) && !opts.bench;
    // The streaming modes refuse to read stdin from a terminal unless forced,
    // as the reference command does.
    if streams && reads_stdin(&opts.inputs) && !opts.force_stdin && opts.console.stdin() {
        bail!("stdin is a console, aborting");
    }
    refuse_console_stdout(&opts, opts.console.stdout())?;
    let has_stdout_output = matches!(opts.mode, Mode::Compress | Mode::Decompress)
        && !opts.bench
        && writes_stdout(&opts);
    // No status message by default when the data goes to stdout.
    if has_stdout_output && opts.verbosity == DEFAULT_LEVEL {
        opts.verbosity = 1;
    }
    // When stderr is not a terminal, do not pollute it with progress updates
    // unless asked.
    if !opts.console.stderr() && opts.progress != Progress::Always {
        opts.progress = Progress::Never;
    }
    if has_stdout_output && opts.remove_source {
        display!(
            opts.verbosity,
            3,
            "Note: src files are not removed when output is stdout"
        );
        opts.remove_source = false;
    }
    if opts.mode == Mode::Test {
        opts.remove_source = false;
    }
    // A benchmark of generated data measures it alone, as the reference's does
    // (`BMK_syntheticTest` passes no dictionary and no patch reference), so a
    // `-D` or `--patch-from` there is not read: through either the same
    // command line would measure another codec path, and the patch setup below
    // would resize a window for a patch nobody is making.
    if opts.bench && opts.inputs.is_empty() {
        opts.dict = None;
        opts.patch_from = None;
    }
    if opts.patch_from.is_some() {
        // A patch is one input against one reference: the reference command
        // refuses several, and stdin only with a declared length, since the
        // window is sized from it.
        if opts.inputs.len() > 1 {
            bail!("error : can't use --patch-from=# on multiple files");
        }
        if compresses(&opts) {
            // Sized as the frame will be: a named file at its own size, which
            // it is compressed at whatever `--stream-size` says, and stdin at
            // the declared one. Upstream zstd lets `--stream-size` win for a
            // file too (fileio.c, `FIO_createCResources`), refusing a patch it
            // could make or leaving the reference out of reach.
            let source_size = match (opts.inputs.first(), opts.pledged_size) {
                (Some(input), _) if input != Path::new("-") => fs::metadata(input)
                    .map_err(|err| eyre!("can't stat {} : {err}", input.display()))?
                    .len(),
                (_, Some(size)) => size,
                _ => bail!("Using --patch-from with stdin requires --stream-size"),
            };
            opts.advanced.window_log = Some(patch_window_log(source_size)?);
            let reference = opts.patch_from.as_deref().expect("set in this branch");
            let reference_size = fs::metadata(reference)
                .map_err(|err| eyre!("can't stat {} : {err}", reference.display()))?
                .len();
            if patch_run_needs_long_distance(&opts, source_size, reference_size) {
                if !opts.long {
                    display!(opts.verbosity, 2, "long mode automatically triggered");
                }
                opts.long = true;
            }
        }
    }

    let dict_bytes = load_dictionary(&opts)?;
    opts.decode_window = decode_window_ceiling(&opts);

    // `-b` benchmarks compression/decompression across levels instead of
    // producing output files; handle it before the streaming flow. It takes the
    // blob rather than the parsed forms, since its own memory ceiling has to be
    // weighed before anything is built from them.
    if opts.bench {
        run_benchmark(&opts, dict_bytes)?;
        return Ok(0);
    }
    let mut codecs = Codecs::prepare(
        dict_bytes.as_deref(),
        opts.patch_from.is_some(),
        compresses(&opts),
        decodes(&opts),
    )?;
    codecs.open_trace(&opts, false)?;
    // Everything from here on primes from the parsed form, so the blob it was
    // parsed out of is released rather than held for the length of the run
    // beside the thing that replaced it.
    drop(dict_bytes);

    // `--train` builds a dictionary from the sample files rather than
    // (de)compressing them; handle it before the streaming flow.
    if opts.mode == Mode::Train {
        train_dictionary(&opts)?;
        return Ok(0);
    }

    // `--list` walks frame headers without decoding; it needs a seekable file
    // (not a stream), so it is handled separately from the (de)compress flow.
    if opts.mode == Mode::List {
        return list_files(&opts);
    }

    // Reached only by the streaming modes, as the reference command's check is
    // (benchmark, training and listing have left by now and ignore the flag).
    // Decompression has no parameters to show; testing is not decompression
    // there, so it is not refused, and prints nothing since it compresses
    // nothing.
    if opts.show_default_cparams {
        if opts.mode == Mode::Decompress {
            bail!("error : can't use --show-default-cparams in decompression mode");
        }
        if opts.mode == Mode::Compress {
            show_default_cparams(&opts)?;
        }
    }

    // A destination named outright belongs to the whole run, whatever it reads:
    // stdin, an explicit `-`, or files. The dictionary is what the frame being
    // written will need to be read back, so an `-o` pointing at it destroys the
    // key to the archive it is producing. Checked here rather than in the
    // per-input scan below, which sees neither stdin nor `-`.
    //
    // Compression only. Decompressing has already finished with the dictionary
    // by the time anything is written, and what it writes is plaintext that
    // never needed it: the reference command permits that, and refusing would
    // break a working script to protect nothing.
    if let (Some(output), Some(dict)) = (&opts.output, dictionary_path(&opts))
        && !opts.to_stdout
        && opts.mode == Mode::Compress
        && names_the_same_file(output, dict)?
    {
        bail!(
            "{} would be written over the dictionary {}",
            output.display(),
            dict.display(),
        );
    }
    // And no `-o` may name one of the inputs: the input would be read through
    // its open descriptor while the finished frame is renamed over it, and
    // `--rm` would then delete even that. The reference command refuses an
    // output that would overwrite its input; the per-input check in
    // `process_separately` covers derived outputs, this one the named output.
    // Compared as files, as there: another spelling or a hard link is the
    // same input. An input that is not there cannot be overwritten, and is
    // left to fail on its own when it is opened.
    if let Some(output) = &opts.output
        && !opts.to_stdout
        && opts.mode != Mode::Test
    {
        for input in &opts.inputs {
            if input != Path::new("-")
                && (names_the_same_file(output, input)?
                    || (output.exists()
                        && input.exists()
                        && paths_point_to_same_file(input, output)?))
            {
                bail!(
                    "{} would be written over {}, which is also an input",
                    output.display(),
                    input.display(),
                );
            }
        }
    }
    let total = opts.inputs.len().max(1);
    match (opts.to_stdout, &opts.output) {
        (true, _) => process_concatenated(&opts, &mut codecs, None, total),
        // `-t` writes nothing, so a destination it was given is set aside.
        (false, Some(output)) if opts.mode != Mode::Test => {
            process_concatenated(&opts, &mut codecs, Some(output), total)
        }
        _ => process_separately(&opts, &mut codecs, total),
    }
}

/// Every input into one destination: stdout, or the `-o` file.
///
/// Several inputs concatenated lose their names and boundaries, so the
/// reference command warns, disables `--rm`, and, for a file it was not
/// forced to write, asks first. An input that cannot be opened is reported
/// and skipped; one that fails while streaming ends the run, since a partial
/// frame would already be in the shared output.
fn process_concatenated(
    opts: &Options,
    codecs: &mut Codecs,
    output: Option<&Path>,
    total: usize,
) -> Result<usize> {
    let mut remove_source = opts.remove_source;
    if total > 1 {
        match output {
            None => display!(
                opts.verbosity,
                2,
                "zstd: WARNING: all input files will be processed and concatenated into stdout."
            ),
            Some(output) => display!(
                opts.verbosity,
                2,
                "zstd: WARNING: all input files will be processed and concatenated into a single output file: {}",
                output.display()
            ),
        }
        display!(
            opts.verbosity,
            2,
            "The concatenated output CANNOT regenerate original file names nor directory structure."
        );
        if remove_source {
            display!(
                opts.verbosity,
                2,
                "Since it's a destructive operation, input files will not be removed."
            );
            remove_source = false;
        }
        if output.is_some() && !opts.force {
            if opts.verbosity <= 1 {
                // Quiet mode: no prompt is possible, so the run refuses.
                display!(
                    opts.verbosity,
                    1,
                    "Concatenating multiple processed inputs into a single output loses file metadata."
                );
                display!(opts.verbosity, 1, "Aborting.");
                return Ok(total);
            }
            if !confirm(
                "Proceed? (y/n): ",
                "Aborting...",
                reads_stdin(&opts.inputs),
                &mut io::stdin().lock(),
            ) {
                return Ok(total);
            }
        }
    }
    let mut tally = Tally::default();
    let inputs: Vec<&Path> = if opts.inputs.is_empty() {
        vec![Path::new("-")]
    } else {
        opts.inputs.iter().map(PathBuf::as_path).collect()
    };
    match output {
        None => {
            // No interrupt guard on this path: there is no file of ours to
            // remove, and the reference command installs its handler only for
            // a regular-file destination (`fileio.c`, `addHandler`), so an
            // interruption here takes the default action as it does there.
            // Reached only under `-c`, which asks for stdout whatever it is, so
            // a terminal is written like any other stream.
            let mut sink = io::stdout().lock();
            for input in inputs {
                let outcome = stream_input_to(opts, codecs, input, &mut sink, STDOUT_MARK, total)?;
                tally.record(outcome);
            }
        }
        Some(output) => {
            // One input keeps the reference command's single-file path, where
            // the output takes the source's permissions; several inputs share
            // an output that takes none of theirs.
            if let [input] = inputs[..] {
                let (source, metadata) = if input == Path::new("-") {
                    (None, None)
                } else {
                    match open_input(opts, input) {
                        Ok(Some((source, metadata))) => (Some(source), Some(metadata)),
                        Ok(None) => return Ok(0),
                        Err(err) => {
                            display!(opts.verbosity, 1, "zstd: {err}");
                            return Ok(1);
                        }
                    }
                };
                let name = if source.is_some() {
                    input.display().to_string()
                } else {
                    STDIN_MARK.to_string()
                };
                let written =
                    write_output_file(opts, output, metadata.as_ref(), |sink| match source {
                        Some(source) => stream_opened(
                            opts,
                            codecs,
                            source,
                            metadata.as_ref().expect("an opened input has metadata"),
                            sink,
                        ),
                        None => stream_stdin(opts, codecs, sink),
                    })?;
                match written {
                    Some((processed, placement)) => {
                        file_summary(
                            opts,
                            total,
                            &name,
                            &output.display().to_string(),
                            &processed,
                        );
                        if remove_source && input != Path::new("-") {
                            remove_source_if_requested(opts, input, placement)?;
                        }
                        tally.record(Outcome::Done(processed));
                    }
                    None => tally.record(Outcome::Refused),
                }
            } else {
                // An existing output is replaced only by a concatenation that
                // holds something: when no input could be read, the file keeps
                // what it had rather than becoming empty, and the failures are
                // still counted.
                let written = write_output_file_if(
                    opts,
                    output,
                    None,
                    |sink| {
                        let mut tally = Tally::default();
                        for input in &inputs {
                            let outcome = stream_input_to(
                                opts,
                                codecs,
                                input,
                                &mut *sink,
                                &output.display().to_string(),
                                total,
                            )?;
                            tally.record(outcome);
                        }
                        Ok(tally)
                    },
                    |tally| tally.processed > 0,
                )?;
                // A concatenation removes no source, wherever it went.
                match written {
                    Some((inner, _)) => tally = inner,
                    None => tally.failed = total,
                }
            }
        }
    }
    multi_summary(opts, total, &tally);
    Ok(tally.failed)
}

/// Every input into its own output, placed beside it or under the output
/// directory; stdin, when it is among them, goes to stdout. An input that
/// fails is reported and the rest are still processed, as the reference
/// command does; the count that failed decides the exit status.
fn process_separately(opts: &Options, codecs: &mut Codecs, total: usize) -> Result<usize> {
    // The inputs are processed one after another, so an output derived from an
    // early one can land on a file still waiting its turn: `-f foo foo.zst`
    // would replace `foo.zst` before it is ever read. The `-D` dictionary is a
    // file this run needs too, and the one a frame will need to be read back,
    // so writing over it destroys the key to what was just produced. `-f`
    // permits overwriting the output, not destroying either, so everything the
    // run reads is checked before the first byte is written.
    //
    // Only for the modes that write one. Testing decodes into a sink and names
    // no destination, so asking what it would produce has no answer. An input
    // whose output cannot be derived is left for the loop below to report.
    if matches!(opts.mode, Mode::Compress | Mode::Decompress) {
        for input in &opts.inputs {
            if input == Path::new("-") {
                continue;
            }
            let Ok(output) = derive_output_path(opts, input) else {
                continue;
            };
            // Compared as files rather than as spellings: `foo.zst`,
            // `./foo.zst` and `dir/../dir/foo.zst` name one file, and a match
            // on the string alone would miss two of the three. Compression
            // only, for the reason given at the `-o` check in `run`.
            if let Some(dict) = dictionary_path(opts)
                && opts.mode == Mode::Compress
                && names_the_same_file(&output, dict)?
            {
                bail!(
                    "{} would be written over the dictionary {}",
                    input.display(),
                    dict.display(),
                );
            }
            // `--rm` deletes an input once its output is written, and an input
            // that is itself the dictionary is the one file that output cannot
            // be read back without: `--rm -D data data` would leave an archive
            // nothing can open. Removing the source is a convenience, so it
            // yields to the file that gives the result meaning. Both files are
            // there to be compared, so identity is asked of the filesystem as
            // well: a hard link is a second name for one file, and no amount of
            // resolving either name tells them apart.
            if let Some(dict) = dictionary_path(opts)
                && opts.remove_source
                && !opts.keep
                && (names_the_same_file(input, dict)?
                    || (dict.exists() && paths_point_to_same_file(input, dict)?))
            {
                bail!(
                    "--rm would delete {}, which is also the dictionary {} needed to read the result",
                    input.display(),
                    dict.display(),
                );
            }
            for other in &opts.inputs {
                if other != Path::new("-") && names_the_same_file(&output, other)? {
                    bail!(
                        "{} would be written over {}, which is also an input",
                        input.display(),
                        other.display(),
                    );
                }
            }
        }
    }
    let mut tally = Tally::default();
    if opts.inputs.is_empty() {
        let outcome = stream_input_to(
            opts,
            codecs,
            Path::new("-"),
            io::stdout().lock(),
            STDOUT_MARK,
            total,
        )?;
        tally.record(outcome);
    }
    for input in &opts.inputs {
        let outcome = if input == Path::new("-") {
            stream_input_to(opts, codecs, input, io::stdout().lock(), STDOUT_MARK, total)?
        } else {
            match process_file(opts, input, codecs, total) {
                Ok(outcome) => outcome,
                Err(err) => {
                    display!(opts.verbosity, 1, "zstd: {err}");
                    Outcome::Refused
                }
            }
        };
        tally.record(outcome);
    }
    for name in flat_output_collisions(opts) {
        display!(
            opts.verbosity,
            2,
            "WARNING: Two files have same filename: {}",
            Path::new(&name).display()
        );
    }
    multi_summary(opts, total, &tally);
    Ok(tally.failed)
}

/// The output names that more than one input lands on under
/// `--output-dir-flat`, where the later output replaces the earlier; the run
/// warns once per name, as the reference command does.
///
/// Judged by the derived output names rather than the inputs' own, which the
/// reference command compares: decompression drops a suffix, so `a/foo.zst`
/// and `b/foo.zstd` are two names for one `out/foo`. An input whose output
/// cannot be derived writes nothing and collides with nothing.
fn flat_output_collisions(opts: &Options) -> Vec<OsString> {
    if opts.output_dir.is_none()
        || opts.output_dir_mirror.is_some()
        || !matches!(opts.mode, Mode::Compress | Mode::Decompress)
    {
        return Vec::new();
    }
    let outputs: Vec<PathBuf> = opts
        .inputs
        .iter()
        .filter(|input| input.as_path() != Path::new("-"))
        .filter_map(|input| derive_output_path(opts, input).ok())
        .collect();
    inputs::shared_file_names(&outputs)
}

/// What became of one input.
enum Outcome {
    /// Processed, with what went in and came out.
    Done(Processed),
    /// Deliberately left alone (`--exclude-compressed`); not a failure.
    Skipped,
    /// Not processed, and already reported.
    Refused,
}

/// Bytes an input contributed: read from it, and written for it.
struct Processed {
    read: u64,
    written: u64,
}

/// The run's running totals, for the multi-file summary and the exit status.
#[derive(Default)]
struct Tally {
    processed: usize,
    failed: usize,
    read: u64,
    written: u64,
}

impl Tally {
    fn record(&mut self, outcome: Outcome) {
        match outcome {
            Outcome::Done(processed) => {
                self.processed += 1;
                self.read += processed.read;
                self.written += processed.written;
            }
            Outcome::Skipped => {}
            Outcome::Refused => self.failed += 1,
        }
    }
}

/// The per-file result line, in the reference command's layout, shown for a
/// single input or under `-v` for each of several.
fn file_summary(
    opts: &Options,
    total: usize,
    name: &str,
    destination: &str,
    processed: &Processed,
) {
    if total > 1 && opts.verbosity < 3 {
        return;
    }
    let verbose = opts.verbosity > 3;
    match opts.mode {
        Mode::Compress => {
            let read = HumanSize::new(processed.read, verbose);
            let written = HumanSize::new(processed.written, verbose);
            if processed.read == 0 {
                display!(
                    opts.verbosity,
                    2,
                    "{name:<20} :  ({read:>6} => {written:>6}, {destination})"
                );
            } else {
                display!(
                    opts.verbosity,
                    2,
                    "{name:<20} :{:>6.2}%   ({read:>6} => {written:>6}, {destination})",
                    processed.written as f64 / processed.read as f64 * 100.0
                );
            }
        }
        Mode::Decompress | Mode::Test => {
            display!(opts.verbosity, 2, "{name:<20}: {} bytes", processed.written);
        }
        Mode::List | Mode::Train => {}
    }
}

/// The closing line of a run over several inputs, when at least one went
/// through.
fn multi_summary(opts: &Options, total: usize, tally: &Tally) {
    if tally.processed < 1 || total <= 1 {
        return;
    }
    let verbose = opts.verbosity > 3;
    match opts.mode {
        Mode::Compress => {
            let read = HumanSize::new(tally.read, verbose);
            let written = HumanSize::new(tally.written, verbose);
            if tally.read == 0 {
                display!(
                    opts.verbosity,
                    2,
                    "{:>3} files compressed : ({} => {})",
                    tally.processed,
                    read.columns(6),
                    written.columns(6)
                );
            } else {
                display!(
                    opts.verbosity,
                    2,
                    "{:>3} files compressed : {:.2}% ({} => {})",
                    tally.processed,
                    tally.written as f64 / tally.read as f64 * 100.0,
                    read.columns(6),
                    written.columns(6)
                );
            }
        }
        Mode::Decompress | Mode::Test => {
            display!(
                opts.verbosity,
                2,
                "{} files decompressed : {:>6} bytes total",
                tally.processed,
                tally.written
            );
        }
        Mode::List | Mode::Train => {}
    }
}

/// `-b`: benchmark compression + decompression of the inputs, or of generated
/// data when none is named, across the requested level range, reporting ratio
/// and best-of throughput. A simplified `zstd -b#` (per-level row); honours
/// `-D` so dictionary throughput can be measured. Time-budgeted per level
/// rather than fixed-iteration.
fn run_benchmark(opts: &Options, dict: Option<Vec<u8>>) -> Result<()> {
    // With no input named the reference measures data it generates
    // (`BMK_syntheticTest`): `-B` bytes of it, ten million by default.
    let synthetic = opts.inputs.is_empty();
    // `-` is stdin everywhere else in this tool, and a benchmark cannot measure
    // it: the whole input is held and read again per pass, which a stream
    // affords neither. Answered before the stat below, or the marker would name
    // a file whenever one happens to sit in the working directory under that
    // name — and stdin whenever one does not. A file really called `-` is still
    // reachable, spelled `./-`.
    if opts.inputs.iter().any(|input| input == Path::new("-")) {
        bail!("-b cannot benchmark stdin; name a file (`./-` for one called `-`)");
    }
    // Benchmarking is the one path that holds whole files, so it needs inputs
    // with an end and a length that means something. A FIFO would block on the
    // read that never returns, a character device would grow the buffer until
    // the allocator gave up, and neither reports a size the ceiling below could
    // be weighed against. Settled before any of them is opened.
    let mut sum = 0u64;
    let mut largest = 0u64;
    // Kept, not just summed: these are the lengths the ceiling below is weighed
    // against, and the read is bounded by the same ones — so what was approved
    // and what is taken cannot be two different figures.
    let mut sizes = Vec::with_capacity(opts.inputs.len().max(1));
    if synthetic {
        let size = opts.block_size.unwrap_or(synthetic::DEFAULT_SIZE as u64);
        sum = size;
        largest = size;
        sizes.push(size);
    }
    for input in &opts.inputs {
        let metadata = fs::metadata(input)
            .wrap_err_with(|| format!("failed to inspect {}", input.display()))?;
        if !metadata.is_file() {
            bail!("-b needs regular files: {} is not one", input.display());
        }
        sum = sum
            .checked_add(metadata.len())
            .ok_or_else(|| eyre!("the inputs add up to more than any machine can address"))?;
        largest = largest.max(metadata.len());
        sizes.push(metadata.len());
    }

    // Those whole-file buffers dwarf the decoder's own workspace, so a ceiling
    // that ignored them would be kept in the small and broken in the large.
    // What they add up to is kept: the decoder's window gets only what the
    // limit leaves past them (see `bench_decode_settings`).
    let mut held = None;
    if let Some(limit) = opts.memory_limit {
        // With `-S` only one input is in memory at a time, so the largest file
        // is what has to fit rather than their sum.
        let subject: &[u64] = if opts.bench_separately {
            let at = sizes
                .iter()
                .position(|&size| size == largest)
                .expect("the largest size is one of the sizes");
            &sizes[at..=at]
        } else {
            &sizes
        };
        let inputs = if opts.bench_separately { largest } else { sum };
        // Three buffers exist at once: the input, the frames it compresses to,
        // and the decoded copy. Each is allocated at the size named here and
        // never grows past it, so this is what the run actually holds rather
        // than a lower bound on it. The frames' is `compress_bound` of each,
        // which is the input plus the framing an incompressible input still
        // pays — the case a ceiling has to survive. The encoder is sized by the
        // frame it builds, so the widest frame is the source it is weighed
        // against.
        let extent = bench_frames_extent(subject, opts.block_size);
        let frame = extent.map(|(room, _)| room);
        let widest_chunk = extent.map_or(0, |(_, widest)| widest);
        // Beside them stands the match finder every compression pass builds,
        // whose tables are the largest thing at the higher levels — hundreds of
        // MiB where the buffers are tens. It is sized by the level, by the
        // source (both cap the window and the tables) and by what the run has
        // asked for on top: `--long` widens the window and adds a matcher with
        // a table of its own, and every `--zstd=` knob resizes a table or moves
        // the level to another backend, none of it in the level's own figures.
        // So it is asked for the levels this run will measure, the input it
        // will measure them on, and the very parameters `compress_stream` will
        // set for each. One level runs at a time and its encoder is dropped
        // before the next, so the largest of them is what stands at the peak.
        //
        // The dictionary is one of those parameters, and the one that moves the
        // figure most: past the size at which it stops being searched in place,
        // the frame runs the dictionary's own table geometry rather than the
        // source's, so 64 KiB measured against a 256 KiB dictionary asks for
        // three times what the file alone does, and a large dictionary at the
        // top levels asks for hundreds of MiB more. Weighed here from the
        // blob's own length, which is what the parameters are chosen by; the
        // content of a trained dictionary is smaller than the blob it arrived
        // in, and overstating it can only pick the larger of the two geometries.
        let dictionary = dict
            .as_ref()
            .map(|bytes| structured_zstd::encoding::DictionarySizes::raw_content(bytes.len()));
        let mut encoder = 0u64;
        for level in opts.bench_start..=opts.bench_end {
            let settings = FrameSettings {
                level,
                ..FrameSettings::from_options(opts)
            };
            let compression_level = CompressionLevel::from_level(level);
            let bytes = match frame_parameters(compression_level, &settings)? {
                Some(parameters) => {
                    structured_zstd::encoding::estimated_compression_workspace_bytes_for_parameters(
                        &parameters,
                        Some(widest_chunk),
                        dictionary,
                    )
                }
                None => structured_zstd::encoding::estimated_compression_workspace_bytes_for_run(
                    compression_level,
                    Some(widest_chunk),
                    None,
                    false,
                    dictionary,
                ),
            };
            encoder = encoder.max(bytes as u64);
        }
        let buffers = frame
            .and_then(|frame| {
                inputs
                    .checked_mul(2)?
                    .checked_add(frame)?
                    .checked_add(encoder)
            })
            .ok_or_else(|| eyre!("the inputs add up to more than any machine can address"))?;
        check_memory_limit(limit, buffers, 1)?;
        // The dictionary is held alongside them, and more than once: a
        // benchmark measures both directions, so the blob is parsed into an
        // encoder's tables and a decoder's, and the blob itself is still there
        // while they are built from it. All of it is counted with the buffers
        // rather than on its own, since allocations that each clear the ceiling
        // separately can still exceed it together.
        let mut total = buffers;
        if let Some(bytes) = &dict {
            total = (bytes.len() as u64)
                .checked_mul(3)
                .and_then(|dictionaries| buffers.checked_add(dictionaries))
                .ok_or_else(|| eyre!("the inputs add up to more than any machine can address"))?;
            check_memory_limit(limit, total, 1)?;
        }
        held = Some(total);
    }
    let decode = bench_decode_settings(opts, held);

    // Both directions are measured in turn, so both forms are wanted — parsed
    // here, once, rather than inside the timed loops below. The blob is then
    // done with: it is released before the measuring starts rather than held
    // beside the two forms parsed out of it for the rest of the run.
    let codecs = &mut Codecs::prepare(dict.as_deref(), opts.patch_from.is_some(), true, true)?;
    // The reference benchmarks whole buffers in one call each way, which its
    // trace reports as single-pass.
    codecs.open_trace(opts, true)?;
    drop(dict);

    if synthetic {
        // `-B` is read as a `u32` and `--block-size` capped at `usize`, and the
        // default is ten million, so the size always addresses.
        let size = usize::try_from(sizes[0]).expect("a benchmark block size fits usize");
        let (label, data) = match opts.bench_compressibility {
            Some(percent) => (
                format!("Synthetic {percent}%"),
                synthetic::compressible(size, percent),
            ),
            None => ("Lorem ipsum".to_string(), synthetic::lorem(size)),
        };
        let data = data.map_err(|err| {
            eyre!("-b: not enough memory for {size} bytes of generated data: {err}")
        })?;
        return benchmark_one(opts, codecs, &decode, &label, &data, &sizes);
    }

    if opts.bench_separately {
        for (input, size) in opts.inputs.iter().zip(&sizes) {
            let data =
                read_inputs_bounded(std::slice::from_ref(input), std::slice::from_ref(size))?;
            benchmark_one(
                opts,
                codecs,
                &decode,
                &input.display().to_string(),
                &data,
                std::slice::from_ref(size),
            )?;
        }
        return Ok(());
    }

    let data = read_inputs_bounded(&opts.inputs, &sizes)?;
    // Several inputs are one measurement, named by their count as the
    // reference command names it.
    let label = match opts.inputs.as_slice() {
        [only] => only.display().to_string(),
        many => format!(" {} files", many.len()),
    };
    benchmark_one(opts, codecs, &decode, &label, &data, &sizes)
}

/// The settings a benchmark decodes with. `held` is what the benchmark holds
/// while it decodes (input, frames, decoded copy, encoder, dictionaries), as
/// weighed against `-M`; the window may have only what the promise leaves after
/// it and the decoder's other buffers. The limit was checked to leave at least
/// the default window, which stays the floor.
fn bench_decode_settings(opts: &Options, held: Option<u64>) -> DecodeSettings {
    use structured_zstd::decoding::{MAX_DECODER_WINDOW_SIZE, MAXIMUM_ALLOWED_WINDOW_SIZE};

    let settings = DecodeSettings::from_options(opts);
    let (Some(limit), Some(held)) = (opts.memory_limit, held) else {
        return settings;
    };
    let overhead = held.checked_add(DECODER_AUXILIARY_BYTES);
    DecodeSettings {
        max_window: overhead
            .and_then(|overhead| limit.checked_sub(overhead))
            .unwrap_or(0)
            .clamp(MAXIMUM_ALLOWED_WINDOW_SIZE, MAX_DECODER_WINDOW_SIZE),
        memory_overhead: overhead,
        ..settings
    }
}

/// Read every input into one buffer, taking no more room — and no more bytes —
/// than the `sizes` it was weighed against.
///
/// The `-M` ceiling counts three copies of this buffer, so it has to be the size
/// it was counted at: appending file by file leaves a `Vec` holding up to twice
/// the bytes it needs, and reading each file into its own buffer first holds the
/// largest one twice over. The room is taken once, from those same sizes, and
/// each file is read straight into it and no further than its own — a file that
/// grew since is an error rather than a buffer past what was approved.
///
/// `sizes` are the lengths the ceiling saw, in the order of `inputs`; passing
/// the pair keeps the figure that was checked and the figure that is read the
/// same one.
fn read_inputs_bounded(inputs: &[PathBuf], sizes: &[u64]) -> Result<Vec<u8>> {
    let mut total = 0usize;
    for size in sizes {
        total = usize::try_from(*size)
            .ok()
            .and_then(|size| total.checked_add(size))
            .ok_or_else(|| eyre!("the inputs add up to more than this machine can hold"))?;
    }
    let mut data = Vec::with_capacity(total);
    for (input, size) in inputs.iter().zip(sizes) {
        let file = File::open(input)
            .wrap_err_with(|| format!("failed to open input file {}", input.display()))?;
        let before = data.len();
        // One byte past the size that was weighed: reading it means the file
        // holds more than the ceiling was told, so the buffer would grow past
        // what a caller approved. A length that underreports its content — a
        // file being written, or one whose directory entry is not a byte count
        // at all — stops here rather than filling memory nobody agreed to.
        file.take(size + 1)
            .read_to_end(&mut data)
            .wrap_err_with(|| format!("failed to read {}", input.display()))?;
        // Short is refused as well as long: the frames are cut at the sizes
        // recorded before the read, so a file that shrank would be cut past
        // the end of what was read.
        if (data.len() - before) as u64 != *size {
            bail!(
                "{} changed size while it was being read; run again",
                input.display()
            );
        }
    }
    Ok(data)
}

/// The lengths of the independent frames a benchmark compresses its inputs as,
/// in order: every input a frame of its own, cut into `block_size` pieces when
/// one of at least [`MIN_BENCH_BLOCK_SIZE`] is given. An empty input yields no
/// frame. This is the reference's block table (`benchzstd.c`,
/// `BMK_benchMemAdvancedNoAlloc`), so ratio and speed describe the same frames.
///
/// Yielded, not listed: with a small `-B` over a large input a list would hold
/// a word per frame that the `-M` ceiling never counted.
fn bench_chunk_lengths(
    file_sizes: &[u64],
    block_size: Option<u64>,
) -> impl Iterator<Item = u64> + '_ {
    let block = block_size.filter(|&size| size >= MIN_BENCH_BLOCK_SIZE);
    file_sizes.iter().flat_map(move |&size| {
        let piece = block.unwrap_or(size.max(1));
        (0..size.div_ceil(piece)).map(move |at| piece.min(size - at * piece))
    })
}

/// The frames [`bench_chunk_lengths`] cuts `file_sizes` into, measured without
/// listing them: the room they take at most (`compress_bound` of each) and the
/// widest of them. Worked out per file from its whole blocks and its tail, so a
/// small `-B` over a large input costs nothing before `-M` has weighed it.
/// `None` when the room is more than this machine can address.
fn bench_frames_extent(file_sizes: &[u64], block_size: Option<u64>) -> Option<(u64, u64)> {
    let block = block_size.filter(|&size| size >= MIN_BENCH_BLOCK_SIZE);
    let bound = |len: u64| -> Option<u64> {
        u64::try_from(structured_zstd::encoding::compress_bound(
            usize::try_from(len).ok()?,
        ))
        .ok()
    };
    let mut room = 0u64;
    let mut widest = 0u64;
    for &size in file_sizes {
        if size == 0 {
            continue;
        }
        let piece = block.unwrap_or(size);
        let whole = size / piece;
        let tail = size % piece;
        room = room.checked_add(whole.checked_mul(bound(piece)?)?)?;
        if tail > 0 {
            room = room.checked_add(bound(tail)?)?;
        }
        widest = widest.max(size.min(piece));
    }
    Some((room, widest))
}

/// Measure one benchmark subject: every input together, or a single file under
/// `-S`. Split out so the two modes differ only in what they hand over, not in
/// how the measurement is taken. `file_sizes` are the lengths of the inputs
/// `data` holds, in order; each is compressed as frames of its own. `decode`
/// is what the frames are decoded with (see [`bench_decode_settings`]).
fn benchmark_one(
    opts: &Options,
    codecs: &mut Codecs,
    decode: &DecodeSettings,
    label: &str,
    data: &[u8],
    file_sizes: &[u64],
) -> Result<()> {
    use std::time::Instant;

    if data.is_empty() {
        bail!("-b: {label} is empty");
    }
    // Per-level time budget; best (fastest) pass wins, like upstream's -i loop.
    let mb = data.len() as f64 / 1e6;
    let name = bench_display_name(label);
    display!(
        opts.verbosity,
        3,
        "Benchmarking {label} from level {} to {}",
        opts.bench_start,
        opts.bench_end
    );
    if let Some(header) = bench_quiet_header(opts, data.len()) {
        println!("{header}");
    }

    debug_assert_eq!(
        bench_chunk_lengths(file_sizes, opts.block_size).sum::<u64>(),
        data.len() as u64,
        "the frames cover the input exactly"
    );
    // The two buffers the measurement fills, sized once from what they will
    // hold: the frames can be no larger than `compress_bound` of each says,
    // and the decoded copy is exactly the input again. That keeps them the size
    // the `-M` ceiling counted them at instead of the doubled capacity a
    // growing `Vec` ends up with — and it keeps the growth out of the timed
    // sections, which would otherwise be reported as compression and
    // decompression speed.
    let frames_bound = bench_frames_extent(file_sizes, opts.block_size)
        .and_then(|(room, _)| usize::try_from(room).ok())
        .ok_or_else(|| eyre!("-b: {label} is more than this machine can hold compressed"))?;
    // Taken fallibly: their sizes follow the input and `-B`, so a machine that
    // cannot hold them is answered with an error rather than an abort.
    let mut compressed = Vec::new();
    compressed
        .try_reserve_exact(frames_bound)
        .map_err(|err| eyre!("-b: not enough memory for the frames of {label}: {err}"))?;
    let mut decoded = Vec::new();
    decoded
        .try_reserve_exact(data.len())
        .map_err(|err| eyre!("-b: not enough memory to decode {label}: {err}"))?;
    // Raised for the measurement alone: the subject is read or generated and
    // the buffers taken by now, and the guard puts the priority back when this
    // subject is done, before a `-S` run reads the next one. The reference
    // raises at the same point (`BMK_benchCLevels`) and ignores a refusal too.
    let _realtime = if opts.bench_realtime {
        display!(opts.verbosity, 2, "Note : switching to real-time priority ");
        let raised = priority::raise_to_realtime();
        if raised.is_none() {
            display!(
                opts.verbosity,
                3,
                "Note : real-time priority was refused; measuring at the ordinary priority"
            );
        }
        raised
    } else {
        None
    };
    for level in opts.bench_start..=opts.bench_end {
        validate_level(level)?;
        let settings = FrameSettings {
            level,
            size_hint: None,
            // The reference's benchmark compresses with the library's frame
            // defaults (`BMK_initCCtx` sets no checksum), not the command's, so
            // its sizes and decoding speeds carry no content checksum.
            checksum: false,
            ..FrameSettings::from_options(opts)
        };
        let mut best_compress = f64::MAX;
        let start = Instant::now();
        loop {
            compressed.clear();
            let t = Instant::now();
            let mut rest = data;
            for chunk in bench_chunk_lengths(file_sizes, opts.block_size) {
                // Each piece is a frame of its own, as the reference's
                // benchmark compresses every block independently. The length is
                // exact, so it is pledged rather than estimated.
                let (piece, tail) = rest.split_at(chunk as usize);
                rest = tail;
                compress_stream(
                    piece,
                    &mut compressed,
                    &FrameSettings {
                        pledged_size: Some(chunk),
                        ..settings
                    },
                    codecs,
                )?;
            }
            best_compress = best_compress.min(t.elapsed().as_secs_f64());
            if start.elapsed().as_secs_f64() >= opts.bench_secs {
                break;
            }
        }

        let mut best_decompress = f64::MAX;
        let start = Instant::now();
        loop {
            decoded.clear();
            let t = Instant::now();
            decompress_stream(compressed.as_slice(), &mut decoded, codecs, decode)?;
            best_decompress = best_decompress.min(t.elapsed().as_secs_f64());
            if start.elapsed().as_secs_f64() >= opts.bench_secs {
                break;
            }
        }
        // A speed measured on output that is not the input measures nothing;
        // the reference's benchmark checks the round trip the same way.
        if decoded != data {
            bail!("-b: level {level} did not decode {label} back to its input");
        }

        let c_speed = if best_compress > 0.0 {
            mb / best_compress
        } else {
            f64::INFINITY
        };
        let d_speed = if best_decompress > 0.0 {
            mb / best_decompress
        } else {
            f64::INFINITY
        };
        let result = BenchResult {
            level,
            input: data.len() as u64,
            output: compressed.len() as u64,
            compress_mb_s: c_speed,
            decompress_mb_s: d_speed,
        };
        if opts.verbosity >= DEFAULT_LEVEL {
            println!("{}", result.line(&name));
        } else if opts.verbosity == 1 {
            println!("{}", result.quiet_line(&name, opts.bench_param));
        }
    }
    Ok(())
}

/// The reference command's machine-readable header for scripts that drive
/// `-b -q`, the block size printed as asked for. A `-p#` sweep gets none: its
/// output is the tagged result rows alone (`benchzstd.c:955`).
fn bench_quiet_header(opts: &Options, input_len: usize) -> Option<String> {
    (opts.verbosity == 1 && opts.bench_param.is_none_or(|param| param == 0)).then(|| {
        format!(
            "bench {UPSTREAM_VERSION} : input {input_len} bytes, {} seconds, {} KB blocks",
            opts.bench_secs as u64,
            opts.block_size.unwrap_or(0) >> 10
        )
    })
}

/// What one level of a benchmark measured.
struct BenchResult {
    level: i32,
    input: u64,
    output: u64,
    compress_mb_s: f64,
    decompress_mb_s: f64,
}

impl BenchResult {
    /// Compression ratio, as the reference command computes it.
    fn ratio(&self) -> f64 {
        self.input as f64 / self.output as f64
    }

    /// The reference command's result line at the default display level:
    /// `%2i#%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s`, the ratio
    /// shown to three significant figures and the compression speed to two
    /// decimals below 10 MB/s.
    fn line(&self, name: &str) -> String {
        let ratio = self.ratio();
        let ratio_digits = 1 + usize::from(ratio < 100.0) + usize::from(ratio < 10.0);
        let speed_digits = if self.compress_mb_s < 10.0 { 2 } else { 1 };
        format!(
            "{:>2}#{:<17}:{:>10} ->{:>10} (x{:>5.ratio_digits$}), {:>6.speed_digits$} MB/s, {:>6.1} MB/s",
            self.level,
            name,
            self.input,
            self.output,
            ratio,
            self.compress_mb_s,
            self.decompress_mb_s,
        )
    }

    /// The reference command's line under `-q`, which its own speed scripts
    /// parse: `-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s`, followed by
    /// ` (param=%d)` when `-p#` set one.
    fn quiet_line(&self, name: &str, param: Option<u32>) -> String {
        let mut line = format!(
            "-{:<3}{:>11} ({:>5.3}) {:>6.2} MB/s {:>6.1} MB/s  {}",
            self.level,
            self.output,
            self.ratio(),
            self.compress_mb_s,
            self.decompress_mb_s,
            name,
        );
        if let Some(param) = param.filter(|&param| param != 0) {
            line.push_str(&format!(" (param={param})"));
        }
        line
    }
}

/// The name a benchmark line carries: the file's own name, cut to its last
/// 17 characters as the reference command cuts it.
fn bench_display_name(label: &str) -> String {
    let name = Path::new(label)
        .file_name()
        .map_or(label, |name| name.to_str().unwrap_or(label));
    let chars = name.chars().count();
    if chars > 17 {
        name.chars().skip(chars - 17).collect()
    } else {
        name.to_string()
    }
}

/// `--train`: build a dictionary from the sample files with the selected
/// trainer (FastCOVER, COVER or legacy) and write it to `-o` (default
/// `dictionary`). Mirrors upstream `zstd --train FILEs -o dict --maxdict=N
/// [--dictID=N]`.
fn train_dictionary(opts: &Options) -> Result<()> {
    use structured_zstd::dictionary::{
        FinalizeOptions, create_legacy_dict_from_slice, optimize_cover_dict,
        optimize_fastcover_dict, train_cover_dict, train_fastcover_dict,
    };

    if opts.inputs.iter().any(|input| input == Path::new("-")) {
        // The third mode that takes named inputs, and `-` is stdin in all of
        // them: training reads every sample whole and rewinds nothing, so a
        // stream is no more usable here than for `-b` or `-l`. Answered before
        // the stat below, or the marker would name a file whenever one happens
        // to sit in the working directory under that name.
        bail!("--train cannot read stdin; name the sample files (`./-` for one called `-`)");
    }
    if opts.inputs.is_empty() {
        bail!("--train requires one or more sample files");
    }
    // `-c` and `-o` clear one another, so this pair leaves no destination and
    // the default below would stand in: the run would write a file nobody
    // named, and with `-f` over whatever was already there. The reference
    // command fails on the combination as well, so refuse it rather than
    // choose a destination on the caller's behalf.
    if opts.to_stdout {
        bail!("--train cannot write to stdout; name the dictionary with -o");
    }
    // Every trainer refuses a size below its minimum, and finding out inside
    // the trainer means every sample has been read and concatenated first. The
    // real bound is higher and depends on the entropy tables the corpus
    // produces, which is why the trainer still checks; this only settles the
    // part that is knowable without reading anything.
    if opts.max_dict < structured_zstd::dictionary::MIN_TRAINED_DICT_SIZE {
        bail!(
            "--maxdict must be at least {} bytes",
            structured_zstd::dictionary::MIN_TRAINED_DICT_SIZE
        );
    }
    // Whether the trainer takes the tuning it was given is a question about the
    // command line alone, so it is answered before any sample is touched: a run
    // bound to be refused does not first read a corpus that may be large.
    enum Plan {
        FastCover(structured_zstd::dictionary::FastCoverOptions),
        Cover(structured_zstd::dictionary::CoverOptions),
        Legacy,
    }
    let plan = match opts.trainer {
        Trainer::FastCover => Plan::FastCover(fastcover_options(&opts.trainer_params)?),
        Trainer::Cover => Plan::Cover(cover_options(&opts.trainer_params)?),
        // The legacy trainer is tuned by selectivity alone; a cover tuning list
        // given before `--train-legacy` names a trainer that no longer runs,
        // as it does in the reference.
        Trainer::Legacy => Plan::Legacy,
    };
    // Whether any segment the tuning allows fits the dictionary is the
    // codec's rule, and it needs no sample either.
    let tuning_fits = match &plan {
        Plan::FastCover(options) => {
            structured_zstd::dictionary::check_fastcover_options(options, opts.max_dict)
        }
        Plan::Cover(options) => {
            structured_zstd::dictionary::check_cover_options(options, opts.max_dict)
        }
        Plan::Legacy => Ok(()),
    };
    tuning_fits.map_err(|err| eyre!("dictionary training failed: {err}"))?;
    let output = training_output(opts);
    // Settled before the corpus is read: whether this run may write at all is
    // knowable now, and a command that is going to be refused should not first
    // load every sample and spend minutes training a dictionary to throw away.
    // A device or pipe is written in place, as for any other output.
    let in_place = writes_in_place(&output)?;
    if !in_place {
        ensure_regular_output_destination(&output)?;
        if output.exists() && !opts.force {
            bail!("{} already exists; use -f to overwrite", output.display());
        }
    }
    // The default destination is a plain `dictionary`, which a sample can
    // easily be named: the run would read that file and then replace it with
    // what it learned from it. `-f` permits replacing the output, not spending
    // a sample to make one. Compared as files rather than as paths, because
    // `dictionary` and `sub/../dictionary` are one file and only the second
    // spelling has to appear on the command line for a path comparison to miss
    // it; a sample hard-linked to an existing output is the same collision
    // reached a third way.
    for sample in &opts.inputs {
        let clashes = names_the_same_file(sample, &output)?
            || (output.exists() && paths_point_to_same_file(sample, &output)?);
        if clashes {
            bail!(
                "{} is a training sample; the dictionary cannot be written over it",
                sample.display()
            );
        }
    }

    // Training reads every sample whole, so a sample needs an end and a size
    // that means something: a FIFO would block on a read that never returns
    // and a character device would grow the corpus until the allocator gave
    // up. Settled for all of them before the first is opened.
    for input in &opts.inputs {
        let metadata = fs::metadata(input)
            .wrap_err_with(|| format!("failed to inspect {}", input.display()))?;
        if !metadata.is_file() {
            bail!(
                "--train needs regular files: {} is not one",
                input.display()
            );
        }
    }

    // The dictionary is built for the command's level, as the reference's is
    // for its `-#` (zstdcli.c, `dictCLevel`).
    let finalize = FinalizeOptions {
        dict_id: opts.dict_id,
        level: opts.level,
    };
    // Every trainer counts samples, so they are loaded as the reference's
    // command loads them: shuffled, capped per file, and cut by `-B`. The same
    // files then yield the same corpus. `-M` caps what is loaded, as the
    // reference's command passes its memory limit to `DiB_trainFromFiles`
    // (zstdcli.c), which keeps whole samples up to it (dibio.c).
    let failed = |err: std::io::Error| eyre!("dictionary training failed: {err}");
    // How many samples the trainer builds from after its split is known from
    // the files' sizes, so a count it must refuse is refused before loading.
    let enough_samples = |count: usize| match &plan {
        Plan::FastCover(options) => {
            structured_zstd::dictionary::check_fastcover_sample_count(options, count)
        }
        Plan::Cover(options) => {
            structured_zstd::dictionary::check_cover_sample_count(options, count)
        }
        Plan::Legacy => Ok(()),
    };
    let set = load_training_samples(&opts.inputs, opts.block_size, opts.memory_limit, |count| {
        enough_samples(count).map_err(failed)
    })?;
    let dict = match plan {
        Plan::Legacy => {
            let mut dict = Vec::new();
            create_legacy_dict_from_slice(
                &set.corpus,
                &set.sizes,
                &mut dict,
                opts.max_dict,
                opts.selectivity,
                finalize,
            )
            .map_err(failed)?;
            dict
        }
        // Both `k` and `d` fix the segment, and anything less asks for the
        // search, as the reference's command decides (zstdcli.c, `optimize`).
        Plan::Cover(options) if options.k != 0 && options.d != 0 => {
            train_cover_dict(&set.corpus, &set.sizes, opts.max_dict, &options, finalize)
                .map_err(failed)?
        }
        Plan::Cover(options) => {
            let (dict, chosen) =
                optimize_cover_dict(&set.corpus, &set.sizes, opts.max_dict, &options, finalize)
                    .map_err(failed)?;
            display!(
                opts.verbosity,
                2,
                "k={}\nd={}\nsteps={}\nsplit={}",
                chosen.k,
                chosen.d,
                chosen.steps,
                split_percent(chosen.split_point)
            );
            dict
        }
        Plan::FastCover(options) if options.cover.k != 0 && options.cover.d != 0 => {
            train_fastcover_dict(&set.corpus, &set.sizes, opts.max_dict, &options, finalize)
                .map_err(failed)?
        }
        Plan::FastCover(options) => {
            let (dict, chosen) =
                optimize_fastcover_dict(&set.corpus, &set.sizes, opts.max_dict, &options, finalize)
                    .map_err(failed)?;
            display!(
                opts.verbosity,
                2,
                "k={}\nd={}\nf={}\nsteps={}\nsplit={}\naccel={}",
                chosen.cover.k,
                chosen.cover.d,
                chosen.f,
                chosen.cover.steps,
                split_percent(chosen.cover.split_point),
                chosen.accel
            );
            dict
        }
    };
    let sources = set.sources;

    // A trained dictionary is an output file like any other, so it is written
    // through a temporary that is renamed into place: an interrupted run
    // leaves the previous dictionary intact rather than a half-written one.
    // The overwrite gate ran before the corpus was read. A device or pipe has
    // no previous content to keep and is written straight through.
    if in_place {
        let mut sink = open_in_place(&output)?;
        sink.write_all(&dict)
            .and_then(|()| sink.flush())
            .wrap_err_with(|| format!("failed to write dictionary {}", output.display()))?;
    } else {
        place_trained_dictionary(&output, &dict, &sources)?;
    }
    display!(
        opts.verbosity,
        2,
        "trained {} ({}) from {} sample file(s)",
        output.display(),
        HumanSize::new(dict.len() as u64, false),
        opts.inputs.len()
    );
    Ok(())
}

/// Most bytes one file contributes as a sample when `-B` does not cut it
/// (`dibio.c`, `SAMPLESIZE_MAX`).
const TRAINING_SAMPLE_MAX: u64 = 128 << 10;

/// Most training data loaded at all (`dibio.c`, `MAX_SAMPLES_SIZE`).
const TRAINING_DATA_MAX: u64 = 2 << 30;

/// Fewest samples a trainer is given (`dibio.c`: "nb of samples too low").
const TRAINING_SAMPLES_MIN: usize = 5;

/// The samples a trainer is handed, loaded the way the reference's command
/// loads them (`dibio.c`, `DiB_trainFromFiles`).
struct TrainingSet {
    /// Every sample back to back.
    corpus: Vec<u8>,
    /// The length of each sample in `corpus`.
    sizes: Vec<usize>,
    /// What each file read was, taken from the open file.
    sources: Vec<fs::Metadata>,
}

/// Reorder the sample files the way the reference does before loading
/// (`DiB_shuffle`), so a sample set too large to load keeps a spread of files
/// rather than the first ones, and the corpus is laid out as there.
///
/// The same loop step for step (dibio.c, `DiB_shuffle` and `DiB_rand`, alike in
/// 1.5.7 and later): from the last position down to 1, swap with
/// `rand % (i + 1)`, the generator seeded with `0xFD2FB528`.
fn shuffle_training_files<T>(files: &mut [T]) {
    let mut seed: u32 = 0xFD2F_B528;
    let mut next = || {
        seed = (seed.wrapping_mul(2_654_435_761) ^ 2_246_822_519).rotate_left(13);
        seed >> 5
    };
    for i in (1..files.len()).rev() {
        let j = (next() % (i as u32 + 1)) as usize;
        files.swap(i, j);
    }
}

/// How many samples `file_sizes` make as the loader would take them without a
/// limit: each file one sample, or cut into `block_size` samples; empty files
/// left out.
fn training_extent(file_sizes: &[u64], block_size: Option<u64>) -> u128 {
    // Summed exactly: sparse files report any length, and the sum of a slice of
    // `u64`s cannot outgrow `u128` (a slice holds fewer than 2^64 of them).
    let mut samples = 0u128;
    for &size in file_sizes {
        if size == 0 {
            continue;
        }
        samples += u128::from(block_size.map_or(1, |block| size.div_ceil(block)));
    }
    samples
}

/// Bytes a loaded sample's recorded length costs beside its bytes: under a
/// small `-B` the lengths outweigh the bytes they describe, a word per byte at
/// `-B1`, and a limit on the bytes alone would be exceeded by the list.
const TRAINING_SIZE_ENTRY: u64 = core::mem::size_of::<usize>() as u64;

/// How many samples the loader takes from each of `file_sizes`, in load order,
/// within `budget` bytes of samples and recorded lengths and at most `limit`
/// samples in all: a file is taken whole, cut into `block_size` pieces or
/// capped at [`TRAINING_SAMPLE_MAX`]; loading stops at the first file none of
/// which fits. Known from the sizes alone, so it is settled before a file is
/// read. Returns the pieces per file and the bytes they hold.
fn plan_training_load(
    file_sizes: &[u64],
    block_size: Option<u64>,
    budget: u64,
    limit: u128,
) -> (Vec<u64>, u64) {
    let mut plan = vec![0u64; file_sizes.len()];
    let mut bytes = 0u64;
    let mut entries = 0u64;
    'files: for (planned, &size) in plan.iter_mut().zip(file_sizes) {
        if u128::from(entries) >= limit {
            break;
        }
        let mut taken = 0u64;
        while taken < size {
            let piece = match block_size {
                Some(block) => (size - taken).min(block),
                None => size.min(TRAINING_SAMPLE_MAX),
            };
            // What is held with this sample's entry, never more than a word
            // past the budget; compared without adding `piece`, which a large
            // `-B` makes as large as the file.
            let held = bytes + (entries + 1) * TRAINING_SIZE_ENTRY;
            if held > budget || piece > budget - held {
                if taken == 0 {
                    break 'files;
                }
                break;
            }
            bytes += piece;
            entries += 1;
            taken += piece;
            *planned += 1;
            if block_size.is_none() || u128::from(entries) >= limit {
                break;
            }
        }
    }
    (plan, bytes)
}

/// Load the training samples as the reference's command does: files in its
/// shuffled order, each one sample of at most [`TRAINING_SAMPLE_MAX`] bytes, or
/// cut whole into `block_size` samples when `-B` gives one; empty files left
/// out; at most [`TRAINING_DATA_MAX`] bytes, or `memory_limit` when smaller.
/// `enough_samples` is asked, before any file is read, whether the trainer can
/// build from as many samples as the files make.
fn load_training_samples(
    inputs: &[PathBuf],
    block_size: Option<u64>,
    memory_limit: Option<u64>,
    enough_samples: impl Fn(usize) -> Result<()>,
) -> Result<TrainingSet> {
    let mut order: Vec<&PathBuf> = inputs.iter().collect();
    shuffle_training_files(&mut order);

    let mut file_sizes = Vec::with_capacity(order.len());
    for input in &order {
        file_sizes.push(
            fs::metadata(input)
                .wrap_err_with(|| format!("failed to inspect {}", input.display()))?
                .len(),
        );
    }
    let samples = training_extent(&file_sizes, block_size);
    if samples < TRAINING_SAMPLES_MIN as u128 {
        bail!(
            "{samples} training sample(s) is too few; provide one file per sample, or \
             split files into fixed-size samples with -B#"
        );
    }
    let budget = TRAINING_DATA_MAX.min(memory_limit.unwrap_or(u64::MAX));
    let (plan, bytes) = plan_training_load(&file_sizes, block_size, budget, samples);
    // What the budget keeps, not what the files hold, is what the trainer gets.
    // The five-sample floor above is on the files, as upstream's is
    // (dibio.c, `fs.nbSamples < 5`); the samples kept under the budget go to
    // the trainer's own check, and the legacy trainer, as upstream's, has
    // none.
    let retained: u64 = plan.iter().sum();
    enough_samples(usize::try_from(retained).unwrap_or(usize::MAX))?;
    // Both buffers are sized to exactly what the plan loads, which the budget
    // already bounds.
    let corpus_room = usize::try_from(bytes)
        .map_err(|_| eyre!("{bytes} bytes of samples is more than this machine can hold"))?;
    let entries = usize::try_from(retained)
        .map_err(|_| eyre!("{retained} samples is more than this machine can hold"))?;

    let mut set = TrainingSet {
        corpus: Vec::with_capacity(corpus_room),
        sizes: Vec::with_capacity(entries),
        sources: Vec::new(),
    };
    for ((input, &size), &pieces) in order.into_iter().zip(&file_sizes).zip(&plan) {
        if pieces == 0 {
            continue;
        }
        let file = File::open(input)
            .wrap_err_with(|| format!("failed to open training sample {}", input.display()))?;
        let metadata = file
            .metadata()
            .wrap_err_with(|| format!("failed to inspect {}", input.display()))?;
        // The plan was drawn from the size this file had a moment ago.
        if metadata.len() != size {
            bail!(
                "{} changed while it was being read; run again",
                input.display()
            );
        }
        let mut reader = file;
        let mut taken = 0u64;
        for _ in 0..pieces {
            let piece = match block_size {
                Some(block) => (size - taken).min(block),
                None => size.min(TRAINING_SAMPLE_MAX),
            };
            let before = set.corpus.len();
            (&mut reader)
                .take(piece)
                .read_to_end(&mut set.corpus)
                .wrap_err_with(|| format!("failed to read training sample {}", input.display()))?;
            if (set.corpus.len() - before) as u64 != piece {
                bail!(
                    "{} changed while it was being read; run again",
                    input.display()
                );
            }
            set.sizes.push(piece as usize);
            taken += piece;
        }
        set.sources.push(metadata);
    }
    Ok(set)
}

/// Write a trained dictionary to the regular file `output` through a
/// temporary renamed into place, no more readable than the strictest of the
/// `samples` (their metadata) it was trained on.
fn place_trained_dictionary(output: &Path, dict: &[u8], samples: &[fs::Metadata]) -> Result<()> {
    // Until it is in place, an interruption removes the temporary rather than
    // leaving it beside the dictionary's name, as for every other output.
    let (temp_path, mut temp_file) =
        interrupt::create_guarded(|| create_temporary_output_file(output))?;
    let placed = (|| {
        // And like any other output it is no more readable than what it was
        // made from. A dictionary carries stretches of its corpus verbatim, so
        // training on private samples and leaving the result at whatever the
        // umask allows hands those stretches to everyone; with several samples
        // the strictest decides, since the bytes of each are in there. Applied
        // to the temporary file so the dictionary is never briefly readable
        // under the old mode, and handed to the replace below so a `-f`
        // retrain over a permissive name does not restore it.
        // Asked of the temporary file, which is the one that gets renamed into
        // place: it is where the group the dictionary will belong to is decided.
        let sample_permissions = match strictest_sample_permissions(samples, &temp_path) {
            Ok(permissions) => permissions,
            Err(err) => {
                let _ = fs::remove_file(&temp_path);
                return Err(err);
            }
        };
        if let Some(permissions) = sample_permissions.clone()
            && let Err(err) = fs::set_permissions(&temp_path, permissions)
        {
            let _ = fs::remove_file(&temp_path);
            return Err(err).wrap_err("failed to apply the samples' permissions to the dictionary");
        }
        let written = temp_file
            .write_all(dict)
            .and_then(|()| temp_file.flush())
            .wrap_err_with(|| format!("failed to write dictionary {}", output.display()));
        if let Err(err) = written {
            let _ = fs::remove_file(&temp_path);
            return Err(err);
        }
        drop(temp_file);
        // Removes the temporary itself when it fails.
        replace_output_file(&temp_path, output, sample_permissions)
    })();
    interrupt::clear();
    placed
}

/// The COVER tuning `--train-cover=...` asked for. A listed tuning starts from
/// zero, a bare flag from the command's defaults. `split` is a percentage and
/// `k` at least `d` (the most a search over `d` tries, 8, when `d` is not
/// given); both are settled here, before any sample is read.
fn cover_options(params: &TrainerParams) -> Result<structured_zstd::dictionary::CoverOptions> {
    cover_tuning(params, "--train-cover")
}

/// The split a tuning report shows: the percentage `split=` was given as.
fn split_percent(split_point: f64) -> u32 {
    // Rounded: a percentage over a hundred is not exact in binary, and 0.29
    // scales back to 28.999...
    (split_point * 100.0).round() as u32
}

fn cover_tuning(
    params: &TrainerParams,
    flag: &str,
) -> Result<structured_zstd::dictionary::CoverOptions> {
    use structured_zstd::dictionary::CoverOptions;

    let mut options = if params.listed {
        CoverOptions {
            k: 0,
            d: 0,
            steps: 0,
            split_point: 0.0,
            shrink: None,
        }
    } else {
        CoverOptions::default()
    };
    if let Some(split) = params.split_percent {
        if split > 100 {
            bail!("{flag} split is a percentage, got {split}");
        }
        options.split_point = f64::from(split) / 100.0;
    }
    if let Some(k) = params.k {
        let d = params.d.unwrap_or(8);
        if k < d {
            bail!("{flag} k must be at least d, got k={k} d={d}");
        }
        options.k = k;
    }
    options.d = params.d.unwrap_or(options.d);
    options.steps = params.steps.unwrap_or(options.steps);
    options.shrink = params.shrink;
    Ok(options)
}

/// The FastCOVER tuning `--train-fastcover=...` asked for, checked the way the
/// reference trainer checks it: `d` is 6 or 8, `f` lies in `1..=31`, `accel`
/// in `1..=10`, and the rest as [`cover_options`] checks it.
fn fastcover_options(
    params: &TrainerParams,
) -> Result<structured_zstd::dictionary::FastCoverOptions> {
    use structured_zstd::dictionary::FastCoverOptions;

    const FLAG: &str = "--train-fastcover";
    if let Some(d) = params.d
        && d != 6
        && d != 8
    {
        bail!("{FLAG} d must be 6 or 8, got {d}");
    }
    let mut options = FastCoverOptions {
        cover: cover_tuning(params, FLAG)?,
        ..FastCoverOptions::default()
    };
    if params.listed {
        // Zero asks the trainer for its own table width and acceleration.
        options.f = 0;
        options.accel = 0;
    } else {
        // The bare flag's split is FastCOVER's, not COVER's.
        options.cover.split_point = FastCoverOptions::default().cover.split_point;
    }
    if let Some(f) = params.f {
        if f > 31 {
            bail!("{FLAG} f must be in 1..=31, got {f}");
        }
        options.f = f;
    }
    if let Some(accel) = params.accel {
        if accel > 10 {
            bail!("{FLAG} accel must be in 1..=10, got {accel}");
        }
        options.accel = accel;
    }
    Ok(options)
}

/// The permissions a file made from all of `samples` may carry: every bit that
/// each of them grants, and no other.
///
/// A dictionary holds pieces of every sample, so anyone who could not read one
/// of them must not be able to read it. On Unix that is the bitwise AND of the
/// modes. Elsewhere `Permissions` says only whether a file is read-only, which
/// answers a different question and would make the dictionary unwritable rather
/// than unreadable, so nothing is applied and the platform's own inheritance
/// stands.
#[cfg(unix)]
fn strictest_sample_permissions(
    samples: &[fs::Metadata],
    destination: &Path,
) -> Result<Option<fs::Permissions>> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    if samples.is_empty() {
        return Ok(None);
    }
    let samples_by_group: Vec<(u32, u32)> = samples
        .iter()
        .map(|sample| (sample.permissions().mode(), sample.gid()))
        .collect();
    // The group the file itself is in, which is the one its group bits would
    // admit. It is the process's, or the directory's when that is setgid, so it
    // is read from the file rather than assumed.
    let output_gid = fs::metadata(destination)
        .wrap_err_with(|| format!("failed to inspect {}", destination.display()))?
        .gid();
    Ok(Some(fs::Permissions::from_mode(output_mode_for_sources(
        &samples_by_group,
        output_gid,
    ))))
}

/// The mode a file built from all of `sources` may carry, given the group it
/// will itself belong to.
///
/// An output carries its sources' bytes — an archive its file's, a dictionary
/// stretches of every sample's — so nobody may reach it who could not reach
/// them. Each source contributes its mode and the group those bits admit, and
/// the intersection of the modes is where the answer starts.
///
/// Bits alone do not say WHO they let in, though: `0640` on two sources of
/// different groups admits two different sets of people, and a file belongs to
/// one group — which is not even necessarily theirs, since a setgid directory
/// gives the file its own. So the group bits survive only when every source
/// names one group and the file is in it. The owner's bits stand, because every
/// source was read to build this and so this user was entitled to its bytes,
/// and the world's name no one in particular, so their intersection means what
/// it says.
#[cfg(unix)]
fn output_mode_for_sources(sources: &[(u32, u32)], output_gid: u32) -> u32 {
    // Only the bits that say who may read, write and run the file. Set-user-ID
    // and set-group-ID say who a program runs AS, which is not a permission the
    // bytes carry and not one to hand to a file with a different owner: a
    // privileged run over someone else's `04755` archive would otherwise write
    // a root-owned `04755` file. The reference command carries neither.
    let mut mode = 0o0777;
    let mut group = None;
    let mut one_group = true;
    for (source_mode, source_gid) in sources {
        mode &= *source_mode;
        match group {
            None => group = Some(*source_gid),
            Some(seen) => one_group &= seen == *source_gid,
        }
    }
    if !one_group || group != Some(output_gid) {
        mode &= !0o070;
    }
    mode
}

#[cfg(not(unix))]
fn strictest_sample_permissions(
    _samples: &[fs::Metadata],
    _destination: &Path,
) -> Result<Option<fs::Permissions>> {
    Ok(None)
}

/// The mode an output built from one source may carry, by the same rule the
/// trainer applies to its samples: an archive holds its source's bytes, so
/// nobody may read it who could not read that source.
#[cfg(unix)]
fn permissions_from_source(
    source: &fs::Metadata,
    destination: &Path,
) -> Result<Option<fs::Permissions>> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    let output_gid = fs::metadata(destination)
        .wrap_err_with(|| format!("failed to inspect {}", destination.display()))?
        .gid();
    Ok(Some(fs::Permissions::from_mode(output_mode_for_sources(
        &[(source.permissions().mode(), source.gid())],
        output_gid,
    ))))
}

/// Elsewhere `Permissions` says only whether a file is read-only, which answers
/// a different question than who may read it, so the source's own is carried
/// over unchanged and the platform decides the rest.
#[cfg(not(unix))]
fn permissions_from_source(
    source: &fs::Metadata,
    _destination: &Path,
) -> Result<Option<fs::Permissions>> {
    Ok(Some(source.permissions()))
}

/// Read into `buf` until it is full or EOF, returning the number of bytes read.
/// Unlike a single `read`, this fills as much as the source has, so a header
/// parse sees the whole header even when the OS hands back short reads.
fn read_filling<R: Read>(reader: &mut R, buf: &mut [u8]) -> Result<usize> {
    let mut filled = 0;
    while filled < buf.len() {
        match reader.read(&mut buf[filled..]) {
            Ok(0) => break,
            Ok(n) => filled += n,
            Err(err) if err.kind() == ErrorKind::Interrupted => continue,
            Err(err) => return Err(err).wrap_err("failed to read frame header"),
        }
    }
    Ok(filled)
}

/// `--list`: one row per archive in the reference command's layout, or one
/// block per archive under `-v`, then a total when there are several. An
/// archive that cannot be listed is reported and the rest are still listed;
/// the count that failed comes back.
fn list_files(opts: &Options) -> Result<usize> {
    if opts.inputs.is_empty() {
        bail!("No files given");
    }
    // `-` is stdin, which the walk cannot seek through any more than a FIFO.
    // Answered before any file is opened, or the marker would name a file
    // whenever one happens to sit in the working directory under that name,
    // and stdin whenever one does not. A file really called `-` is still
    // reachable, spelled `./-`.
    if opts.inputs.iter().any(|input| input == Path::new("-")) {
        bail!("--list does not support reading from standard input");
    }
    let verbose = opts.verbosity > DEFAULT_LEVEL;
    if !verbose {
        println!("Frames  Skips  Compressed  Uncompressed  Ratio  Check  Filename");
    }
    let mut total = Some(ListTotal::default());
    let mut failed = 0;
    for input in &opts.inputs {
        match list_file(input, verbose, opts.verbosity) {
            Ok(summary) => {
                // A total past 64 bits has no row to be printed in, so the
                // closing row is dropped and the run fails; each archive's own
                // row stands.
                if let Some(sum) = total.as_mut()
                    && let Err(err) = sum.add(&summary)
                {
                    display!(opts.verbosity, 1, "zstd: {}: {err}", input.display());
                    failed += 1;
                    total = None;
                }
            }
            Err(err) => {
                display!(opts.verbosity, 1, "zstd: {err}");
                failed += 1;
            }
        }
    }
    if let Some(total) = total
        && opts.inputs.len() > 1
        && !verbose
    {
        total.print();
    }
    Ok(failed)
}

/// What the archives listed so far add up to, for the closing row.
#[derive(Default)]
struct ListTotal {
    frames: u64,
    skips: u64,
    compressed: u64,
    decompressed: u64,
    /// Some archive omitted a Frame_Content_Size, so the total is unknowable.
    decompressed_unknown: bool,
    /// Some archive carries no checksum, so the total's `Check` says nothing.
    without_check: bool,
    files: usize,
}

impl ListTotal {
    /// Add one archive to the totals. Fails when a total outgrows 64 bits: the
    /// content sizes are declared by the headers, and two tiny crafted files
    /// can claim nearly 2^64 bytes each.
    fn add(&mut self, summary: &ArchiveSummary) -> Result<()> {
        let overflow = || eyre!("the listed files total more than 2^64 bytes");
        self.frames = self
            .frames
            .checked_add(summary.frames)
            .ok_or_else(overflow)?;
        self.skips = self.skips.checked_add(summary.skips).ok_or_else(overflow)?;
        self.compressed = self
            .compressed
            .checked_add(summary.compressed)
            .ok_or_else(overflow)?;
        match summary.decompressed {
            // Once one archive's size is unknown so is the total, and no later
            // declaration is added to it.
            Some(decompressed) if !self.decompressed_unknown => {
                self.decompressed = self
                    .decompressed
                    .checked_add(decompressed)
                    .ok_or_else(overflow)?;
            }
            Some(_) => {}
            None => self.decompressed_unknown = true,
        }
        self.without_check |= !summary.check;
        self.files += 1;
        Ok(())
    }

    fn print(&self) {
        println!("----------------------------------------------------------------- ");
        let compressed = HumanSize::new(self.compressed, false);
        let check = if self.without_check { "" } else { "XXH64" };
        if self.decompressed_unknown {
            println!(
                "{:>6}  {:>5}  {}                       {:>5}  {} files",
                self.frames,
                self.skips,
                compressed.columns(6),
                check,
                self.files
            );
        } else {
            let ratio = if self.compressed == 0 {
                0.0
            } else {
                self.decompressed as f64 / self.compressed as f64
            };
            println!(
                "{:>6}  {:>5}  {}  {}  {:>5.3}  {:>5}  {} files",
                self.frames,
                self.skips,
                compressed.columns(6),
                HumanSize::new(self.decompressed, false).columns(8),
                ratio,
                check,
                self.files
            );
        }
    }
}

/// Largest possible zstd frame header: 4-byte magic + 1-byte descriptor + up to
/// 8-byte Frame_Content_Size + up to 4-byte Dictionary_ID + 1-byte
/// Window_Descriptor (RFC 8878 §3.1.1.1).
const MAX_FRAME_HEADER_LEN: usize = 18;

/// What one `--list` row says about an archive.
#[derive(Debug)]
struct ArchiveSummary {
    frames: u64,
    skips: u64,
    compressed: u64,
    /// `None` when any frame omits its Frame_Content_Size, since the total is
    /// then unknowable without decoding.
    decompressed: Option<u64>,
    /// Whether any data frame carries a content checksum.
    ///
    /// That is the question the reference tool's `Check` column answers, not
    /// whether every frame carries one: zstd 1.5.7 prints `XXH64` for an
    /// archive of one checksummed and one unchecked frame — in either order —
    /// and `None` only when no frame has one. Reporting a mixed state here
    /// would say something true about the archive in a column scripts read as
    /// upstream's, so the answer stays the one they parse. Verification is
    /// per frame regardless: `-t` and `-d` compare every checksum that is
    /// there, so a frame without one is unchecked whatever this column says.
    check: bool,
    /// The dictionary the archive needs, and `None` both when it needs none and
    /// when its frames name different ones — an archive with no single answer
    /// has no id to print, and claiming the first frame's would send the reader
    /// after a dictionary that decodes only part of it.
    dict_id: Option<u32>,
    /// Whether the data frames named one dictionary between them. False makes
    /// the id above absent rather than wrong.
    dict_ids_agree: bool,
    /// The largest window any data frame declares, which is what a decoder
    /// needs in memory to read the whole archive.
    window_size: u64,
    /// The stored checksum of the last data frame that carries one; shown
    /// under `-lv` for a single-frame archive, as the reference command
    /// shows it.
    checksum: Option<[u8; 4]>,
}

/// Walk every frame in the file (no body decode), summing compressed and
/// declared content sizes.
///
/// Reads each frame header, then walks the 3-byte block headers by `seek`ing
/// past every block body, so peak memory stays O(1) regardless of archive size
/// (a multi-GB file is never loaded whole).
fn summarize_archive(path: &Path) -> Result<ArchiveSummary> {
    use std::io::{Seek, SeekFrom};
    use structured_zstd::decoding::errors::ReadFrameHeaderError;
    use structured_zstd::decoding::{FrameContentSize, read_frame_header_info};

    let mut file =
        File::open(path).wrap_err_with(|| format!("failed to open {}", path.display()))?;
    let compressed = file
        .metadata()
        .wrap_err_with(|| format!("failed to stat {}", path.display()))?
        .len();
    // An empty file is not a zstd stream: without this guard the walk loop
    // below never runs and we would print a spurious 0-frame success row.
    if compressed == 0 {
        bail!("{}: not a zstd frame: empty file", path.display());
    }
    let mut offset = 0u64;
    // `Frames` counts every frame in the file and `Skips` says how many of them
    // were skippable, which is how the reference tool fills these columns:
    // zstd 1.5.7 prints `Frames 3, Skips 1` for an archive of two data frames
    // around one metadata frame. Reporting 2 and 1 for that file would read as
    // four frames to anyone adding the columns up.
    let mut frames = 0u64;
    let mut data_frames = 0u64;
    let mut skips = 0u64;
    let mut decompressed = Some(0u64);
    let mut check = false;
    let mut dict_id = None;
    let mut dict_ids_agree = true;
    let mut window_size = 0u64;
    let mut checksum = None;

    while offset < compressed {
        // Read just enough for the frame header (a short read near EOF is fine —
        // `read_frame_header_info` reports the exact length it consumed).
        file.seek(SeekFrom::Start(offset))?;
        let mut header_buf = [0u8; MAX_FRAME_HEADER_LEN];
        let header_read = read_filling(&mut file, &mut header_buf)?;
        let info = match read_frame_header_info(&header_buf[..header_read], false) {
            Ok(info) => info,
            // Metadata frames sit inside ordinary archives (a seekable-zstd
            // index is one), so the walk steps over them: 4-byte magic +
            // 4-byte length + the payload.
            Err(ReadFrameHeaderError::SkipFrame { length, .. }) => {
                offset = offset
                    .checked_add(8 + u64::from(length))
                    .filter(|end| *end <= compressed)
                    .ok_or_else(|| eyre!("{}: truncated skippable frame", path.display()))?;
                // Upstream counts a skippable frame in both columns: `Frames`
                // is every frame in the file, `Skips` the metadata ones.
                skips += 1;
                frames += 1;
                continue;
            }
            Err(err) => bail!(
                "File \"{}\" not compressed by zstd ({err:?})",
                path.display()
            ),
        };

        // The frame's Block_Maximum_Size bounds every block (RFC 8878 §3.1.1.2).
        let block_size_max = info.window_size.min(128 * 1024);
        // Walk block headers, seeking past each body, to find the frame's end.
        let mut block_offset = offset + info.header_size as u64;
        loop {
            file.seek(SeekFrom::Start(block_offset))?;
            let mut block_header = [0u8; 3];
            file.read_exact(&mut block_header)
                .map_err(|_| eyre!("{}: truncated mid-frame", path.display()))?;
            let raw = u32::from(block_header[0])
                | (u32::from(block_header[1]) << 8)
                | (u32::from(block_header[2]) << 16);
            let last_block = (raw & 1) != 0;
            let block_type = (raw >> 1) & 0b11;
            let block_size = u64::from(raw >> 3);
            if block_size > block_size_max {
                bail!("{}: block exceeds Block_Maximum_Size", path.display());
            }
            // On-disk bytes after the header: RLE stores one byte, Raw/Compressed
            // store Block_Size, the reserved type is invalid.
            let on_disk = match block_type {
                1 => 1,
                0 | 2 => block_size,
                _ => bail!("{}: reserved block type", path.display()),
            };
            block_offset = block_offset
                .checked_add(3 + on_disk)
                .filter(|end| *end <= compressed)
                .ok_or_else(|| eyre!("{}: truncated mid-frame", path.display()))?;
            if last_block {
                break;
            }
        }
        // A trailing 4-byte content checksum follows the last block when present.
        let frame_end = if info.content_checksum {
            let end = block_offset
                .checked_add(4)
                .filter(|end| *end <= compressed)
                .ok_or_else(|| eyre!("{}: truncated content checksum", path.display()))?;
            file.seek(SeekFrom::Start(block_offset))?;
            let mut stored = [0u8; 4];
            file.read_exact(&mut stored)
                .map_err(|_| eyre!("{}: truncated content checksum", path.display()))?;
            checksum = Some(stored);
            end
        } else {
            block_offset
        };
        // The largest, not the last: a small frame after a large one does not
        // lower what decoding the archive needs. The reference command shows
        // the last frame's, which understates it.
        window_size = window_size.max(info.window_size);

        match info.content_size {
            // Declared, not measured: a handful of header bytes can claim any
            // size, so the running total is checked rather than trusted.
            FrameContentSize::Known(n) => {
                decompressed = match decompressed {
                    Some(total) => Some(total.checked_add(n).ok_or_else(|| {
                        eyre!(
                            "{}: declared content sizes total more than 2^64 bytes",
                            path.display()
                        )
                    })?),
                    None => None,
                }
            }
            FrameContentSize::Unknown => decompressed = None,
        }
        // Any frame carrying one makes the archive checksummed, which is what
        // the reference tool reports for a mixed file as well.
        check |= info.content_checksum;
        // The first DATA frame sets the id; a leading metadata frame counts
        // towards `frames` but carries no header to read one from. Every later
        // frame has to agree, because one id is what the column can say: an
        // archive whose frames name different dictionaries needs more than one
        // to be read, and the first frame's alone would decode only its own
        // part.
        if data_frames == 0 {
            dict_id = info.dictionary_id;
        } else if dict_id != info.dictionary_id {
            dict_ids_agree = false;
        }
        data_frames += 1;
        frames += 1;
        offset = frame_end;
    }

    Ok(ArchiveSummary {
        frames,
        skips,
        compressed,
        decompressed,
        check,
        dict_id: dict_ids_agree.then_some(dict_id).flatten(),
        dict_ids_agree,
        window_size,
        checksum,
    })
}

/// Print one `--list` entry: a row in the reference command's `zstd -l`
/// layout, or, when `verbose`, the block its `-lv` prints. The decompressed
/// columns are left blank when any frame omits its Frame_Content_Size.
fn list_file(path: &Path, verbose: bool, verbosity: i32) -> Result<ArchiveSummary> {
    // The walk seeks between frame headers, so it needs a file that can seek.
    // Settled before the file is opened: opening a FIFO blocks until a writer
    // appears, and the failure would then arrive from the seek rather than
    // from the thing that was wrong.
    let metadata =
        fs::metadata(path).wrap_err_with(|| format!("Error : {} is not a file", path.display()))?;
    if !metadata.is_file() {
        bail!("Error : {} is not a file", path.display());
    }
    let summary = summarize_archive(path)?;
    // The id column holds one id, so an archive built from several
    // dictionaries has nothing to put there. Said out loud rather than left to
    // the `0`, which on its own reads as "no dictionary needed".
    if !summary.dict_ids_agree {
        display!(
            verbosity,
            2,
            "WARNING: File contains multiple frames with different dictionary IDs. Showing dictID 0 instead"
        );
    }
    let ratio = summary
        .decompressed
        .map(|decompressed| decompressed as f64 / summary.compressed as f64);
    let check = if summary.check { "XXH64" } else { "None" };
    let compressed = HumanSize::new(summary.compressed, false);
    if !verbose {
        match (summary.decompressed, ratio) {
            (Some(decompressed), Some(ratio)) => println!(
                "{:>6}  {:>5}  {}  {}  {ratio:>5.3}  {check:>5}  {}",
                summary.frames,
                summary.skips,
                compressed.columns(6),
                HumanSize::new(decompressed, false).columns(8),
                path.display()
            ),
            _ => println!(
                "{:>6}  {:>5}  {}                       {check:>5}  {}",
                summary.frames,
                summary.skips,
                compressed.columns(6),
                path.display()
            ),
        }
        return Ok(summary);
    }
    let data_frames = summary.frames - summary.skips;
    println!("{} ", path.display());
    println!("# Zstandard Frames: {data_frames}");
    if summary.skips > 0 {
        println!("# Skippable Frames: {}", summary.skips);
    }
    println!("DictID: {}", summary.dict_id.unwrap_or(0));
    println!(
        "Window Size: {} ({} B)",
        HumanSize::new(summary.window_size, false),
        summary.window_size
    );
    println!("Compressed Size: {compressed} ({} B)", summary.compressed);
    if let (Some(decompressed), Some(ratio)) = (summary.decompressed, ratio) {
        println!(
            "Decompressed Size: {} ({decompressed} B)",
            HumanSize::new(decompressed, false)
        );
        println!("Ratio: {ratio:.4}");
    }
    match summary.checksum {
        Some(stored) if summary.check && data_frames == 1 => println!(
            "Check: {check} {:02x}{:02x}{:02x}{:02x}",
            stored[3], stored[2], stored[1], stored[0]
        ),
        _ => println!("Check: {check}"),
    }
    println!();
    Ok(summary)
}

/// Remove the source file after a successful (de)compression when `--rm` is set
/// (and `-k` was not) and a regular file now holds the output (`placement`).
/// A no-op otherwise.
fn remove_source_if_requested(opts: &Options, input: &Path, placement: Placement) -> Result<()> {
    // Never when the output went to stdout: that may have been a pipe whose
    // reader is gone, a terminal, or anything else we cannot read back, so
    // there is no saved copy to justify deleting the original. Upstream keeps
    // the file for `-c` too.
    if !opts.remove_source || opts.keep || opts.to_stdout {
        return Ok(());
    }
    // Nor when a device or pipe took the output in place (`-o /dev/null`, a
    // FIFO), for the same reason: it keeps nothing, and the source is the only
    // copy left. The reference command removes it there as well.
    if placement != Placement::File {
        display!(
            opts.verbosity,
            3,
            "Note: {} is not removed: its output is not a regular file",
            input.display()
        );
        return Ok(());
    }
    // Removing the source is past the point where an interruption should
    // delete anything: the output is in place, and the guard would take it
    // along with the source.
    interrupt::clear();
    fs::remove_file(input).wrap_err("failed to remove source file after success")?;
    Ok(())
}

/// Counts what passes through to the writer beneath, so the summary can say
/// how much came out of a compression whatever the sink was.
struct CountingWriter<W: Write> {
    inner: W,
    written: u64,
}

impl<W: Write> Write for CountingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = self.inner.write(buf)?;
        self.written += written as u64;
        Ok(written)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// A destination that knows how many bytes it has taken, so a frame's
/// compressed size is read off it after the frame rather than counted on the
/// way in: a buffer already knows its length.
trait BytesWritten {
    fn bytes_written(&self) -> u64;
}

impl<W: Write> BytesWritten for CountingWriter<W> {
    fn bytes_written(&self) -> u64 {
        self.written
    }
}

impl BytesWritten for Vec<u8> {
    fn bytes_written(&self) -> u64 {
        self.len() as u64
    }
}

impl<T: BytesWritten + ?Sized> BytesWritten for &mut T {
    fn bytes_written(&self) -> u64 {
        (**self).bytes_written()
    }
}

/// Whether a file type is a named pipe.
fn is_fifo_type(kind: &fs::FileType) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt;
        kind.is_fifo()
    }
    #[cfg(not(unix))]
    {
        let _ = kind;
        false
    }
}

/// Whether a file type is a block device.
fn is_block_device_type(kind: &fs::FileType) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt;
        kind.is_block_device()
    }
    #[cfg(not(unix))]
    {
        let _ = kind;
        false
    }
}

/// Open one named input for streaming, or say why it cannot be.
///
/// `Ok(None)` is an input deliberately left alone under
/// `--exclude-compressed`. A directory, a socket or a device is refused the
/// way the reference command refuses them ("-- ignored"); `-f` admits block
/// devices. The kind and length that matter are those of the OPEN file: a
/// path is only a name, and can be made to name something else between the
/// look and the open.
fn open_input(opts: &Options, input: &Path) -> Result<Option<(File, fs::Metadata)>> {
    let named = fs::metadata(input)
        .map_err(|err| eyre!("can't stat {} : {err} -- ignored", input.display()))?;
    if named.is_dir() {
        bail!("{} is a directory -- ignored", input.display());
    }
    let admissible = |kind: &fs::FileType| {
        kind.is_file() || is_fifo_type(kind) || (opts.force && is_block_device_type(kind))
    };
    if !admissible(&named.file_type()) {
        bail!("{} is not a regular file -- ignored", input.display());
    }
    if skips_as_compressed(opts, input) {
        display!(
            opts.verbosity,
            4,
            "File is already compressed : {}",
            input.display()
        );
        return Ok(None);
    }
    let source = File::open(input).wrap_err_with(|| input.display().to_string())?;
    let metadata = source
        .metadata()
        .wrap_err_with(|| format!("failed to inspect {}", input.display()))?;
    if metadata.is_dir() || !admissible(&metadata.file_type()) {
        bail!("{} is not a regular file -- ignored", input.display());
    }
    Ok(Some((source, metadata)))
}

/// Stream one opened input through the codec into `sink`.
fn stream_opened<W: Write>(
    opts: &Options,
    codecs: &mut Codecs,
    source: File,
    metadata: &fs::Metadata,
    sink: W,
) -> Result<Processed> {
    // Kept as the `u64` the filesystem reports: the work streams, so a file
    // only has to fit the window, and narrowing to a pointer would refuse
    // 4 GiB archives on 32-bit targets for no reason the work has.
    let source_size = metadata.len();
    // Only a regular file's length says how many bytes will be read. A FIFO,
    // a device or a socket reports something unrelated (commonly zero), and
    // pledging that turns a perfectly good stream into a length mismatch.
    let pledged_size = metadata.is_file().then_some(source_size);
    // The same length is the counter's total, and a FIFO's has none to show.
    let reader = progress_monitor(
        opts,
        BufReader::with_capacity(IO_CHUNK, source),
        pledged_size,
    );
    let decode = DecodeSettings::for_file(opts);
    stream(opts, codecs, reader, pledged_size, &decode, sink)
}

/// Stream stdin through the codec into `sink`. stdin has no length to stat,
/// which is exactly why `--stream-size` / `--size-hint` exist: whatever the
/// caller pledged travels in `opts`.
fn stream_stdin<W: Write>(opts: &Options, codecs: &mut Codecs, sink: W) -> Result<Processed> {
    let stdin = io::stdin();
    let decode = DecodeSettings::for_stdin(opts);
    stream(
        opts,
        codecs,
        stdin_monitor(opts, stdin.lock()),
        None,
        &decode,
        sink,
    )
}

/// The counter over `reader` expecting `total` bytes, drawn under the
/// `--progress` rule every input shares.
fn progress_monitor<R: Read>(opts: &Options, reader: R, total: Option<u64>) -> ProgressMonitor<R> {
    let shown = opts.progress.shown(opts.verbosity, opts.console.stderr());
    ProgressMonitor::new(reader, total, shown)
}

/// The counter over stdin: drawn like a file's, over the `--stream-size`
/// pledge when there is one, since stdin has no length of its own to stat.
/// Read [`IO_CHUNK`] at a time, as a file is.
fn stdin_monitor<R: Read>(opts: &Options, reader: R) -> ProgressMonitor<BufReader<R>> {
    progress_monitor(
        opts,
        BufReader::with_capacity(IO_CHUNK, reader),
        opts.pledged_size,
    )
}

/// Run the mode's codec from `reader` into `sink` and count both sides.
/// `pledged_size` is the exact length of THIS input when it has one to stat;
/// `--stream-size` stands in when it does not. `decode` is how THIS input is
/// decoded, its destination included. `-t` decodes into nothing, whatever sink
/// it was handed.
fn stream<R: BufRead, W: Write>(
    opts: &Options,
    codecs: &mut Codecs,
    mut reader: ProgressMonitor<R>,
    pledged_size: Option<u64>,
    decode: &DecodeSettings,
    mut sink: W,
) -> Result<Processed> {
    let written = match opts.mode {
        Mode::Compress => compress_stream(
            &mut reader,
            CountingWriter {
                inner: &mut sink,
                written: 0,
            },
            &FrameSettings {
                pledged_size: pledged_size.or(opts.pledged_size),
                ..FrameSettings::from_options(opts)
            },
            codecs,
        )?,
        Mode::Decompress => decompress_stream(&mut reader, &mut sink, codecs, decode)?,
        Mode::Test => decompress_stream(&mut reader, io::sink(), codecs, decode)?,
        Mode::List | Mode::Train => unreachable!("list / train never stream"),
    };
    sink.flush().wrap_err("failed to flush output")?;
    Ok(Processed {
        read: reader.read,
        written,
    })
}

/// One input into a destination that is already open and shared: stdout, or
/// the `-o` file being filled. An input that cannot be opened is reported
/// here and refused; a failure while streaming is returned for the caller to
/// end the run on, since the shared output now holds a partial frame.
fn stream_input_to<W: Write>(
    opts: &Options,
    codecs: &mut Codecs,
    input: &Path,
    mut sink: W,
    destination: &str,
    total: usize,
) -> Result<Outcome> {
    let (name, processed) = if input == Path::new("-") {
        (
            STDIN_MARK.to_string(),
            stream_stdin(opts, codecs, &mut sink)?,
        )
    } else {
        match open_input(opts, input) {
            Ok(Some((source, metadata))) => (
                input.display().to_string(),
                stream_opened(opts, codecs, source, &metadata, &mut sink)?,
            ),
            Ok(None) => return Ok(Outcome::Skipped),
            Err(err) => {
                display!(opts.verbosity, 1, "zstd: {err}");
                return Ok(Outcome::Refused);
            }
        }
    };
    file_summary(opts, total, &name, destination, &processed);
    Ok(Outcome::Done(processed))
}

/// Where an output's bytes went, which decides whether its source may go.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Placement {
    /// A regular file holds them: the source has a durable replacement.
    File,
    /// A device or pipe took them in place and keeps nothing.
    Stream,
    /// Nothing was placed: the result was turned down and the output left as
    /// it was.
    Discarded,
}

/// Fill `output` atomically: `fill` writes into a sibling temporary, which is
/// renamed into place on success and removed on failure or interruption.
///
/// Honours the `-f` overwrite gate the way the reference command does: an
/// existing output is refused outright below the default display level, where
/// no question can be asked, and asked about at it. `Ok(None)` is such a
/// refusal, already reported. `source` is the file whose permissions the
/// output takes; `None` (stdin, a concatenation) leaves the umask to decide.
///
/// A destination that already exists and is not a regular file (`/dev/null`,
/// a pipe, `/dev/stdout`) is opened and written in place instead; see
/// [`writes_in_place`]. The [`Placement`] returned says which happened.
fn write_output_file<T>(
    opts: &Options,
    output: &Path,
    source: Option<&fs::Metadata>,
    fill: impl FnOnce(&mut File) -> Result<T>,
) -> Result<Option<(T, Placement)>> {
    write_output_file_if(opts, output, source, fill, |_| true)
}

/// [`write_output_file`], with `keep` deciding from what `fill` returned
/// whether the result replaces the output at all. When it does not, the
/// temporary is removed and whatever `output` held stays as it was; the value
/// is still returned, since the caller's accounting comes from it. A device
/// or pipe written in place has no earlier content to keep, so `keep` is not
/// asked there.
fn write_output_file_if<T>(
    opts: &Options,
    output: &Path,
    source: Option<&fs::Metadata>,
    fill: impl FnOnce(&mut File) -> Result<T>,
    keep: impl FnOnce(&T) -> bool,
) -> Result<Option<(T, Placement)>> {
    if writes_in_place(output)? {
        let mut sink = open_in_place(output)?;
        let value = fill(&mut sink)?;
        sink.flush().wrap_err("failed to flush output")?;
        return Ok(Some((value, Placement::Stream)));
    }
    ensure_regular_output_destination(output)?;
    if output.exists() && !opts.force {
        if opts.verbosity <= 1 {
            display!(
                opts.verbosity,
                1,
                "zstd: {} already exists; not overwritten",
                output.display()
            );
            return Ok(None);
        }
        eprint!("zstd: {} already exists; ", output.display());
        if !confirm(
            "overwrite (y/n) ? ",
            "Not overwritten",
            reads_stdin(&opts.inputs),
            &mut io::stdin().lock(),
        ) {
            return Ok(None);
        }
    }
    // From its creation until the rename, an interruption removes the
    // temporary rather than leaving it beside the source.
    let (temp_path, temp_file) =
        interrupt::create_guarded(|| create_temporary_output_file(output))?;
    let abandon = |temp_path: &Path| {
        let _ = fs::remove_file(temp_path);
        interrupt::clear();
    };
    // The output is as private as its source, whether it is created or replaced:
    // an archive of a 0600 secret must not arrive at whatever the umask allows,
    // and must not take a world-readable mode from the name it lands on either.
    // The reference command applies the source's mode in both directions. Only a
    // source with no mode of its own (stdin) leaves the destination's alone.
    // Asked of the temporary file, since that is the one renamed into place and
    // so the one whose own group the mode's group bits would admit.
    let source_permissions = match source {
        Some(metadata) => match permissions_from_source(metadata, &temp_path) {
            Ok(permissions) => permissions,
            Err(err) => {
                abandon(&temp_path);
                return Err(err);
            }
        },
        None => None,
    };
    if let Some(permissions) = source_permissions.clone()
        && let Err(err) = fs::set_permissions(&temp_path, permissions)
    {
        abandon(&temp_path);
        return Err(err).wrap_err("failed to apply the source's permissions to the output");
    }
    let result: Result<T> = (|| {
        let mut sink = temp_file;
        let value = fill(&mut sink)?;
        sink.flush().wrap_err("failed to flush output")?;
        Ok(value)
    })();
    let value = match result {
        Ok(value) => value,
        Err(err) => {
            abandon(&temp_path);
            return Err(err);
        }
    };
    if !keep(&value) {
        abandon(&temp_path);
        return Ok(Some((value, Placement::Discarded)));
    }
    // `replace_output_file` removes the temporary itself when it fails.
    let replaced = replace_output_file(&temp_path, output, source_permissions);
    interrupt::clear();
    replaced.map(|()| Some((value, Placement::File)))
}

/// Resolve the output path for a file input under the current mode: the
/// input's name with the suffix added or removed, placed beside it, under
/// `--output-dir-flat`, or under the mirrored tree of `--output-dir-mirror`.
fn derive_output_path(opts: &Options, input: &Path) -> Result<PathBuf> {
    if let Some(out) = &opts.output {
        return Ok(out.clone());
    }
    let beside = match opts.mode {
        Mode::Compress => add_extension(input, ZSTD_SUFFIX),
        Mode::Decompress => {
            // Drop the extension as a path component rather than as text: a
            // path is bytes, and rebuilding it from a lossy string renames the
            // file it decompresses, with different inputs colliding on one
            // replacement-character name.
            let replacement = input.extension().and_then(|extension| {
                DECOMPRESS_SUFFIXES
                    .iter()
                    .find(|(known, _)| extension == *known)
                    .map(|(_, replacement)| *replacement)
            });
            let Some(replacement) = replacement else {
                bail!(
                    "{}: unknown suffix (.zst/.tzst/.zstd expected). Can't derive the output \
                     file name. Specify it with -o dstFileName. Ignoring.",
                    input.display()
                );
            };
            input.with_extension(replacement)
        }
        Mode::Test | Mode::List | Mode::Train => {
            unreachable!("test / list / train modes never write an output file")
        }
    };
    if let Some(root) = &opts.output_dir_mirror {
        let verb = if opts.mode == Mode::Compress {
            "compress"
        } else {
            "decompress"
        };
        let directory = inputs::mirrored_output_dir(input, root).ok_or_else(|| {
            eyre!(
                "--output-dir-mirror cannot {verb} '{}' into '{}'",
                input.display(),
                root.display()
            )
        })?;
        return Ok(directory.join(beside.file_name().unwrap_or(beside.as_os_str())));
    }
    if let Some(directory) = &opts.output_dir {
        return Ok(inputs::flat_output_path(&beside, directory));
    }
    Ok(beside)
}

/// One named input into an output of its own, derived from its name.
fn process_file(
    opts: &Options,
    input: &Path,
    codecs: &mut Codecs,
    total: usize,
) -> Result<Outcome> {
    let Some((source, metadata)) = open_input(opts, input)? else {
        return Ok(Outcome::Skipped);
    };
    let name = input.display().to_string();

    // Test mode: decompress into the void, report what was there.
    if opts.mode == Mode::Test {
        let processed = stream_opened(opts, codecs, source, &metadata, io::sink())?;
        file_summary(opts, total, &name, "", &processed);
        return Ok(Outcome::Done(processed));
    }

    let output = derive_output_path(opts, input)?;
    ensure_distinct_paths(input, &output)?;
    if let Some(root) = &opts.output_dir_mirror {
        inputs::create_mirrored_dirs(input, root)?;
    }
    let Some((processed, placement)) = write_output_file(opts, &output, Some(&metadata), |sink| {
        stream_opened(opts, codecs, source, &metadata, sink)
    })?
    else {
        return Ok(Outcome::Refused);
    };
    file_summary(
        opts,
        total,
        &name,
        &output.display().to_string(),
        &processed,
    );
    remove_source_if_requested(opts, input, placement)?;
    Ok(Outcome::Done(processed))
}

/// Everything the command line says about how one frame is to be built.
///
/// Grouped rather than passed one by one: these travel together through every
/// compression entry point, and a positional list this long invites the caller
/// to line the arguments up wrong.
#[derive(Clone, Copy, PartialEq)]
struct FrameSettings {
    /// Numeric compression level.
    level: i32,
    /// Exact input length, recorded in the frame header.
    pledged_size: Option<u64>,
    /// Estimated input length; steers geometry, never reaches the header.
    size_hint: Option<u64>,
    /// Long-distance matching, with the window log if `--long=N` gave one.
    long: bool,
    long_window_log: Option<u32>,
    /// Soft block-size target from `--target-compressed-block-size`.
    target_block_size: Option<u32>,
    /// Trailing XXH64 checksum (`--[no-]check`).
    checksum: bool,
    /// Whether a known length is recorded in the header (`--[no-]content-size`).
    content_size_flag: bool,
    /// Whether a dictionary frame records the dictionary's ID (`--no-dictID`).
    dict_id_flag: bool,
    /// Per-knob overrides from `--zstd=...`.
    advanced: AdvancedParams,
    /// Whether literals are entropy-coded (`--[no-]compress-literals`).
    literals: LiteralCompressionMode,
}

impl Default for FrameSettings {
    /// The frame the reference COMMAND writes by default: checksummed, with
    /// the content size and the dictionary ID in the header. (The library's
    /// own default omits the checksum, which is why this is spelled out.)
    fn default() -> Self {
        Self {
            level: CompressionLevel::DEFAULT_LEVEL,
            pledged_size: None,
            size_hint: None,
            long: false,
            long_window_log: None,
            target_block_size: None,
            checksum: true,
            content_size_flag: true,
            dict_id_flag: true,
            advanced: AdvancedParams::default(),
            literals: LiteralCompressionMode::Auto,
        }
    }
}

impl FrameSettings {
    /// The settings the command line asked for, less the per-input size, which
    /// each caller knows and fills in.
    fn from_options(opts: &Options) -> Self {
        Self {
            level: opts.level,
            pledged_size: opts.pledged_size,
            size_hint: opts.size_hint,
            long: opts.long,
            long_window_log: opts.long_window_log,
            target_block_size: opts.target_block_size,
            checksum: opts.checksum,
            content_size_flag: opts.content_size_flag,
            dict_id_flag: opts.dict_id_flag,
            advanced: opts.advanced,
            literals: opts.literals,
        }
    }
}

/// The fine-grained parameters a frame runs under, or `None` when nothing
/// overrides the level: `--zstd=` knobs, `--long` (whose window yields to a
/// `--zstd=wlog=`, as the reference command has it), and the literal mode.
/// The long-distance knobs from `--zstd=` reach the encoder only with
/// `--long`, since there they tune a matcher that otherwise does not run.
fn frame_parameters(
    level: CompressionLevel,
    settings: &FrameSettings,
) -> Result<Option<CompressionParameters>> {
    let advanced = settings.advanced;
    if !settings.long && advanced.is_default() && settings.literals == LiteralCompressionMode::Auto
    {
        return Ok(None);
    }
    let mut builder = CompressionParameters::builder(level);
    let window_log = advanced
        .window_log
        .or(settings.long.then_some(settings.long_window_log).flatten());
    if let Some(log) = window_log {
        builder = builder.window_log(log);
    }
    if let Some(log) = advanced.chain_log {
        builder = builder.chain_log(log);
    }
    if let Some(log) = advanced.hash_log {
        builder = builder.hash_log(log);
    }
    if let Some(log) = advanced.search_log {
        builder = builder.search_log(log);
    }
    if let Some(length) = advanced.min_match {
        builder = builder.min_match(length);
    }
    if let Some(length) = advanced.target_length {
        builder = builder.target_length(length);
    }
    if let Some(strategy) = advanced.strategy {
        builder = builder.strategy(strategy);
    }
    if settings.long {
        builder = builder.enable_long_distance_matching(true);
        if let Some(log) = advanced.ldm_hash_log {
            builder = builder.ldm_hash_log(log);
        }
        if let Some(length) = advanced.ldm_min_match {
            builder = builder.ldm_min_match(length);
        }
        if let Some(log) = advanced.ldm_bucket_size_log {
            builder = builder.ldm_bucket_size_log(log);
        }
        if let Some(log) = advanced.ldm_hash_rate_log {
            builder = builder.ldm_hash_rate_log(log);
        }
    }
    builder = builder.literal_compression(settings.literals);
    builder
        .build()
        .map(Some)
        .map_err(|err| eyre!("invalid compression parameters: {err}"))
}

/// How a stream is decoded: whether a stored checksum is compared, what
/// happens to input that is not a zstd stream, and the widest window taken.
#[derive(Clone, Copy)]
struct DecodeSettings {
    /// Compare the trailing checksum against the data (`--[no-]check`).
    verify_checksum: bool,
    /// Copy input that is not a zstd stream through unchanged rather than
    /// failing on it (`--pass-through`).
    pass_through: bool,
    /// The decoder's window ceiling; see [`decode_window_ceiling`].
    max_window: u64,
    /// What the `--memory` a refusal names adds to the window: nothing for a
    /// plain decode, whose `-M` is the window, and what a benchmark holds
    /// besides it for one (see [`bench_decode_settings`]).
    memory_overhead: Option<u64>,
}

impl Default for DecodeSettings {
    fn default() -> Self {
        Self {
            verify_checksum: true,
            pass_through: false,
            max_window: structured_zstd::decoding::MAXIMUM_ALLOWED_WINDOW_SIZE,
            memory_overhead: Some(0),
        }
    }
}

impl DecodeSettings {
    /// What the command line asked for, for an input whose output goes to
    /// stdout or not. Pass-through defaults to the reference command's rule,
    /// taken per input as it takes it (`fileio.c`, `FIO_decompressFrames`): on
    /// when forced and this input's output is stdout, which is how `zstdcat`
    /// and `zstd -dcf` behave. Never under `-t`, which asks whether the input
    /// is a sound archive: passed through, plain input would be reported as
    /// one, whichever flag or preset turned it on.
    fn with_destination(opts: &Options, to_stdout: bool) -> Self {
        Self {
            verify_checksum: opts.checksum,
            pass_through: opts.mode != Mode::Test
                && opts.pass_through.unwrap_or(opts.force && to_stdout),
            max_window: opts.decode_window,
            memory_overhead: Some(0),
        }
    }

    /// For the whole run, as a run with one destination has.
    fn from_options(opts: &Options) -> Self {
        Self::with_destination(opts, writes_stdout(opts))
    }

    /// For stdin, whose output is stdout unless `-o` names a file, even in a
    /// run whose named inputs are written to files of their own.
    fn for_stdin(opts: &Options) -> Self {
        Self::with_destination(opts, opts.to_stdout || opts.output.is_none())
    }

    /// For a named file, whose output is stdout only under `-c`.
    fn for_file(opts: &Options) -> Self {
        Self::with_destination(opts, opts.to_stdout)
    }
}

/// A compression context configured for every frame under `settings`, less the
/// pledge, which belongs to one frame and is set by [`compress_stream`].
fn new_compressor(
    settings: &FrameSettings,
    dictionary: Option<&structured_zstd::encoding::EncoderDictionary>,
) -> Result<CompressionContext> {
    let &FrameSettings {
        level,
        size_hint,
        target_block_size,
        checksum,
        content_size_flag,
        dict_id_flag,
        ..
    } = settings;
    let compression_level = CompressionLevel::from_level(level);
    let mut context = CompressionContext::new(compression_level);
    // The reference `zstd` COMMAND defaults the content checksum ON (unlike
    // the library API, whose default is off and which our encoder mirrors), so
    // it is set explicitly either way: on by default, off under `--no-check`.
    context
        .set_content_checksum(checksum)
        .wrap_err("failed to set the content checksum flag")?;
    context
        .set_content_size_flag(content_size_flag)
        .wrap_err("failed to set the content size flag")?;
    context
        .set_dictionary_id_flag(dict_id_flag)
        .wrap_err("failed to set the dictionary ID flag")?;
    // A smaller block target is what the caller asked for when they want
    // bounded latency; the encoder clamps it to the format's own range. Zero
    // is the parameter's own way of saying "no target", so it stays off rather
    // than being clamped up into the smallest block the format allows.
    if let Some(target) = target_block_size.filter(|target| *target != 0) {
        context
            .set_target_block_size(Some(target))
            .wrap_err("failed to set the block-size target")?;
    }
    // `--long`, `--zstd=` and the literal mode are per-knob overrides applied
    // via the compression-parameters API.
    if let Some(params) = frame_parameters(compression_level, settings)? {
        context
            .set_parameters(&params)
            .wrap_err("failed to apply the compression parameters")?;
    }
    // Only an estimate (`--size-hint`): it steers the encoder's geometry and
    // must NOT reach the header, or a wrong guess would turn a successful
    // compression into a failure. It holds for every frame, as upstream's
    // `ZSTD_c_srcSizeHint` does, and a frame's exact pledge takes its place.
    // Zero is not a hint (the parameter says so), and taking it as one would
    // size the encoder for an empty source and shrink the window a real
    // stream needs.
    if let Some(size) = size_hint.filter(|size| *size != 0) {
        context
            .set_source_size_hint(size)
            .wrap_err("failed to set source size hint")?;
    }
    // Parsed once for the whole run, and held by the context from here on:
    // its frames reference it rather than taking a handle each.
    if let Some(prepared) = dictionary {
        context
            .set_encoder_dictionary(prepared.clone())
            .wrap_err("failed to load dictionary for compression")?;
    }
    Ok(context)
}

/// Streaming compression core (file or stdout), optionally dictionary-primed.
/// The encoder takes each piece straight from `reader`'s buffer: a file or
/// stdin [`IO_CHUNK`] at a time, a slice in one piece. Returns the bytes of the
/// frame written, and records the frame in the run's `--trace`.
fn compress_stream<R: BufRead, W: Write + BytesWritten>(
    reader: R,
    writer: W,
    settings: &FrameSettings,
    codecs: &mut Codecs,
) -> Result<u64> {
    let compressed = compress_frame(reader, writer, settings, codecs);
    if compressed.is_err() {
        // A frame that failed part-way leaves the context inside it, or
        // refusing further work; the next input starts from a new one rather
        // than continuing this frame.
        codecs.compressor = None;
    }
    compressed
}

/// [`compress_stream`] on the run's context, which it leaves as the frame
/// left it. With a trace open, the frame is recorded, timed as the encoder's
/// own time: from before the context is set up, as the reference starts the
/// trace in `ZSTD_compressBegin_internal`, to the end of the frame, less the
/// time `reader` took to deliver the input and `writer` took over the output,
/// so the speed reported is the encoder's whatever the source and
/// destination.
fn compress_frame<R: BufRead, W: Write + BytesWritten>(
    reader: R,
    writer: W,
    settings: &FrameSettings,
    codecs: &mut Codecs,
) -> Result<u64> {
    let before = writer.bytes_written();
    if codecs.trace.is_none() {
        let writer = encode_frame(reader, writer, settings, codecs)?;
        // A writer only takes bytes, so its count has not gone down.
        return Ok(writer.bytes_written() - before);
    }
    let started = std::time::Instant::now();
    let mut source = TimedReader {
        inner: reader,
        spent: std::time::Duration::ZERO,
        consumed: 0,
    };
    let timed = TimedWriter {
        inner: writer,
        spent: std::time::Duration::ZERO,
    };
    let timed = encode_frame(&mut source, timed, settings, codecs)?;
    let consumed = source.consumed;
    // Both sums are spans of the monotonic clock inside this one, apart from
    // each other, so together they are never the larger.
    let duration = started.elapsed() - timed.spent - source.spent;
    let written = timed.bytes_written() - before;
    // The dictionary as it was given, header and entropy tables included:
    // upstream sets `dictContentSize` to the whole buffer
    // (`ZSTD_initCDict_internal`, `ZSTD_compressBegin_internal`) and traces
    // that.
    let dictionary_size = codecs
        .encoder
        .as_ref()
        .map_or(0, |_| codecs.dictionary_size);
    trace_frame(
        &mut codecs.trace,
        &trace::Frame {
            method: trace::Method::Compress,
            // Level 0 asks for the default, and the frame is compressed at
            // it; the reference stores 0 as `ZSTD_CLEVEL_DEFAULT` and traces
            // that (`ZSTD_CCtxParams_setParameter`).
            level: if settings.level == 0 {
                structured_zstd::encoding::CompressionLevel::DEFAULT_LEVEL
            } else {
                settings.level
            },
            dictionary_size,
            uncompressed_size: consumed,
            compressed_size: written,
            duration,
        },
    );
    Ok(written)
}

/// A writer that keeps the time it spends writing, so a trace can leave the
/// destination's time out of the encoder's.
struct TimedWriter<W> {
    inner: W,
    spent: std::time::Duration,
}

impl<W: Write> Write for TimedWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let started = std::time::Instant::now();
        let written = self.inner.write(buf);
        self.spent += started.elapsed();
        written
    }

    fn flush(&mut self) -> io::Result<()> {
        let started = std::time::Instant::now();
        let flushed = self.inner.flush();
        self.spent += started.elapsed();
        flushed
    }
}

impl<W: BytesWritten> BytesWritten for TimedWriter<W> {
    fn bytes_written(&self) -> u64 {
        self.inner.bytes_written()
    }
}

/// A buffered reader that keeps the time it spends in its source, reading and
/// consuming (a progress display updates on `consume`), so a trace can leave
/// the source's time out of the encoder's, and the bytes taken from it, the
/// frame's uncompressed size.
struct TimedReader<R> {
    inner: R,
    spent: std::time::Duration,
    consumed: u64,
}

impl<R: Read> Read for TimedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let started = std::time::Instant::now();
        let read = self.inner.read(buf);
        self.spent += started.elapsed();
        if let Ok(n) = read {
            self.consumed += n as u64;
        }
        read
    }
}

impl<R: BufRead> BufRead for TimedReader<R> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        let started = std::time::Instant::now();
        let filled = self.inner.fill_buf();
        self.spent += started.elapsed();
        filled
    }

    fn consume(&mut self, amount: usize) {
        let started = std::time::Instant::now();
        self.inner.consume(amount);
        self.spent += started.elapsed();
        self.consumed += amount as u64;
    }
}

/// One frame of `reader` into `writer` on the run's context: the writer back.
fn encode_frame<R: BufRead, W: Write>(
    mut reader: R,
    writer: W,
    settings: &FrameSettings,
    codecs: &mut Codecs,
) -> Result<W> {
    let mut encoder = StreamingEncoder::with_context(writer, codecs.compressor(settings)?);
    if let Some(size) = settings.pledged_size {
        // The size is known exactly (a regular file, or `--stream-size`), so
        // pledge it: the frame records Frame_Content_Size (decoders can
        // pre-allocate, `zstd -l` reports it) and the matcher sizes its tables
        // to the source. A stream that then differs in length is an error.
        encoder
            .set_pledged_content_size(size)
            .wrap_err("failed to set pledged content size")?;
    }
    // `io::copy` would pass the data through an 8 KiB buffer of its own.
    loop {
        let piece = match reader.fill_buf() {
            Ok(piece) => piece,
            Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
            Err(err) => return Err(err).wrap_err("streaming compression failed"),
        };
        if piece.is_empty() {
            break;
        }
        let len = piece.len();
        encoder
            .write_all(piece)
            .wrap_err("streaming compression failed")?;
        reader.consume(len);
    }
    encoder.finish().wrap_err("failed to finalize zstd frame")
}

/// The magic number every zstd frame opens with (RFC 8878 §3.1.1).
const FRAME_MAGIC: u32 = 0xFD2F_B528;

/// The 16 magic numbers a skippable frame may open with, less their low
/// nibble (RFC 8878 §3.1.2).
const SKIPPABLE_MAGIC_BASE: u32 = 0x184D_2A50;

/// Streaming decompression core (file, stdout, or sink), optionally
/// dict-primed. Returns the number of bytes written.
///
/// A zstd stream is a sequence of frames: `cat a.zst b.zst` is a valid archive
/// that decodes to `a` then `b`, and skippable frames may sit between them. The
/// decoder's `Read` walks them itself, streaming, so one decoder takes the
/// whole archive whatever its size.
///
/// The input is recognised by its magic number before a decoder is built on
/// it, the way the reference command looks before it decodes: input that is
/// not a zstd stream is then copied through under `--pass-through`, or
/// refused as an unknown format. Bytes after a frame that are not a frame are
/// refused either way, with the reference command's message.
fn decompress_stream<R: Read, W: Write>(
    reader: R,
    mut writer: W,
    codecs: &mut Codecs,
    settings: &DecodeSettings,
) -> Result<u64> {
    // Parsed once for the whole run rather than per stream or per frame, and
    // decoded against by one decoder: the decoder keeps its buffers and, for
    // this one dictionary, the handle it took on the first frame.
    let Codecs {
        decoder: handle,
        decompressor,
        chunk,
        dictionary_size,
        trace,
        ..
    } = codecs;
    // The dictionary every frame here is decoded against, when there is one.
    let dictionary_size = if handle.is_some() {
        *dictionary_size
    } else {
        0
    };
    decompressor
        .set_max_window_size(settings.max_window)
        .map_err(|err| eyre!("{err}"))?;
    let mut source = BufReader::new(reader);
    let mut frames = 0u64;
    let mut written = 0u64;
    loop {
        // The magic is read ahead of the decoder and handed back to it in
        // front of the rest of the stream, so the source itself is never
        // rewound.
        let mut magic = [0u8; 4];
        let read = read_filling(&mut source, &mut magic)?;
        if read == 0 {
            // End of the last frame is success; end before the first one means
            // the input never held a frame at all, which is not an archive that
            // decodes to nothing. Under pass-through it is plain input like any
            // other, and passes through as the empty output (the reference
            // command refuses it there too; `cat`, `zcat -f` and `xzcat -f`
            // pass it).
            if frames == 0 && !settings.pass_through {
                bail!("unexpected end of file");
            }
            return Ok(written);
        }
        let is_frame = read == 4 && {
            let magic = u32::from_le_bytes(magic);
            magic == FRAME_MAGIC || magic & 0xFFFF_FFF0 == SKIPPABLE_MAGIC_BASE
        };
        if !is_frame {
            // Only input that is not zstd from its first byte is passed
            // through. What follows a frame and is not one is a damaged or
            // truncated archive, and copying it would hand its raw bytes on as
            // content with success; xz refuses it the same way, where the
            // reference command and gzip copy it.
            if settings.pass_through && frames == 0 {
                writer
                    .write_all(&magic[..read])
                    .wrap_err("failed to write the passed-through input")?;
                written += read as u64;
                written += io::copy(&mut source, &mut writer)
                    .wrap_err("failed to pass the input through")?;
                return Ok(written);
            }
            if read < 4 {
                bail!("unknown header");
            }
            bail!("unsupported format");
        }
        frames += 1;
        let stream = Frames {
            magic,
            source: &mut source,
            handle: handle.as_ref(),
            decompressor,
            chunk,
            trace,
            dictionary_size,
            settings,
        };
        // The clock is chosen once per stream, so an untraced one decodes
        // through bare reads.
        written += if stream.trace.is_some() {
            decode_frames(
                stream,
                &mut writer,
                &core::cell::Cell::new(Some(std::time::Duration::ZERO)),
            )?
        } else {
            decode_frames(stream, &mut writer, &Untimed)?
        };
    }
}

/// What [`decode_frames`] decodes: the stream from its first frame's magic
/// on, and the run's decoder state.
struct Frames<'a, R> {
    magic: [u8; 4],
    source: &'a mut R,
    handle: Option<&'a structured_zstd::decoding::DictionaryHandle>,
    decompressor: &'a mut structured_zstd::decoding::FrameDecoder,
    chunk: &'a mut Vec<u8>,
    trace: &'a mut Option<trace::Trace>,
    dictionary_size: u64,
    settings: &'a DecodeSettings,
}

/// Decode every frame from `frames.magic` on into `writer`, the source's
/// reads timed on `read_time`, until the stream ends or what follows is no
/// frame. Returns the number of bytes written.
fn decode_frames<R: Read, W: Write, C: ReadClock>(
    frames: Frames<'_, R>,
    writer: &mut W,
    read_time: &C,
) -> Result<u64> {
    use structured_zstd::decoding::StreamingDecoder;
    use structured_zstd::decoding::errors::FrameDecoderError;

    let Frames {
        magic,
        source,
        handle,
        decompressor,
        chunk,
        trace,
        dictionary_size,
        settings,
    } = frames;
    let mut stream = Watched {
        inner: io::Cursor::new(magic).chain(source),
        failed: false,
        read_time,
    };
    // Borrowed, not moved: the reader stays with the caller after the decoder.
    let mut decoder = match handle {
        // The dictionary constructors FORCE the supplied dictionary, which
        // the registration path does not: a frame may legitimately omit the
        // optional dictionary ID, and then nothing would select it.
        Some(h) => StreamingDecoder::new_with_decoder_and_dictionary_handle(
            &mut stream,
            &mut *decompressor,
            h,
        )
        .map_err(|err| eyre!("invalid dictionary: {err}"))?,
        None => StreamingDecoder::new_with_decoder(&mut stream, &mut *decompressor),
    };
    // The library computes the digest but does not compare it, leaving the
    // decision to the caller. For a command-line tool that decision is
    // made: the reference command validates by default, and `-t` exists to
    // answer exactly this question, so a frame whose stored checksum
    // disagrees with its data has to fail rather than decode quietly.
    // `--no-check` asks for the opposite. Read at the end of the frame, so
    // setting it after construction is in time.
    decoder
        .decoder_mut()
        .set_content_checksum(if settings.verify_checksum {
            structured_zstd::decoding::ContentChecksum::Verify
        } else {
            structured_zstd::decoding::ContentChecksum::None
        });
    // The decoder reads every frame and skippable frame of the stream, the
    // first one's header included, so whatever is wrong with the input is
    // reported here. The chunk is taken only now, by input that is a
    // frame: plain or empty input never decodes into it.
    chunk.resize(IO_CHUNK, 0);
    let err = match drain_decoded(
        &mut decoder,
        writer,
        chunk,
        trace,
        read_time,
        dictionary_size,
    ) {
        Ok(n) => return Ok(n),
        Err(err) => err,
    };
    // A source that fails is a read failure, whatever the decoder was
    // reading at the time, a frame header or a skippable frame's content.
    if decoder.get_ref().failed {
        bail!("failed to read the input: {err}");
    }
    match err
        .get_ref()
        .and_then(|e| e.downcast_ref::<FrameDecoderError>())
    {
        Some(&FrameDecoderError::WindowSizeTooBig {
            requested, limit, ..
        }) => bail!(
            "{}",
            window_too_large_message(requested, limit, settings.memory_overhead)
        ),
        Some(frame_err) => match after_frame_message(frame_err) {
            Some(message) => bail!("{message}"),
            None => bail!("invalid zstd frame: {frame_err:?}"),
        },
        None => Err(err).wrap_err("streaming decompression failed"),
    }
}

/// Hand everything `decoder` produces to `writer`, `buffer` at a time: the
/// decoder writes into it directly, so its length is the size of each write.
/// `io::copy` would do the same through an 8 KiB buffer of its own.
///
/// With a `trace` open, each frame the decoder finishes is recorded against
/// `dictionary_size`, timed as the decoder's own time on it: the calls into
/// the decoder from the end of the frame before to the moment this one is
/// verified, less the time its source took over the reads, which the source
/// times on `read_time`. The writes to `writer` and the trace line's own
/// write fall outside it, so the speed reported is the decoder's, whatever
/// the source and sink. The reference times the span between its begin and
/// end hooks instead, which takes in the caller's I/O of every block but the
/// last. When the trace closes, `read_time` stops, and so does the timing.
fn drain_decoded<
    R: Read,
    D: core::borrow::BorrowMut<structured_zstd::decoding::FrameDecoder>,
    C: ReadClock,
>(
    decoder: &mut structured_zstd::decoding::StreamingDecoder<R, D>,
    writer: &mut impl Write,
    buffer: &mut [u8],
    trace: &mut Option<trace::Trace>,
    read_time: &C,
    dictionary_size: u64,
) -> io::Result<u64> {
    // The decoder's time spent on the frame in progress, over the calls so far.
    let mut spent = std::time::Duration::ZERO;
    let mut written = 0u64;
    let read_sum = || read_time.spent();
    // The decoder's time since `mark`: the clock's, less the source's reads
    // in that span, which lie inside it.
    let since = |mark: std::time::Instant, read_at_mark: std::time::Duration| {
        mark.elapsed() - (read_sum() - read_at_mark)
    };
    // While the trace is open; a failed write closes it, and the plain drain
    // below takes the rest without timing or reporting anything.
    while trace.is_some() {
        let mut mark = std::time::Instant::now();
        let mut read_at_mark = read_sum();
        let read = decoder.read_reporting_frames(buffer, |frame| {
            let duration = spent + since(mark, read_at_mark);
            spent = std::time::Duration::ZERO;
            trace_frame(
                trace,
                &trace::Frame {
                    method: trace::Method::Decompress,
                    level: 0,
                    dictionary_size,
                    uncompressed_size: frame.decompressed_size,
                    compressed_size: frame.compressed_size,
                    duration,
                },
            );
            // A failed write closed the trace: the reads left in this call,
            // through any number of empty or skippable frames, go untimed.
            if trace.is_none() {
                read_time.stop();
            }
            mark = std::time::Instant::now();
            read_at_mark = read_sum();
        });
        spent += since(mark, read_at_mark);
        let n = match read {
            Ok(0) => return Ok(written),
            Ok(n) => n,
            Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
            Err(err) => return Err(err),
        };
        writer.write_all(&buffer[..n])?;
        written += n as u64;
    }
    read_time.stop();
    loop {
        let n = match decoder.read(buffer) {
            Ok(0) => return Ok(written),
            Ok(n) => n,
            Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
            Err(err) => return Err(err),
        };
        writer.write_all(&buffer[..n])?;
        written += n as u64;
    }
}

/// How the decoder's source accounts for the time its reads take, so a trace
/// can leave it out of the decoder's. Chosen once per stream: an untraced one
/// decodes through [`Untimed`], which compiles to the bare read.
trait ReadClock {
    /// Make one read, adding its time to the sum while timing.
    fn time<T>(&self, read: impl FnOnce() -> T) -> T;
    /// The reads' time so far.
    fn spent(&self) -> std::time::Duration;
    /// Stop timing: the trace that would read the sum has closed.
    fn stop(&self);
}

/// The clock of a stream no trace times: no reads timed, no time spent.
struct Untimed;

impl ReadClock for Untimed {
    #[inline(always)]
    fn time<T>(&self, read: impl FnOnce() -> T) -> T {
        read()
    }

    fn spent(&self) -> std::time::Duration {
        std::time::Duration::ZERO
    }

    fn stop(&self) {}
}

/// The clock of a traced stream: the sum while the trace is open, `None` once
/// it has closed. Shared with the drain, which reads it while the decoder
/// owns the source.
impl ReadClock for core::cell::Cell<Option<std::time::Duration>> {
    fn time<T>(&self, read: impl FnOnce() -> T) -> T {
        match self.get() {
            Some(sum) => {
                let started = std::time::Instant::now();
                let result = read();
                self.set(Some(sum + started.elapsed()));
                result
            }
            None => read(),
        }
    }

    fn spent(&self) -> std::time::Duration {
        self.get().unwrap_or_default()
    }

    fn stop(&self) {
        self.set(None);
    }
}

/// The decoder's source, remembering whether it failed, so a decode error can
/// be told apart from the input device failing under it, and timing its reads
/// on `read_time`.
struct Watched<'a, R, C> {
    inner: R,
    failed: bool,
    read_time: &'a C,
}

impl<R: Read, C: ReadClock> Read for Watched<'_, R, C> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let inner = &mut self.inner;
        let result = self.read_time.time(|| inner.read(buf));
        if let Err(e) = &result
            && e.kind() != io::ErrorKind::Interrupted
        {
            self.failed = true;
        }
        result
    }
}

/// The reference command's message for a frame whose window is past the
/// ceiling: libzstd's `frameParameter_windowTooLarge` through its decoding-error
/// line (fileio.c:2720), then the hint (fileio.c:2674-2684) naming the flag that
/// would let it decode. The `--memory` named is the window plus
/// `memory_overhead`, what `-M` counts besides it, so the limit it names does
/// decode the frame; it is left out when that sum has no value.
fn window_too_large_message(window: u64, limit: u64, memory_overhead: Option<u64>) -> String {
    use structured_zstd::decoding::MAX_DECODER_WINDOW_SIZE;

    let head = format!(
        "Decoding error (36) : Frame requires too much memory for decoding\n\
         Window size larger than maximum : {window} > {limit}"
    );
    // The window rounded up to a power of two, and the memory to whole MiB.
    let window_log = window.next_power_of_two().ilog2();
    if window <= MAX_DECODER_WINDOW_SIZE {
        match memory_overhead.and_then(|overhead| window.checked_add(overhead)) {
            Some(memory) => format!(
                "{head}\nUse --long={window_log} or --memory={}MB",
                memory.div_ceil(1 << 20)
            ),
            None => format!("{head}\nUse --long={window_log}"),
        }
    } else {
        format!(
            "{head}\nWindow log larger than ZSTD_WINDOWLOG_MAX={}; not supported",
            MAX_DECODER_WINDOW_SIZE.ilog2()
        )
    }
}

/// The reference command's message for what follows a frame and is not one:
/// fewer than four bytes, a magic number that is no frame's, or a skippable
/// frame cut short; and for a frame header it refuses outright. `None` for a
/// damaged frame, and for a source that failed rather than ended.
fn after_frame_message(
    err: &structured_zstd::decoding::errors::FrameDecoderError,
) -> Option<&'static str> {
    use structured_zstd::decoding::errors::{
        FrameDecoderError, FrameDescriptorError, ReadFrameHeaderError,
    };
    match err {
        // The reference command prints libzstd's `frameParameter_unsupported`
        // through its decoding-error line (fileio.c:2720).
        FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::InvalidFrameDescriptor(
            FrameDescriptorError::ReservedBitSet,
        )) => Some("Decoding error (36) : Unsupported frame parameter"),
        FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::BadMagicNumber(_)) => {
            Some("unsupported format")
        }
        FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::MagicNumberReadError(e))
            if e.kind() == io::ErrorKind::UnexpectedEof =>
        {
            Some("unknown header")
        }
        FrameDecoderError::FailedToSkipFrame => Some("skippable frame is truncated"),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// File-output plumbing (atomic temp-write + replace, alias guards). Unchanged
// from the original CLI; shared by compress and decompress.
// ---------------------------------------------------------------------------

fn ensure_distinct_paths(input: &Path, output: &Path) -> Result<()> {
    let canonical_input = match fs::canonicalize(input) {
        Ok(path) => path,
        Err(err) if err.kind() == ErrorKind::NotFound => {
            return Err(err).wrap_err("failed to open input file");
        }
        Err(err) => {
            return Err(err).wrap_err("failed to canonicalize input file");
        }
    };
    if output.exists() {
        let canonical_output =
            fs::canonicalize(output).wrap_err("failed to canonicalize existing output file")?;
        if canonical_input == canonical_output || paths_point_to_same_file(input, output)? {
            return Err(eyre!(
                "input and output paths refer to the same file: {input:?} -> {output:?}"
            ));
        }
    }
    Ok(())
}

/// Whether two paths name the same file, for a path that may not exist yet.
///
/// A path that is there is resolved whole, so a symlink counts as the file it
/// points at: `dict-link -> data` and `data` are one file, and a guard that
/// read the link's own name would let the pair through. The preflight also
/// compares a derived OUTPUT, which is usually still to be created and which
/// `canonicalize` therefore cannot resolve; that side falls back to its
/// canonical directory plus its own file name, which still collapses `.`, `..`
/// and any symlinked directory above it. A path whose directory cannot be
/// resolved either names nothing this run could collide with, so it simply does
/// not match.
fn names_the_same_file(left: &Path, right: &Path) -> Result<bool> {
    fn resolved(path: &Path) -> Option<PathBuf> {
        if let Ok(whole) = fs::canonicalize(path) {
            return Some(whole);
        }
        let parent = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty());
        let directory = fs::canonicalize(parent.unwrap_or_else(|| Path::new("."))).ok()?;
        Some(directory.join(path.file_name()?))
    }
    match (resolved(left), resolved(right)) {
        (Some(left), Some(right)) => Ok(left == right),
        _ => Ok(false),
    }
}

/// Whether two different paths name one file, as a hard link does: compared
/// by the identity the filesystem gives the file (see [`identity`]).
fn paths_point_to_same_file(input: &Path, output: &Path) -> Result<bool> {
    fs::metadata(input).wrap_err("failed to inspect input file metadata")?;
    fs::metadata(output).wrap_err("failed to inspect existing output file metadata")?;
    Ok(identity::of_path(input).is_some_and(|input| identity::of_path(output) == Some(input)))
}

#[cfg(windows)]
fn create_temporary_output_path(output: &Path) -> Result<PathBuf> {
    let (path, file) = create_temporary_output_file(output)?;
    drop(file);
    fs::remove_file(&path).wrap_err("failed to reserve temporary output path")?;
    Ok(path)
}

fn create_temporary_output_file(output: &Path) -> Result<(PathBuf, File)> {
    let parent = output.parent().unwrap_or_else(|| Path::new("."));
    let file_name = output
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("output.zst");
    for attempt in 0..u16::MAX {
        let candidate = parent.join(format!(
            ".{file_name}.tmp.{}.{}",
            std::process::id(),
            attempt
        ));
        match OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&candidate)
        {
            Ok(file) => return Ok((candidate, file)),
            Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,
            // Named after the output rather than the temporary: the reader
            // knows the output they asked for, and the usual cause is its
            // directory not being there.
            Err(err) => {
                return Err(err).wrap_err_with(|| output.display().to_string());
            }
        }
    }
    Err(eyre!("failed to allocate unique temporary output file"))
}

/// Move the finished temporary file into place.
///
/// `source_permissions` is the mode the content asks for — the file it came
/// from, or the strictest of the samples a dictionary was trained on. When
/// there is one it decides, replacing whatever the destination happened to
/// carry: an archive of a private file is private even if it lands on a
/// world-readable name, which is what the reference command does in both
/// directions. Only when the content names no mode of its own (stdin has no
/// file to take one from) does the destination keep the permissions it had.
fn replace_output_file(
    temporary_output_path: &Path,
    output: &Path,
    source_permissions: Option<fs::Permissions>,
) -> Result<()> {
    let output_kind = match output_destination_kind(output).inspect_err(|_err| {
        let _ = fs::remove_file(temporary_output_path);
    })? {
        Some(kind) => kind,
        None => {
            return match fs::rename(temporary_output_path, output) {
                Ok(()) => Ok(()),
                Err(err) => {
                    let _ = fs::remove_file(temporary_output_path);
                    Err(err).wrap_err("failed to move temporary output file into final location")
                }
            };
        }
    };
    if !output_kind.is_file() {
        let _ = fs::remove_file(temporary_output_path);
        return Err(eyre!(
            "output path exists and is not a regular file: {output:?}"
        ));
    }
    let original_permissions = match source_permissions {
        Some(permissions) => permissions,
        None => fs::metadata(output)
            .wrap_err("failed to read existing output file metadata")
            .inspect_err(|_err| {
                let _ = fs::remove_file(temporary_output_path);
            })?
            .permissions(),
    };
    if let Err(err) = fs::set_permissions(temporary_output_path, original_permissions.clone()) {
        let _ = fs::remove_file(temporary_output_path);
        return Err(err).wrap_err("failed to apply the output's permissions to temporary file");
    }

    #[cfg(not(windows))]
    {
        match fs::rename(temporary_output_path, output) {
            Ok(()) => Ok(()),
            Err(err) => {
                let _ = fs::remove_file(temporary_output_path);
                Err(err).wrap_err("failed to move temporary output file into final location")
            }
        }
    }

    #[cfg(windows)]
    {
        let backup_output_path = match create_temporary_output_path(output) {
            Ok(path) => path,
            Err(err) => {
                let _ = fs::remove_file(temporary_output_path);
                return Err(err).wrap_err("failed to allocate backup output path");
            }
        };
        if let Err(err) = fs::rename(output, &backup_output_path) {
            let _ = fs::remove_file(temporary_output_path);
            return Err(err).wrap_err("failed to move existing output file into backup location");
        }

        if let Err(err) = fs::rename(temporary_output_path, output) {
            let restore_result = fs::rename(&backup_output_path, output);
            let _ = fs::remove_file(temporary_output_path);
            if let Err(restore_err) = restore_result {
                return Err(err).wrap_err(format!(
                "failed to move temporary output file into final location; also failed to restore backup from {backup_output_path:?}: {restore_err}"
            ));
            }
            return Err(err).wrap_err("failed to move temporary output file into final location");
        }

        let _ = fs::remove_file(&backup_output_path);
        Ok(())
    }
}

fn output_destination_kind(output: &Path) -> Result<Option<std::fs::FileType>> {
    match fs::symlink_metadata(output) {
        Ok(metadata) => Ok(Some(metadata.file_type())),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
        Err(err) => Err(err).wrap_err("failed to inspect existing output path"),
    }
}

/// Whether `output` is written in place rather than through a temporary: it
/// exists, links followed, and is neither a regular file nor a directory: a
/// device, a pipe or a socket.
///
/// The reference command opens every destination with `fopen(.., "wb")`, and
/// asks about overwriting and installs its interrupt handler only for a
/// regular file (`fileio.c`, `FIO_openDstFile`, `addHandler`). The temporary
/// and rename that give a regular output its atomicity would, for a device,
/// replace the device node with a file, so those destinations take the
/// reference command's path: no question, no temporary, no handler. A link to
/// a regular file is not among them; the rename would replace the link, so it
/// stays refused below.
fn writes_in_place(output: &Path) -> Result<bool> {
    match fs::metadata(output) {
        Ok(metadata) => Ok(!metadata.is_file() && !metadata.is_dir()),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
        Err(err) => Err(err).wrap_err("failed to inspect existing output path"),
    }
}

/// Open a destination [`writes_in_place`] accepted, as the reference command
/// does: for writing, truncated where truncation means anything.
fn open_in_place(output: &Path) -> Result<File> {
    OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(output)
        .wrap_err_with(|| output.display().to_string())
}

fn ensure_regular_output_destination(output: &Path) -> Result<()> {
    if output_destination_kind(output)?.is_some_and(|kind| !kind.is_file()) {
        return Err(eyre!(
            "output path exists and is not a regular file: {output:?}"
        ));
    }
    Ok(())
}

/// Append a file extension to `path` (pending stdlib `PathBuf::add_extension`,
/// stable in 1.91).
fn add_extension<P: AsRef<Path>>(path: &Path, extension: P) -> PathBuf {
    let mut output = path.to_path_buf().into_os_string();
    output.push(extension.as_ref().as_os_str());
    output.into()
}

#[cfg(test)]
mod tests;