lzvolt 1.0.0

LZ, variable. A byte-oriented LZ77 codec that chooses its token layout per value, with hand-written assembly kernels per CPU part line. Decodes 14-83% faster than LZ4 on every shape measured, packs smaller, and reads raw LZ4 blocks too. Rust and C.
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
//! A byte-oriented LZ77 packer for entry values.
//!
//! Written rather than pulled in, for the same reason the protocol crate has no
//! dependencies: [`unpack`] reads bytes that came from a socket or a snapshot
//! file, so every length in them is attacker-controlled. Code on that path
//! should be short enough to audit in one sitting.
//!
//! # Format
//!
//! ```text
//! [header: 1-4 bytes][block][block]...[switch: 2x2 or 2x4 bytes, if hybrid]
//!
//! header := [cc h ppppp][more payload, most significant first]
//!           cc     = class, the header is cc+1 bytes long
//!           h      = hybrid: the stream changes split once, see the trailer
//!                    (class 0 has no room for it and needs none)
//!           p      = declared, big-endian across the header's bytes
//!
//! block  := [token: u8][extended literal length][literals]
//!           [offset: u16][extended match length]
//!           even token: 4 bits literal, 4 bits match
//!           wide token: 2 bits literal, 5 bits match, 1 bit repeat
//!           a field at its maximum means "read an extension chain"
//!           the match field holds length - 4
//! ```
//!
//! There is no split bit. A stream that is not hybrid is even throughout, and
//! the wide layout is reachable only through the switch. `docs/FORMAT.md` is
//! the normative description; this is the sketch.
//!
//! The final block carries literals and no match, which is what terminates the
//! stream — decoding stops when the declared length has been produced.
//!
//! The token's two fields are not fixed at four bits each. `split` chooses
//! between 4/4 and 2/6, and `hybrid` says the stream changes from one to the
//! other partway; the trailer then gives the two positions where that happens,
//! as an offset into the body and the count of bytes produced so far. Both are
//! two bytes for a value up to 64 KiB and four above it, a width that follows
//! from `declared` alone so the decoder knows it before it needs it. See
//! `Split` and `switch_width` below.
//!
//! Compatibility with LZ4 runs one way, and both directions are tested.
//! `our_decoder_reads_what_liblz4_wrote` passes: an LZ4 block decodes here
//! correctly. `liblz4_refuses_what_we_wrote` also passes, and that is the
//! interesting one — the even split *is* the LZ4 token layout, so the body of
//! such a value looks like an LZ4 block. It is not one. LZ4 also constrains
//! where a block may end, and this packer enforces none of that: it runs
//! matches to the final byte and then writes a zero token, which LZ4 has no
//! concept of.
//!
//! # What it is tuned for
//!
//! Values, not archives. A four-byte minimum match and a 16-bit offset keep the
//! inner loop to a hash lookup and a comparison, which is where the throughput
//! comes from; the ratio is deliberately traded away for it. On a store where
//! reads outnumber writes ten to one, the asymmetry is the point: unpacking is
//! a `memcpy` loop and costs a fraction of what packing does.
//!
//! # Verification
//!
//! [`unpack`] copies with raw pointers, so the checks in front of those copies
//! are the only thing between a malformed value and memory unsafety. Three
//! things stand behind that: every truncation and every single-bit flip of a
//! packed stream, thousands of multi-byte corruptions and streams that were
//! never packed at all, and all of it run under Miri, which reports
//! out-of-bounds access and uninitialised reads that a passing test would not.
//!
//! `cargo +nightly miri test --lib format`
//!
//! That belongs in CI. A change here that keeps the tests green but drops a
//! bounds check is exactly the failure this module is shaped to prevent.
//!
//! # What it does not do
//!
//! Entropy coding. That is where the remaining ratio lives, and it would cost
//! several times the CPU on both sides. If a namespace needs archival density
//! it wants a different tool, not a slower version of this one.

/// Shortest run worth encoding as a reference rather than as literals.
///
/// Below four bytes a match costs more than it saves: the token plus a two-byte
/// offset is three bytes already.
const MIN_MATCH: usize = 4;

/// Longest backward reference. Sixteen bits is the whole reason the inner loop
/// stays cheap, and values are small enough that a longer window would find
/// almost nothing.
const MAX_OFFSET: usize = 65_535;

/// Positions indexed by a hash of the four bytes starting there.
///
/// A single slot per hash, so a collision simply loses a match rather than
/// costing a search. That is the trade that keeps packing near memory speed.
///
/// A second candidate per slot -- keeping the previous occupant and taking
/// whichever gives the longer match -- was built and measured twice, and
/// neither form pays.
///
/// Used wherever it matches, it does not lengthen matches, it creates them:
/// where the newer candidate lost to a collision the older one wins, at a
/// position the search would have walked past. varied_64k went to 2.07x from
/// 1.98x and to 3945 blocks from 3618. Denser and slower to read, which is the
/// trade this format exists to refuse.
///
/// Restricted to positions that already matched, so it can only lengthen, the
/// shape is right -- 3503 blocks at 18.7 bytes each and 2.02x -- and it still
/// does not pay: decoding records_64k fell 11% and packing varied_64k 23%, for
/// two table loads and two verifies on every position visited.
///
/// Three attempts on this axis now, counting reaching two bytes past a match
/// (see [`LAZY_REACH`]). Each moved the ratio and left decoding where it was.
///
/// Eleven bits, not twelve, and the reason is the cache rather than the hash.
/// The table shares L1 with the data it indexes, so every slot it gains is a
/// line the input loses. Measured on a 64 KiB value, where the two are actually
/// in contention:
///
/// ```text
///   bits   table     GiB/s   ratio
///     10    4 KiB     0.78    1.86x
///     11    8 KiB     0.72    1.91x
///     12   16 KiB     0.60    1.96x
///     13   32 KiB     0.55    1.94x
/// ```
///
/// Halving the table buys 21% and costs 2.5% of the ratio; halving it again
/// buys 30% and costs 5%. Eleven is where that trade stops being obviously
/// worth it. On a 4 KiB value, where nothing is in contention, eleven measures
/// 1% ahead of twelve at an identical ratio -- so this is not a compromise for
/// small values, it is simply better there too.
const HASH_BITS: usize = 12;

/// Table bits for a value large enough that the table competes with it for L1.
///
/// The full table is always allocated; this only narrows how much of it a large
/// value touches, and touched lines are what the cache actually pays for.
///
/// Re-measured against the single-pass packer, because the number above was
/// settled with a method that could not resolve less than 8%. It holds, and for
/// a better reason than cache pressure. On 64 KiB of data that compresses
/// two-fold:
///
/// ```text
///   bits   table    packing    ratio   blocks
///     11   8 KiB   0.65 GiB/s  1.98x     3618
///     12  16 KiB   0.52        2.03x     3976
///     13  32 KiB   0.40        2.08x     4306
/// ```
///
/// A wider table does find more matches -- but they are *short* ones, and a
/// short match is a whole block: a token decode and an offset load for a
/// handful of bytes. Nineteen percent more blocks at thirteen bits is nineteen
/// percent more per-block work on every read, against five percent of ratio
/// once. Decoding is what this store does most, so the wider table is worse on
/// the axis that matters and slower to pack besides.
///
/// This is the same trade liblz4 makes and loses: 2.00x at 4872 blocks and 5.06
/// GiB/s decoding, against our 1.98x at 3618 and 7.27.
///
/// Re-measured again once the hash grew to five bytes, since a hash that stops
/// proposing four-byte matches might have made a wider table affordable. It
/// does not. On 64 KiB of `varied`, cycles per byte and packed bytes:
///
/// ```text
///   bits    11             12             13
///          3.459  33180   3.900  32490   5.018  31968
/// ```
///
/// Eleven still wins by more than a wider table can return in ratio.
const HASH_BITS_LARGE: usize = 11;

/// Where the table stops being free and starts being a rival for cache.
///
/// Below this a value and the whole table sit in L1 together, and the wider
/// table is simply better: fewer collisions, so fewer verify loads that go to a
/// random address only to fail. Incompressible data is where that shows up
/// hardest, since every collision there is pure waste -- 4 KiB of noise packs at
/// 4.47 GiB/s with twelve bits and 3.74 with eleven.
///
/// Above it the relationship inverts, because the table is displacing the data:
/// a 64 KiB value packs at 0.61 GiB/s with twelve bits and 0.87 with eleven.
const NARROW_TABLE_ABOVE: usize = 8192;
const HASH_SIZE: usize = 1 << HASH_BITS;

/// A slot that has never been written.
///
/// Zero would be the obvious choice and it costs a branch: the search would
/// have to ask "is this slot empty" before asking "is this candidate usable",
/// and the first question is only ever asked to avoid mis-answering the second.
///
/// Any value far above the largest reachable position folds the two into one:
/// the search rejects a candidate that is not behind the cursor, and this one
/// never is. No position can collide with it, since a value would have to be
/// two gigabytes long to reach it.
///
/// The table used to hold the position *plus one*, left from when zero was the
/// empty marker, and the search subtracted it back on every position visited --
/// two instructions of the fourteen in the inner loop, for a distinction the
/// sentinel had already made unnecessary.
const EMPTY: u32 = 0x8000_0000;

/// A table slot, so the same pass can be compiled over two widths.
///
/// The profile says the table is where the packer spends its time: on 4 KiB of
/// records, the store into it and the load that stalls behind it are the two
/// largest single instructions in the kernel. A 64-byte line holds sixteen
/// `u32` or thirty-two `u16`, so the same four thousand slots are 256 lines or
/// 128 -- and touched lines are what the cache charges for.
///
/// A position fits in sixteen bits whenever the value does, which the window
/// already bounds at [`MAX_OFFSET`]. The sentinel is the only thing that does
/// not carry over: [`EMPTY`] is far above any reachable position and there is
/// no room for that in sixteen bits. `0xFFFF` serves instead, and is reachable
/// only by a value long enough that this width is not used for it.
///
/// This is liblz4's layout, which holds `u16` entries for an input that fits
/// the window and widens above it.
trait Slot: Copy {
    /// A slot that has never been written.
    const EMPTY: Self;
    /// Largest value this width may be used for. Above it a position would not
    /// fit, or would collide with the sentinel.
    const LIMIT: usize;
    fn position(self) -> usize;
    fn of(at: usize) -> Self;
}

impl Slot for u32 {
    const EMPTY: u32 = EMPTY;
    const LIMIT: usize = usize::MAX;
    #[inline(always)]
    fn position(self) -> usize {
        self as usize
    }
    #[inline(always)]
    fn of(at: usize) -> u32 {
        at as u32
    }
}

impl Slot for u16 {
    const EMPTY: u16 = 0xFFFF;
    /// The search stops at `len - HASH_WORD`, so a value of this length never
    /// reaches position `0xFFFF` and the sentinel stays unambiguous.
    const LIMIT: usize = 0x1_0000;
    #[inline(always)]
    fn position(self) -> usize {
        self as usize
    }
    #[inline(always)]
    fn of(at: usize) -> u16 {
        at as u16
    }
}

/// The match-finding table, held across calls.
///
/// Clearing this was the dominant cost for small values: sixteen kilobytes of
/// initialisation against a 512-byte value is thirty-two times more setup than
/// work, and measured at roughly 88% of the time such a call took.
///
/// It is never cleared. An entry left from a previous value is not a
/// correctness problem, because a candidate is only used after being checked
/// against the current position and then verified byte for byte — a stale one
/// yields a short match that is discarded like any other. The cost is a
/// slightly worse ratio in the first few bytes of a value, which is a good
/// trade for removing the setup entirely.
#[derive(Debug)]
pub struct Packer {
    /// The position, with [`EMPTY`] for a slot never written.
    table: Box<[u32; HASH_SIZE]>,
}

impl Default for Packer {
    fn default() -> Self {
        Packer {
            table: Box::new([EMPTY; HASH_SIZE]),
        }
    }
}

impl Packer {
    pub fn new() -> Packer {
        Packer::default()
    }

    /// Pack `input` into `out`. See [`pack`] for the contract.
    pub fn pack(&mut self, input: &[u8], out: &mut Vec<u8>) -> bool {
        pack_dispatch(input, out, &mut self.table)
    }
}

/// The kernel where this target has one that implements the production pass,
/// and the portable packer otherwise.
///
/// There is no fallback behind this. The kernel answers 0 for exactly the cases
/// [`pack_with`] answers `false` for -- a value shorter than the hash word, one
/// the probe writes off, and one whose output did not come out smaller -- so a
/// declined pack is an answer, not a request to try again in another language.
/// The byte-for-byte test is what makes that safe to rely on.
///
/// AArch64 is deliberately not routed here. Its kernel implements the eager,
/// fixed-split search rather than this one, so it would pack correctly and
/// differently, and a store whose compressed form depends on which machine
/// wrote it is a store that cannot be replicated.
#[inline]
fn pack_dispatch(input: &[u8], out: &mut Vec<u8>, table: &mut [u32; HASH_SIZE]) -> bool {
    if crate::kernel::encode::kernel_is_production_packer() {
        return crate::kernel::encode::pack_asm(input, out, table.as_mut_slice()).is_some();
    }
    pack_with(input, out, table)
}

/// The portable packer, reachable without the kernel taking the call.
///
/// [`Packer`] dispatches to the assembly where a target has it, which is what
/// production wants and what makes the two impossible to compare inside one
/// binary. A profiler needs both in one process: separate builds put the code
/// at different addresses, under different page mappings, with a different
/// heap, and a two-percent difference does not survive that.
///
/// So this is the same pass with the dispatch removed. It is not a fallback and
/// nothing in the store calls it.
#[derive(Debug)]
pub struct PortablePacker {
    table: Box<[u32; HASH_SIZE]>,
}

impl Default for PortablePacker {
    fn default() -> Self {
        PortablePacker {
            table: Box::new([EMPTY; HASH_SIZE]),
        }
    }
}

impl PortablePacker {
    pub fn new() -> PortablePacker {
        PortablePacker::default()
    }

    /// Pack `input` into `out`. See [`pack`] for the contract.
    pub fn pack(&mut self, input: &[u8], out: &mut Vec<u8>) -> bool {
        pack_with(input, out, &mut self.table)
    }
}

/// The same pass over a sixteen-bit table, for measuring that width.
///
/// Not on any production path and deliberately so. Narrowing the table changes
/// nothing about which matches are found -- the positions are identical and so
/// is the output -- but it changes it for whichever packer is narrowed, and the
/// assembly kernel is still thirty-two bits wide. Switching one of them alone
/// would leave the two producing different bytes for the same value, and the
/// test that says they do not is the only reason either is trusted.
///
/// So the width is measured first and migrated afterwards, both sides together.
/// `Slot::LIMIT` bounds what this may be handed.
#[derive(Debug)]
pub struct NarrowPacker {
    table: Box<[u16; HASH_SIZE]>,
}

impl Default for NarrowPacker {
    fn default() -> Self {
        NarrowPacker {
            table: Box::new([<u16 as Slot>::EMPTY; HASH_SIZE]),
        }
    }
}

impl NarrowPacker {
    pub fn new() -> NarrowPacker {
        NarrowPacker::default()
    }

    /// Largest value this packer accepts. Above it a position does not fit.
    pub const LIMIT: usize = <u16 as Slot>::LIMIT;

    /// Pack `input` into `out`. Returns `false` for a value this width cannot
    /// index, as well as for one that did not get smaller.
    pub fn pack(&mut self, input: &[u8], out: &mut Vec<u8>) -> bool {
        out.clear();
        if input.len() < HASH_WORD || input.len() > Self::LIMIT {
            return false;
        }
        if !worth_packing(input) {
            return false;
        }
        if input.len() > NARROW_TABLE_ABOVE {
            pack_pass::<{ (64 - HASH_BITS_LARGE) as u32 }, u16>(
                input,
                out,
                &mut self.table,
                EVEN,
                LAZY,
                ADAPTIVE,
            );
        } else {
            pack_pass::<{ (64 - HASH_BITS) as u32 }, u16>(
                input,
                out,
                &mut self.table,
                EVEN,
                LAZY,
                ADAPTIVE,
            );
        }
        worth_storing(out.len(), input.len())
    }
}

/// Why a packed value could not be read back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackError {
    /// The stream ended in the middle of a field.
    Truncated,
    /// A backward reference pointed before the start of the output.
    BadOffset,
    /// The stream declared a length it then did not produce, or exceeded it.
    LengthMismatch,
    /// The declared length was larger than any value may be.
    TooLarge,
    /// The buffer handed in cannot hold the length the stream declares.
    ///
    /// Only [`unpack_into_slice`] can produce this. The `Vec` entry points
    /// grow their own output and never run out.
    OutputTooSmall,
    /// The header used a longer class than its length needs.
    ///
    /// Decoding such a stream would work — the length reads back correctly —
    /// and it is refused anyway, so that one length has exactly one encoding.
    /// Anything that compares or hashes packed bytes to decide two values are
    /// the same depends on that, and nothing in the stream would reveal the
    /// difference to it.
    NonCanonicalHeader,
}

impl std::fmt::Display for PackError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            PackError::Truncated => "packed value ends mid-field",
            PackError::BadOffset => "backward reference points before the output",
            PackError::LengthMismatch => "packed value does not produce its declared length",
            PackError::TooLarge => "packed value declares an implausible length",
            PackError::NonCanonicalHeader => {
                "packed value's header is longer than its length needs"
            }
            PackError::OutputTooSmall => "output buffer is smaller than the declared length",
        })
    }
}

impl std::error::Error for PackError {}

/// Largest value this will unpack, as a guard against a declared length that
/// would otherwise reserve gigabytes before failing.
const MAX_UNPACKED: usize = 512 * 1024 * 1024;

/// Hash four bytes the caller has already read.
///
/// It takes the word rather than a slice because the search needs those same
/// four bytes a moment later to reject a candidate, and a slice-taking hash
/// read them a second time.
///
/// That was measured and it is neutral: LLVM already folded the second read
/// away, since the only write between the two is to the table, which it can
/// prove does not alias the input. The redundancy was in the source and never
/// reached the machine code. Kept because saying it once is clearer than
/// relying on the compiler to notice, not because it is faster.
#[inline]
fn hash4(word: u32, shift: u32) -> usize {
    (word.wrapping_mul(0x9E37_79B1) >> shift) as usize
}

/// How far to shift the hash for a value of this length. See
/// [`NARROW_TABLE_ABOVE`].
#[inline]
fn hash_shift(len: usize) -> u32 {
    if len > NARROW_TABLE_ABOVE {
        (64 - HASH_BITS_LARGE) as u32
    } else {
        (64 - HASH_BITS) as u32
    }
}

/// How many bytes the hash reads, which is more than it uses: five bytes are
/// hashed and eight are loaded, because one unaligned 64-bit read is cheaper
/// than assembling five bytes.
const HASH_WORD: usize = 8;

/// The low five bytes at `at`, hashed.
///
/// Both references hash five bytes on a 64-bit target and we hashed four, which
/// was the last thing separating us on data that only partly repeats.
///
/// A four-byte hash proposes every position that shares four bytes, and a
/// four-byte match is a whole block -- a token, an offset, and a literal run cut
/// in two -- bought for nothing. Those are the matches a wider table finds more
/// of, which is why widening ours always made it slower: twelve bits on a 64 KiB
/// value cost 50% and bought 2.6% of ratio. Hashing five bytes does the
/// opposite. It does not propose them at all, so the same table finds fewer and
/// longer matches:
///
/// ```text
///                      four bytes        five bytes
///     varied_64k    3.719   33237 B   3.459   33180 B
///     varied_4k     2.916    2249     2.711    2229
///     records_64k   0.996    6827     0.910    6509
///     records_2k    1.095     392     1.038     394
///     records_512   1.592     192     1.351     195
/// ```
///
/// Faster and denser at once nearly everywhere, and 4.7% denser on 64 KiB of
/// records. The exception is a 512-byte value, where three bytes go the other
/// way: short values have proportionally more four-byte matches worth taking,
/// and there is no room to lose them. Switching the hash on size the way the
/// references switch their table was measured and is worse than either -- the
/// test lands in the inner loop and costs more than it saves, because we cannot
/// compile the loop twice the way a C macro does.
///
/// Wider tables remain wrong even with this: at twelve bits a 64 KiB `varied`
/// value costs 3.900 against 3.459 for 690 bytes of ratio, and at thirteen it
/// is 5.018.
#[inline]
fn hash5(seq: u64, shift: u32) -> usize {
    ((seq << 24).wrapping_mul(889_523_592_379u64) >> shift) as usize
}

/// The eight bytes at `at`, as one word.
///
/// # Safety
///
/// `at + 8 <= input.len()`, which the search bound guarantees.
#[inline]
unsafe fn word8(input: &[u8], at: usize) -> u64 {
    u64::from_le(input.as_ptr().add(at).cast::<u64>().read_unaligned())
}

/// The four bytes at `at`, as one word.
///
/// # Safety
///
/// `at + 4 <= input.len()`. Every caller is inside the search loop, whose
/// condition is `at + MIN_MATCH <= input.len()`, or is reading a candidate
/// position which is strictly behind `at`.
#[inline]
unsafe fn word4(input: &[u8], at: usize) -> u32 {
    // The checked form goes through `try_into` and a `Result`, which profiling
    // found at 3.8% of the packer -- for a bound the loop has already tested.
    u32::from_le(input.as_ptr().add(at).cast::<u32>().read_unaligned())
}

/// How fast the search gives up. After `1 << SKIP_TRIGGER` consecutive misses
/// the cursor starts advancing by more than one byte, and keeps accelerating.
///
/// Without it, data that does not compress is walked one byte at a time to no
/// purpose — and even data that does compress spends most positions between
/// matches. The cost is a slightly worse ratio, since a skipped position is a
/// match never looked for. LZ4 waits for sixty-four misses and we waited with
/// it, which was inherited rather than measured. Thirty-two is better on every
/// shape here, and on two of them it is better on *both* axes -- skipping
/// sooner changes which positions get visited, and on `records` the ones it
/// lands on happen to be worth more:
///
/// ```text
///   misses before skipping        64      32      16
///     noise_512                1.597   1.200   0.910
///     noise_4k                 0.375   0.276   0.202
///     records_512     cycles   1.765   1.598   1.578
///                     bytes      191     192     191
///     records_2k      cycles   1.210   1.079   1.098
///                     bytes      394     392     400
///     records_4k      cycles   1.046   0.962   0.958
///                     bytes      603     601     609
/// ```
///
/// Sixteen is faster still and would halve noise again, but it starts costing
/// ratio on the values a store actually keeps -- one and a half percent on
/// `records_2k`. Density is what this is being sold on and packing happens once
/// per write, so that is the wrong side to spend on.
const SKIP_TRIGGER: usize = 5;

/// How long a match has to be before lazy stops looking for a better one.
///
/// Lazy matching pays for itself when the match in hand is short, because the
/// one a byte later can be much longer. Once it is already long the second
/// search is nearly always wasted: on 64 KiB of `varied` the probe runs 4138
/// times and wins 521, and on `records`, where matches average nineteen bytes,
/// it is worse than that.
///
/// The gate costs one comparison and buys, against no gate at all:
///
/// ```text
///   gate at              none      12      16      20      24
///     records_4k        1.046   0.945   0.962   0.949   0.976
///     records_2k        1.210   1.080   1.079   1.092   1.090
///     records_64k       1.081   0.999   1.009   1.001   1.022
///     varied_64k        3.766   3.509   3.617   3.669   3.748
///     varied_64k    B   33117   33283   33237   33161   33123
/// ```
///
/// Twelve is a shade faster and a shade worse on ratio; sixteen is where the
/// two stop trading against each other. Matches shorter than this are exactly
/// the ones worth improving, and they are the ones the gate lets through.
const LAZY_UNTIL: usize = 16;

/// Write a length that did not fit in a nibble: 255s until a smaller byte.
/// # Safety
///
/// The cursor must have room for the chain; [`Cursor::room`] provides it.
#[inline]
unsafe fn put_extended(mut remaining: usize, out: &mut Cursor) {
    while remaining >= 255 {
        out.byte(255);
        remaining -= 255;
    }
    out.byte(remaining as u8);
}

/// Read the counterpart of [`put_extended`], bounded so a run of 255s cannot
/// spin forever on a corrupt stream.
fn get_extended(input: &[u8], at: &mut usize) -> Result<usize, PackError> {
    let mut total = 0usize;
    loop {
        let byte = *input.get(*at).ok_or(PackError::Truncated)?;
        *at += 1;
        total = total
            .checked_add(byte as usize)
            .ok_or(PackError::TooLarge)?;
        if byte != 255 {
            return Ok(total);
        }
        if total > MAX_UNPACKED {
            return Err(PackError::TooLarge);
        }
    }
}

/// Pack `input` into `out`, replacing whatever it held.
///
/// Returns `false` when the result would not be smaller, which is the common
/// case for short values and for anything already compressed. The caller stores
/// the original in that case, so a namespace holding JPEGs pays the packing
/// attempt and nothing else.
pub fn pack(input: &[u8], out: &mut Vec<u8>) -> bool {
    let mut table = Box::new([EMPTY; HASH_SIZE]);
    pack_dispatch(input, out, &mut table)
}

/// How far the probe reads before writing a value off, and how many slots it
/// reads it into.
///
/// A kilobyte, split across [`PROBE_WINDOWS`] windows, because the question is
/// only whether the value repeats itself at all.
///
/// Eight bits, not more, because the table is zeroed on every call and that is
/// the probe's whole fixed cost -- it returns on one of the first few positions
/// whenever the data repeats, so the memset is what a compressible value
/// actually pays. Halving it from nine bits halves that: with nine, probing
/// costs 2.9% on `records_4k` and 3.1% on `varied_4k`; with eight, 1.6% and
/// 2.0%, at identical output on every shape in the corpus.
///
/// Collisions do not cost accuracy the way they would in the search -- equal
/// words always land in the same slot, and data that compresses repeats often
/// enough that one pair survives a quarter of the slots.
const PROBE: usize = 1024;
const PROBE_BITS: u32 = 8;

/// How many places in the value the probe looks.
///
/// Refusing wrongly costs the whole ratio, not a few percent of throughput, so
/// where the probe reads matters more than how much. Two windows -- head and
/// middle -- judge a value on a tenth of it and miss anything compressible that
/// happens to sit elsewhere, which is not a contrived shape: a buffer written
/// at a high offset, a fixed-size record partly filled, a ciphertext followed
/// by plaintext. Measured on 64 KiB values, packed bytes:
///
/// ```text
///                                    2 windows   4   8   16   unprobed
///   40 KiB of noise then zeros          65536     41276 all the same
///   noise with 30 KiB of zeros mid      65536     35833 all the same
/// ```
///
/// Two windows store both whole. Four recover them completely.
///
/// More than four costs more than it buys, because each window restarts the
/// miss counter and pays its own run-up before the cursor starts skipping.
/// That is charged against incompressible data, which is the case the probe
/// exists for:
///
/// ```text
///   cycles per byte      2       4       8      16   unprobed
///     noise_4k       0.274   0.362   0.471   0.594      0.498
///     noise_64k      0.017   0.022   0.030   0.037      0.156
/// ```
///
/// At eight the probe has nearly stopped paying for itself at 4 KiB, and at
/// sixteen it is worse than not probing at all.
const PROBE_WINDOWS: usize = 4;

/// Only values above this are probed. Below it a full search is a couple of
/// thousand cycles and there is nothing worth saving.
///
/// Two kilobytes rather than four, because four leaves the one shape the probe
/// was built for outside it: a 4 KiB value that does not compress is exactly
/// the size the threshold excluded, and it packs at 0.709 cycles per byte
/// unprobed against 0.362 probed. Rather than one, because a value of exactly
/// two kilobytes then stays outside and keeps its speed -- probing from one
/// kilobyte costs `records_2k` 3.9% and buys nothing it does not already get
/// here.
///
/// ```text
///                unprobed   >4096   >2048   >1024
///   noise_4k        0.709   0.709   0.362   0.371
///   records_2k      1.134   1.134   1.126   1.178
///   records_4k      0.979   0.979   0.995   1.013
///   varied_4k       2.657   2.657   2.711   2.761
/// ```
const PROBE_ABOVE: usize = 2048;

/// Whether the value repeats itself inside its first [`PROBE`] bytes.
///
/// A value that does not is not going to compress, and searching the rest of it
/// produces a stream longer than the input that [`pack_with`] then throws away.
/// That is the shape this packer was furthest behind on: 0.22 cycles per byte
/// spent on 64 KiB of noise to answer a question a kilobyte could answer.
///
/// The probe has its own table and runs before the search, so the search sees
/// exactly the slots it would have seen and the packed bytes are unchanged. Two
/// attempts to answer this inside the search instead -- one testing a byte
/// budget on the miss path, one running the loop to a checkpoint and continuing
/// past it -- both cost 7.5% on compressible 64 KiB, because splitting that
/// loop in two costs more than the branch did.
///
/// It skips on misses exactly as the search does, so it is cheap from both
/// Whether a packed result is worth storing instead of the original bytes.
///
/// Was `out.len() < input.len()`, which says yes to saving a single byte. That
/// is a bad trade and the measurement is unambiguous: reading a packed value
/// costs a factor of four to five against the memcpy that reads a stored one,
/// at every size, because one is arithmetic and the other is not. The space is
/// the only thing bought, so the space is what has to clear a bar.
///
/// An eighth. A 512-byte record packs to 195 and clears it by a mile; a
/// 32-byte one saved exactly one byte -- 3% for that factor of five -- and no
/// longer qualifies. The floor of eight bytes keeps the rule from admitting
/// tiny absolute wins on tiny values where the ratio flatters them.
///
/// Where the trade is genuinely good this changes nothing: every shape the
/// benchmark packs saves between 30% and 62%. See docs/MEASUREMENTS.md, the
/// sweep from L1 to RAM.
#[inline]
fn worth_storing(packed: usize, original: usize) -> bool {
    let saved = match original.checked_sub(packed) {
        Some(n) => n,
        None => return false,
    };
    saved >= 8 && saved * 8 >= original
}

/// ends: on data that repeats it returns on one of the first few positions, and
/// on data that does not it accelerates away rather than walking the kilobyte.
#[inline(never)]
fn worth_packing(input: &[u8]) -> bool {
    if input.len() <= PROBE_ABOVE {
        return true;
    }
    let mut seen = [0u32; 1 << PROBE_BITS];
    // Windows spread across the value rather than one long one at the front, so
    // it is judged on more than its head. Positions are absolute and the table
    // is shared between windows, so a word in the last window still matches one
    // recorded in the first -- which is what finds a value built from two
    // identical halves.
    let wide = PROBE / PROBE_WINDOWS;
    let step = input.len() / PROBE_WINDOWS;
    for i in 0..PROBE_WINDOWS {
        let start = i * step;
        let last = (start + wide).min(input.len() - MIN_MATCH);
        let mut at = start;
        let mut misses = 1usize << SKIP_TRIGGER;
        while at <= last {
            // SAFETY: `at <= last` is `at + MIN_MATCH <= input.len()`.
            let here = unsafe { word4(input, at) };
            let slot = hash4(here, 32 - PROBE_BITS);
            let stored = seen[slot];
            // Stored one past the position, so an untouched slot is zero and
            // position zero is not mistaken for one.
            seen[slot] = at as u32 + 1;
            // SAFETY: `stored - 1` is a position one of these loops read at.
            if stored != 0 && unsafe { word4(input, stored as usize - 1) } == here {
                return true;
            }
            at += misses >> SKIP_TRIGGER;
            misses += 1;
        }
    }
    false
}

/// The body, with the match table supplied so it can outlive one call.
fn pack_with(input: &[u8], out: &mut Vec<u8>, table: &mut [u32; HASH_SIZE]) -> bool {
    out.clear();
    // Eight, not four: the hash reads eight bytes at every position it visits,
    // so a shorter value has nothing that can be searched. Nothing is lost --
    // a header, a token and an offset already outweigh a seven-byte value.
    if input.len() < HASH_WORD {
        return false;
    }
    if !worth_packing(input) {
        return false;
    }

    // One pass. The split is decided while packing, not by packing twice.
    // Which of the two instantiations, decided once for the whole value.
    if input.len() > NARROW_TABLE_ABOVE {
        pack_pass::<{ (64 - HASH_BITS_LARGE) as u32 }, u32>(
            input, out, table, EVEN, LAZY, ADAPTIVE,
        );
    } else {
        pack_pass::<{ (64 - HASH_BITS) as u32 }, u32>(input, out, table, EVEN, LAZY, ADAPTIVE);
    }
    worth_storing(out.len(), input.len())
}

/// How far past a match the search looks for a longer one.
///
/// One, and the reason two is not better is worth writing down, because the
/// obvious argument says it should be. A longer match is one block instead of
/// two and the decoder is paid by blocks, so reaching further ought to pay
/// twice over. Measured at two:
///
/// ```text
///   varied_64k   3618 -> 3428 blocks   18.1 -> 19.1 B/block   1.98x -> 1.99x
///   decoding                                                   7.51 -> 7.51
///   packing records_64k                                        2.74 -> 2.27
/// ```
///
/// Five percent fewer blocks, five percent more bytes in each, and not one
/// percent of decoding. The block counts moved and the cost per block moved
/// with them: extended match lengths went from 16.8% of blocks to 18.0% and
/// extended literal runs from 15.3% to 17.4%, because a longer match overflows
/// its field and the bytes the step turns loose lengthen the literal run past
/// its own. Every one of those is a chain of 255s -- a dependent load in the
/// decoder's block, which is exactly what the wide split was introduced to
/// remove.
///
/// So bytes per block is not the lever by itself. It is bytes per block *at a
/// fixed cost per block*, and a block pushed over a field boundary is not fixed
/// cost. The wide split worked because it removed chains; the first lazy step
/// worked because it lengthened matches that still fit. This one lengthens them
/// past the fit and gives the gain straight back, and costs 17% of packing to
/// do it.
const LAZY_REACH: usize = 1;

/// Blocks the running window looks back over before changing the split.
///
/// A window rather than a total, because a value is not required to have one
/// character throughout -- a document with a blob in the middle changes shape
/// partway, and a decision taken over the whole value gets such a value wrong
/// no matter which way it goes. Sixteen is short enough that a value of a
/// hundred blocks still spends most of itself in the right split, and long
/// enough that a handful of unusual blocks at the start cannot flip it.
const SPLIT_WINDOW: usize = 16;

/// Whether the pass may change split partway. Off for the reference the
/// assembly packer is diffed against, which has one split and no window.
const ADAPTIVE: bool = true;
#[cfg(test)]
const FIXED: bool = false;

/// Whether the search may give up a byte to look for a longer match.
///
/// A constant with two call sites rather than a setting: the packer always
/// wants it, and the assembly kernel does not have it, so the differential test
/// needs a reference that searches the way the kernel does. Without that the
/// test compares two different algorithms and can only pass by accident -- which
/// is exactly what it did until a `varied` case was added to its corpus.
const LAZY: bool = true;
/// The other value, used only by the differential test below.
#[cfg(test)]
const EAGER: bool = false;

/// The packer as the assembly kernel implements it, for the differential test.
#[cfg(test)]
fn pack_with_eager(input: &[u8], out: &mut Vec<u8>, table: &mut [u32; HASH_SIZE]) -> bool {
    out.clear();
    // Eight, not four: the hash reads eight bytes at every position it visits,
    // so a shorter value has nothing that can be searched. Nothing is lost --
    // a header, a token and an offset already outweigh a seven-byte value.
    if input.len() < HASH_WORD {
        return false;
    }
    if input.len() > NARROW_TABLE_ABOVE {
        pack_pass::<{ (64 - HASH_BITS_LARGE) as u32 }, u32>(input, out, table, EVEN, EAGER, FIXED);
    } else {
        pack_pass::<{ (64 - HASH_BITS) as u32 }, u32>(input, out, table, EVEN, EAGER, FIXED);
    }
    worth_storing(out.len(), input.len())
}

/// One pass, deciding the split as it goes.
///
/// The header is written first and patched last, which works because its length
/// depends only on the declared size -- known at the first byte -- and not on
/// the two flag bits in it. So the pass commits to nothing up front: it starts
/// in `split`, watches a running window of how often the match field overflows,
/// and if it does so in more than half of the last [`SPLIT_WINDOW`] blocks it
/// changes split there and then, records where, and sets the bit at the end.
///
/// This replaces packing the value twice and throwing the first away. It also
/// answers a question two passes could not: which split fits *this part* of the
/// value. A sample can be unrepresentative and a total cannot see a change of
/// character; a window sees both.
fn pack_pass<const SHIFT: u32, S: Slot>(
    input: &[u8],
    out: &mut Vec<u8>,
    table: &mut [S; HASH_SIZE],
    start_split: Split,
    lazy: bool,
    adaptive: bool,
) {
    // Written with the flag bits clear. Their value cannot be known yet, and
    // does not need to be: the varint's length is fixed by `input.len()`.
    debug_assert_eq!(start_split, EVEN, "nothing starts in the wide split");
    put_header(input.len(), false, out);
    let header_len = out.len();
    // Reserved once, so nothing below has to ask again -- and asked about
    // first, because the caller reuses its buffer and growth is the case that
    // never happens. `Vec::reserve` is a call; a capacity compare is not.
    let want = Cursor::room(input.len());
    if out.capacity() - out.len() < want {
        out.reserve(want);
    }
    // SAFETY: the reserve above is exactly what the cursor's writes assume.
    let mut cur = unsafe { Cursor::new(out) };
    let mut split = start_split;
    // Where the second section starts, as (offset into the body, output
    // position). Both are needed: the decoder splits the input at the first and
    // resumes producing at the second.
    let mut switch: Option<(usize, usize)> = None;
    let mut recent: u32 = 0;
    let mut seen = 0usize;
    // The offset the previous block wrote, so this one can say "the same".
    // `usize::MAX` never matches a real offset, so the first block always writes.
    let mut last_offset = usize::MAX;

    let mut blocks = 0usize;
    let mut saturated = 0usize;
    let mut at = 0usize;
    let mut literal_start = 0usize;
    // Starts at the trigger, so the first step is one byte. Starting at one
    // would make the shift zero and the cursor would sit on the same position
    // for the first sixty-four attempts.
    let mut misses = 1usize << SKIP_TRIGGER;
    // One probe ahead of `at`, so a miss hands over an address that was formed
    // a loop earlier. Re-seeded from `at` wherever the cursor jumps for another
    // reason.
    let mut next_at = at;
    // The shift is a constant here, not a value, and that is worth a whole
    // instruction per position. It takes exactly two values -- 64 - HASH_BITS
    // or 64 - HASH_BITS_LARGE -- chosen once from the length, but x86 has no
    // register-to-register variable shift outside BMI2: the count has to be in
    // CL, and CL is wanted two instructions later, so the generated code
    // reloaded it every single iteration:
    //
    //     imulq %r11, %rsi
    //     movl  %r13d, %ecx      <- every position, for a loop invariant
    //     shrq  %cl, %rsi
    //
    // As a constant it is `shrq $52` and CL stays free. AArch64 shifts by a
    // register in one instruction and neither gains nor loses.
    debug_assert_eq!(SHIFT, hash_shift(input.len()));

    // Hoisted: the loop asked `at + MIN_MATCH <= input.len()` and paid an `add`
    // for it on every position visited.
    // SAFETY of every `word8` below: the callers refuse a value shorter than
    // `HASH_WORD`, so this does not wrap and the last position visited has a
    // full hash word above it.
    let last = input.len() - HASH_WORD;
    loop {
        // The advance sits before the probe, not after it, which is what makes
        // it a lookahead rather than a rename: the address this iteration loads
        // from was formed last iteration, so it does not wait on the branch
        // that closed the last one. lz4_flex writes the same two lines at the
        // same place.
        at = next_at;
        next_at = at + (misses >> SKIP_TRIGGER);
        if at > last {
            break;
        }
        // One load, not two. These were written as `word4(at)` and `word8(at)`
        // and the generated x86 kept them apart:
        //
        //     movl  (%r15,%r14), %esi        ; word4
        //     movq  (%r15,%r14), %rax        ; word8, same address
        //
        // Both are little-endian reads at the same address, so the four bytes
        // are the low half of the eight and taking them from the register is
        // exact. That is a load and an address-generation slot per position, on
        // the path data that does not repeat spends nearly all of its time in.
        //
        // SAFETY: `at <= last` is `at + 8 <= input.len()`, which covers both.
        let word = unsafe { word8(input, at) };
        let here = word as u32;
        let slot = hash5(word, SHIFT);
        let stored = table[slot];
        table[slot] = S::of(at);

        // A slot holds a position from this value or a previous one, and only
        // positions behind the cursor are usable. An untouched slot holds
        // [`EMPTY`], which is far enough ahead of any real position that the
        // same test rejects it — see the constant.
        //
        // The four bytes are compared inline before anything else happens. On
        // data that varies, almost every candidate fails here — and the
        // previous form paid two bounds-checked slice constructions and a call
        // to find that out. Since the hash is of exactly these four bytes, a
        // candidate that disagrees on them cannot match at all, so this rejects
        // without touching the extension loop.
        // Two tests, and they stay two.
        //
        // "Behind the cursor" and "inside the window" are one question asked of
        // the distance -- `(at - candidate - 1) < MAX_OFFSET` in unsigned
        // arithmetic covers both, since an empty or ahead slot wraps to
        // something enormous. That was built and measured: noise_4k improved 3%
        // and everything else got worse, varied_64k by 5%, varied_4k by 4%,
        // records_4k by 3%. Three runs each.
        //
        // The reason is the short circuit. Once the table is warm the first
        // test is almost always true and almost always predicted, so the second
        // is cheap; folding them makes both arithmetic on every position
        // whether or not it is needed. Only on data that does not compress,
        // where the table holds stale entries and neither test predicts, does
        // the fold pay.
        //
        // Two candidates for a different search were built. Neither wins.
        //
        // Folding the two tests into `(at - candidate - 1) < MAX_OFFSET`,
        // measured back to back against this in one sitting: noise_4k 0.748 ->
        // 0.734 cycles per byte, varied_64k 3.853 -> 4.331, records_4k 1.014 ->
        // 1.024. Two percent on the target, twelve against everywhere else.
        //
        // Reading the candidate unconditionally and branching only on whether
        // four bytes agree -- which is what liblz4 does, and why it executes
        // more instructions per byte than we do: noise_4k flat, varied_64k 11%
        // worse, worse on every other shape. The unconditional read costs more
        // where the branch would have predicted than it saves where it would
        // not, and predictable positions are the overwhelming majority
        // everywhere except noise.
        //
        // A second search remains the right idea -- which search found a match
        // is invisible to the decoder, so switching costs nothing in the format
        // and could ride the miss streak the way the split rides the saturation
        // window. What is missing is a second search that wins on its own
        // target. These two do not.
        //
        // Which is where the real gap is, and it is not this. Profiling both
        // packers over the same 4 KiB of noise:
        //
        //     lzvolt   0.740 cycles/byte   IPC 3.13   2.3 instr/byte   16.5% mispredicts
        //     liblz4   0.539               IPC 6.12   3.3             2.1%
        //
        // liblz4 executes half again as many instructions per byte and is 27%
        // faster, at twice the issue rate, because it loses almost nothing to
        // misprediction. Ours is a search whose branches depend on what the
        // table happens to hold; theirs is shaped so that they do not. Closing
        // that is a different loop, not a smaller one.
        let candidate = stored.position();
        let matched = if candidate < at
            && at - candidate <= MAX_OFFSET
            // SAFETY: `candidate < at`, and `at + MIN_MATCH <= input.len()`.
            && unsafe { word4(input, candidate) } == here
        {
            // SAFETY: same, and `candidate + MIN_MATCH < at + MIN_MATCH`.
            MIN_MATCH + unsafe { common_prefix(input, candidate + MIN_MATCH, at + MIN_MATCH) }
        } else {
            0
        };

        if matched < MIN_MATCH {
            // The cursor for the next probe is formed here rather than being
            // derived from this one at the top, which is what lz4_flex does:
            //
            //     cur = next_cur;
            //     next_cur += step_size;
            //
            // Same arithmetic, one iteration earlier. The address the next
            // probe loads from stops depending on this iteration reaching its
            // end, so the load can issue while the rest of this block is still
            // in flight instead of after the branch that closes it.
            misses += 1;
            continue;
        }
        misses = 1 << SKIP_TRIGGER;

        // The first match found is not always the one worth taking.
        //
        // The search moves forward and commits to whatever it finds, so a
        // four-byte match at one position hides a forty-byte match starting a
        // byte later. Giving up the byte to the literal run costs one byte of
        // ratio and buys the difference between the two lengths.
        //
        // This matters here more than it would in an archiver, because block
        // count is what the decoder is paid by: a longer match is not just
        // denser, it is one block instead of two, and the two would each have
        // cost a token decode and an offset load. Counting real blocks put us
        // 25% above lz4_flex on the same data at the same ratio, and this is
        // that difference.
        //
        // The step repeats while it keeps winning, which terminates because
        // every round demands a strictly longer match than the last.
        let mut candidate = candidate;
        let mut matched = matched;
        // A guard on the outside and a loop on the inside, because `lazy` never
        // changes and `while lazy` reads as though it might.
        if lazy && matched < LAZY_UNTIL {
            'lazy: loop {
                // One byte on, and if that finds nothing better, two.
                //
                // Stepping only by one gives up as soon as the very next position
                // fails, which loses a long match sitting two bytes away -- and a
                // long match is what the decoder is paid by, since it is one block
                // instead of two. The second probe costs a hash and a lookup on a
                // position the search would otherwise have skipped, and the entry it
                // leaves behind is one a later search can use.
                for step in 1..=LAZY_REACH {
                    let next = at + step;
                    if next > last {
                        break 'lazy;
                    }
                    // SAFETY: `next + MIN_MATCH <= input.len()` was tested above.
                    let ahead = unsafe { word4(input, next) };
                    // SAFETY: `next <= last` is `next + 8 <= input.len()`.
                    let slot = hash5(unsafe { word8(input, next) }, SHIFT);
                    let stored = table[slot];
                    // Inserted whether or not it wins: the position is real and a
                    // later search may want it, and the search itself would never
                    // have visited it.
                    table[slot] = S::of(next);

                    let other = stored.position();
                    if other < next
                        && next - other <= MAX_OFFSET
                        // SAFETY: `other < next` and `next + MIN_MATCH <= input.len()`.
                        && unsafe { word4(input, other) } == ahead
                    {
                        let len = MIN_MATCH
                            + unsafe { common_prefix(input, other + MIN_MATCH, next + MIN_MATCH) };
                        // Strictly longer, and by enough to pay for the literals the
                        // step turns loose: moving `step` bytes out of a match and
                        // into the literal run costs about that many bytes.
                        if len > matched + step - 1 {
                            matched = len;
                            candidate = other;
                            at = next;
                            continue 'lazy;
                        }
                    }
                }
                break;
            }
        }

        // The bounds checks in this loop stay, and that is measured rather than
        // assumed. In the disassembly it is eleven instructions per byte walked
        // where six do the work, with a range check per iteration whose answer
        // the loop conditions already guarantee. Hoisting them into an unsafe
        // helper was tried twice: folding the two conditions into a `min` up
        // front cost 4.8% on varied_64k for 2 to 4% on records, and keeping the
        // short circuit while dropping only the checks was worse than either --
        // 4.72 cycles a byte against 4.42. Three runs each.
        //
        // The reason the disassembly misleads is that this loop usually runs
        // zero times: a match found by a forward search rarely extends
        // backwards on data that does not repeat, so what the body costs per
        // iteration hardly matters and disturbing the code around it does.
        //
        // Walk the match backwards into the literals that were about to be
        // emitted. The bytes are already known to be equal there; they were
        // simply never looked at, because the search only ever moves forward.
        //
        // This is worth more than the ratio it adds. Every byte moved out of a
        // literal run and into a match is a byte the decoder copies in a block
        // instead of individually, and — since it shortens the run rather than
        // splitting it — it produces fewer, longer blocks. Decoding is bounded
        // by per-block work, so fewer blocks is the lever.
        let mut back = 0usize;
        while candidate > back
            && at - back > literal_start
            && input[candidate - back - 1] == input[at - back - 1]
        {
            back += 1;
        }

        blocks += 1;
        let overflowed = matched + back - MIN_MATCH >= split.mat_max();
        if overflowed {
            saturated += 1;
        }
        // The decision, taken before this block is written so that the block
        // itself already uses the split it argued for. `literal_start` is the
        // output position every emitted block has produced so far, and the body
        // offset is simply how much has been written past the header.
        if adaptive && switch.is_none() && split == EVEN {
            recent = (recent << 1) | overflowed as u32;
            seen += 1;
            let mask = (1u32 << SPLIT_WINDOW) - 1;
            let fits = |v: usize| v < 1 << (8 * switch_width(input.len()));
            if seen >= SPLIT_WINDOW
                && (recent & mask).count_ones() as usize * 2 > SPLIT_WINDOW
                // The window sits at the front of the value, so this holds in
                // practice; it is checked rather than argued because the
                // trailer's width cannot represent more.
                && fits(cur.len() - header_len)
                && fits(literal_start)
            {
                switch = Some((cur.len() - header_len, literal_start));
                split = LONG_MATCH;
                // Nothing on the other side of the boundary may claim a repeat
                // against a block the decoder read under a different layout.
                last_offset = usize::MAX;
            }
        }
        let literals = &input[literal_start..at - back];
        // The slice the fixed-width move reads, not just the run: the copy
        // needs a pointer entitled to all sixteen bytes.
        let wide = wide_literals_fit(literals, at - back, input.len())
            .then(|| &input[literal_start..literal_start + WIDE_LITERAL]);
        let offset = at - candidate;
        // Only the layout that has the bit may claim a repeat: the even split
        // spends all eight token bits on lengths, the wide one keeps the low
        // bit for this.
        let repeat = split.rep_bits == 1 && offset == last_offset;
        last_offset = offset;
        emit_block(
            literals,
            offset,
            matched + back,
            &mut cur,
            split,
            wide,
            repeat,
        );

        at += matched;
        next_at = at;
        literal_start = at;
    }

    // Everything left over is literals, with no match to follow.
    emit_literals_only(&input[literal_start..], &mut cur, split);
    // SAFETY: every byte below the cursor was written by the calls above.
    unsafe { out.set_len(cur.len()) };

    if let Some((in_at, out_at)) = switch {
        // At the end rather than in the header, so a value that never switches
        // pays nothing for the possibility. Fixed width because a varint cannot
        // be read backwards without ambiguity -- its continuation bits look no
        // different from a body byte's high bit.
        let w = switch_width(input.len());
        put_switch(in_at, w, out);
        put_switch(out_at, w, out);
        // The flag lives in the first byte whatever the class, and a value
        // that switches is far past the one-byte class that has no room.
        debug_assert!(out[0] >> 6 != 0, "a switching value is never one byte");
        out[0] |= HYBRID_BIT;
    }
    let _ = (blocks, saturated);
}

/// The block header: a two-bit class, one flag, and the length.
///
/// ```text
///   00 LLLLLL              1 byte,   6 bits, up to 63
///   01 H LLLLL + 1 byte    2 bytes, 13 bits, up to 8191
///   10 H LLLLL + 2 bytes   3 bytes, 21 bits, up to 2097151
///   11 H LLLLL + 3 bytes   4 bytes, 29 bits, up to 536870911
/// ```
///
/// Was `varint(declared << 2 | hybrid << 1 | split)`, and two things were wrong
/// with that. `split` was never set -- all six `pack_pass` call sites pass
/// `EVEN`, so the wide layout is reachable only through the hybrid switch -- so
/// the header paid two bits to carry one. And LEB128 has to be walked a byte at
/// a time, each byte a dependent load and a branch the predictor cannot see
/// through.
///
/// Here the class says how many bytes to read before any of them is examined,
/// so the whole header is one load and a shift. `MASK` and `SHIFT` are indexed
/// by the class rather than branched on, which is also what keeps the one-byte
/// case at six bits of payload while the others spend one on `hybrid`.
///
/// The short class needs no flag because it cannot have one: a value of 63
/// bytes or less is always plain even. The switch is gated on sixteen blocks
/// and a block produces at least `MIN_MATCH` bytes, so nothing under 64 bytes
/// of output ever reaches the question. See docs/MEASUREMENTS.md.
///
/// Size is unchanged against LEB128 in the range we use -- both spend one bit
/// per byte on the length, and no encoding does better below 35 bits. This buys
/// decode, not bytes.
const HEADER_MASK: [u8; 4] = [0x3F, 0x1F, 0x1F, 0x1F];
const HEADER_SHIFT: [u32; 4] = [24, 16, 8, 0];
const HYBRID_BIT: u8 = 0x20;

/// Bytes the header will take for this length.
#[inline]
fn header_len(declared: usize) -> usize {
    match declared {
        0..=63 => 1,
        64..=8191 => 2,
        8192..=2_097_151 => 3,
        _ => 4,
    }
}

/// Write the header. `hybrid` is ignored in the one-byte class, which cannot
/// occur with a switch.
#[inline]
fn put_header(declared: usize, hybrid: bool, out: &mut Vec<u8>) {
    let n = header_len(declared);
    let class = (n - 1) as u8;
    let payload = declared as u32;
    let top = (payload >> (8 * (n - 1))) as u8;
    debug_assert!(top & !HEADER_MASK[class as usize] == 0);
    let mut first = (class << 6) | top;
    if hybrid && n > 1 {
        first |= HYBRID_BIT;
    }
    out.push(first);
    for i in (0..n - 1).rev() {
        out.push((payload >> (8 * i)) as u8);
    }
}

/// Read it back: one four-byte load, one shift, no branch on the length.
///
/// The load is unconditional because a header is never the whole stream -- a
/// body always follows, and the shortest body is a token and a literal. Callers
/// that hand in fewer than four bytes get `None` rather than a wild read.
#[inline]
fn get_header(input: &[u8]) -> Option<(usize, bool, usize)> {
    let head: [u8; 4] = match input.get(..4) {
        Some(b) => b.try_into().unwrap(),
        // A stream this short is malformed, but it must not fault; pad and let
        // the length checks downstream reject it.
        None => {
            let mut b = [0u8; 4];
            b[..input.len()].copy_from_slice(input);
            b
        }
    };
    let class = (head[0] >> 6) as usize;
    let declared = u32::from_be_bytes([head[0] & HEADER_MASK[class], head[1], head[2], head[3]])
        >> HEADER_SHIFT[class];
    let hybrid = class != 0 && head[0] & HYBRID_BIT != 0;
    let n = class + 1;
    if input.len() < n {
        return None;
    }
    Some((declared as usize, hybrid, n))
}

/// Bytes each of the two switch offsets takes at the end of a hybrid stream.
///
/// Both are bounded by the value: the output position is below `declared` and
/// the body offset below the body, which is shorter still. So a value that fits
/// in sixteen bits needs two bytes per field rather than four, and since the
/// window is fixed at the front of the value the offsets are small whatever the
/// value's size.
///
/// The width follows from `declared` alone, which the decoder reads before it
/// needs the trailer. It is not a flag, because a flag would be another bit to
/// get wrong.
///
/// This is worth being careful about. Measured against the two-pass packer, the
/// eight-byte trailer *was* the entire ratio cost of switching -- 272 to 279
/// bytes at 1 KiB, 599 to 607 at 4 KiB, 6784 to 6791 at 64 KiB. The prefix left
/// in the assumed split costs nothing; it comes out a byte ahead.
#[inline]
fn switch_width(declared: usize) -> usize {
    if declared <= 0x1_0000 {
        2
    } else {
        4
    }
}

#[inline]
fn put_switch(value: usize, width: usize, out: &mut Vec<u8>) {
    match width {
        2 => out.extend_from_slice(&(value as u16).to_le_bytes()),
        _ => out.extend_from_slice(&(value as u32).to_le_bytes()),
    }
}

#[inline]
fn get_switch(bytes: &[u8]) -> usize {
    match bytes.len() {
        2 => u16::from_le_bytes(bytes.try_into().unwrap()) as usize,
        _ => u32::from_le_bytes(bytes.try_into().unwrap()) as usize,
    }
}

/// Length of the shared prefix, eight bytes at a time.
///
/// A byte-wise loop costs a load, a compare and a branch per byte; a 64-bit
/// load turns eight of those into one XOR whose trailing zero count gives the
/// exact position of the first difference. The tail below eight bytes falls
/// back to the simple loop.
/// Length of the run shared by `input[a..]` and `input[b..]`, with `a < b`.
///
/// Takes positions rather than two slices. Building the slices cost two range
/// checks and a `min` of their lengths on every match found -- profiling put
/// 3.8% of the packer in that `min` alone -- and the caller already knows both
/// facts: the later position bounds the comparison, and it is the later one by
/// construction.
///
/// # Safety
///
/// `a < b` and `b <= input.len()`.
unsafe fn common_prefix(input: &[u8], a: usize, b: usize) -> usize {
    let limit = input.len() - b;
    let base = input.as_ptr();
    let mut i = 0;

    while i + 8 <= limit {
        // SAFETY: `b + i + 8 <= input.len()` from the loop condition, and
        // `a < b`, so both reads are inside the slice.
        let left = u64::from_le(base.add(a + i).cast::<u64>().read_unaligned());
        let right = u64::from_le(base.add(b + i).cast::<u64>().read_unaligned());
        let diff = left ^ right;
        if diff != 0 {
            // Little-endian, so the first differing byte is the lowest set bit.
            return i + (diff.trailing_zeros() / 8) as usize;
        }
        i += 8;
    }

    while i < limit && *base.add(a + i) == *base.add(b + i) {
        i += 1;
    }
    i
}

/// How the token's eight bits are split between the two lengths.
///
/// Four and four is LZ4's, and it is what a block liblz4 wrote uses. It is not
/// what our own data wants: counting the lengths a real value decomposes into
/// says the match length overflows its four bits in 99% of blocks on data that
/// compresses six-fold, because the average match there is 34 bytes. Six bits
/// take that to zero, and the two bits it leaves for literals are enough
/// because the same data averages 0.4 to 2.1 of them.
///
/// Data that compresses only two-fold wants the opposite: its matches never
/// overflow four bits, and its literal runs average five to six, so narrowing
/// the literal field to two bits would overflow 86% of them. One split cannot
/// serve both, so the packer picks per value and records the choice in the
/// header.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Split {
    lit_bits: u32,
    /// One when the token's low bit says "the offset the last block used".
    ///
    /// Measured before it was built: offsets repeat 90% of the time on 512-byte
    /// records and 75.8% at 4 KiB, and a repeat costs the decoder no load and no
    /// address to compute. Smaller on every shape tried, free to pack, faster to
    /// read -- see `docs/ROADMAP.md`.
    rep_bits: u32,
}

/// Four bits each, which is also the LZ4 block format.
///
/// The repeat bit was taken out of this field and put back: it cost 22.9% on
/// records_512 and 21.5% on varied_512. The census said why -- the share of
/// blocks whose literal length needs an extension chain doubled, and a
/// saturated literal length is the one thing that branches out of the decoder's
/// hot loop, where a saturated match length does not. See docs/MEASUREMENTS.md.
const EVEN: Split = Split {
    lit_bits: 4,
    rep_bits: 0,
};
/// Two for the literal run, five for the match, one for the repeat.
///
/// Was two and six. This is where the repeat bit belongs and the census is not
/// ambiguous about it: in the wide split 31.8% of records_64k's offsets repeat
/// the one before and 72.8% of records_4k's, while a five-bit match field costs
/// *nothing* -- the share of blocks needing a chain goes 32.5% -> 32.5% on
/// records_64k and 32.1% -> 33.3% on records_4k.
///
/// Free here and ruinous in the even split because wide match lengths are
/// bimodal: what passes 31 almost always passes 63 as well, so the blocks that
/// need a chain need one either way. Literal lengths are not like that. They
/// cluster just above whatever the ceiling is.
///
/// Records reach this split after fifteen blocks and stay, so it is the layout
/// they are decoded under: 1552 of records_64k's 1567 blocks.
const LONG_MATCH: Split = Split {
    lit_bits: 2,
    rep_bits: 1,
};

impl Split {
    #[inline]
    fn lit_max(self) -> usize {
        (1 << self.lit_bits) - 1
    }
    #[inline]
    fn mat_max(self) -> usize {
        (1 << (8 - self.lit_bits - self.rep_bits)) - 1
    }
    /// How far the match field sits above the token's low bit.
    #[inline]
    fn mat_shift(self) -> u32 {
        self.rep_bits
    }
    #[inline]
    fn shift(self) -> u32 {
        8 - self.lit_bits
    }
    /// The other of the two splits.
    #[inline]
    fn other(self) -> Split {
        if self == EVEN {
            LONG_MATCH
        } else {
            EVEN
        }
    }
    #[inline]
    fn kernel(self) -> crate::kernel::decode::Split {
        if self == LONG_MATCH {
            crate::kernel::decode::Split::WideMatch
        } else {
            crate::kernel::decode::Split::Even
        }
    }
}

/// Bytes the fixed-width literal move writes, whatever the run's true length.
///
/// `extend_from_slice` compiles to a call to `memmove` with a length the
/// compiler cannot see, and a literal run averages six bytes -- so the call
/// costs more than the copy. Profiling found 19.5% of the packer there. A move
/// of constant width has no call in it; it reads past the run, so the caller
/// shows that those bytes are inside the input, and it writes past the output,
/// which the reserve covers.
const WIDE_LITERAL: usize = 16;

/// Whether a literal run ending at `end` can be copied the wide way.
///
/// The run is a slice of the input, so reading a fixed width past its end has
/// to stay inside the input.
#[inline]
fn wide_literals_fit(literals: &[u8], end: usize, input_len: usize) -> bool {
    literals.len() <= WIDE_LITERAL && end + WIDE_LITERAL <= input_len
}

/// A write cursor into the output, past the point where its size is in doubt.
///
/// Every `push` and `extend_from_slice` in the block writer carries a capacity
/// check, and profiling put 9.4% of the packer in that bookkeeping -- for a
/// buffer whose worst case is known before the pass starts.
///
/// The bound is the whole input as literals, plus a token and an offset for
/// each block, plus the chains of 255s, plus the overshoot the fixed-width
/// literal move makes. A block covers at least [`MIN_MATCH`] output bytes, so
/// there are at most `n / MIN_MATCH` of them. In a debug build every write
/// checks itself against the reserve, so an overrun is a failing test rather
/// than a corrupted heap.
struct Cursor {
    p: *mut u8,
    base: *mut u8,
    #[cfg(debug_assertions)]
    limit: *mut u8,
}

impl Cursor {
    #[inline]
    fn room(n: usize) -> usize {
        n + n / MIN_MATCH * 3 + n / 128 + WIDE_LITERAL + 64
    }

    /// # Safety
    ///
    /// `out` must have [`Cursor::room`] spare capacity past its length.
    unsafe fn new(out: &mut Vec<u8>) -> Cursor {
        let base = out.as_mut_ptr();
        Cursor {
            p: base.add(out.len()),
            base,
            #[cfg(debug_assertions)]
            limit: base.add(out.capacity()),
        }
    }

    #[inline]
    fn guard(&self, _n: usize) {
        #[cfg(debug_assertions)]
        debug_assert!(
            unsafe { self.p.add(_n) } <= self.limit,
            "the packer wrote past its reserve"
        );
    }

    #[inline]
    unsafe fn byte(&mut self, b: u8) {
        self.guard(1);
        *self.p = b;
        self.p = self.p.add(1);
    }

    #[inline]
    unsafe fn offset(&mut self, v: u16) {
        self.guard(2);
        self.p.cast::<u16>().write_unaligned(v.to_le());
        self.p = self.p.add(2);
    }

    /// Copies a fixed width and advances by the true length. See
    /// [`WIDE_LITERAL`].
    ///
    /// `src` is the input from the run's start and must be at least
    /// `WIDE_LITERAL` long; `n` is how much of it is the run. Those are two
    /// arguments rather than one because they have to be: this used to take the
    /// run alone and read `WIDE_LITERAL` through its pointer, which Miri
    /// rejects. The bytes were always inside the input -- `wide_literals_fit`
    /// guarantees that and still does -- but a pointer derived from a one-byte
    /// subslice may not reach sixteen bytes, however valid the memory is. It
    /// worked, and it was undefined.
    #[inline]
    unsafe fn literals_wide(&mut self, src: &[u8], n: usize) {
        debug_assert!(src.len() >= WIDE_LITERAL, "the wide source is short");
        debug_assert!(n <= WIDE_LITERAL, "the run is wider than the move");
        self.guard(WIDE_LITERAL);
        std::ptr::copy_nonoverlapping(src.as_ptr(), self.p, WIDE_LITERAL);
        self.p = self.p.add(n);
    }

    #[inline]
    unsafe fn literals(&mut self, src: &[u8]) {
        self.guard(src.len());
        std::ptr::copy_nonoverlapping(src.as_ptr(), self.p, src.len());
        self.p = self.p.add(src.len());
    }

    #[inline]
    fn len(&self) -> usize {
        // SAFETY: `p` never moves below `base`.
        unsafe { self.p.offset_from(self.base) as usize }
    }
}

fn emit_block(
    literals: &[u8],
    offset: usize,
    matched: usize,
    out: &mut Cursor,
    split: Split,
    // `Some(src)` takes the fixed-width literal move, with `src` a slice of
    // the input long enough for it to read. `None` copies the run exactly.
    wide: Option<&[u8]>,
    repeat: bool,
) {
    let match_extra = matched - MIN_MATCH;
    let lit_field = literals.len().min(split.lit_max());
    let mat_field = match_extra.min(split.mat_max());
    // SAFETY: the pass reserved `Cursor::room` before the first block, and a
    // debug build checks every write against it.
    unsafe {
        out.byte(
            ((lit_field as u8) << split.shift())
                | ((mat_field as u8) << split.mat_shift())
                | (repeat as u8 & split.rep_bits as u8),
        );
        if literals.len() >= split.lit_max() {
            put_extended(literals.len() - split.lit_max(), out);
        }
        match wide {
            Some(src) => out.literals_wide(src, literals.len()),
            None => out.literals(literals),
        }
        if !repeat {
            out.offset(offset as u16);
        }
        if match_extra >= split.mat_max() {
            put_extended(match_extra - split.mat_max(), out);
        }
    }
}

fn emit_literals_only(literals: &[u8], out: &mut Cursor, split: Split) {
    let lit_field = literals.len().min(split.lit_max());
    // SAFETY: as in `emit_block`.
    unsafe {
        // A zero match field with no offset following is what marks the tail;
        // the decoder knows to stop because the declared length has been
        // reached.
        out.byte((lit_field as u8) << split.shift());
        if literals.len() >= split.lit_max() {
            put_extended(literals.len() - split.lit_max(), out);
        }
        out.literals(literals);
    }
}

/// Lay down a match whose source overlaps the output it is producing.
///
/// The naive form copies `offset` bytes at a time, so a run of one repeated
/// byte costs one call per byte. Instead the chunk doubles each round while the
/// read always starts at `src`: after writing `n` bytes, the pattern at `src`
/// is `offset + n` bytes long, so the next round may take twice what the last
/// one did. A hundred-byte run at offset one becomes seven copies rather than a
/// hundred.
///
/// This is the case LZ4 handles with jump tables and ClickHouse with `pshufb`.
/// Doubling needs neither, and costs the same on both architectures.
///
/// # Safety
///
/// `src` must equal `dst.sub(offset)` with `offset >= 1`, the pattern at `src`
/// must be initialised for `offset` bytes, and `dst` must be writable for
/// `len` bytes.
#[inline]
unsafe fn overlapping_copy(dst: *mut u8, src: *const u8, offset: usize, len: usize) {
    let mut written = 0usize;
    let mut chunk = offset;
    while written < len {
        let take = chunk.min(len - written);
        std::ptr::copy_nonoverlapping(src, dst.add(written), take);
        written += take;
        chunk *= 2;
    }
}

/// Unpack into `out`, replacing whatever it held.
///
/// Every length and offset in `input` is treated as hostile: the declared size
/// is capped before anything is reserved, each field is bounds-checked, and a
/// backward reference is verified against what has actually been produced.
/// Bytes a block copy may write past the logical end of the output.
///
/// The whole point of copying in fixed blocks is not having to trim the last
/// one, so the buffer is over-allocated by a block and the length is set to the
/// declared size at the end. Nothing ever reads the slack.
const OVERRUN: usize = 32;

/// Input bytes the fast path must be able to read past the token.
///
/// Computed once rather than per block: the guard runs on every block, and a
/// `max` there is arithmetic the loop does not need.
const FAST_INPUT_SLACK: usize = if FAST_LITERAL > OVERRUN {
    FAST_LITERAL
} else {
    OVERRUN
};

/// Bytes the fast path copies for a literal run.
///
/// The short form carries at most fourteen, so sixteen covers it. Copying a
/// full [`OVERRUN`] there would move twice the bytes for no gain, and on data
/// that compresses poorly literals are most of the output.
const FAST_LITERAL: usize = 16;

/// Copy `len` bytes from `src` to `dst` in fixed blocks, overrunning freely.
///
/// # Safety
///
/// `src` must be readable for `len.next_multiple_of(OVERRUN)` bytes and `dst`
/// writable for the same. The caller establishes both before calling; that is
/// the entire reason this is not doing it itself.
#[inline]
unsafe fn wildcopy(mut dst: *mut u8, mut src: *const u8, len: usize) {
    let mut copied = 0usize;
    loop {
        std::ptr::copy_nonoverlapping(src, dst, OVERRUN);
        copied += OVERRUN;
        if copied >= len {
            return;
        }
        src = src.add(OVERRUN);
        dst = dst.add(OVERRUN);
    }
}

/// Unpack into `out`, replacing whatever it held.
///
/// Every length and offset in `input` is treated as hostile: the declared size
/// is capped before anything is reserved, each field is bounds-checked, and a
/// backward reference is verified against what has actually been produced.
///
/// # How the unchecked copies are made safe
///
/// The copies below use raw pointers, and each one is preceded by the check
/// that makes it sound rather than relying on a later one to catch it:
///
/// - the output is reserved for `declared + OVERRUN`, so a block copy may
///   overrun the logical end by up to one block without leaving the allocation;
/// - a literal run is copied only after `at + literal_len` has been shown to be
///   within `input`, and blockwise only when a further `OVERRUN` bytes are also
///   within it, falling back to an exact copy near the end of the stream;
/// - a match is copied only after its offset has been shown to be no larger
///   than what has already been produced, so it never reads uninitialised
///   memory, and only after `produced + match_len <= declared`;
/// - the length is set once, at the end, to `declared` — never to whatever the
///   overrun happened to reach.
///
/// The corruption test walks every truncation and every single-bit flip of a
/// packed stream. With the bounds moved out of the copies, that test is what
/// stands between a malformed value and memory unsafety, so it is not
/// optional.
pub fn unpack(input: &[u8], out: &mut Vec<u8>) -> Result<(), PackError> {
    // The kernel is handed a body and a length and answers one question: did it
    // decode. Declining is not an error report — it means "this needs the
    // decoder that can name what is wrong", which is the one below. So a stream
    // the kernel refuses is never rejected on its word alone.
    if crate::kernel::decode::asm_available() {
        if let Ok(f) = frame(input) {
            let ok = match f.switch {
                None => {
                    crate::kernel::decode::unpack_asm(f.body, out, f.declared, f.split.kernel())
                }
                Some(switch) => crate::kernel::decode::unpack_asm_hybrid(
                    f.body,
                    out,
                    f.declared,
                    switch,
                    f.split.kernel(),
                    f.split.other().kernel(),
                ),
            };
            if ok {
                return Ok(());
            }
        }
    }
    unpack_portable(input, out)
}

/// Decode into a buffer the caller owns, returning how many bytes were written.
///
/// The same decoder [`unpack`] runs — the assembled kernels first, the
/// portable one where they decline — writing straight into `out` instead of
/// into a `Vec`. Nothing is copied afterwards, which is the whole point: this
/// is what the C ABI is built on, and a codec that reads at 13 GiB/s cannot
/// afford to hand its output through a `memcpy`.
///
/// `out` must hold at least the declared length, or this is
/// [`PackError::OutputTooSmall`] and nothing is written. It **should** hold
/// [`decompressed_bound`] of it: both decoders copy in wide blocks and both
/// check for that much room before they do. A tight buffer decodes the same
/// bytes, only block by block.
pub fn unpack_into_slice(input: &[u8], out: &mut [u8]) -> Result<usize, PackError> {
    let f = frame(input)?;
    if out.len() < f.declared {
        return Err(PackError::OutputTooSmall);
    }
    if crate::kernel::decode::asm_available() {
        let ok = match f.switch {
            None => {
                crate::kernel::decode::unpack_into_slice(f.body, out, f.declared, f.split.kernel())
            }
            Some(switch) => crate::kernel::decode::unpack_hybrid_into_slice(
                f.body,
                out,
                f.declared,
                switch,
                f.split.kernel(),
                f.split.other().kernel(),
            ),
        };
        if ok {
            return Ok(f.declared);
        }
    }
    // SAFETY: `out` is a live slice and is therefore writable for its length.
    unsafe { unpack_framed(f, out.as_mut_ptr(), out.len()) }
}

/// The uncompressed length a stream declares, without decoding it.
///
/// Reads the header and validates it — length, class and, for a hybrid stream,
/// the trailer — so a caller can size a buffer before committing to the
/// decode. The same checks run again inside [`unpack_into_slice`]; they are a
/// handful of compares on a path that is once per value.
pub fn declared_len(input: &[u8]) -> Result<usize, PackError> {
    Ok(frame(input)?.declared)
}

/// How much room [`unpack_into_slice`] wants for a value of `declared` bytes.
///
/// The decoders write past the end of the last block rather than trimming it,
/// so this slack is what buys the wide copies. It is not required — a buffer
/// of exactly `declared` produces the same bytes — but on `noise_4k` the
/// difference between copying wide and not was 34%.
pub const fn decompressed_bound(declared: usize) -> usize {
    declared + crate::kernel::decode::UNPACK_SLACK
}

/// Unpack a block whose uncompressed length the caller already knows.
///
/// This is the shape LZ4's own API has -- `LZ4_decompress_safe` is handed the
/// destination and its size, because an LZ4 block carries no length of its own.
/// [`unpack`] reads ours from the varint in front of the stream; this skips it.
///
/// The compatibility runs one way only, and it is worth being exact about
/// which. **Reading**: this decoder accepts any block liblz4 wrote, byte for
/// byte, which the interop test checks — the even split is the LZ4 token
/// layout, extended lengths are the same chains of 255, the offset is the same
/// two little-endian bytes, and match lengths are stored less four. That is
/// what makes a decoder-against-decoder measurement possible with no format
/// difference left in it.
///
/// **Writing**: our packer's output is not an LZ4 block and liblz4 refuses it.
/// The layout matches; the constraints do not. LZ4 requires a block to end in a
/// literal run of at least five bytes with no match inside the last twelve,
/// while our packer emits matches up to the final byte and then a zero token to
/// close. Half our values also choose the wide split, whose token is not LZ4's
/// at all. See `liblz4_refuses_what_we_wrote` for the measurement.
pub fn unpack_into(block: &[u8], out: &mut Vec<u8>, declared: usize) -> Result<(), PackError> {
    if declared > MAX_UNPACKED {
        return Err(PackError::TooLarge);
    }
    // The LZ4 body, not our own. Which of the two runs is decided here and
    // nowhere else, by the shape of the call rather than by looking at the
    // bytes: a caller who has to hand over a length is holding a block that
    // does not carry one, and only LZ4 blocks do not carry one.
    if crate::kernel::decode::asm_available()
        && crate::kernel::decode::unpack_lz4_asm(block, out, declared)
    {
        return Ok(());
    }
    // The portable decoder wants the header, so give it one.
    let mut framed = Vec::with_capacity(block.len() + 10);
    put_header(declared, false, &mut framed);
    framed.extend_from_slice(block);
    unpack_portable(&framed, out)
}

/// What a packed value's frame says: the declared size, the body, and where the
/// split changes if it does.
struct Frame<'a> {
    declared: usize,
    body: &'a [u8],
    split: Split,
    /// `(offset into body, output position)` where the second section starts.
    switch: Option<(usize, usize)>,
}

/// Read the header, and the trailer if the header says there is one.
///
/// Both offsets come off the wire. They are range-checked here so that
/// everything downstream can treat them as ordinary positions, and anything
/// inconsistent is a truncated stream rather than a silent mis-decode.
fn frame(input: &[u8]) -> Result<Frame<'_>, PackError> {
    let (declared, hybrid, header) = get_header(input).ok_or(PackError::Truncated)?;

    // One length, one encoding. A class wider than the length needs decodes to
    // the same value, which is exactly the problem: two byte strings that mean
    // one value defeat anything deduplicating packed bytes, and nothing
    // downstream can tell them apart. The kernels never see this -- both are
    // handed a body and a length from here. See docs/FORMAT.md, "Header".
    //
    // The class is minimal exactly when the length does not fit in the class
    // below, so the rule is one load and one compare. Written first as
    // `header_len(declared) != header`, which is the same rule and reads
    // better, and cost 6.2% to 7.5% of `own/records_512` across four runs --
    // three compares and their branches, on a call that is forty nanoseconds
    // long. Measured, not reasoned about.
    //
    // This stands where `declared > MAX_UNPACKED` used to. That test cannot
    // fire: four bytes of header hold 29 bits and 2^29-1 is below
    // MAX_UNPACKED, so no stream can declare a length too large. Trading a
    // check that never fires for one that does leaves the count where it was.
    const CLASS_MIN: [usize; 4] = [0, 64, 8192, 2_097_152];
    if declared < CLASS_MIN[(header - 1) & 3] {
        return Err(PackError::NonCanonicalHeader);
    }
    // Only the switch reaches the wide split, so a stream always starts even.
    let split = EVEN;
    let rest = input.get(header..).ok_or(PackError::Truncated)?;

    if !hybrid {
        return Ok(Frame {
            declared,
            body: rest,
            split,
            switch: None,
        });
    }

    let w = switch_width(declared);
    let cut = rest.len().checked_sub(2 * w).ok_or(PackError::Truncated)?;
    let (body, tail) = rest.split_at(cut);
    let in_at = get_switch(&tail[..w]);
    let out_at = get_switch(&tail[w..]);
    if in_at > body.len() || out_at == 0 || out_at >= declared {
        return Err(PackError::Truncated);
    }
    Ok(Frame {
        declared,
        body,
        split,
        switch: Some((in_at, out_at)),
    })
}

/// The decoder every kernel is diffed against, and the only place an error is
/// given a name.
fn unpack_portable(input: &[u8], out: &mut Vec<u8>) -> Result<(), PackError> {
    out.clear();
    let f = frame(input)?;
    let declared = f.declared;
    out.reserve(declared + OVERRUN);
    // SAFETY: the reserve above is what the writes below assume, and
    // `capacity()` is this allocation's true size. The length is set only
    // after the decode reports having filled `declared` bytes.
    let produced = unsafe { unpack_framed(f, out.as_mut_ptr(), out.capacity())? };
    debug_assert_eq!(produced, declared);
    // Set once, to the declared size: the overrun inside may have written past
    // it, and those bytes are not part of the value.
    unsafe { out.set_len(produced) };
    Ok(())
}

/// The body of the portable decoder, writing into memory rather than a `Vec`.
///
/// Split out so a caller holding its own buffer — the C ABI, above all — gets
/// the same decoder rather than a copy of its output. The `Vec` above is this
/// function plus a `reserve` and a `set_len`, which is all a `Vec` ever added.
///
/// # Safety
///
/// `base` must be writable for `capacity` bytes. `capacity` **should** be at
/// least `declared + OVERRUN`; less is safe but turns off the wide copies,
/// which check it.
unsafe fn unpack_framed(f: Frame<'_>, base: *mut u8, capacity: usize) -> Result<usize, PackError> {
    let (declared, body) = (f.declared, f.body);
    let mut split = f.split;
    let switch_at = f.switch.map(|(_, out_at)| out_at);

    let mut produced = 0usize;
    let mut at = 0usize;
    // The offset a repeat block reuses. Cleared at the switch, where the layout
    // changes and the packer stops claiming repeats across it.
    let mut last_offset = 0usize;
    let input = body;

    while produced < declared {
        // The second section begins on a block boundary, so this is the only
        // place the split can change. A stream that steps over the boundary
        // instead of landing on it decodes the rest with the wrong split and
        // fails the length check below, which is the same outcome as any other
        // corruption.
        if switch_at == Some(produced) {
            split = split.other();
            last_offset = 0;
        }
        let token = *input.get(at).ok_or(PackError::Truncated)?;

        // The common block: neither length escaped its nibble, and there is
        // room to read and write whole copy units without checking either
        // again. Everything the slow path computes step by step is bounded
        // here by construction — a literal run is at most 14 bytes and a match
        // at most 18 — so the two copies run at fixed sizes and the arithmetic
        // between them disappears.
        //
        // LZ4 owes most of its decode speed to exactly this shape. Without it
        // a block costs a dozen branches; with it, four.
        let short_literal = (token >> split.shift()) as usize;
        let short_match = ((token >> split.mat_shift()) & split.mat_max() as u8) as usize;
        let repeat = split.rep_bits == 1 && token & 1 == 1;
        // The fixed-size match copy below moves one OVERRUN block, so a match
        // longer than that belongs on the exact path. Under the even split no
        // short match can reach it -- fourteen plus four is eighteen -- but the
        // wide split carries them to sixty-seven.
        if short_literal != split.lit_max()
            && short_match != split.mat_max()
            && short_match + MIN_MATCH <= OVERRUN
            && at + 1 + short_literal + 2 + FAST_INPUT_SLACK <= input.len()
            && produced + 64 <= capacity
        {
            let literal_at = at + 1;
            let offset_at = literal_at + short_literal;
            // Left bounds-checked deliberately. Replacing this with two
            // unchecked byte reads measured 4.5% *slower*: the checked slice
            // becomes one 16-bit load, the unchecked pair does not.
            // Where the bit is set there is nothing to read and no address to
            // compute: the value is already here from the block before.
            let offset = if repeat {
                last_offset
            } else {
                u16::from_le_bytes(input[offset_at..offset_at + 2].try_into().unwrap()) as usize
            };
            last_offset = offset;
            let match_len = short_match + MIN_MATCH;
            let after_literals = produced + short_literal;

            // Validated before either copy, because the match may reach into
            // the literals this block is about to write.
            if offset == 0 || offset > after_literals {
                return Err(PackError::BadOffset);
            }
            if after_literals + match_len > declared {
                return Err(PackError::LengthMismatch);
            }

            unsafe {
                std::ptr::copy_nonoverlapping(
                    input.as_ptr().add(literal_at),
                    base.add(produced),
                    FAST_LITERAL,
                );
                let src = base.add(after_literals - offset);
                let dst = base.add(after_literals);
                if offset >= OVERRUN {
                    std::ptr::copy_nonoverlapping(src, dst, OVERRUN);
                } else {
                    overlapping_copy(dst, src, offset, match_len);
                }
            }

            produced = after_literals + match_len;
            at = offset_at + if repeat { 0 } else { 2 };
            continue;
        }

        at += 1;

        let mut literal_len = (token >> split.shift()) as usize;
        if literal_len == split.lit_max() {
            literal_len += get_extended(input, &mut at)?;
        }

        let end = at.checked_add(literal_len).ok_or(PackError::TooLarge)?;
        if end > input.len() {
            return Err(PackError::Truncated);
        }
        if produced + literal_len > declared {
            return Err(PackError::LengthMismatch);
        }

        // Blockwise only while a whole block is readable from the input and
        // writable into the reservation; the tail of the stream takes the exact
        // path, because overrunning the input would read memory that is not
        // ours.
        if literal_len > 0 {
            let blocked = literal_len.next_multiple_of(OVERRUN);
            unsafe {
                if end + OVERRUN <= input.len() && produced + blocked <= capacity {
                    wildcopy(base.add(produced), input.as_ptr().add(at), literal_len);
                } else {
                    std::ptr::copy_nonoverlapping(
                        input.as_ptr().add(at),
                        base.add(produced),
                        literal_len,
                    );
                }
            }
            produced += literal_len;
        }
        at = end;

        if produced == declared {
            break;
        }

        let offset = if repeat {
            last_offset
        } else {
            let b = input.get(at..at + 2).ok_or(PackError::Truncated)?;
            at += 2;
            u16::from_le_bytes([b[0], b[1]]) as usize
        };
        last_offset = offset;

        let mut match_len = ((token >> split.mat_shift()) & split.mat_max() as u8) as usize;
        if match_len == split.mat_max() {
            match_len += get_extended(input, &mut at)?;
        }
        let match_len = match_len + MIN_MATCH;

        if offset == 0 || offset > produced {
            return Err(PackError::BadOffset);
        }
        if produced + match_len > declared {
            return Err(PackError::LengthMismatch);
        }

        // A match may overlap the output it is still producing — that is how a
        // repeated pattern is encoded. Blockwise copying is only sound when the
        // source is at least a block behind the destination; closer than that,
        // the copy would read bytes it has not written yet, so the pattern is
        // laid down offset by offset instead.
        unsafe {
            let src = base.add(produced - offset);
            let dst = base.add(produced);
            if offset >= OVERRUN && produced + match_len.next_multiple_of(OVERRUN) <= capacity {
                wildcopy(dst, src, match_len);
            } else {
                overlapping_copy(dst, src, offset, match_len);
            }
        }
        produced += match_len;
    }

    if produced != declared {
        return Err(PackError::LengthMismatch);
    }
    Ok(produced)
}

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

    /// How much bulk a test carries, scaled down when Miri is interpreting it.
    ///
    /// Miri executes every operation in software, and the difference is not
    /// small: `the_published_vectors_hold` took **2229 seconds** under it
    /// against a hundredth of a second native, almost all of it in one vector
    /// that decodes 2 MiB through the overlapping-copy path.
    ///
    /// That time buys nothing. What Miri checks is the pointer arithmetic and
    /// the provenance of every access, and a 300-byte match exercises those
    /// exactly as a 2 MiB one does -- it is the same code on the same branches,
    /// just fewer times round. So these tests keep their shape under Miri and
    /// lose their volume, which is what makes running it per-change possible
    /// at all. The full-size run still exists as `make miri-full`.
    fn bulk(native: usize) -> usize {
        if cfg!(miri) {
            (native / 50).max(1)
        } else {
            native
        }
    }

    /// The largest output a single test case decodes, same reasoning as [`bulk`].
    fn biggest(native: usize) -> usize {
        if cfg!(miri) {
            native.min(4096)
        } else {
            native
        }
    }

    fn records(total: usize) -> Vec<u8> {
        let mut out = Vec::with_capacity(total);
        let mut i = 0u64;
        while out.len() < total {
            out.extend_from_slice(
                format!("{{\"id\":{i},\"tenant\":\"t42\",\"active\":true}}").as_bytes(),
            );
            i += 1;
        }
        out.truncate(total);
        out
    }

    fn roundtrip(input: &[u8]) {
        let mut packed = Vec::new();
        let mut unpacked = Vec::new();
        if pack(input, &mut packed) {
            unpack(&packed, &mut unpacked).expect("must unpack what it packed");
            assert_eq!(unpacked, input, "round trip changed the bytes");
        }
    }

    /// The rule that decides whether a packed value replaces the original.
    ///
    /// Reading a packed value costs a factor of four to five against reading a
    /// stored one, at every size, so a saving has to be worth that. One byte in
    /// thirty-two is not.
    #[test]
    fn a_saving_has_to_be_worth_the_decode() {
        // One byte of thirty-two: what `out.len() < input.len()` used to accept,
        // measured at -78% on the read for 3% of the space.
        assert!(!worth_storing(31, 32));
        // The floor, so a tiny absolute win cannot ride in on a good ratio.
        assert!(!worth_storing(9, 16));
        assert!(worth_storing(8, 16));
        // An eighth exactly, and one byte short of it.
        assert!(worth_storing(896, 1024));
        assert!(!worth_storing(897, 1024));
        // Every shape the benchmark packs clears it with room to spare.
        assert!(worth_storing(195, 512));
        assert!(worth_storing(487, 4096));
        assert!(worth_storing(5524, 65536));
        // A packer that grew the value says no rather than underflowing.
        assert!(!worth_storing(600, 512));
        assert!(!worth_storing(512, 512));
    }

    #[test]
    fn round_trips_repetitive_data() {
        let input = vec![b'x'; 4096];
        let mut packed = Vec::new();
        assert!(pack(&input, &mut packed));
        assert!(
            packed.len() < input.len() / 20,
            "4096 identical bytes packed to {} bytes",
            packed.len()
        );

        let mut out = Vec::new();
        unpack(&packed, &mut out).unwrap();
        assert_eq!(out, input);
    }

    #[test]
    fn round_trips_structured_data() {
        let mut input = Vec::new();
        for i in 0..500 {
            input.extend_from_slice(format!("{{\"user\":{i},\"active\":true}}").as_bytes());
        }
        let mut packed = Vec::new();
        assert!(pack(&input, &mut packed), "JSON-ish data must compress");

        let mut out = Vec::new();
        unpack(&packed, &mut out).unwrap();
        assert_eq!(out, input);
    }

    /// The property that keeps a namespace of JPEGs from paying twice: if
    /// packing did not help, the caller is told so and stores the original.
    #[test]
    fn refuses_when_it_would_not_help() {
        let mut incompressible = Vec::new();
        let mut state = 0x2545_F491_4F6C_DD1Du64;
        for _ in 0..4096 {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            incompressible.push(state as u8);
        }
        let mut packed = Vec::new();
        assert!(
            !pack(&incompressible, &mut packed),
            "random bytes must not claim to compress"
        );
    }

    #[test]
    fn handles_the_edges() {
        for input in [
            b"".as_slice(),
            b"a",
            b"ab",
            b"abc",
            b"abcd",
            b"abcde",
            &[0u8; 15],
            &[0u8; 16],
            &[0u8; 17],
            &[0xFFu8; 300],
        ] {
            roundtrip(input);
        }
    }

    /// A run longer than its own offset: the match overlaps what it is still
    /// producing, which is how `aaaa...` is encoded and where a bulk copy
    /// would read uninitialised bytes.
    #[test]
    fn overlapping_matches_round_trip() {
        let mut input = b"ab".to_vec();
        input.extend(std::iter::repeat(b'c').take(1000));
        input.extend_from_slice(b"ab");
        roundtrip(&input);

        let alternating: Vec<u8> = (0..2000)
            .map(|i| if i % 2 == 0 { b'a' } else { b'b' })
            .collect();
        roundtrip(&alternating);
    }

    /// Every byte of a packed value is attacker-controlled once it has been
    /// through a snapshot file. None of these may panic.
    #[test]
    fn corrupt_input_is_refused_rather_than_trusted() {
        let input = vec![b'q'; bulk(2000)];
        let mut packed = Vec::new();
        assert!(pack(&input, &mut packed));

        let mut out = Vec::new();

        // Truncation at every length.
        for cut in 0..packed.len() {
            let _ = unpack(&packed[..cut], &mut out);
        }

        // Every single-byte corruption.
        for i in 0..packed.len() {
            for bit in 0..8 {
                let mut broken = packed.clone();
                broken[i] ^= 1 << bit;
                let _ = unpack(&broken, &mut out);
            }
        }

        // The largest length the header can express, over a body holding
        // nothing like it.
        //
        // Note what this deliberately does *not* assert. The four-byte class
        // tops out at 2^29-1, which is below `MAX_UNPACKED`, so no stream can
        // declare a length this decoder calls too large: the two
        // `declared > MAX_UNPACKED` guards on the unpack paths are unreachable
        // from a stream and earn their keep only on the LZ4 entry, where the
        // length comes from the caller instead of the bytes. This used to build
        // its header with a LEB128 varint of `u64::MAX` and accept either error,
        // which passed while testing neither. See docs/FORMAT.md, "Limits".
        let mut absurd = Vec::new();
        put_header(0x1FFF_FFFF, false, &mut absurd);
        absurd.push(0);
        assert_eq!(unpack(&absurd, &mut out), Err(PackError::Truncated));
    }

    /// The copies in `unpack` are unchecked, so the checks that precede them
    /// are the only thing between a malformed value and memory unsafety. Single
    /// bit flips are covered above; this adds the shapes a corrupt file or a
    /// hostile sender actually produces — several bytes wrong at once, a
    /// plausible header over a garbage body, and streams that were never packed
    /// at all.
    ///
    /// Nothing here asserts a particular error. The property under test is that
    /// none of it reads or writes out of bounds, which shows up as a crash or,
    /// under Miri, as undefined behaviour.
    #[test]
    fn hostile_input_stays_within_bounds() {
        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };

        let source = records(bulk(3000));
        let mut packed = Vec::new();
        assert!(pack(&source, &mut packed));
        let mut out = Vec::new();

        // Several bytes corrupted at once, which single-bit coverage misses:
        // a length field can be made large and its guard byte made consistent
        // by the same edit.
        for _ in 0..bulk(4000) {
            let mut broken = packed.clone();
            let hits = 1 + (next() % 6) as usize;
            for _ in 0..hits {
                let at = (next() as usize) % broken.len();
                broken[at] = next() as u8;
            }
            let _ = unpack(&broken, &mut out);
        }

        // A believable declared length in front of noise, in every header class
        // and with the hybrid flag both ways -- a stream claiming a second
        // section it does not have has to be refused like any other corruption.
        //
        // The lengths straddle all three class boundaries, because the class is
        // what decides how many bytes the decoder consumes before it has looked
        // at any of them. This built its headers as `varint(len << 2 | flags)`
        // until the spec pass caught it: a header format two revisions old, so
        // the classes it actually produced had nothing to do with the list here.
        for len in [0usize, 1, 63, 64, 8191, 8192, 1 << 20, 2_097_151, 2_097_152] {
            for hybrid in [false, true] {
                for _ in 0..bulk(200) {
                    let mut stream = Vec::new();
                    put_header(len, hybrid, &mut stream);
                    for _ in 0..(next() % 200) {
                        stream.push(next() as u8);
                    }
                    let _ = unpack(&stream, &mut out);
                }
            }
        }

        // Streams that were never packed.
        for _ in 0..bulk(2000) {
            let n = (next() % 300) as usize;
            let stream: Vec<u8> = (0..n).map(|_| next() as u8).collect();
            let _ = unpack(&stream, &mut out);
        }
    }

    /// A match whose offset is smaller than one copy block takes the overlapping
    /// path, and one that is larger takes the blockwise path. Both have to
    /// produce the same bytes, and the boundary between them is where a
    /// blockwise copy would read what it has not yet written.
    #[test]
    fn both_match_copy_paths_agree() {
        for offset in [1usize, 2, 3, 7, 8, 15, 16, 31, 32, 33, 64, 200] {
            let mut input = Vec::new();
            let pattern: Vec<u8> = (0..offset).map(|i| b'a' + (i % 26) as u8).collect();
            while input.len() < 4000 {
                input.extend_from_slice(&pattern);
            }
            input.truncate(4000);
            roundtrip(&input);
        }
    }

    /// The assembly packer must produce exactly what the Rust one produces.
    ///
    /// Not merely something that unpacks to the same bytes — the identical
    /// stream. A different but valid encoding would mean two builds of the same
    /// version writing different bytes for the same value, which surfaces much
    /// later as two nodes disagreeing about a snapshot.
    /// Drive both decoders over everything the packer can emit, and require
    /// that they produce the same bytes.
    ///
    /// The sizes are chosen around the widths the kernel copies in: sixteen for
    /// a short literal run, thirty-two for a block. The repeating patterns are
    /// there for the other reason — a two- or three-byte offset takes the
    /// doubling path, which is the only part of the decoder that reads bytes it
    /// wrote moments earlier, and it is where an off-by-one would corrupt data
    /// rather than crash.
    /// The reference implementation as a third opinion.
    ///
    /// Two decoders written by one author can share one misreading of the
    /// format; a third that predates both cannot. liblz4 compresses, we decode,
    /// and the bytes have to come back — which also establishes the claim the
    /// benchmark rests on, that our decoder reads a genuine LZ4 block and a
    /// decoder-against-decoder measurement has no format difference left in it.
    ///
    /// Off by default because it links a C library:
    ///   cargo test --features liblz4
    #[cfg(feature = "liblz4")]
    #[test]
    fn our_decoder_reads_what_liblz4_wrote() {
        #[link(name = "lz4")]
        extern "C" {
            fn LZ4_compress_default(src: *const u8, dst: *mut u8, n: i32, cap: i32) -> i32;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [1usize, 4, 15, 16, 17, 63, 64, 65, 1000, 4096, 65_536] {
            cases.push(records(size));
            cases.push(vec![b'a'; size]);
            cases.push((0..size).map(|_| noise_byte()).collect());
        }
        cases.push(b"ab".repeat(3000));
        cases.push(b"abcdefg".repeat(900));

        let mut out = Vec::new();
        for data in &cases {
            let mut block = vec![0u8; data.len() + 1024];
            let n = unsafe {
                LZ4_compress_default(
                    data.as_ptr(),
                    block.as_mut_ptr(),
                    data.len() as i32,
                    block.len() as i32,
                )
            };
            assert!(n > 0, "liblz4 refused {} bytes", data.len());
            block.truncate(n as usize);

            unpack_into(&block, &mut out, data.len())
                .unwrap_or_else(|e| panic!("{} bytes from liblz4: {e}", data.len()));
            assert_eq!(&out[..], &data[..], "differs on {} bytes", data.len());
        }
    }

    /// A narrower table must find the same matches, not merely valid ones.
    ///
    /// The whole argument for sixteen-bit slots is that they change nothing
    /// except how much cache the table occupies: the positions are the same
    /// numbers, so the same candidates are proposed and the same bytes come
    /// out. If that is wrong the width is not a free optimisation but a format
    /// change, and this is what says which.
    ///
    /// It also pins the sentinel. `0xFFFF` stands for an untouched slot, and a
    /// value long enough to reach position 65535 would make that ambiguous --
    /// [`NarrowPacker::LIMIT`] is where that line sits, and the boundary
    /// lengths below are on both sides of it.
    #[test]
    fn a_narrow_table_packs_the_same_bytes() {
        let mut state = 0x2545_F491_4F6C_DD1Du64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [
            8usize, 64, 512, 2048, 2049, 4096, 8192, 8193, 40_000, 65_536,
        ] {
            cases.push(records(size));
            cases.push(vec![b'a'; size]);
            cases.push((0..size).map(|_| next() as u8).collect());
        }

        let mut wide_out = Vec::new();
        let mut narrow_out = Vec::new();
        let mut wide = PortablePacker::new();
        let mut narrow = NarrowPacker::new();

        let mut compared = 0usize;
        for input in &cases {
            if input.len() > NarrowPacker::LIMIT {
                continue;
            }
            let a = wide.pack(input, &mut wide_out);
            let b = narrow.pack(input, &mut narrow_out);
            assert_eq!(
                a,
                b,
                "the two widths disagreed on whether packing helped for {} bytes",
                input.len()
            );
            if a {
                assert_eq!(
                    wide_out,
                    narrow_out,
                    "a {}-byte value packs differently at sixteen bits",
                    input.len()
                );
                compared += 1;
            }
        }
        assert!(compared > 10, "only {compared} cases actually packed");
    }

    /// A block that is one literal run and nothing else, asked of the kernel
    /// directly.
    ///
    /// This is the shape liblz4 writes for data that does not compress, and it
    /// needs no liblz4 to construct: a token carrying the literal count, the
    /// chain of 255s when it does not fit, and then the bytes. It is the same
    /// encoding [`emit_literals_only`] produces, which is why it can be built
    /// here.
    ///
    /// Worth its own test because it is the one block shape our own packer
    /// never stores -- a value that does not compress is kept raw, so the only
    /// way this reaches the decoder is a store migrating from LZ4. Everything
    /// covering that path goes through `unpack_into`, which falls back to the
    /// portable decoder without saying so.
    #[test]
    fn the_kernel_reads_a_block_that_is_all_literals() {
        if !crate::kernel::decode::asm_available() {
            return;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut refused = Vec::new();
        for n in [
            1usize, 4, 14, 15, 16, 17, 24, 30, 31, 32, 33, 40, 47, 48, 49, 56, 63, 64, 65, 96, 127,
            128, 129, 269, 270, 512, 1000, 4096, 65_536,
        ] {
            let data: Vec<u8> = (0..n).map(|_| noise_byte()).collect();

            let mut block = Vec::new();
            block.push((n.min(15) as u8) << 4);
            if n >= 15 {
                let mut rest = n - 15;
                while rest >= 255 {
                    block.push(255);
                    rest -= 255;
                }
                block.push(rest as u8);
            }
            block.extend_from_slice(&data);

            // Through the LZ4 body only. These blocks are LZ4's token layout,
            // and our even split stopped being that when it took a bit for the
            // repeat code -- three for the literal run, four for the match, one
            // for "same offset as last time". Handing them to our own body
            // would be asking it to read a format it does not claim to read.

            // And through every LZ4 body, which is where the wide copy for the
            // last run lives. Building the block by hand rather than asking
            // liblz4 for one is what lets this run everywhere: the interop test
            // needs the library linked, and there is no x86-64 build of it on
            // an Apple machine, so without this the changed path would be
            // exercised on rented hardware and nowhere else.
            for &body in crate::kernel::decode::Lz4Body::all() {
                let mut out = vec![0u8; n + crate::kernel::decode::UNPACK_SLACK];
                if !crate::kernel::decode::unpack_lz4_into_slice_on(body, &block, &mut out, n) {
                    refused.push(n);
                    continue;
                }
                assert_eq!(
                    &out[..n],
                    &data[..],
                    "the {body:?} LZ4 body produced wrong bytes for a {n}-byte run"
                );
                // Nothing past the declared length may have been written
                // outside the slack the caller promised.
                assert_eq!(
                    out.len(),
                    n + crate::kernel::decode::UNPACK_SLACK,
                    "the buffer moved"
                );
            }
        }

        assert!(
            refused.is_empty(),
            "the kernel refused an all-literal block at these lengths: {refused:?}"
        );
    }

    /// Blocks that carry no literals at all, which is most of them.
    ///
    /// The fast path takes the offset and the match length's extension byte
    /// out of the same word as the token when the literal run is empty, so
    /// none of it is exercised by a test whose blocks all carry literals --
    /// and the one above sets its literal count from the offset, so it never
    /// reaches zero. liblz4 writes these constantly (88% of a records value),
    /// but the interop test needs the library linked and there is no x86-64
    /// build of it on an Apple machine, so without this the path that changed
    /// would be checked on one architecture only.
    #[test]
    fn the_kernel_reads_blocks_with_no_literals() {
        // There is no kernel to test in a build without the assembly, and
        // "the kernel refused all of them" is the correct answer there rather
        // than a failure. Asserting otherwise made `--no-default-features`
        // red the first time anyone ran it.
        if !crate::kernel::decode::asm_available() {
            return;
        }
        let mut failed = Vec::new();
        let (mut decided, mut refused) = (0usize, 0usize);

        for offset in [1usize, 2, 7, 15, 16, 17, 31, 32, 33, 64, 255, 256, 1000] {
            for mat in [
                4usize, 5, 14, 18, 19, 20, 31, 32, 33, 66, 200, 268, 269, 270, 271, 600,
            ] {
                let seed: Vec<u8> = (0..offset.max(16) + 8)
                    .map(|i| (i as u8).wrapping_mul(31).wrapping_add(11))
                    .collect();
                let tail: Vec<u8> = (0..12u8).map(|i| i ^ 0x3C).collect();

                // The first block seeds the window and takes the shortest
                // match there is; the three after it carry no literals at all,
                // which is the path this exercises.
                let mut block = Vec::new();
                let mut want = Vec::new();
                push_token(&mut block, seed.len(), 0);
                block.extend_from_slice(&seed);
                block.extend_from_slice(&(offset as u16).to_le_bytes());
                want.extend_from_slice(&seed);
                for _ in 0..4 {
                    want.push(want[want.len() - offset]);
                }

                for _ in 0..3 {
                    push_token(&mut block, 0, mat - 4);
                    block.extend_from_slice(&(offset as u16).to_le_bytes());
                    push_extension(&mut block, mat - 4);
                    for _ in 0..mat {
                        want.push(want[want.len() - offset]);
                    }
                }

                // The stream ends in a literal run, as LZ4 requires.
                push_token(&mut block, tail.len(), 0);
                block.extend_from_slice(&tail);
                want.extend_from_slice(&tail);

                let n = want.len();
                for &body in crate::kernel::decode::Lz4Body::all() {
                    let mut out = vec![0u8; n + crate::kernel::decode::UNPACK_SLACK];
                    if !crate::kernel::decode::unpack_lz4_into_slice_on(body, &block, &mut out, n) {
                        refused += 1;
                        continue; // a refusal is the caller's fallback
                    }
                    decided += 1;
                    if out[..n] != want[..] {
                        let at = (0..n).find(|&i| out[i] != want[i]).unwrap();
                        failed.push((body, offset, mat, at));
                    }
                }
            }
        }

        assert!(
            failed.is_empty(),
            "a block with no literals decoded wrong: {failed:?}"
        );
        // A refusal is a legitimate answer -- the caller falls back -- but it
        // is also how a broken fast path hides: it mis-frames the stream, the
        // next block fails a guard, and a test that only compares decoded
        // bytes stays green. Every one of these blocks is well formed and the
        // kernel decodes all of them today, so anything less is a regression.
        assert_eq!(
            refused,
            0,
            "the kernel refused {refused} of {} well-formed blocks",
            decided + refused
        );
    }

    /// The token itself, with the literal length's extension if it needs one.
    fn push_token(block: &mut Vec<u8>, lit: usize, mat_nibble: usize) {
        block.push(((lit.min(15) as u8) << 4) | mat_nibble.min(15) as u8);
        push_extension(block, lit);
    }

    /// The bytes that follow a saturated nibble.
    fn push_extension(block: &mut Vec<u8>, n: usize) {
        if n >= 15 {
            let mut rest = n - 15;
            while rest >= 255 {
                block.push(255);
                rest -= 255;
            }
            block.push(rest as u8);
        }
    }

    /// A match that reaches back less far than it is long, at every offset.
    ///
    /// This is the one shape the all-literal test above cannot reach, and the
    /// aarch64 LZ4 body executed its own shuffle tables on it: `L(rep_ret)`
    /// sat in front of five hundred and twelve bytes of mask, and the return
    /// that should have stood between them was emitted after the `#endif` that
    /// ends them. Only the body that carries the tables was affected, so every
    /// test here stayed green while a foreign block with an overlapping match
    /// at offset sixteen or more killed the process.
    ///
    /// Built by hand rather than asked of liblz4, so it runs on every body and
    /// on machines with no library to link.
    #[test]
    fn the_kernel_reads_a_match_that_overlaps_itself() {
        let mut failed = Vec::new();

        // Both sides of the vector: under sixteen goes through the shuffle,
        // sixteen and over through the doubling ladder that was returning into
        // the tables.
        for offset in 1usize..=40 {
            for extra in [0usize, 1, 7, 13, 60, 200, 300] {
                let run = offset + extra + 4;

                // token: `offset` literals to seed the window, then the match
                let lit = offset;
                let (lit_tok, mat) = (lit.min(15), run - 4);
                let mut block = vec![((lit_tok as u8) << 4) | (mat.min(15) as u8)];
                if lit_tok == 15 {
                    let mut rest = lit - 15;
                    while rest >= 255 {
                        block.push(255);
                        rest -= 255;
                    }
                    block.push(rest as u8);
                }
                let seed: Vec<u8> = (0..lit).map(|i| (i as u8).wrapping_add(7)).collect();
                block.extend_from_slice(&seed);
                block.extend_from_slice(&(offset as u16).to_le_bytes());
                if mat >= 15 {
                    let mut rest = mat - 15;
                    while rest >= 255 {
                        block.push(255);
                        rest -= 255;
                    }
                    block.push(rest as u8);
                }
                // LZ4 needs five literals after the last match; give it more.
                let tail: Vec<u8> = (0..12u8).map(|i| i ^ 0x5A).collect();
                block.push((tail.len() as u8) << 4);
                block.extend_from_slice(&tail);

                let mut want = seed.clone();
                for _ in 0..run {
                    want.push(want[want.len() - offset]);
                }
                want.extend_from_slice(&tail);
                let n = want.len();

                for &body in crate::kernel::decode::Lz4Body::all() {
                    let mut out = vec![0u8; n + crate::kernel::decode::UNPACK_SLACK];
                    if !crate::kernel::decode::unpack_lz4_into_slice_on(body, &block, &mut out, n) {
                        continue; // a refusal is the caller's fallback, not a fault
                    }
                    if out[..n] != want[..] {
                        failed.push((body, offset, run));
                    }
                }
            }
        }

        assert!(
            failed.is_empty(),
            "an overlapping match decoded wrong: {failed:?}"
        );
    }

    /// The *kernel* must read what liblz4 wrote, not merely the store.
    ///
    /// [`our_decoder_reads_what_liblz4_wrote`] goes through `unpack_into`,
    /// which falls back to the portable decoder the moment the kernel declines.
    /// So it passes whether the kernel reads an LZ4 block or refuses every one
    /// of them, and it has been passing while the kernel refused.
    ///
    /// That is the failure mode this crate has already paid for once: a kernel
    /// that merely declines leaves every output-comparing test green, and the
    /// only thing that noticed was a benchmark assertion on rented hardware.
    /// This asks the kernel directly, one shape at a time, and says which ones
    /// it refused.
    #[cfg(feature = "liblz4")]
    #[test]
    fn the_kernel_itself_reads_what_liblz4_wrote() {
        if !crate::kernel::decode::asm_available() {
            return;
        }

        #[link(name = "lz4")]
        extern "C" {
            fn LZ4_compress_default(src: *const u8, dst: *mut u8, n: i32, cap: i32) -> i32;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut cases: Vec<(String, Vec<u8>)> = Vec::new();
        for size in [16usize, 64, 512, 1000, 4096, 65_536] {
            cases.push((format!("records_{size}"), records(size)));
            cases.push((format!("runs_{size}"), vec![b'a'; size]));
            cases.push((
                format!("noise_{size}"),
                (0..size).map(|_| noise_byte()).collect(),
            ));
        }

        let mut refused = Vec::new();
        for (label, data) in &cases {
            let mut block = vec![0u8; data.len() + 1024];
            let n = unsafe {
                LZ4_compress_default(
                    data.as_ptr(),
                    block.as_mut_ptr(),
                    data.len() as i32,
                    block.len() as i32,
                )
            };
            assert!(n > 0, "liblz4 refused {label}");
            block.truncate(n as usize);

            // Every body, not just this machine's. Dispatch runs one of them
            // here, so a divergence in any other would sit unseen until it
            // reached a part nobody tests on -- which has happened once
            // already, to the Xeon decoder on Emerald Rapids.
            let bodies = crate::kernel::decode::Lz4Body::all();
            // Four on an x86-64 part with AVX, two without -- the line bodies
            // copy 256 bits at a time and are not callable there. Two on
            // AArch64 since Neoverse V2 got its own, and both run anywhere
            // because that part line changes the shape of a loop rather than
            // the instructions it uses. One on anything else.
            //
            // Pinned so that adding a body without extending this loop is a
            // failure rather than a silent gap, which is what it did: the
            // Neoverse body went in and this assertion has been red ever since,
            // unseen for a day because the loop that checked every change ran
            // `cargo test` without `--features liblz4` and never
            // reached the four tests that need it. The standardised run found
            // it, which is what the standardised run is for.
            let want = if cfg!(target_arch = "x86_64") {
                if crate::cpu::features().avx2 {
                    4
                } else {
                    2
                }
            } else if cfg!(target_arch = "aarch64") {
                2
            } else {
                1
            };
            assert_eq!(
                bodies.len(),
                want,
                "a body was added or removed without this test noticing"
            );
            for &body in bodies {
                let mut out = vec![0u8; data.len() + crate::kernel::decode::UNPACK_SLACK];
                let ok = crate::kernel::decode::unpack_lz4_into_slice_on(
                    body,
                    &block,
                    &mut out,
                    data.len(),
                );
                if !ok {
                    refused.push(format!("{label} on {body:?} ({} block bytes)", block.len()));
                    continue;
                }
                assert_eq!(
                    &out[..data.len()],
                    &data[..],
                    "the {body:?} LZ4 body decoded {label} to the wrong bytes"
                );
            }
        }

        assert!(
            refused.is_empty(),
            "the assembly decoder refused {} of {} liblz4 blocks: {}",
            refused.len(),
            cases.len(),
            refused.join(", ")
        );
    }

    /// Adopting this format needs no flag day, and that is the point of
    /// reading LZ4 at all.
    ///
    /// A store whose values are LZ4 blocks can move to this one value at a
    /// time: the old bytes still decode, and whatever gets rewritten comes back
    /// in the new format. No offline conversion, no second decoder linked
    /// forever to read the past, no moment where both must be true at once.
    ///
    /// Two things the caller still owes, neither of them ours. The uncompressed
    /// length, because the LZ4 *block* format has never carried it -- anyone
    /// storing blocks already keeps it. And a bit saying which format an entry
    /// is in, because the two are not distinguishable by inspection: ours opens
    /// with a length varint and an LZ4 block opens with a token, and no byte
    /// value separates them.
    #[cfg(feature = "liblz4")]
    #[test]
    fn an_lz4_store_migrates_one_value_at_a_time() {
        #[link(name = "lz4")]
        extern "C" {
            fn LZ4_compress_default(src: *const u8, dst: *mut u8, n: i32, cap: i32) -> i32;
        }

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [512usize, 1024, 4096, 65_536] {
            cases.push(records(size));
        }

        let (mut was, mut now, mut migrated) = (0usize, 0usize, 0usize);
        let mut value = Vec::new();
        let mut repacked = Vec::new();
        let mut check = Vec::new();

        for original in &cases {
            // What is already on disk: an LZ4 block and a length beside it.
            let mut legacy = vec![0u8; original.len() + 1024];
            let n = unsafe {
                LZ4_compress_default(
                    original.as_ptr(),
                    legacy.as_mut_ptr(),
                    original.len() as i32,
                    legacy.len() as i32,
                )
            };
            assert!(n > 0, "liblz4 refused {} bytes", original.len());
            legacy.truncate(n as usize);

            // A read: the old entry decodes with no LZ4 library present.
            unpack_into(&legacy, &mut value, original.len())
                .unwrap_or_else(|e| panic!("legacy entry of {} bytes: {e}", original.len()));
            assert_eq!(&value[..], &original[..], "the old value came back wrong");

            // A write: it goes back in the new format.
            assert!(
                pack(&value, &mut repacked),
                "{} bytes did not pack",
                value.len()
            );
            unpack(&repacked, &mut check).expect("what we just wrote");
            assert_eq!(
                &check[..],
                &original[..],
                "the migrated value came back wrong"
            );

            was += legacy.len();
            now += repacked.len();
            migrated += 1;
        }

        eprintln!(
            "  migrated {migrated} values: {was} bytes of LZ4 -> {now} of ours, {:.1}% smaller",
            100.0 * (1.0 - now as f64 / was as f64)
        );
        assert!(now < was, "the rewrite must not cost space: {was} -> {now}");
    }

    /// The other direction, and it does not hold: liblz4 refuses what we wrote.
    ///
    /// The even split is the LZ4 token layout, so the body of such a value
    /// looks like an LZ4 block. It is not one. The format also constrains where
    /// a block may end -- a literal run of at least five bytes to close, and no
    /// match inside the last twelve -- and the packer enforces neither. It runs
    /// matches to the final byte and then writes a zero token, which LZ4 has no
    /// concept of.
    ///
    /// The assertion is inverted on purpose: it pins what is true today rather
    /// than leaving the question open. Should the packer ever be taught LZ4's
    /// end rules, this fails, and the fix is to turn it into the positive test
    /// it is already shaped like.
    #[cfg(feature = "liblz4")]
    #[test]
    fn liblz4_refuses_what_we_wrote() {
        #[link(name = "lz4")]
        extern "C" {
            fn LZ4_decompress_safe(src: *const u8, dst: *mut u8, n: i32, cap: i32) -> i32;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [16usize, 17, 63, 64, 65, 1000, 4096, 65_536] {
            cases.push(records(size));
            cases.push(vec![b'a'; size]);
            cases.push((0..size).map(|_| noise_byte()).collect());
        }
        cases.push(b"ab".repeat(3000));
        cases.push(b"abcdefg".repeat(900));

        let mut packed = Vec::new();
        let (mut even, mut wide, mut refused) = (0, 0, 0);
        for data in &cases {
            if !pack(data, &mut packed) {
                continue;
            }
            let (_, hybrid, header) = get_header(&packed).expect("a header");
            // A value that switches is read by two calls; this test wants the
            // single-body case, and counts the others so the split is visible.
            if hybrid {
                wide += 1;
                continue;
            }
            even += 1;

            let body = &packed[header..];
            let mut out = vec![0u8; data.len()];
            let n = unsafe {
                LZ4_decompress_safe(
                    body.as_ptr(),
                    out.as_mut_ptr(),
                    body.len() as i32,
                    out.len() as i32,
                )
            };
            if n != data.len() as i32 {
                refused += 1;
                continue;
            }
            assert_eq!(
                &out[..],
                &data[..],
                "liblz4 read {} bytes wrong",
                data.len()
            );
        }
        eprintln!("  even {even}, wide {wide}, refused by liblz4 {refused}");
        assert!(
            even > 0,
            "no case chose the even split, so nothing was tested"
        );
        assert_eq!(
            refused, even,
            "liblz4 accepted one of our blocks -- see the note above"
        );
    }

    /// The probe judges the whole value, not the part of it it happens to read.
    ///
    /// Both of these are values a store really sees -- a buffer written at a
    /// high offset, a record of fixed size only partly filled, a ciphertext
    /// followed by plaintext -- and both were stored whole when the probe read
    /// only the head and the middle. The cost of that is not a few percent, it
    /// is the entire ratio: `mix_tail` packs to 41276 bytes of 65536 and was
    /// being kept at 65536.
    #[test]
    fn a_value_that_compresses_anywhere_is_not_written_off() {
        let noise = |n: usize| {
            let mut st = 0x2545_F491_4F6C_DD1Du64;
            (0..n)
                .map(|_| {
                    st ^= st << 13;
                    st ^= st >> 7;
                    st ^= st << 17;
                    st as u8
                })
                .collect::<Vec<u8>>()
        };

        // Compressible only in the last third, past the midpoint the probe
        // used to stop at.
        let mut tail = noise(40 * 1024);
        tail.resize(64 * 1024, 0);

        // Compressible only in the middle, missing both a head window and a
        // window at the halfway mark.
        let mut middle = noise(64 * 1024);
        middle[1024..31_000].fill(0);

        for (what, data) in [("tail", tail), ("middle", middle)] {
            let mut out = Vec::new();
            assert!(pack(&data, &mut out), "{what}: refused outright");
            assert!(
                out.len() * 3 < data.len() * 2,
                "{what}: {} of {} bytes, so the compressible part was never searched",
                out.len(),
                data.len()
            );
        }
    }

    /// What the probe is allowed to get wrong, and what it is not.
    ///
    /// [`worth_packing`] refuses a value on the strength of two kilobyte-wide
    /// windows, and refusing wrongly is expensive in a way that being slow is
    /// not: the value is stored whole, so the cost is the entire compression
    /// ratio, not a few percent of pack throughput. A random header in front of
    /// a body that repeats is a real shape -- a nonce, a checksum block, an
    /// embedded thumbnail -- and judging the value on its head alone would lose
    /// it. The second window is what this holds in place.
    #[test]
    fn a_random_head_does_not_write_off_the_body() {
        let mut st = 0x2545_F491_4F6C_DD1Du64;
        let mut input: Vec<u8> = (0..4096)
            .map(|_| {
                st ^= st << 13;
                st ^= st >> 7;
                st ^= st << 17;
                st as u8
            })
            .collect();
        while input.len() < 64 * 1024 {
            input.extend_from_slice(b"the body of this value repeats itself, ");
        }

        let mut out = Vec::new();
        assert!(pack(&input, &mut out), "refused a value that compresses");
        assert!(
            out.len() * 4 < input.len(),
            "{} of {} bytes: the body was not searched",
            out.len(),
            input.len()
        );
    }

    /// The kernel must *accept* what the packer writes, not merely agree with
    /// the portable decoder about the answer.
    ///
    /// Those are different claims, and the difference hid a register-clobbering
    /// bug for three commits. A kernel that declines returns zero, the caller
    /// runs the portable decoder, and the bytes come out right -- so every test
    /// that compares output passes while the assembly is never exercised at
    /// all. This one fails instead.
    #[test]
    fn the_kernel_accepts_every_stream_the_packer_writes() {
        if !crate::kernel::decode::asm_available() {
            return;
        }
        let mut packed = Vec::new();
        let mut out = Vec::new();
        let mut sizes: Vec<usize> = vec![256, 512, 1000, 1024, 4096, 16_384, 65_536];
        sizes.extend([5usize, 17, 64, 100]);
        for size in sizes {
            for input in [records(size), vec![b'a'; size]] {
                if !pack(&input, &mut packed) {
                    continue;
                }
                let f = frame(&packed).expect("the packer wrote a header");
                let took = match f.switch {
                    None => crate::kernel::decode::unpack_asm(
                        f.body,
                        &mut out,
                        f.declared,
                        f.split.kernel(),
                    ),
                    Some(switch) => crate::kernel::decode::unpack_asm_hybrid(
                        f.body,
                        &mut out,
                        f.declared,
                        switch,
                        f.split.kernel(),
                        f.split.other().kernel(),
                    ),
                };
                assert!(
                    took,
                    "the kernel declined {} bytes ({})",
                    input.len(),
                    if f.switch.is_some() {
                        "two sections"
                    } else {
                        "one section"
                    }
                );
                assert_eq!(&out[..], &input[..], "and then lost bytes");
            }
        }
    }

    #[test]
    fn the_assembly_decoder_agrees_with_the_portable_one() {
        if !crate::kernel::decode::asm_available() {
            return;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [
            1usize, 2, 3, 4, 5, 7, 8, 15, 16, 17, 31, 32, 33, 47, 48, 49, 64, 1000, 4096, 8192,
            65_536,
        ] {
            cases.push(records(size));
            cases.push(vec![b'a'; size]);
            cases.push((0..size).map(|_| noise_byte()).collect());
        }
        cases.push(b"ab".repeat(3000));
        cases.push(b"abc".repeat(2000));
        cases.push(b"abcdefg".repeat(900));
        cases.push([b"xy".repeat(500), vec![0u8; 4000], b"xy".repeat(500)].concat());

        // A *short* match at a short distance, which the cases above never
        // produce: `"ab".repeat(3000)` is one enormous match and takes the
        // extended path. This is the fast path's overlapping copy, where the
        // source is closer than one copy block and the bytes have to be laid
        // down offset by offset. It was unreachable from this corpus, which was
        // found by splicing a jump into that branch and watching every test
        // still pass.
        for period in [4usize, 5, 7, 8, 11, 12, 14, 16, 24, 31] {
            let mut v = Vec::new();
            let mut n = 0u8;
            while v.len() < 4096 {
                let chunk: Vec<u8> = (0..period)
                    .map(|_| {
                        n = n.wrapping_add(37);
                        n
                    })
                    .collect();
                // Twice, so the second copy is a match of exactly `period`
                // bytes at a distance of exactly `period`.
                v.extend_from_slice(&chunk);
                v.extend_from_slice(&chunk);
            }
            cases.push(v);
        }

        let mut packed = Vec::new();
        let mut asm_out = Vec::new();
        let mut ref_out = Vec::new();

        for input in &cases {
            if !pack(input, &mut packed) {
                continue;
            }
            let f = frame(&packed).expect("the packer wrote a header");
            let took = match f.switch {
                None => crate::kernel::decode::unpack_asm(
                    f.body,
                    &mut asm_out,
                    f.declared,
                    f.split.kernel(),
                ),
                Some(switch) => crate::kernel::decode::unpack_asm_hybrid(
                    f.body,
                    &mut asm_out,
                    f.declared,
                    switch,
                    f.split.kernel(),
                    f.split.other().kernel(),
                ),
            };
            assert!(
                took,
                "the kernel declined a stream the packer produced, {} bytes ({})",
                input.len(),
                if f.switch.is_some() {
                    "two sections"
                } else {
                    "one section"
                }
            );
            unpack_portable(&packed, &mut ref_out).expect("the portable decoder accepts it");

            assert_eq!(
                asm_out,
                ref_out,
                "decoders disagree on {} bytes",
                input.len()
            );
            assert_eq!(
                &asm_out[..],
                &input[..],
                "round trip lost {} bytes",
                input.len()
            );
        }
    }

    /// A corrupt stream may be refused by the kernel and named by the portable
    /// decoder, and that asymmetry is deliberate. What must never happen is the
    /// kernel accepting something the portable decoder would reject, or the two
    /// accepting it and producing different bytes — that is how a silently
    /// wrong value reaches a client.
    #[test]
    fn the_assembly_decoder_never_accepts_more_than_the_portable_one() {
        if !crate::kernel::decode::asm_available() {
            return;
        }

        let mut packed = Vec::new();
        assert!(pack(&records(4096), &mut packed));

        let mut broken: Vec<Vec<u8>> = Vec::new();
        for cut in [0usize, 1, 2, 3, 5, 9, 17, 33, 64, 128] {
            if cut < packed.len() {
                broken.push(packed[..packed.len() - cut].to_vec());
            }
        }
        for at in [0usize, 1, 2, 3, 4, 8, 16, 32, 64, 100] {
            for xor in [0x01u8, 0x0F, 0xF0, 0xFF] {
                if at < packed.len() {
                    let mut c = packed.clone();
                    c[at] ^= xor;
                    broken.push(c);
                }
            }
        }

        let mut asm_out = Vec::new();
        let mut ref_out = Vec::new();
        for case in &broken {
            let Ok(f) = frame(case) else {
                continue;
            };
            let took = match f.switch {
                None => crate::kernel::decode::unpack_asm(
                    f.body,
                    &mut asm_out,
                    f.declared,
                    f.split.kernel(),
                ),
                Some(switch) => crate::kernel::decode::unpack_asm_hybrid(
                    f.body,
                    &mut asm_out,
                    f.declared,
                    switch,
                    f.split.kernel(),
                    f.split.other().kernel(),
                ),
            };
            if !took {
                continue; // refused, which the portable decoder is free to name
            }
            let reference = unpack_portable(case, &mut ref_out);
            assert!(
                reference.is_ok(),
                "the kernel accepted a stream the portable decoder rejects"
            );
            assert_eq!(asm_out, ref_out, "decoders disagree on a corrupt stream");
        }
    }

    #[test]
    fn the_assembly_packer_agrees_byte_for_byte() {
        if !crate::kernel::encode::asm_available() {
            // No kernel on this target. That is a supported configuration, not
            // a skipped test — there is simply nothing to diff against.
            return;
        }

        let mut state = 0x2545_F491_4F6C_DD1Du64;
        let mut noise_byte = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state as u8
        };

        let mut cases: Vec<Vec<u8>> = Vec::new();
        for size in [0usize, 1, 3, 4, 5, 7, 8, 15, 16, 17, 64, 1000, 4096, 65_536] {
            cases.push(records(size));
            cases.push(vec![b'a'; size]);
            cases.push((0..size).map(|_| noise_byte()).collect());
        }
        cases.push([b'a', b'b'].repeat(2048));
        let mut edge = b"prefix".to_vec();
        edge.extend(std::iter::repeat(b'z').take(3000));
        edge.extend_from_slice(b"suffix");
        cases.push(edge);
        // Data that keeps the even split and has matches worth a second look.
        // Without it every case here either fails to pack or takes the wide
        // split and is skipped below, so the diff had nothing to compare on the
        // one path the kernel actually implements -- and stayed green through a
        // change to the search that moved 4 KiB of it by 94 bytes.
        for size in [1000usize, 4096, 65_536] {
            let mut mixed = Vec::with_capacity(size);
            let mut i = 0u64;
            while mixed.len() < size {
                mixed.extend_from_slice(
                    format!(
                        "{{\"k\":\"{:08x}\",\"role\":\"member\",\"n\":{}}}",
                        i.wrapping_mul(2654435761),
                        i % 97
                    )
                    .as_bytes(),
                );
                i += 1;
            }
            mixed.truncate(size);
            cases.push(mixed);
        }

        let mut rust_out = Vec::new();
        let mut asm_out = Vec::new();
        let mut round_trip = Vec::new();

        // Which portable packer this kernel is the counterpart of. The two are
        // not the same: AArch64 implements the eager, fixed-split search and
        // must be diffed against the reference that matches it, while the
        // x86-64 kernel implements the production pass and is diffed against
        // the packer that actually runs. Diffing either against the other's
        // reference would compare two different algorithms and could only pass
        // by accident.
        let production = crate::kernel::encode::kernel_is_production_packer();

        // Coverage asserted rather than assumed: if the dispatch ever stops
        // reporting the bodies that exist, this test would quietly shrink to
        // one line and keep passing.
        #[cfg(target_arch = "x86_64")]
        assert_eq!(
            crate::kernel::encode::PartLine::all().len(),
            3,
            "x86-64 has three assembled bodies and the test must drive all of them"
        );

        // Every assembled body, not merely the one this machine dispatches to.
        // The three part lines are identical today and this is what says so;
        // without it an Intel runner would never execute the AMD body, and a
        // divergence in it would wait for production to find it.
        for &line in crate::kernel::encode::PartLine::all() {
            // Both sides start from the sentinel, not from zero: a zero slot reads
            // as position -1 and would send the kernel's verify load out of bounds.
            // Fresh per line, because the table is carried across records and a
            // line that inherited another's table would be searching a different
            // one.
            let mut rust_table = Box::new([EMPTY; HASH_SIZE]);
            let mut asm_table = crate::kernel::encode::new_table();

            for input in &cases {
                let rust_kept = if production {
                    pack_with(input, &mut rust_out, &mut rust_table)
                } else {
                    pack_with_eager(input, &mut rust_out, &mut rust_table)
                };
                let asm_kept =
                    crate::kernel::encode::pack_asm_on(line, input, &mut asm_out, &mut asm_table)
                        .is_some();

                // The eager kernel writes the even split only. Where the portable
                // packer chose the wide match it also made a second pass over the
                // table, so the two tables no longer hold the same thing -- both are
                // reset rather than letting the divergence follow into later cases.
                // The production kernel writes every split, so it has nothing to
                // skip.
                if rust_kept && !production {
                    let (_, hybrid, _) = get_header(&rust_out).expect("a header");
                    if hybrid {
                        rust_table.fill(EMPTY);
                        asm_table.fill(EMPTY);
                        continue;
                    }
                }

                assert_eq!(
                    rust_kept,
                    asm_kept,
                    "{line:?} disagreed on whether packing helped for {} bytes",
                    input.len()
                );

                if rust_kept {
                    assert_eq!(
                        rust_out,
                        asm_out,
                        "{line:?} produced a different encoding for the same {} byte input",
                        input.len()
                    );
                    unpack(&asm_out, &mut round_trip).expect("assembly output must unpack");
                    assert_eq!(&round_trip, input, "assembly output lost bytes");
                }
            }
        }
    }

    /// The kernel is assembled four times -- two splits by two table widths --
    /// and a diff that only ever reaches one of them is a diff that proves
    /// nothing about the other three.
    ///
    /// So this walks a randomised corpus and *counts* which bodies it entered,
    /// failing if any stayed cold. Coverage asserted rather than assumed: the
    /// eager corpus above reached the wide split on none of its cases for a
    /// while, and the test stayed green through a change that moved 4 KiB of
    /// output by 94 bytes.
    #[test]
    fn every_assembled_body_is_reached_and_agrees() {
        if !crate::kernel::encode::asm_available()
            || !crate::kernel::encode::kernel_is_production_packer()
        {
            return;
        }

        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };

        // Shapes chosen to straddle the two thresholds the kernel branches on:
        // NARROW_TABLE_ABOVE picks the table width, and how often the match
        // field overflows decides whether the split changes partway.
        let mut cases: Vec<Vec<u8>> = Vec::new();
        for &size in &[512usize, 2049, 4096, 8192, 8193, 20_000, 65_536] {
            // Long matches, which overflow a four-bit match field and are what
            // drives the stream into the wide split.
            let mut runs = Vec::with_capacity(size);
            while runs.len() < size {
                let n = 20 + (next() % 200) as usize;
                let b = (next() % 7) as u8 + b'a';
                runs.extend(std::iter::repeat(b).take(n));
            }
            runs.truncate(size);
            cases.push(runs);

            // Short matches and long literal runs, which keep the even split.
            let mut mixed = Vec::with_capacity(size);
            let mut i = 0u64;
            while mixed.len() < size {
                mixed.extend_from_slice(
                    format!("{{\"id\":{},\"v\":\"{:x}\"}}", i % 32, next() & 0xFFFF).as_bytes(),
                );
                i += 1;
            }
            mixed.truncate(size);
            cases.push(mixed);

            // A literal run past 255, which is the chain the extended length
            // field encodes, followed by something that matches.
            let mut long_lit: Vec<u8> = (0..size.min(600)).map(|_| next() as u8).collect();
            long_lit.extend_from_slice(&long_lit.clone());
            cases.push(long_lit);
        }

        let mut seen_even = 0usize;
        let mut seen_hybrid = 0usize;
        let mut seen_narrow = 0usize;
        let mut seen_wide_table = 0usize;

        let mut rust_out = Vec::new();
        let mut asm_out = Vec::new();
        let mut rust_table = Box::new([EMPTY; HASH_SIZE]);
        let mut asm_table = crate::kernel::encode::new_table();
        let mut round_trip = Vec::new();

        for input in &cases {
            let rust_kept = pack_with(input, &mut rust_out, &mut rust_table);
            let asm_kept =
                crate::kernel::encode::pack_asm(input, &mut asm_out, &mut asm_table).is_some();

            assert_eq!(
                rust_kept,
                asm_kept,
                "disagreed on whether packing helped for {} bytes",
                input.len()
            );

            if !rust_kept {
                continue;
            }
            assert_eq!(
                rust_out,
                asm_out,
                "different encodings for the same {} byte input",
                input.len()
            );
            unpack(&asm_out, &mut round_trip).expect("assembly output must unpack");
            assert_eq!(&round_trip, input, "assembly output lost bytes");

            let (_, hybrid, _) = get_header(&asm_out).expect("a header");
            if hybrid {
                seen_hybrid += 1;
            } else {
                seen_even += 1;
            }
            if input.len() > NARROW_TABLE_ABOVE {
                seen_narrow += 1;
            } else {
                seen_wide_table += 1;
            }
        }

        assert!(seen_even > 0, "no case stayed in the even split");
        assert!(
            seen_hybrid > 0,
            "no case changed split, so the wide bodies and the trailer went untested"
        );
        assert!(seen_wide_table > 0, "no case used the twelve-bit table");
        assert!(seen_narrow > 0, "no case used the eleven-bit table");
    }

    #[test]
    fn an_offset_before_the_start_is_refused() {
        // Declared length 8, one literal, then a match reaching back further
        // than anything produced.
        let mut stream = Vec::new();
        // Declared 8, not hybrid. Written as `varint(8 << 2)` before the spec
        // pass, which in the class encoding is a one-byte header declaring 32 --
        // the test passed, for a value it did not name.
        put_header(8, false, &mut stream);
        stream.push(1 << 4); // one literal, and a match-length nibble of zero
        stream.push(b'a');
        stream.extend_from_slice(&99u16.to_le_bytes()); // offset far too large

        let mut out = Vec::new();
        assert_eq!(unpack(&stream, &mut out), Err(PackError::BadOffset));
    }

    /// Decoding into a caller's buffer produces what decoding into a `Vec` does.
    ///
    /// The two share `unpack_framed` but not the path above it: the slice
    /// version drives the kernels itself, and the hybrid case drives them
    /// twice. Both are exercised here, and both buffer sizes are, because the
    /// slack is what decides whether the wide copies are allowed to run — a
    /// tight buffer takes a different path through the same decoder and has to
    /// produce the same bytes.
    #[test]
    fn decoding_into_a_slice_agrees_with_decoding_into_a_vec() {
        let mut seen_hybrid = 0usize;
        let mut seen_plain = 0usize;

        // The second shape exists to reach the switch: `records` repeats too
        // regularly to make the packer change split, and the two-kernel path
        // is the half of this function that the first shape cannot reach.
        let varied = |total: usize| -> Vec<u8> {
            let mut state = 0x2545_F491_4F6C_DD1Du64;
            let mut next = move || {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                state
            };
            let mut out = Vec::with_capacity(total);
            while out.len() < total {
                let r = next();
                out.extend_from_slice(
                    format!(
                        "{{\"id\":\"{:016x}\",\"tenant\":\"{:08x}\",\"score\":{}}}",
                        r,
                        next() as u32,
                        next() % 100_000
                    )
                    .as_bytes(),
                );
            }
            out.truncate(total);
            out
        };

        for len in [8usize, 64, 517, 4096, 9000, 65_536].map(biggest) {
            for (which, data) in [("records", records(len)), ("varied", varied(len))] {
                let mut packed = Vec::new();
                if !pack(&data, &mut packed) {
                    continue;
                }
                if get_header(&packed).unwrap().1 {
                    seen_hybrid += 1;
                } else {
                    seen_plain += 1;
                }

                let mut want = Vec::new();
                unpack(&packed, &mut want).expect("the vec path decodes");
                assert_eq!(want, data, "{which}_{len}");

                // With the slack, which is what the kernels ask for.
                let mut roomy = vec![0u8; decompressed_bound(data.len())];
                let n = unpack_into_slice(&packed, &mut roomy).expect("roomy");
                assert_eq!(n, data.len(), "{which}_{len} roomy length");
                assert_eq!(&roomy[..n], &data[..], "{which}_{len} roomy bytes");

                // And exactly the declared length, which turns them off.
                let mut tight = vec![0u8; data.len()];
                let n = unpack_into_slice(&packed, &mut tight).expect("tight");
                assert_eq!(n, data.len(), "{which}_{len} tight length");
                assert_eq!(tight, data, "{which}_{len} tight bytes");

                // One byte short is refused, and refused before anything runs.
                if !data.is_empty() {
                    let mut short = vec![0xAAu8; data.len() - 1];
                    assert_eq!(
                        unpack_into_slice(&packed, &mut short),
                        Err(PackError::OutputTooSmall),
                        "{which}_{len} short"
                    );
                    assert!(short.iter().all(|&b| b == 0xAA), "short buffer was written");
                }
            }
        }

        assert!(seen_plain > 0, "no single-section case");
        assert!(
            seen_hybrid > 0,
            "no hybrid case -- the two-kernel path is untested"
        );
    }

    /// The published vectors are what this decoder actually does.
    ///
    /// `docs/vectors.txt` is what a second implementation measures itself
    /// against, so it is the one document that has to be exactly right. It is
    /// generated by `cargo run --example make_vectors`, which checks every
    /// vector as it builds it -- and that is not enough on its own, because it
    /// only runs when someone runs it. Parsing the committed file here means
    /// the vectors go red the day the format drifts away from them, not the
    /// day someone thinks to regenerate.
    ///
    /// The parser is deliberately dumb, because a second implementer has to
    /// write one too.
    #[test]
    fn the_published_vectors_hold() {
        let text = include_str!("../docs/vectors.txt");
        let mut fields: Vec<(String, String)> = Vec::new();
        let mut checked = 0usize;
        let mut skipped = 0usize;

        fn unhex(text: &str) -> Vec<u8> {
            text.split_whitespace()
                .map(|b| u8::from_str_radix(b, 16).expect("not a hex byte"))
                .collect()
        }

        fn finish(fields: &mut Vec<(String, String)>, checked: &mut usize, skipped: &mut usize) {
            if fields.is_empty() {
                return;
            }
            let get = |key: &str| -> Option<String> {
                fields
                    .iter()
                    .find(|(k, _)| k == key)
                    .map(|(_, v)| v.clone())
            };
            let name = get("name").expect("a record with no name");
            let stream = unhex(&get("stream").unwrap_or_else(|| panic!("{name}: no stream")));

            let mut out = Vec::new();
            let got = unpack(&stream, &mut out);

            if let Some(want) = get("output") {
                assert_eq!(got, Ok(()), "{name}: refused");
                assert_eq!(out, unhex(&want), "{name}");
            } else if let Some(spec) = get("output-repeat") {
                let (unit, count) = spec
                    .split_once('*')
                    .unwrap_or_else(|| panic!("{name}: no '*'"));
                let unit = unhex(unit);
                let count: usize = count.trim().parse().expect("a count");
                // The class-3 vector decodes 2 MiB through the overlapping
                // copy, which is 37 minutes under Miri and no extra coverage:
                // the same branches, more times round. Skipped there, and the
                // count below is checked so that skipping cannot go unnoticed.
                if cfg!(miri) && unit.len() * count > 4096 {
                    *skipped += 1;
                    fields.clear();
                    return;
                }
                assert_eq!(got, Ok(()), "{name}: refused");
                assert_eq!(out.len(), unit.len() * count, "{name}: length");
                assert!(
                    out.chunks_exact(unit.len()).all(|c| c == unit),
                    "{name}: not the repeated unit"
                );
            } else if let Some(want) = get("reject") {
                let err = got.expect_err(&format!("{name}: accepted"));
                assert_eq!(format!("{err:?}"), want, "{name}");
            } else {
                panic!("{name}: no output, output-repeat or reject");
            }

            *checked += 1;
            fields.clear();
        }

        for line in text.lines() {
            if line.starts_with('#') {
                continue;
            }
            if line.trim().is_empty() {
                finish(&mut fields, &mut checked, &mut skipped);
                continue;
            }
            if line.starts_with(char::is_whitespace) {
                // A continuation of the field above it.
                let last = fields.last_mut().expect("a continuation with no field");
                last.1.push(' ');
                last.1.push_str(line.trim());
                continue;
            }
            let (key, value) = line.split_once(':').expect("a line that is not a field");
            fields.push((key.trim().to_owned(), value.trim().to_owned()));
        }
        finish(&mut fields, &mut checked, &mut skipped);

        // A parser that silently skipped every record would otherwise pass.
        // Under Miri three vectors are deliberately left out for size, so
        // the two counts are asserted separately rather than loosened.
        assert_eq!(
            checked + skipped,
            16,
            "wrong number of vectors seen ({checked} checked, {skipped} skipped)"
        );
        if cfg!(miri) {
            // The class-2 and class-3 vectors, which decode 8 KiB and 2 MiB.
            // Everything else is small enough to interpret.
            assert_eq!(skipped, 2, "the set of oversized vectors changed");
        } else {
            assert_eq!(skipped, 0, "a vector was skipped in a native run");
        }
    }

    /// One length, one encoding.
    ///
    /// A header may not spend more bytes than its length needs. The stream
    /// would decode correctly either way, which is why this has to be tested
    /// rather than noticed: the only symptom is that two byte strings mean the
    /// same value, and a cache that deduplicates packed bytes stores both.
    ///
    /// Each length is built in its own class, which must round-trip, and then
    /// in every longer class, which must be refused.
    #[test]
    fn a_header_wider_than_its_length_needs_is_refused() {
        for declared in [0usize, 1, 63, 64, 8191, 8192, 2_097_151, 2_097_152] {
            let mut literals = Vec::new();
            let mut body = Vec::new();
            // One block of literals is enough: the header is rejected before
            // the body is read, and a short declared length keeps the vector
            // small. Long ones are covered by the classes below them.
            let n = declared.min(8);
            body.push((n as u8) << 4);
            for i in 0..n {
                literals.push(b'a' + (i % 26) as u8);
            }
            body.extend_from_slice(&literals);

            let shortest = header_len(declared);
            // The index is the class, and the class is also the shift and the
            // top two bits of the first byte. Iterating the mask array instead
            // would hide the one number this test is about.
            #[allow(clippy::needless_range_loop)]
            for class in 0..4usize {
                let mut stream = Vec::new();
                // put_header always picks the shortest, so a wider one is
                // written by hand -- which is the whole point of the check.
                let payload = declared as u32;
                let top = (payload >> (8 * class)) as u8;
                if class == 0 && declared > 63 {
                    continue; // does not fit; not a non-canonical encoding
                }
                if class > 0 && top & !HEADER_MASK[class] != 0 {
                    continue; // likewise: this class cannot hold this length
                }
                stream.push(((class as u8) << 6) | top);
                for i in (0..class).rev() {
                    stream.push((payload >> (8 * i)) as u8);
                }
                stream.extend_from_slice(&body);

                let mut out = Vec::new();
                let got = unpack(&stream, &mut out);
                if class + 1 == shortest {
                    // The claim here is about the header, not the body: a
                    // length above eight outruns the literals and comes back
                    // `LengthMismatch`, which still means the header passed.
                    assert_ne!(
                        got,
                        Err(PackError::NonCanonicalHeader),
                        "declared {declared} refused in its own class"
                    );
                    if declared <= 8 {
                        assert_eq!(got, Ok(()), "declared {declared}");
                        assert_eq!(out, literals, "declared {declared}");
                    }
                } else {
                    assert_eq!(
                        got,
                        Err(PackError::NonCanonicalHeader),
                        "declared {declared} accepted in class {class}"
                    );
                }
            }
        }
    }

    /// The encoder's floors are not the format's floors.
    ///
    /// `pack` refuses anything under eight bytes, and `worth_storing` refuses
    /// anything it cannot shrink by an eighth, so no stream this encoder writes
    /// ever declares a tiny length. Neither rule is in the format, and a decoder
    /// that inferred them from the streams it happens to see would reject valid
    /// input from a conforming encoder that made other choices.
    ///
    /// So: every length the one-byte class can express, hand-built, all
    /// literals, no match. Zero included -- an empty value is a header and a
    /// token, and it decodes to nothing rather than to an error.
    #[test]
    fn a_length_the_encoder_would_never_emit_still_decodes() {
        for declared in 0usize..=63 {
            let mut stream = Vec::new();
            put_header(declared, false, &mut stream);
            // One final block: literals only. The token's nibble saturates at
            // fifteen and the rest continues in an extension chain.
            let lit_max = EVEN.lit_max();
            if declared < lit_max {
                stream.push((declared as u8) << 4);
            } else {
                stream.push((lit_max as u8) << 4);
                let mut rest = declared - lit_max;
                while rest >= 255 {
                    stream.push(255);
                    rest -= 255;
                }
                stream.push(rest as u8);
            }
            let literals: Vec<u8> = (0..declared).map(|i| b'a' + (i % 26) as u8).collect();
            stream.extend_from_slice(&literals);

            let mut out = Vec::new();
            assert_eq!(
                unpack(&stream, &mut out),
                Ok(()),
                "declared {declared} was refused"
            );
            assert_eq!(out, literals, "declared {declared}");
        }
    }
}