asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! HPACK header compression for HTTP/2.
//!
//! Implements RFC 7541: HPACK - Header Compression for HTTP/2.

use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;

use crate::bytes::{Bytes, BytesMut};

use super::error::H2Error;

/// Pre-built Huffman decode index: (code, code_bits) → symbol byte.
/// Covers codes of 9-30 bits (5-8 bit codes are handled by inline fast paths).
/// Symbol 256 (EOS) is stored as `None` so the decoder can reject it.
static HUFFMAN_DECODE_INDEX: LazyLock<HashMap<(u32, u8), Option<u8>>> = LazyLock::new(|| {
    let mut map = HashMap::with_capacity(257);
    for (sym, &(code, code_bits)) in HUFFMAN_TABLE.iter().enumerate() {
        if code_bits >= 9 {
            let value = if sym == 256 { None } else { Some(sym as u8) };
            map.insert((code, code_bits), value);
        }
    }
    map
});

/// Pre-built index for exact (name, value) → 1-based static table index lookups.
static STATIC_EXACT_INDEX: LazyLock<HashMap<(&'static str, &'static str), usize>> =
    LazyLock::new(|| {
        STATIC_TABLE
            .iter()
            .enumerate()
            .map(|(i, &(n, v))| ((n, v), i + 1))
            .collect()
    });

/// Pre-built index for name-only → first 1-based static table index lookups.
static STATIC_NAME_INDEX: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
    let mut map = HashMap::with_capacity(STATIC_TABLE.len());
    for (i, &(name, _)) in STATIC_TABLE.iter().enumerate() {
        map.entry(name).or_insert(i + 1);
    }
    map
});

/// Maximum allowed HPACK table size to prevent DoS (1MB).
const MAX_ALLOWED_TABLE_SIZE: usize = 1024 * 1024;

/// Maximum size of the dynamic table (default: 4096 bytes).
pub const DEFAULT_MAX_TABLE_SIZE: usize = 4096;

/// Static table entries as defined in RFC 7541 Appendix A.
static STATIC_TABLE: &[(&str, &str)] = &[
    (":authority", ""),                   // 1
    (":method", "GET"),                   // 2
    (":method", "POST"),                  // 3
    (":path", "/"),                       // 4
    (":path", "/index.html"),             // 5
    (":scheme", "http"),                  // 6
    (":scheme", "https"),                 // 7
    (":status", "200"),                   // 8
    (":status", "204"),                   // 9
    (":status", "206"),                   // 10
    (":status", "304"),                   // 11
    (":status", "400"),                   // 12
    (":status", "404"),                   // 13
    (":status", "500"),                   // 14
    ("accept-charset", ""),               // 15
    ("accept-encoding", "gzip, deflate"), // 16
    ("accept-language", ""),              // 17
    ("accept-ranges", ""),                // 18
    ("accept", ""),                       // 19
    ("access-control-allow-origin", ""),  // 20
    ("age", ""),                          // 21
    ("allow", ""),                        // 22
    ("authorization", ""),                // 23
    ("cache-control", ""),                // 24
    ("content-disposition", ""),          // 25
    ("content-encoding", ""),             // 26
    ("content-language", ""),             // 27
    ("content-length", ""),               // 28
    ("content-location", ""),             // 29
    ("content-range", ""),                // 30
    ("content-type", ""),                 // 31
    ("cookie", ""),                       // 32
    ("date", ""),                         // 33
    ("etag", ""),                         // 34
    ("expect", ""),                       // 35
    ("expires", ""),                      // 36
    ("from", ""),                         // 37
    ("host", ""),                         // 38
    ("if-match", ""),                     // 39
    ("if-modified-since", ""),            // 40
    ("if-none-match", ""),                // 41
    ("if-range", ""),                     // 42
    ("if-unmodified-since", ""),          // 43
    ("last-modified", ""),                // 44
    ("link", ""),                         // 45
    ("location", ""),                     // 46
    ("max-forwards", ""),                 // 47
    ("proxy-authenticate", ""),           // 48
    ("proxy-authorization", ""),          // 49
    ("range", ""),                        // 50
    ("referer", ""),                      // 51
    ("refresh", ""),                      // 52
    ("retry-after", ""),                  // 53
    ("server", ""),                       // 54
    ("set-cookie", ""),                   // 55
    ("strict-transport-security", ""),    // 56
    ("transfer-encoding", ""),            // 57
    ("user-agent", ""),                   // 58
    ("vary", ""),                         // 59
    ("via", ""),                          // 60
    ("www-authenticate", ""),             // 61
];

/// A header name-value pair.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Header {
    /// Header name (lowercase).
    pub name: String,
    /// Header value.
    pub value: String,
}

impl Header {
    /// Create a new header.
    #[must_use]
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }

    /// Calculate the size of this header for HPACK table purposes.
    /// Size = name bytes + value bytes + 32 overhead.
    #[must_use]
    pub fn size(&self) -> usize {
        self.name.len() + self.value.len() + 32
    }
}

/// Dynamic table for HPACK encoding/decoding.
///
/// Uses `VecDeque` so that front insertion (`push_front`) is O(1) amortized
/// rather than the O(n) of `Vec::insert(0, ...)`.
#[derive(Debug)]
pub struct DynamicTable {
    entries: VecDeque<Header>,
    size: usize,
    max_size: usize,
}

impl DynamicTable {
    /// Create a new dynamic table with default max size.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: VecDeque::new(),
            size: 0,
            max_size: DEFAULT_MAX_TABLE_SIZE,
        }
    }

    /// Create a dynamic table with specified max size.
    #[must_use]
    pub fn with_max_size(max_size: usize) -> Self {
        Self {
            entries: VecDeque::new(),
            size: 0,
            max_size: max_size.min(MAX_ALLOWED_TABLE_SIZE),
        }
    }

    /// Get the current size of the table.
    #[must_use]
    pub fn size(&self) -> usize {
        self.size
    }

    /// Get the maximum size of the table.
    #[must_use]
    pub fn max_size(&self) -> usize {
        self.max_size
    }

    /// Set the maximum size of the table, evicting entries if necessary.
    pub fn set_max_size(&mut self, max_size: usize) {
        self.max_size = max_size.min(MAX_ALLOWED_TABLE_SIZE);
        self.evict();
    }

    /// Insert a new entry at the beginning of the table.
    pub fn insert(&mut self, header: Header) {
        let entry_size = header.size();

        // Evict oldest entries (at back) to make room
        while self.size.saturating_add(entry_size) > self.max_size && !self.entries.is_empty() {
            if let Some(evicted) = self.entries.pop_back() {
                self.size = self.size.saturating_sub(evicted.size());
            }
        }

        // Only insert if it fits
        if entry_size <= self.max_size {
            self.entries.push_front(header);
            self.size = self.size.saturating_add(entry_size);
        }
    }

    /// Get an entry by index (1-indexed, after static table).
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&Header> {
        if index == 0 || index > self.entries.len() {
            None
        } else {
            Some(&self.entries[index - 1])
        }
    }

    /// Find an entry by name and value, returning the index if found.
    #[must_use]
    pub fn find(&self, name: &str, value: &str) -> Option<usize> {
        for (i, entry) in self.entries.iter().enumerate() {
            if entry.name == name && entry.value == value {
                return Some(STATIC_TABLE.len() + i + 1);
            }
        }
        None
    }

    /// Find an entry by name only, returning the index if found.
    #[must_use]
    pub fn find_name(&self, name: &str) -> Option<usize> {
        for (i, entry) in self.entries.iter().enumerate() {
            if entry.name == name {
                return Some(STATIC_TABLE.len() + i + 1);
            }
        }
        None
    }

    /// Evict oldest entries (at back) to fit within max size.
    fn evict(&mut self) {
        while self.size > self.max_size && !self.entries.is_empty() {
            if let Some(evicted) = self.entries.pop_back() {
                self.size = self.size.saturating_sub(evicted.size());
            }
        }
    }
}

impl Default for DynamicTable {
    fn default() -> Self {
        Self::new()
    }
}

/// Find entry in static table by name and value (O(1) via pre-built index).
fn find_static(name: &str, value: &str) -> Option<usize> {
    STATIC_EXACT_INDEX.get(&(name, value)).copied()
}

/// Find entry in static table by name only (O(1) via pre-built index).
fn find_static_name(name: &str) -> Option<usize> {
    STATIC_NAME_INDEX.get(name).copied()
}

/// Get entry from static table by index.
fn get_static(index: usize) -> Option<(&'static str, &'static str)> {
    if index == 0 || index > STATIC_TABLE.len() {
        None
    } else {
        Some(STATIC_TABLE[index - 1])
    }
}

/// HPACK encoder for encoding headers.
#[derive(Debug)]
pub struct Encoder {
    dynamic_table: DynamicTable,
    use_huffman: bool,
    /// Minimum dynamic table size observed since the last header block.
    /// RFC 7541 Section 4.2 requires emitting a size reduction if the size
    /// dropped and then increased between blocks.
    min_size_update: Option<usize>,
    /// Pending final dynamic table size update to emit at the start of the next header block.
    /// RFC 7541 Section 6.3 requires this when the table size changes.
    pending_size_update: Option<usize>,
}

impl Encoder {
    /// Create a new encoder with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            dynamic_table: DynamicTable::new(),
            use_huffman: true,
            min_size_update: None,
            pending_size_update: None,
        }
    }

    /// Create an encoder with specified max table size.
    #[must_use]
    pub fn with_max_size(max_size: usize) -> Self {
        Self {
            dynamic_table: DynamicTable::with_max_size(max_size),
            use_huffman: true,
            min_size_update: None,
            pending_size_update: None,
        }
    }

    /// Set whether to use Huffman encoding for strings.
    pub fn set_use_huffman(&mut self, use_huffman: bool) {
        self.use_huffman = use_huffman;
    }

    /// Set the maximum dynamic table size.
    ///
    /// Per RFC 7541 Section 6.3, the encoder will emit a dynamic table size
    /// update at the start of the next encoded header block.
    pub fn set_max_table_size(&mut self, size: usize) {
        let capped = size.min(MAX_ALLOWED_TABLE_SIZE);
        self.dynamic_table.set_max_size(capped);

        if let Some(min_so_far) = self.min_size_update {
            self.min_size_update = Some(min_so_far.min(capped));
        } else {
            self.min_size_update = Some(capped);
        }
        self.pending_size_update = Some(capped);
    }

    /// Returns the current dynamic table size in bytes.
    #[must_use]
    pub fn dynamic_table_size(&self) -> usize {
        self.dynamic_table.size()
    }

    /// Returns the current dynamic table size limit in bytes.
    #[must_use]
    pub fn dynamic_table_max_size(&self) -> usize {
        self.dynamic_table.max_size()
    }

    /// Encode a list of headers.
    ///
    /// If a dynamic table size update is pending (from `set_max_table_size`),
    /// it is emitted at the start of the block per RFC 7541 Section 6.3.
    pub fn encode(&mut self, headers: &[Header], dst: &mut BytesMut) {
        self.emit_pending_size_update(dst);
        for header in headers {
            self.encode_header(header, dst, true);
        }
    }

    /// Encode headers as "never indexed" (for sensitive headers like auth tokens).
    ///
    /// Uses RFC 7541 §6.2.3 "Literal Header Field Never Indexed" representation,
    /// which signals to intermediaries that these headers must not be compressed
    /// or added to any index, even on re-encoding.
    ///
    /// If a dynamic table size update is pending, it is emitted first.
    pub fn encode_sensitive(&mut self, headers: &[Header], dst: &mut BytesMut) {
        self.emit_pending_size_update(dst);
        for header in headers {
            self.encode_header(header, dst, false);
        }
    }

    /// Emit a pending dynamic table size update instruction on the wire.
    fn emit_pending_size_update(&mut self, dst: &mut BytesMut) {
        if let Some(min_size) = self.min_size_update.take() {
            if let Some(final_size) = self.pending_size_update.take() {
                if min_size < final_size {
                    encode_integer(dst, min_size, 5, 0x20);
                }
                encode_integer(dst, final_size, 5, 0x20);
            }
        }
    }

    /// Encode a single header.
    fn encode_header(&mut self, header: &Header, dst: &mut BytesMut, index: bool) {
        let normalized_name = if header.name.bytes().any(|byte| byte.is_ascii_uppercase()) {
            Cow::Owned(header.name.to_ascii_lowercase())
        } else {
            Cow::Borrowed(header.name.as_str())
        };
        let name = normalized_name.as_ref();
        let value = header.value.as_str();

        if index {
            // Exact-match indexing is only legal for regular indexed fields.
            // Sensitive headers must stay on the RFC 7541 §6.2.3 "never
            // indexed" representation even if the same name/value is already
            // present in the static or dynamic table.
            if let Some(idx) =
                find_static(name, value).or_else(|| self.dynamic_table.find(name, value))
            {
                encode_integer(dst, idx, 7, 0x80);
                return;
            }
        }

        // Try to find name match
        let name_idx = find_static_name(name).or_else(|| self.dynamic_table.find_name(name));

        if index {
            // Literal with incremental indexing
            if let Some(idx) = name_idx {
                encode_integer(dst, idx, 6, 0x40);
            } else {
                dst.put_u8(0x40);
                encode_string(dst, name, self.use_huffman);
            }
            encode_string(dst, value, self.use_huffman);

            // Add to dynamic table
            let mut indexed_header = header.clone();
            indexed_header.name = normalized_name.into_owned();
            self.dynamic_table.insert(indexed_header);
        } else {
            // Literal without indexing (never indexed for sensitive)
            if let Some(idx) = name_idx {
                encode_integer(dst, idx, 4, 0x10);
            } else {
                dst.put_u8(0x10);
                encode_string(dst, name, self.use_huffman);
            }
            encode_string(dst, value, self.use_huffman);
        }
    }
}

impl Default for Encoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Maximum allowed decoded string length to prevent DoS (256 KB).
/// This bounds the allocation size before the header-list-size check runs.
const MAX_STRING_LENGTH: usize = 256 * 1024;
/// Maximum consecutive dynamic table size updates allowed at block start.
const MAX_SIZE_UPDATES: usize = 16;

/// HPACK decoder for decoding headers.
#[derive(Debug)]
pub struct Decoder {
    dynamic_table: DynamicTable,
    max_header_list_size: usize,
    /// Maximum table size allowed by SETTINGS (from peer).
    /// Dynamic table size updates must not exceed this.
    allowed_table_size: usize,
}

impl Decoder {
    /// Create a new decoder with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            dynamic_table: DynamicTable::new(),
            max_header_list_size: 16384,
            allowed_table_size: 4096, // HTTP/2 default
        }
    }

    /// Create a decoder with specified max table size.
    #[must_use]
    pub fn with_max_size(max_size: usize) -> Self {
        let capped_size = max_size.min(MAX_ALLOWED_TABLE_SIZE);
        Self {
            dynamic_table: DynamicTable::with_max_size(capped_size),
            max_header_list_size: 16384,
            allowed_table_size: capped_size,
        }
    }

    /// Set the maximum header list size.
    pub fn set_max_header_list_size(&mut self, size: usize) {
        self.max_header_list_size = size;
    }

    /// Set the allowed table size (from SETTINGS frame).
    /// This limits what the peer can request via dynamic table size updates.
    pub fn set_allowed_table_size(&mut self, size: usize) {
        self.allowed_table_size = size.min(MAX_ALLOWED_TABLE_SIZE);
    }

    /// Returns the current dynamic table size in bytes.
    #[must_use]
    pub fn dynamic_table_size(&self) -> usize {
        self.dynamic_table.size()
    }

    /// Returns the current dynamic table size limit in bytes.
    #[must_use]
    pub fn dynamic_table_max_size(&self) -> usize {
        self.dynamic_table.max_size()
    }

    /// Returns the maximum table size currently allowed by peer SETTINGS.
    #[must_use]
    pub fn allowed_table_size(&self) -> usize {
        self.allowed_table_size
    }

    /// Decode headers from a buffer.
    ///
    /// Per RFC 7541 §4.2, dynamic table size updates are only permitted at the
    /// beginning of the header block (before the first header field
    /// representation). Any size update after a header field representation is
    /// a COMPRESSION_ERROR.
    pub fn decode(&mut self, src: &mut Bytes) -> Result<Vec<Header>, H2Error> {
        let mut headers = Vec::with_capacity(8);
        let mut total_size = 0;

        // RFC 7541 §4.2: dynamic table size updates are valid at the beginning
        // of a header block and MAY appear multiple times there.
        // Accept update-only blocks as valid.
        let mut size_update_count = 0;
        while !src.is_empty() && (src[0] & 0xe0 == 0x20) {
            size_update_count += 1;
            if size_update_count > MAX_SIZE_UPDATES {
                return Err(H2Error::compression(
                    "too many consecutive dynamic table size updates",
                ));
            }

            let new_size = decode_integer(src, 5)?;
            if new_size > self.allowed_table_size {
                return Err(H2Error::compression(
                    "dynamic table size update exceeds allowed maximum",
                ));
            }
            self.dynamic_table.set_max_size(new_size);
        }

        while !src.is_empty() {
            let header = self.decode_header(src)?;
            total_size += header.size();
            if total_size > self.max_header_list_size {
                return Err(H2Error::compression("header list too large"));
            }
            headers.push(header);
        }

        Ok(headers)
    }

    /// Decode a single header.
    ///
    fn decode_header(&mut self, src: &mut Bytes) -> Result<Header, H2Error> {
        if src.is_empty() {
            return Err(H2Error::compression("unexpected end of header block"));
        }

        let first = src[0];

        if first & 0x80 != 0 {
            // Indexed header field
            let index = decode_integer(src, 7)?;
            return self.get_indexed(index);
        }

        if first & 0x40 != 0 {
            // Literal with incremental indexing
            let (name, value) = self.decode_literal(src, 6)?;
            let header = Header::new(name, value);
            self.dynamic_table.insert(header.clone());
            return Ok(header);
        }

        if first & 0x20 != 0 {
            return Err(H2Error::compression(
                "dynamic table size update after first header in block",
            ));
        }

        if first & 0x10 != 0 {
            // Literal never indexed
            let (name, value) = self.decode_literal(src, 4)?;
            return Ok(Header::new(name, value));
        }

        // Literal without indexing
        let (name, value) = self.decode_literal(src, 4)?;
        Ok(Header::new(name, value))
    }

    /// Decode a literal header field.
    ///
    /// Validates header name and value characters per RFC 9113 Section 8.2.1:
    /// - Names must be lowercase ASCII (a-z, 0-9, and `!#$%&'*+-.^_`|~`).
    /// - Values must not contain NUL (`\0`), CR (`\r`), or LF (`\n`).
    ///
    /// Rejecting these characters prevents HTTP/1 header injection when H2
    /// frames are forwarded to HTTP/1.1 backends.
    fn decode_literal(
        &self,
        src: &mut Bytes,
        prefix_bits: u8,
    ) -> Result<(String, String), H2Error> {
        let index = decode_integer(src, prefix_bits)?;

        let name = if index == 0 {
            let n = decode_string(src)?;
            validate_header_name(&n)?;
            n
        } else {
            self.get_indexed_name(index)?
        };

        let value = decode_string(src)?;
        validate_header_value(&value)?;
        Ok((name, value))
    }

    /// Get a header by index from static or dynamic table.
    fn get_indexed(&self, index: usize) -> Result<Header, H2Error> {
        if index == 0 {
            return Err(H2Error::compression("invalid index 0"));
        }

        if index <= STATIC_TABLE.len() {
            let (name, value) =
                get_static(index).ok_or_else(|| H2Error::compression("invalid static index"))?;
            Ok(Header::new(name, value))
        } else {
            let dyn_index = index - STATIC_TABLE.len();
            self.dynamic_table
                .get(dyn_index)
                .cloned()
                .ok_or_else(|| H2Error::compression("invalid dynamic index"))
        }
    }

    /// Get only the header name by index from static or dynamic table.
    ///
    /// This avoids cloning full header values on indexed-name literal fields.
    fn get_indexed_name(&self, index: usize) -> Result<String, H2Error> {
        if index == 0 {
            return Err(H2Error::compression("invalid index 0"));
        }

        if index <= STATIC_TABLE.len() {
            let (name, _) =
                get_static(index).ok_or_else(|| H2Error::compression("invalid static index"))?;
            Ok(name.to_string())
        } else {
            let dyn_index = index - STATIC_TABLE.len();
            self.dynamic_table
                .get(dyn_index)
                .map(|h| h.name.clone())
                .ok_or_else(|| H2Error::compression("invalid dynamic index"))
        }
    }
}

impl Default for Decoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Encode an integer using HPACK integer encoding.
#[inline]
fn encode_integer(dst: &mut BytesMut, value: usize, prefix_bits: u8, prefix: u8) {
    let max_first = (1 << prefix_bits) - 1;

    if value < max_first {
        dst.put_u8(prefix | value as u8);
    } else {
        dst.put_u8(prefix | max_first as u8);
        let mut remaining = value - max_first;
        while remaining >= 128 {
            dst.put_u8((remaining & 0x7f) as u8 | 0x80);
            remaining >>= 7;
        }
        dst.put_u8(remaining as u8);
    }
}

/// Decode an integer using HPACK integer encoding.
fn decode_integer(src: &mut Bytes, prefix_bits: u8) -> Result<usize, H2Error> {
    if src.is_empty() {
        return Err(H2Error::compression("unexpected end of integer"));
    }

    let max_first = (1 << prefix_bits) - 1;
    let first = src[0] & max_first as u8;
    let _ = src.split_to(1);

    if (first as usize) < max_first {
        return Ok(first as usize);
    }

    let mut value = max_first;
    let mut shift = 0;

    loop {
        if src.is_empty() {
            return Err(H2Error::compression("unexpected end of integer"));
        }
        let byte = src[0];
        let _ = src.split_to(1);

        // Guard against unbounded continuation sequences. The shift limit
        // ensures the loop terminates even on malicious input.
        if shift > 28 {
            return Err(H2Error::compression("integer too large"));
        }

        // Compute increment = (byte & 0x7f) * 2^shift using checked
        // arithmetic. Note: checked_shl only validates shift < bit_width,
        // it does NOT detect when the result silently truncates (e.g. on
        // 32-bit where 127 << 28 overflows u32). Using checked_mul on the
        // multiplier catches the actual value overflow on all platforms.
        let multiplier = 1usize
            .checked_shl(shift)
            .ok_or_else(|| H2Error::compression("integer overflow in shift"))?;
        let increment = ((byte & 0x7f) as usize)
            .checked_mul(multiplier)
            .ok_or_else(|| H2Error::compression("integer overflow in multiply"))?;
        value = value
            .checked_add(increment)
            .ok_or_else(|| H2Error::compression("integer overflow in addition"))?;
        shift += 7;

        if byte & 0x80 == 0 {
            break;
        }
    }

    Ok(value)
}

const fn build_bit_masks() -> [u64; 65] {
    let mut masks = [0u64; 65];
    let mut i = 0usize;
    while i <= 64 {
        masks[i] = if i == 64 { u64::MAX } else { (1u64 << i) - 1 };
        i += 1;
    }
    masks
}

const BIT_MASKS: [u64; 65] = build_bit_masks();

/// Huffman-encode a byte slice per RFC 7541 Appendix B.
///
/// Packs variable-length Huffman codes into whole bytes with EOS-padding
/// (all-1s) in the final partial byte, as required by Section 5.2.
fn encode_huffman(src: &[u8]) -> Vec<u8> {
    let mut dst = Vec::with_capacity(src.len());
    let mut accumulator: u64 = 0;
    let mut bits: u32 = 0;

    for &byte in src {
        let (code, code_bits) = HUFFMAN_TABLE[byte as usize];
        let code_bits_u32 = u32::from(code_bits);
        accumulator = (accumulator << code_bits_u32) | u64::from(code);
        bits += code_bits_u32;

        while bits >= 8 {
            bits -= 8;
            dst.push((accumulator >> bits) as u8);
            accumulator &= BIT_MASKS[bits as usize];
        }
    }

    // Pad remaining bits with EOS prefix (all 1s) per RFC 7541 Section 5.2.
    if bits > 0 {
        let padding = 8 - bits;
        accumulator = (accumulator << padding) | BIT_MASKS[padding as usize];
        dst.push(accumulator as u8);
    }

    dst
}

/// Encode a string (with optional Huffman encoding per RFC 7541 Section 5.2).
#[inline]
fn encode_string(dst: &mut BytesMut, value: &str, use_huffman: bool) {
    if use_huffman {
        let encoded = encode_huffman(value.as_bytes());
        // High bit (0x80) signals Huffman-encoded string.
        encode_integer(dst, encoded.len(), 7, 0x80);
        dst.extend_from_slice(&encoded);
    } else {
        let bytes = value.as_bytes();
        encode_integer(dst, bytes.len(), 7, 0x00);
        dst.extend_from_slice(bytes);
    }
}

/// Decode a string (handling Huffman encoding).
/// Validate an HTTP/2 header name per RFC 9113 Section 8.2.1.
///
/// Header names must consist of lowercase ASCII letters (`a-z`), digits (`0-9`),
/// and the token characters `!#$%&'*+-.^_`|~`. Uppercase letters, spaces,
/// tabs, and control characters (including NUL, CR, LF) are forbidden.
///
/// Pseudo-header names (starting with `:`) are also permitted.
fn validate_header_name(name: &str) -> Result<(), H2Error> {
    if name.is_empty() {
        return Err(H2Error::compression("empty header name"));
    }
    for (i, b) in name.bytes().enumerate() {
        let valid = matches!(b,
            b'a'..=b'z' | b'0'..=b'9'
            | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*'
            | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~'
        ) || (b == b':' && i == 0);
        if !valid {
            return Err(H2Error::compression(
                "invalid character in header name (RFC 9113 Section 8.2.1)",
            ));
        }
    }
    Ok(())
}

/// Validate an HTTP/2 header value per RFC 9113 Section 8.2.1.
///
/// Header values must not contain NUL (`\0`), CR (`\r`), or LF (`\n`).
/// These characters enable HTTP/1 header injection when H2 frames are
/// forwarded to HTTP/1.1 backends.
fn validate_header_value(value: &str) -> Result<(), H2Error> {
    for b in value.bytes() {
        if matches!(b, b'\0' | b'\r' | b'\n') {
            return Err(H2Error::compression(
                "invalid character in header value (RFC 9113 Section 8.2.1)",
            ));
        }
    }
    Ok(())
}

fn decode_string(src: &mut Bytes) -> Result<String, H2Error> {
    if src.is_empty() {
        return Err(H2Error::compression("unexpected end of string"));
    }

    let huffman = src[0] & 0x80 != 0;
    let length = decode_integer(src, 7)?;

    if length > MAX_STRING_LENGTH {
        return Err(H2Error::compression("string length exceeds maximum"));
    }

    if src.len() < length {
        return Err(H2Error::compression("string length exceeds buffer"));
    }

    let data = src.split_to(length);

    if huffman {
        decode_huffman(&data)
    } else {
        String::from_utf8(data.to_vec())
            .map_err(|_| H2Error::compression("invalid UTF-8 in header"))
    }
}

/// Huffman code table from RFC 7541 Appendix B.
///
/// Each entry is (code, bit_length) where code is the Huffman code for that symbol
/// and bit_length is the number of bits in the code. Symbol 256 is the EOS marker.
#[rustfmt::skip]
#[allow(clippy::unreadable_literal)]
static HUFFMAN_TABLE: [(u32, u8); 257] = [
    (0x1ff8, 13),      // 0
    (0x7fffd8, 23),    // 1
    (0xfffffe2, 28),   // 2
    (0xfffffe3, 28),   // 3
    (0xfffffe4, 28),   // 4
    (0xfffffe5, 28),   // 5
    (0xfffffe6, 28),   // 6
    (0xfffffe7, 28),   // 7
    (0xfffffe8, 28),   // 8
    (0xffffea, 24),    // 9
    (0x3ffffffc, 30),  // 10
    (0xfffffe9, 28),   // 11
    (0xfffffea, 28),   // 12
    (0x3ffffffd, 30),  // 13
    (0xfffffeb, 28),   // 14
    (0xfffffec, 28),   // 15
    (0xfffffed, 28),   // 16
    (0xfffffee, 28),   // 17
    (0xfffffef, 28),   // 18
    (0xffffff0, 28),   // 19
    (0xffffff1, 28),   // 20
    (0xffffff2, 28),   // 21
    (0x3ffffffe, 30),  // 22
    (0xffffff3, 28),   // 23
    (0xffffff4, 28),   // 24
    (0xffffff5, 28),   // 25
    (0xffffff6, 28),   // 26
    (0xffffff7, 28),   // 27
    (0xffffff8, 28),   // 28
    (0xffffff9, 28),   // 29
    (0xffffffa, 28),   // 30
    (0xffffffb, 28),   // 31
    (0x14, 6),         // 32 ' '
    (0x3f8, 10),       // 33 '!'
    (0x3f9, 10),       // 34 '"'
    (0xffa, 12),       // 35 '#'
    (0x1ff9, 13),      // 36 '$'
    (0x15, 6),         // 37 '%'
    (0xf8, 8),         // 38 '&'
    (0x7fa, 11),       // 39 '\''
    (0x3fa, 10),       // 40 '('
    (0x3fb, 10),       // 41 ')'
    (0xf9, 8),         // 42 '*'
    (0x7fb, 11),       // 43 '+'
    (0xfa, 8),         // 44 ','
    (0x16, 6),         // 45 '-'
    (0x17, 6),         // 46 '.'
    (0x18, 6),         // 47 '/'
    (0x0, 5),          // 48 '0'
    (0x1, 5),          // 49 '1'
    (0x2, 5),          // 50 '2'
    (0x19, 6),         // 51 '3'
    (0x1a, 6),         // 52 '4'
    (0x1b, 6),         // 53 '5'
    (0x1c, 6),         // 54 '6'
    (0x1d, 6),         // 55 '7'
    (0x1e, 6),         // 56 '8'
    (0x1f, 6),         // 57 '9'
    (0x5c, 7),         // 58 ':'
    (0xfb, 8),         // 59 ';'
    (0x7ffc, 15),      // 60 '<'
    (0x20, 6),         // 61 '='
    (0xffb, 12),       // 62 '>'
    (0x3fc, 10),       // 63 '?'
    (0x1ffa, 13),      // 64 '@'
    (0x21, 6),         // 65 'A'
    (0x5d, 7),         // 66 'B'
    (0x5e, 7),         // 67 'C'
    (0x5f, 7),         // 68 'D'
    (0x60, 7),         // 69 'E'
    (0x61, 7),         // 70 'F'
    (0x62, 7),         // 71 'G'
    (0x63, 7),         // 72 'H'
    (0x64, 7),         // 73 'I'
    (0x65, 7),         // 74 'J'
    (0x66, 7),         // 75 'K'
    (0x67, 7),         // 76 'L'
    (0x68, 7),         // 77 'M'
    (0x69, 7),         // 78 'N'
    (0x6a, 7),         // 79 'O'
    (0x6b, 7),         // 80 'P'
    (0x6c, 7),         // 81 'Q'
    (0x6d, 7),         // 82 'R'
    (0x6e, 7),         // 83 'S'
    (0x6f, 7),         // 84 'T'
    (0x70, 7),         // 85 'U'
    (0x71, 7),         // 86 'V'
    (0x72, 7),         // 87 'W'
    (0xfc, 8),         // 88 'X'
    (0x73, 7),         // 89 'Y'
    (0xfd, 8),         // 90 'Z'
    (0x1ffb, 13),      // 91 '['
    (0x7fff0, 19),     // 92 '\\'
    (0x1ffc, 13),      // 93 ']'
    (0x3ffc, 14),      // 94 '^'
    (0x22, 6),         // 95 '_'
    (0x7ffd, 15),      // 96 '`'
    (0x3, 5),          // 97 'a'
    (0x23, 6),         // 98 'b'
    (0x4, 5),          // 99 'c'
    (0x24, 6),         // 100 'd'
    (0x5, 5),          // 101 'e'
    (0x25, 6),         // 102 'f'
    (0x26, 6),         // 103 'g'
    (0x27, 6),         // 104 'h'
    (0x6, 5),          // 105 'i'
    (0x74, 7),         // 106 'j'
    (0x75, 7),         // 107 'k'
    (0x28, 6),         // 108 'l'
    (0x29, 6),         // 109 'm'
    (0x2a, 6),         // 110 'n'
    (0x7, 5),          // 111 'o'
    (0x2b, 6),         // 112 'p'
    (0x76, 7),         // 113 'q'
    (0x2c, 6),         // 114 'r'
    (0x8, 5),          // 115 's'
    (0x9, 5),          // 116 't'
    (0x2d, 6),         // 117 'u'
    (0x77, 7),         // 118 'v'
    (0x78, 7),         // 119 'w'
    (0x79, 7),         // 120 'x'
    (0x7a, 7),         // 121 'y'
    (0x7b, 7),         // 122 'z'
    (0x7ffe, 15),      // 123 '{'
    (0x7fc, 11),       // 124 '|'
    (0x3ffd, 14),      // 125 '}'
    (0x1ffd, 13),      // 126 '~'
    (0xffffffc, 28),   // 127
    (0xfffe6, 20),     // 128
    (0x3fffd2, 22),    // 129
    (0xfffe7, 20),     // 130
    (0xfffe8, 20),     // 131
    (0x3fffd3, 22),    // 132
    (0x3fffd4, 22),    // 133
    (0x3fffd5, 22),    // 134
    (0x7fffd9, 23),    // 135
    (0x3fffd6, 22),    // 136
    (0x7fffda, 23),    // 137
    (0x7fffdb, 23),    // 138
    (0x7fffdc, 23),    // 139
    (0x7fffdd, 23),    // 140
    (0x7fffde, 23),    // 141
    (0xffffeb, 24),    // 142
    (0x7fffdf, 23),    // 143
    (0xffffec, 24),    // 144
    (0xffffed, 24),    // 145
    (0x3fffd7, 22),    // 146
    (0x7fffe0, 23),    // 147
    (0xffffee, 24),    // 148
    (0x7fffe1, 23),    // 149
    (0x7fffe2, 23),    // 150
    (0x7fffe3, 23),    // 151
    (0x7fffe4, 23),    // 152
    (0x1fffdc, 21),    // 153
    (0x3fffd8, 22),    // 154
    (0x7fffe5, 23),    // 155
    (0x3fffd9, 22),    // 156
    (0x7fffe6, 23),    // 157
    (0x7fffe7, 23),    // 158
    (0xffffef, 24),    // 159
    (0x3fffda, 22),    // 160
    (0x1fffdd, 21),    // 161
    (0xfffe9, 20),     // 162
    (0x3fffdb, 22),    // 163
    (0x3fffdc, 22),    // 164
    (0x7fffe8, 23),    // 165
    (0x7fffe9, 23),    // 166
    (0x1fffde, 21),    // 167
    (0x7fffea, 23),    // 168
    (0x3fffdd, 22),    // 169
    (0x3fffde, 22),    // 170
    (0xfffff0, 24),    // 171
    (0x1fffdf, 21),    // 172
    (0x3fffdf, 22),    // 173
    (0x7fffeb, 23),    // 174
    (0x7fffec, 23),    // 175
    (0x1fffe0, 21),    // 176
    (0x1fffe1, 21),    // 177
    (0x3fffe0, 22),    // 178
    (0x1fffe2, 21),    // 179
    (0x7fffed, 23),    // 180
    (0x3fffe1, 22),    // 181
    (0x7fffee, 23),    // 182
    (0x7fffef, 23),    // 183
    (0xfffea, 20),     // 184
    (0x3fffe2, 22),    // 185
    (0x3fffe3, 22),    // 186
    (0x3fffe4, 22),    // 187
    (0x7ffff0, 23),    // 188
    (0x3fffe5, 22),    // 189
    (0x3fffe6, 22),    // 190
    (0x7ffff1, 23),    // 191
    (0x3ffffe0, 26),   // 192
    (0x3ffffe1, 26),   // 193
    (0xfffeb, 20),     // 194
    (0x7fff1, 19),     // 195
    (0x3fffe7, 22),    // 196
    (0x7ffff2, 23),    // 197
    (0x3fffe8, 22),    // 198
    (0x1ffffec, 25),   // 199
    (0x3ffffe2, 26),   // 200
    (0x3ffffe3, 26),   // 201
    (0x3ffffe4, 26),   // 202
    (0x7ffffde, 27),   // 203
    (0x7ffffdf, 27),   // 204
    (0x3ffffe5, 26),   // 205
    (0xfffff1, 24),    // 206
    (0x1ffffed, 25),   // 207
    (0x7fff2, 19),     // 208
    (0x1fffe3, 21),    // 209
    (0x3ffffe6, 26),   // 210
    (0x7ffffe0, 27),   // 211
    (0x7ffffe1, 27),   // 212
    (0x3ffffe7, 26),   // 213
    (0x7ffffe2, 27),   // 214
    (0xfffff2, 24),    // 215
    (0x1fffe4, 21),    // 216
    (0x1fffe5, 21),    // 217
    (0x3ffffe8, 26),   // 218
    (0x3ffffe9, 26),   // 219
    (0xffffffd, 28),   // 220
    (0x7ffffe3, 27),   // 221
    (0x7ffffe4, 27),   // 222
    (0x7ffffe5, 27),   // 223
    (0xfffec, 20),     // 224
    (0xfffff3, 24),    // 225
    (0xfffed, 20),     // 226
    (0x1fffe6, 21),    // 227
    (0x3fffe9, 22),    // 228
    (0x1fffe7, 21),    // 229
    (0x1fffe8, 21),    // 230
    (0x7ffff3, 23),    // 231
    (0x3fffea, 22),    // 232
    (0x3fffeb, 22),    // 233
    (0x1ffffee, 25),   // 234
    (0x1ffffef, 25),   // 235
    (0xfffff4, 24),    // 236
    (0xfffff5, 24),    // 237
    (0x3ffffea, 26),   // 238
    (0x7ffff4, 23),    // 239
    (0x3ffffeb, 26),   // 240
    (0x7ffffe6, 27),   // 241
    (0x3ffffec, 26),   // 242
    (0x3ffffed, 26),   // 243
    (0x7ffffe7, 27),   // 244
    (0x7ffffe8, 27),   // 245
    (0x7ffffe9, 27),   // 246
    (0x7ffffea, 27),   // 247
    (0x7ffffeb, 27),   // 248
    (0xffffffe, 28),   // 249
    (0x7ffffec, 27),   // 250
    (0x7ffffed, 27),   // 251
    (0x7ffffee, 27),   // 252
    (0x7ffffef, 27),   // 253
    (0x7fffff0, 27),   // 254
    (0x3ffffee, 26),   // 255
    (0x3fffffff, 30),  // 256 EOS
];

/// Decode a Huffman-encoded string using grouped code-length matching.
///
/// Security: This decoder avoids the O(n*257) worst case of the naive linear
/// scan approach. By grouping codes by bit length and checking shortest first,
/// the decoder consumes at least 5 bits per iteration, bounding the work per
/// input byte to a constant factor.
#[allow(clippy::too_many_lines)] // Huffman decoding table is large; splitting obscures verification.
fn decode_huffman(src: &Bytes) -> Result<String, H2Error> {
    // Shortest HPACK Huffman code is 5 bits, so decoded symbols are bounded by
    // ceil(input_bits / 5). Preallocating to this bound avoids growth reallocs
    // on the common path where decoded output is larger than encoded bytes.
    let estimated_symbols = src.len().saturating_mul(8).saturating_add(4) / 5;
    let mut result = Vec::with_capacity(estimated_symbols);
    let mut accumulator: u64 = 0;
    let mut bits: u32 = 0;

    for &byte in src.iter() {
        accumulator = (accumulator << 8) | u64::from(byte);
        bits += 8;

        while bits >= 5 {
            // Fast path: check 5-bit codes first (most common ASCII symbols).
            // Codes 0x00-0x09 in 5 bits map to: '0','1','2','a','c','e','i','o','s','t'
            let high_5 = (accumulator >> (bits - 5)) as u32 & 0x1F;
            if high_5 < 10 {
                let sym = match high_5 {
                    0 => b'0',
                    1 => b'1',
                    2 => b'2',
                    3 => b'a',
                    4 => b'c',
                    5 => b'e',
                    6 => b'i',
                    7 => b'o',
                    8 => b's',
                    9 => b't',
                    _ => unreachable!(),
                };
                result.push(sym);
                bits -= 5;
                accumulator &= BIT_MASKS[bits as usize];
                continue;
            }

            // Fast path: check 6-bit codes (next most common).
            if bits >= 6 {
                let high_6 = (accumulator >> (bits - 6)) as u32 & 0x3F;
                // 6-bit codes range from 0x14 to 0x2d (symbols: space, %, -, ., /,
                // 3-9, =, A-Z, _, b, d, f-h, l-p, r, u)
                let sym_6 = match high_6 {
                    0x14 => Some(b' '),
                    0x15 => Some(b'%'),
                    0x16 => Some(b'-'),
                    0x17 => Some(b'.'),
                    0x18 => Some(b'/'),
                    0x19 => Some(b'3'),
                    0x1a => Some(b'4'),
                    0x1b => Some(b'5'),
                    0x1c => Some(b'6'),
                    0x1d => Some(b'7'),
                    0x1e => Some(b'8'),
                    0x1f => Some(b'9'),
                    0x20 => Some(b'='),
                    0x21 => Some(b'A'),
                    0x22 => Some(b'_'),
                    0x23 => Some(b'b'),
                    0x24 => Some(b'd'),
                    0x25 => Some(b'f'),
                    0x26 => Some(b'g'),
                    0x27 => Some(b'h'),
                    0x28 => Some(b'l'),
                    0x29 => Some(b'm'),
                    0x2a => Some(b'n'),
                    0x2b => Some(b'p'),
                    0x2c => Some(b'r'),
                    0x2d => Some(b'u'),
                    _ => None,
                };
                if let Some(s) = sym_6 {
                    result.push(s);
                    bits -= 6;
                    accumulator &= BIT_MASKS[bits as usize];
                    continue;
                }
            }

            // Fast path: check 7-bit codes.
            if bits >= 7 {
                let high_7 = (accumulator >> (bits - 7)) as u32 & 0x7F;
                let sym_7 = match high_7 {
                    0x5c => Some(b':'),
                    0x5d => Some(b'B'),
                    0x5e => Some(b'C'),
                    0x5f => Some(b'D'),
                    0x60 => Some(b'E'),
                    0x61 => Some(b'F'),
                    0x62 => Some(b'G'),
                    0x63 => Some(b'H'),
                    0x64 => Some(b'I'),
                    0x65 => Some(b'J'),
                    0x66 => Some(b'K'),
                    0x67 => Some(b'L'),
                    0x68 => Some(b'M'),
                    0x69 => Some(b'N'),
                    0x6a => Some(b'O'),
                    0x6b => Some(b'P'),
                    0x6c => Some(b'Q'),
                    0x6d => Some(b'R'),
                    0x6e => Some(b'S'),
                    0x6f => Some(b'T'),
                    0x70 => Some(b'U'),
                    0x71 => Some(b'V'),
                    0x72 => Some(b'W'),
                    0x73 => Some(b'Y'),
                    0x74 => Some(b'j'),
                    0x75 => Some(b'k'),
                    0x76 => Some(b'q'),
                    0x77 => Some(b'v'),
                    0x78 => Some(b'w'),
                    0x79 => Some(b'x'),
                    0x7a => Some(b'y'),
                    0x7b => Some(b'z'),
                    _ => None,
                };
                if let Some(s) = sym_7 {
                    result.push(s);
                    bits -= 7;
                    accumulator &= BIT_MASKS[bits as usize];
                    continue;
                }
            }

            // Fast path: check 8-bit codes.
            if bits >= 8 {
                let high_8 = (accumulator >> (bits - 8)) as u32 & 0xFF;
                let sym_8 = match high_8 {
                    0xf8 => Some(b'&'),
                    0xf9 => Some(b'*'),
                    0xfa => Some(b','),
                    0xfb => Some(b';'),
                    0xfc => Some(b'X'),
                    0xfd => Some(b'Z'),
                    _ => None,
                };
                if let Some(s) = sym_8 {
                    result.push(s);
                    bits -= 8;
                    accumulator &= BIT_MASKS[bits as usize];
                    continue;
                }
            }

            // Slow path for codes 9-30 bits: O(1) lookup per code length
            // via pre-built HUFFMAN_DECODE_INDEX instead of scanning 257 entries.
            let mut decoded = false;
            for code_len in 9u32..=30 {
                if bits < code_len {
                    break;
                }
                let shift = bits - code_len;
                let candidate = (accumulator >> shift) as u32;
                let mask = (1u32 << code_len) - 1;
                let candidate = candidate & mask;

                if let Some(sym_opt) = HUFFMAN_DECODE_INDEX.get(&(candidate, code_len as u8)) {
                    match sym_opt {
                        None => {
                            return Err(H2Error::compression("invalid huffman code (EOS symbol)"));
                        }
                        Some(sym) => {
                            result.push(*sym);
                            bits = shift;
                            accumulator &= BIT_MASKS[bits as usize];
                            decoded = true;
                        }
                    }
                    break;
                }
            }

            if !decoded {
                // If we have enough bits for the longest possible Huffman
                // code (30 bits for EOS) and still couldn't decode, the
                // input is definitively invalid. Returning early also
                // prevents `bits` from exceeding 64 on subsequent bytes,
                // which would cause a shift overflow in the u64 accumulator.
                if bits >= 30 {
                    return Err(H2Error::compression("invalid huffman code"));
                }
                break;
            }
        }
    }

    if bits >= 8 {
        return Err(H2Error::compression("invalid huffman padding (overlong)"));
    }

    // Check remaining bits are valid padding (all 1s) per RFC 7541 Section 5.2
    if bits > 0 && bits < 8 {
        let mask = BIT_MASKS[bits as usize];
        if accumulator != mask {
            return Err(H2Error::compression(
                "invalid Huffman padding (must be all 1s)",
            ));
        }
    }

    String::from_utf8(result).map_err(|_| H2Error::compression("invalid UTF-8 in huffman"))
}

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

    fn assert_compression_error<T>(result: Result<T, H2Error>) {
        match result {
            Ok(_) => panic!("expected compression error"),
            Err(err) => assert_eq!(err.code, ErrorCode::CompressionError),
        }
    }

    #[test]
    fn test_integer_encoding_small() {
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 10, 5, 0x00);
        assert_eq!(buf.as_ref(), &[10]);

        let mut src = buf.freeze();
        let decoded = decode_integer(&mut src, 5).unwrap();
        assert_eq!(decoded, 10);
    }

    #[test]
    fn test_integer_encoding_large() {
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 1337, 5, 0x00);
        // 1337 = 31 + (154 & 0x7f) + ((10 & 0x7f) << 7)
        assert_eq!(buf.as_ref(), &[31, 154, 10]);

        let mut src = buf.freeze();
        let decoded = decode_integer(&mut src, 5).unwrap();
        assert_eq!(decoded, 1337);
    }

    #[test]
    fn test_integer_decode_empty() {
        let mut src = Bytes::new();
        assert_compression_error(decode_integer(&mut src, 5));
    }

    #[test]
    fn test_integer_decode_truncated() {
        let mut src = Bytes::from_static(&[0x1f, 0x80]);
        assert_compression_error(decode_integer(&mut src, 5));
    }

    #[test]
    fn test_integer_decode_shift_overflow() {
        let mut bytes = vec![0x1f];
        bytes.extend_from_slice(&[0x80; 6]);
        let mut src = Bytes::from(bytes);
        assert_compression_error(decode_integer(&mut src, 5));
    }

    #[test]
    fn test_string_encoding_literal() {
        let mut buf = BytesMut::new();
        encode_string(&mut buf, "hello", false);

        let mut src = buf.freeze();
        let decoded = decode_string(&mut src).unwrap();
        assert_eq!(decoded, "hello");
    }

    #[test]
    fn test_string_decode_length_exceeds_buffer() {
        let mut src = Bytes::from_static(&[0x03, b'a', b'b']);
        assert_compression_error(decode_string(&mut src));
    }

    #[test]
    fn test_string_decode_invalid_utf8() {
        let mut src = Bytes::from_static(&[0x01, 0xff]);
        assert_compression_error(decode_string(&mut src));
    }

    #[test]
    fn test_huffman_decode_invalid_padding() {
        let mut src = Bytes::from_static(&[0x81, 0x00]);
        assert_compression_error(decode_string(&mut src));
    }

    #[test]
    fn test_indexed_header_zero_rejected() {
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[0x80]); // indexed header with index 0
        assert_compression_error(decoder.decode(&mut src));
    }

    #[test]
    fn test_dynamic_table_size_update_exceeds_allowed() {
        let mut decoder = Decoder::new();
        decoder.set_allowed_table_size(1);

        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 2, 5, 0x20);

        let mut src = buf.freeze();
        assert_compression_error(decoder.decode(&mut src));
    }

    #[test]
    fn test_dynamic_table_size_update_without_header_is_accepted() {
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 0, 5, 0x20);

        let mut src = buf.freeze();
        let headers = decoder.decode(&mut src).unwrap();
        assert!(headers.is_empty());
        assert_eq!(decoder.dynamic_table.max_size(), 0);
    }

    #[test]
    fn test_multiple_size_updates_without_headers_apply_last_value() {
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 1024, 5, 0x20);
        encode_integer(&mut buf, 512, 5, 0x20);

        let mut src = buf.freeze();
        let headers = decoder.decode(&mut src).unwrap();
        assert!(headers.is_empty());
        assert_eq!(decoder.dynamic_table.max_size(), 512);
    }

    #[test]
    fn test_dynamic_table_size_update_too_many() {
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();
        for _ in 0..17 {
            encode_integer(&mut buf, 0, 5, 0x20);
        }

        let mut src = buf.freeze();
        assert_compression_error(decoder.decode(&mut src));
    }

    #[test]
    fn test_header_list_size_exceeded() {
        let mut decoder = Decoder::new();
        decoder.set_max_header_list_size(1);

        let mut buf = BytesMut::new();
        // Literal without indexing, name "a", value "b".
        encode_integer(&mut buf, 0, 4, 0x00);
        encode_string(&mut buf, "a", false);
        encode_string(&mut buf, "b", false);

        let mut src = buf.freeze();
        assert_compression_error(decoder.decode(&mut src));
    }

    #[test]
    fn test_decoder_caps_allowed_table_size() {
        let decoder = Decoder::with_max_size(MAX_ALLOWED_TABLE_SIZE + 1);
        assert_eq!(decoder.allowed_table_size, MAX_ALLOWED_TABLE_SIZE);
        assert_eq!(decoder.dynamic_table.max_size(), MAX_ALLOWED_TABLE_SIZE);
    }

    #[test]
    fn test_encoder_with_max_size_caps_to_allowed_maximum() {
        let encoder = Encoder::with_max_size(MAX_ALLOWED_TABLE_SIZE + 1);
        assert_eq!(encoder.dynamic_table_max_size(), MAX_ALLOWED_TABLE_SIZE);
    }

    #[test]
    fn test_dynamic_table_set_max_size_caps_to_allowed_maximum() {
        let mut table = DynamicTable::new();
        table.set_max_size(MAX_ALLOWED_TABLE_SIZE + 1);
        assert_eq!(table.max_size(), MAX_ALLOWED_TABLE_SIZE);
    }

    #[test]
    fn test_set_allowed_table_size_caps() {
        let mut decoder = Decoder::new();
        decoder.set_allowed_table_size(MAX_ALLOWED_TABLE_SIZE + 1);
        assert_eq!(decoder.allowed_table_size, MAX_ALLOWED_TABLE_SIZE);
    }

    #[test]
    fn test_dynamic_table_insert() {
        let mut table = DynamicTable::new();
        table.insert(Header::new("custom-header", "custom-value"));

        assert_eq!(
            table.size(),
            "custom-header".len() + "custom-value".len() + 32
        );
        assert!(table.get(1).is_some());
    }

    #[test]
    fn test_dynamic_table_eviction() {
        let mut table = DynamicTable::with_max_size(100);

        // Insert entries that exceed max size
        table.insert(Header::new("header1", "value1")); // 32 + 7 + 6 = 45
        table.insert(Header::new("header2", "value2")); // 32 + 7 + 6 = 45

        // First entry should be evicted
        assert!(table.size() <= 100);
    }

    #[test]
    fn test_encoder_decoder_roundtrip() {
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);

        let headers = vec![
            Header::new(":method", "GET"),
            Header::new(":path", "/"),
            Header::new(":scheme", "https"),
            Header::new(":authority", "example.com"),
            Header::new("accept", "text/html"),
        ];

        let mut encoded_block = BytesMut::new();
        encoder.encode(&headers, &mut encoded_block);

        let mut decoder = Decoder::new();
        let mut src = encoded_block.freeze();
        let decoded_headers = decoder.decode(&mut src).unwrap();

        assert_eq!(decoded_headers.len(), headers.len());
        for (orig, dec) in headers.iter().zip(decoded_headers.iter()) {
            assert_eq!(orig.name, dec.name);
            assert_eq!(orig.value, dec.value);
        }
    }

    #[test]
    fn test_static_table_indexed() {
        let mut decoder = Decoder::new();

        // Encode ":method: GET" as indexed (index 2 in static table)
        let mut src = Bytes::from_static(&[0x82]); // 0x80 | 2
        let headers = decoder.decode(&mut src).unwrap();

        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, ":method");
        assert_eq!(headers[0].value, "GET");
    }

    #[test]
    fn test_huffman_encode_decode_roundtrip() {
        let inputs = [
            "www.example.com",
            "no-cache",
            "custom-key",
            "custom-value",
            "",
            "a",
            "Hello, World!",
        ];

        for &input in &inputs {
            let encoded = encode_huffman(input.as_bytes());
            let encoded_bytes = Bytes::from(encoded);
            let decoded = decode_huffman(&encoded_bytes).unwrap();
            assert_eq!(decoded, input, "roundtrip failed for {input:?}");
        }
    }

    #[test]
    fn test_huffman_encoding_is_smaller() {
        let input = b"www.example.com";
        let encoded = encode_huffman(input);
        assert!(
            encoded.len() < input.len(),
            "huffman should compress ASCII text: {} >= {}",
            encoded.len(),
            input.len()
        );
    }

    #[test]
    fn test_string_encoding_huffman_roundtrip() {
        let mut buf = BytesMut::new();
        encode_string(&mut buf, "hello", true);

        // First byte should have high bit set (Huffman flag).
        assert_ne!(buf[0] & 0x80, 0, "huffman flag should be set");

        let mut src = buf.freeze();
        let decoded = decode_string(&mut src).unwrap();
        assert_eq!(decoded, "hello");
    }

    #[test]
    fn test_encoder_decoder_roundtrip_with_huffman() {
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(true);

        let headers = vec![
            Header::new(":method", "GET"),
            Header::new(":path", "/index.html"),
            Header::new(":scheme", "https"),
            Header::new(":authority", "www.example.com"),
            Header::new("accept-encoding", "gzip, deflate"),
        ];

        let mut encoded_block = BytesMut::new();
        encoder.encode(&headers, &mut encoded_block);

        let mut decoder = Decoder::new();
        let mut src = encoded_block.freeze();
        let decoded_headers = decoder.decode(&mut src).unwrap();

        assert_eq!(decoded_headers.len(), headers.len());
        for (orig, dec) in headers.iter().zip(decoded_headers.iter()) {
            assert_eq!(orig.name, dec.name, "name mismatch for {:?}", orig.name);
            assert_eq!(orig.value, dec.value, "value mismatch for {:?}", orig.name);
        }
    }

    // =========================================================================
    // RFC 7541 Standard Test Vectors (bd-et96)
    // =========================================================================

    #[test]
    fn test_rfc7541_c1_integer_representation() {
        // RFC 7541 C.1.1: Encoding 10 using a 5-bit prefix
        // Expected: 0x0a (10 fits in 5 bits)
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 10, 5, 0x00);
        assert_eq!(&buf[..], &[0x0a]);

        // RFC 7541 C.1.2: Encoding 1337 using a 5-bit prefix
        // 1337 = 31 + 1306, 1306 = 0x51a = 10 + 128*10 + 128*128*0
        // Expected: 0x1f 0x9a 0x0a
        buf.clear();
        encode_integer(&mut buf, 1337, 5, 0x00);
        assert_eq!(&buf[..], &[0x1f, 0x9a, 0x0a]);

        // RFC 7541 C.1.3: Encoding 42 at an octet boundary (8-bit prefix)
        buf.clear();
        encode_integer(&mut buf, 42, 8, 0x00);
        assert_eq!(&buf[..], &[0x2a]);
    }

    #[test]
    fn test_rfc7541_integer_decode_roundtrip() {
        // Test various integer values using encode/decode roundtrip
        for &(value, prefix_bits) in &[
            (0_usize, 5_u8),
            (1, 5),
            (30, 5),
            (31, 5),
            (32, 5),
            (127, 7),
            (128, 7),
            (255, 8),
            (256, 8),
            (1337, 5),
            (65535, 8),
        ] {
            let mut buf = BytesMut::new();
            encode_integer(&mut buf, value, prefix_bits, 0x00);

            let mut src = buf.freeze();
            let decoded = decode_integer(&mut src, prefix_bits).unwrap();
            assert_eq!(
                decoded, value,
                "roundtrip failed for {value} with {prefix_bits}-bit prefix"
            );
        }
    }

    #[test]
    fn test_rfc7541_c2_header_field_indexed() {
        // RFC 7541 C.2.4: Indexed Header Field
        // Index 2 in static table = :method: GET
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[0x82]);
        let headers = decoder.decode(&mut src).unwrap();

        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, ":method");
        assert_eq!(headers[0].value, "GET");
    }

    #[test]
    fn test_rfc7541_c3_request_without_huffman() {
        // RFC 7541 C.3.1: First Request (without Huffman)
        // :method: GET, :scheme: http, :path: /, :authority: www.example.com
        let wire: &[u8] = &[
            0x82, // :method: GET (indexed 2)
            0x86, // :scheme: http (indexed 6)
            0x84, // :path: / (indexed 4)
            0x41, 0x0f, // :authority: with literal value, 15 bytes
            b'w', b'w', b'w', b'.', b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'c', b'o',
            b'm',
        ];

        let mut decoder = Decoder::new();
        let mut src = Bytes::copy_from_slice(wire);
        let headers = decoder.decode(&mut src).unwrap();

        assert_eq!(headers.len(), 4);
        assert_eq!(headers[0].name, ":method");
        assert_eq!(headers[0].value, "GET");
        assert_eq!(headers[1].name, ":scheme");
        assert_eq!(headers[1].value, "http");
        assert_eq!(headers[2].name, ":path");
        assert_eq!(headers[2].value, "/");
        assert_eq!(headers[3].name, ":authority");
        assert_eq!(headers[3].value, "www.example.com");
    }

    #[test]
    fn test_rfc7541_c4_request_with_huffman() {
        // Encode headers with Huffman, then decode and verify
        let mut enc = Encoder::new();
        enc.set_use_huffman(true);

        let headers = vec![
            Header::new(":method", "GET"),
            Header::new(":scheme", "http"),
            Header::new(":path", "/"),
            Header::new(":authority", "www.example.com"),
        ];

        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let mut src = buf.freeze();
        let headers_out = dec.decode(&mut src).unwrap();

        assert_eq!(headers_out.len(), 4);
        assert_eq!(headers_out[3].value, "www.example.com");
    }

    #[test]
    fn test_rfc7541_c5_response_without_huffman() {
        // Test response headers encoding/decoding
        let mut enc = Encoder::new();
        enc.set_use_huffman(false);

        let headers = vec![
            Header::new(":status", "302"),
            Header::new("cache-control", "private"),
            Header::new("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
            Header::new("location", "https://www.example.com"),
        ];

        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let mut src = buf.freeze();
        let headers_out = dec.decode(&mut src).unwrap();

        assert_eq!(headers_out.len(), 4);
        assert_eq!(headers_out[0].name, ":status");
        assert_eq!(headers_out[0].value, "302");
        assert_eq!(headers_out[3].name, "location");
        assert_eq!(headers_out[3].value, "https://www.example.com");
    }

    #[test]
    fn test_rfc7541_c5_1_first_response_exact_wire_without_huffman() {
        // RFC 7541 Appendix C.5.1 exact wire image.
        let headers = vec![
            Header::new(":status", "302"),
            Header::new("cache-control", "private"),
            Header::new("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
            Header::new("location", "https://www.example.com"),
        ];
        let expected_wire: &[u8] = &[
            0x48, 0x03, 0x33, 0x30, 0x32, 0x58, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65,
            0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20,
            0x32, 0x30, 0x31, 0x33, 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x31, 0x20,
            0x47, 0x4d, 0x54, 0x6e, 0x17, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77,
            0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d,
        ];

        let mut decoder = Decoder::new();
        let mut src = Bytes::copy_from_slice(expected_wire);
        let decoded = decoder.decode(&mut src).expect("RFC 7541 C.5.1 decode");
        assert_eq!(decoded, headers);

        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);
        let mut encoded = BytesMut::new();
        encoder.encode(&headers, &mut encoded);
        assert_eq!(
            encoded.as_ref(),
            expected_wire,
            "RFC 7541 C.5.1 wire image must match the specification exactly"
        );
    }

    #[test]
    fn test_rfc7541_c6_1_first_response_exact_wire_with_huffman() {
        // RFC 7541 Appendix C.6.1 exact wire image.
        let headers = vec![
            Header::new(":status", "302"),
            Header::new("cache-control", "private"),
            Header::new("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
            Header::new("location", "https://www.example.com"),
        ];
        let expected_wire: &[u8] = &[
            0x48, 0x82, 0x64, 0x02, 0x58, 0x85, 0xae, 0xc3, 0x77, 0x1a, 0x4b, 0x61, 0x96, 0xd0,
            0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81,
            0x66, 0xe0, 0x82, 0xa6, 0x2d, 0x1b, 0xff, 0x6e, 0x91, 0x9d, 0x29, 0xad, 0x17, 0x18,
            0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82, 0xae, 0x43, 0xd3,
        ];

        let mut decoder = Decoder::new();
        let mut src = Bytes::copy_from_slice(expected_wire);
        let decoded = decoder.decode(&mut src).expect("RFC 7541 C.6.1 decode");
        assert_eq!(decoded, headers);

        let mut encoder = Encoder::new();
        encoder.set_use_huffman(true);
        let mut encoded = BytesMut::new();
        encoder.encode(&headers, &mut encoded);
        assert_eq!(
            encoded.as_ref(),
            expected_wire,
            "RFC 7541 C.6.1 wire image must match the specification exactly"
        );
    }

    #[test]
    fn test_rfc7541_huffman_decode_www_example_com() {
        // RFC 7541 C.4.1 encoded "www.example.com" with Huffman
        // This is a known encoding from the spec
        let huffman_encoded: &[u8] = &[
            0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff,
        ];
        let decoded = decode_huffman(&Bytes::copy_from_slice(huffman_encoded)).unwrap();
        assert_eq!(decoded, "www.example.com");
    }

    // =========================================================================
    // Dynamic Table Edge Cases (bd-et96)
    // =========================================================================

    #[test]
    fn test_dynamic_table_empty() {
        let table = DynamicTable::new();
        assert_eq!(table.size(), 0);
        assert!(table.get(1).is_none());
        assert!(table.get(0).is_none());
        assert!(table.get(100).is_none());
    }

    #[test]
    fn test_dynamic_table_single_entry() {
        let mut table = DynamicTable::new();
        table.insert(Header::new("x-custom", "value"));

        // Index 1 should return the entry
        let entry = table.get(1).unwrap();
        assert_eq!(entry.name, "x-custom");
        assert_eq!(entry.value, "value");

        // Index 2 should be None (only 1 entry)
        assert!(table.get(2).is_none());
    }

    #[test]
    fn test_dynamic_table_fifo_order() {
        let mut table = DynamicTable::new();
        table.insert(Header::new("first", "1"));
        table.insert(Header::new("second", "2"));
        table.insert(Header::new("third", "3"));

        // Most recent entry is at index 1
        assert_eq!(table.get(1).unwrap().name, "third");
        assert_eq!(table.get(2).unwrap().name, "second");
        assert_eq!(table.get(3).unwrap().name, "first");
    }

    #[test]
    fn test_dynamic_table_size_calculation() {
        let mut table = DynamicTable::new();

        // Entry size = name.len() + value.len() + 32 (RFC 7541 Section 4.1)
        let header = Header::new("custom", "value"); // 6 + 5 + 32 = 43
        table.insert(header);
        assert_eq!(table.size(), 43);

        table.insert(Header::new("a", "b")); // 1 + 1 + 32 = 34
        assert_eq!(table.size(), 43 + 34);
    }

    #[test]
    fn test_dynamic_table_max_size_zero() {
        let mut table = DynamicTable::with_max_size(0);
        table.insert(Header::new("header", "value"));

        // With max_size 0, table should always be empty
        assert_eq!(table.size(), 0);
        assert!(table.get(1).is_none());
    }

    #[test]
    fn test_dynamic_table_exact_fit() {
        // Entry is exactly 43 bytes: 6 + 5 + 32
        let mut table = DynamicTable::with_max_size(43);
        table.insert(Header::new("custom", "value"));

        assert_eq!(table.size(), 43);
        assert!(table.get(1).is_some());

        // Insert another entry, first should be evicted
        table.insert(Header::new("newkey", "newva")); // 6 + 5 + 32 = 43
        assert_eq!(table.size(), 43);
        assert_eq!(table.get(1).unwrap().name, "newkey");
        assert!(table.get(2).is_none()); // First entry evicted
    }

    #[test]
    fn test_dynamic_table_cascade_eviction() {
        let mut table = DynamicTable::with_max_size(100);

        // Insert 3 small entries (each 34 bytes = 1+1+32)
        table.insert(Header::new("a", "1"));
        table.insert(Header::new("b", "2"));
        table.insert(Header::new("c", "3"));

        // With max_size=100, inserting 102 bytes triggers eviction of oldest
        // After eviction, only 2 entries should remain (68 bytes)
        assert_eq!(table.size(), 68);
        assert!(table.size() <= 100);
    }

    #[test]
    fn test_dynamic_table_set_max_size() {
        let mut table = DynamicTable::new();
        table.insert(Header::new("header1", "value1")); // 7 + 6 + 32 = 45
        table.insert(Header::new("header2", "value2")); // 7 + 6 + 32 = 45

        let initial_size = table.size();
        assert_eq!(initial_size, 90); // 45 + 45 = 90

        // Reduce max size to force eviction
        table.set_max_size(50);
        assert!(table.size() <= 50);
    }

    #[test]
    fn test_dynamic_table_resize_to_zero() {
        let mut table = DynamicTable::new();
        table.insert(Header::new("key", "val"));
        assert!(table.size() > 0);

        table.set_max_size(0);
        assert_eq!(table.size(), 0);
        assert!(table.get(1).is_none());
    }

    #[test]
    fn test_encoder_dynamic_table_reuse() {
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);

        // First encode
        let headers1 = vec![Header::new("x-custom", "value1")];
        let mut buf1 = BytesMut::new();
        encoder.encode(&headers1, &mut buf1);

        // Second encode with same header name
        let headers2 = vec![Header::new("x-custom", "value2")];
        let mut buf2 = BytesMut::new();
        encoder.encode(&headers2, &mut buf2);

        // Both should decode correctly
        let mut decoder = Decoder::new();
        let decoded1 = decoder.decode(&mut buf1.freeze()).unwrap();
        let decoded2 = decoder.decode(&mut buf2.freeze()).unwrap();

        assert_eq!(decoded1[0].name, "x-custom");
        assert_eq!(decoded2[0].name, "x-custom");
    }

    #[test]
    fn test_decoder_shared_state_across_blocks() {
        let mut enc = Encoder::new();
        enc.set_use_huffman(false);

        let mut dec = Decoder::new();

        // First block adds to dynamic table
        let headers1 = vec![Header::new("x-custom", "initial")];
        let mut buf1 = BytesMut::new();
        enc.encode(&headers1, &mut buf1);
        dec.decode(&mut buf1.freeze()).unwrap();

        // Second block can reference dynamic table entries
        let headers2 = vec![Header::new("x-custom", "updated")];
        let mut buf2 = BytesMut::new();
        enc.encode(&headers2, &mut buf2);
        let headers_out = dec.decode(&mut buf2.freeze()).unwrap();

        assert_eq!(headers_out[0].value, "updated");
    }

    // =========================================================================
    // Invalid Input Handling (bd-et96)
    // =========================================================================

    #[test]
    fn test_decode_empty_input() {
        let mut decoder = Decoder::new();
        let mut src = Bytes::new();
        let headers = decoder.decode(&mut src).unwrap();
        assert!(headers.is_empty());
    }

    #[test]
    fn test_decode_invalid_indexed_zero() {
        // Index 0 is invalid per RFC 7541 Section 6.1
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[0x80]); // Indexed with index 0
        let result = decoder.decode(&mut src);
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_invalid_index_too_large() {
        // Index beyond static + dynamic table
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[0xff, 0xff, 0xff, 0x7f]); // Very large index
        let result = decoder.decode(&mut src);
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_truncated_integer() {
        // Multi-byte integer without continuation
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[0x1f]); // Needs continuation but none provided
        let result = decoder.decode(&mut src);
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_truncated_string() {
        // String length says 10 bytes but only 3 provided
        let mut decoder = Decoder::new();
        let mut src = Bytes::from_static(&[
            0x40, // Literal header with incremental indexing
            0x0a, // Name length = 10
            b'a', b'b', b'c', // Only 3 bytes
        ]);
        let result = decoder.decode(&mut src);
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_huffman_invalid_eos() {
        // EOS symbol must not appear in the decoded stream.
        let invalid_huffman: &[u8] = &[0xff, 0xff, 0xff, 0xff]; // 32 ones contains EOS (30 ones)
        let result = decode_huffman(&Bytes::copy_from_slice(invalid_huffman));
        assert_compression_error(result);
    }

    #[test]
    fn test_decode_integer_overflow_protection() {
        // Attempt to decode an integer that would overflow
        // First byte 0x7f means "use continuation bytes" for 7-bit prefix
        let mut src =
            Bytes::from_static(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]);
        // Should either error or return a reasonable value, not panic
        let result = decode_integer(&mut src, 7);
        // We're testing that it handles this gracefully (should error on overflow)
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_literal_with_empty_name() {
        // Literal header with empty name (invalid per RFC 9113)
        let mut enc = Encoder::new();
        enc.set_use_huffman(false);

        let headers = vec![Header::new("", "value")];
        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let mut src = buf.freeze();
        let result = dec.decode(&mut src);
        assert_compression_error(result);
    }

    #[test]
    fn test_decode_literal_with_empty_value() {
        let mut enc = Encoder::new();
        enc.set_use_huffman(false);

        let headers = vec![Header::new("x-empty", "")];
        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let headers_out = dec.decode(&mut buf.freeze()).unwrap();

        assert_eq!(headers_out[0].name, "x-empty");
        assert_eq!(headers_out[0].value, "");
    }

    #[test]
    fn test_static_table_all_entries_accessible() {
        // Verify all 61 static table entries are accessible
        for idx in 1..=61usize {
            let entry = get_static(idx);
            assert!(entry.is_some(), "static table entry {idx} should exist");
        }
        assert!(get_static(62).is_none());
        assert!(get_static(0).is_none());
    }

    #[test]
    fn test_static_table_known_entries() {
        // Verify specific well-known entries
        let method_get = get_static(2).unwrap();
        assert_eq!(method_get.0, ":method");
        assert_eq!(method_get.1, "GET");

        let method_post = get_static(3).unwrap();
        assert_eq!(method_post.0, ":method");
        assert_eq!(method_post.1, "POST");

        let status_200 = get_static(8).unwrap();
        assert_eq!(status_200.0, ":status");
        assert_eq!(status_200.1, "200");

        let status_404 = get_static(13).unwrap();
        assert_eq!(status_404.0, ":status");
        assert_eq!(status_404.1, "404");
    }

    #[test]
    fn test_huffman_all_ascii_printable() {
        // Ensure all printable ASCII characters roundtrip correctly
        let mut input = String::new();
        for c in 32u8..=126 {
            input.push(c as char);
        }

        let encoded = encode_huffman(input.as_bytes());
        let decoded = decode_huffman(&Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, input);
    }

    #[test]
    fn test_huffman_empty_string() {
        let encoded = encode_huffman(b"");
        assert!(encoded.is_empty());

        let decoded = decode_huffman(&Bytes::new()).unwrap();
        assert_eq!(decoded, "");
    }

    #[test]
    fn test_sensitive_header_encoding() {
        // Test headers that should never be indexed (sensitive data)
        let mut enc = Encoder::new();
        let mut dec = Decoder::new();

        // Encode with never-index flag for sensitive headers
        let headers = vec![
            Header::new(":method", "GET"),
            Header::new("authorization", "Bearer secret123"),
        ];

        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let headers_out = dec.decode(&mut buf.freeze()).unwrap();
        assert_eq!(headers_out.len(), 2);
        assert_eq!(headers_out[1].name, "authorization");
        assert_eq!(headers_out[1].value, "Bearer secret123");
    }

    #[test]
    fn test_large_header_value() {
        let mut enc = Encoder::new();
        enc.set_use_huffman(false);

        // Create a large header value (but within reasonable limits)
        let large_value: String = "x".repeat(4096);
        let headers = vec![Header::new("x-large", &large_value)];

        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let headers_out = dec.decode(&mut buf.freeze()).unwrap();

        assert_eq!(headers_out[0].value, large_value);
    }

    #[test]
    fn test_many_headers() {
        let mut enc = Encoder::new();
        enc.set_use_huffman(true);

        // Encode many headers
        let headers: Vec<Header> = (0..100)
            .map(|i| Header::new(format!("x-header-{i}"), format!("value-{i}")))
            .collect();

        let mut buf = BytesMut::new();
        enc.encode(&headers, &mut buf);

        let mut dec = Decoder::new();
        let headers_out = dec.decode(&mut buf.freeze()).unwrap();

        assert_eq!(headers_out.len(), 100);
        for (i, header) in headers_out.iter().enumerate() {
            assert_eq!(header.name, format!("x-header-{i}"));
            assert_eq!(header.value, format!("value-{i}"));
        }
    }

    #[test]
    fn test_deterministic_encoding() {
        // Same input should always produce same output (deterministic for testing)
        let mut encoder1 = Encoder::new();
        let mut encoder2 = Encoder::new();

        let headers = vec![
            Header::new(":method", "GET"),
            Header::new(":path", "/api/test"),
            Header::new("content-type", "application/json"),
        ];

        let mut buf1 = BytesMut::new();
        let mut buf2 = BytesMut::new();
        encoder1.encode(&headers, &mut buf1);
        encoder2.encode(&headers, &mut buf2);

        assert_eq!(buf1, buf2, "encoding should be deterministic");
    }

    // =========================================================================
    // Security Stress Tests (bd-1z7e)
    // =========================================================================

    #[test]
    fn stress_test_hpack_integer_malformed() {
        // Malformed multi-byte integer sequences: verify no panics, only clean errors.
        for shift in 0..=40u8 {
            // Continuation bytes that would cause large shifts
            let mut data = vec![0x7f_u8]; // 7-bit prefix full
            data.extend(std::iter::repeat_n(0xff, shift as usize));
            data.push(0x00); // terminator
            let mut src = Bytes::from(data);
            let _ = decode_integer(&mut src, 7);
        }

        // Random-ish malformed sequences
        for seed in 0..1000u16 {
            let len = ((seed % 10) + 1) as usize;
            let mut data = Vec::with_capacity(len);
            for i in 0..len {
                data.push(((seed.wrapping_mul(31).wrapping_add(i as u16)) & 0xff) as u8);
            }
            // Set prefix to trigger multi-byte path
            if !data.is_empty() {
                data[0] |= 0x1f;
            }
            let mut src = Bytes::from(data);
            let _ = decode_integer(&mut src, 5);
        }
    }

    #[test]
    fn stress_test_huffman_random_bytes() {
        // Random byte sequences: verify graceful failure or valid decode, never panic.
        for seed in 0..2000u32 {
            let len = ((seed % 200) + 1) as usize;
            let mut data = Vec::with_capacity(len);
            for i in 0..len {
                data.push(((seed.wrapping_mul(97).wrapping_add(i as u32)) & 0xff) as u8);
            }
            let _ = decode_huffman(&Bytes::from(data));
        }
    }

    #[test]
    fn stress_test_dynamic_table_churn() {
        // Rapid size oscillation with interleaved insertions: verify memory bounded.
        let mut table = DynamicTable::new();
        for i in 0..5000u32 {
            if i % 3 == 0 {
                table.set_max_size(0);
            } else if i % 3 == 1 {
                table.set_max_size(4096);
            }
            table.insert(Header::new(format!("x-churn-{i}"), format!("value-{i}")));
            assert!(table.size() <= 4096);
        }
    }

    #[test]
    fn stress_test_decoder_malformed_blocks() {
        // Fuzz-like: random byte sequences as HPACK header blocks.
        for seed in 0..1000u32 {
            let len = ((seed % 100) + 1) as usize;
            let mut data = Vec::with_capacity(len);
            for i in 0..len {
                data.push(((seed.wrapping_mul(53).wrapping_add(i as u32 * 7)) & 0xff) as u8);
            }
            let mut decoder = Decoder::new();
            let mut src = Bytes::from(data);
            let _ = decoder.decode(&mut src);
        }
    }

    #[test]
    fn test_huffman_all_single_bytes() {
        // Every single byte value 0x00-0xFF: encode always works, decode
        // succeeds for valid UTF-8 bytes and fails gracefully for others.
        for byte in 0..=255u8 {
            let input = [byte];
            let encoded = encode_huffman(&input);
            let result = decode_huffman(&Bytes::from(encoded));
            if std::str::from_utf8(&input).is_ok() {
                let decoded = result.unwrap_or_else(|e| {
                    panic!("decode failed for valid UTF-8 byte 0x{byte:02x}: {e:?}")
                });
                assert_eq!(
                    decoded.as_bytes(),
                    &input,
                    "roundtrip failed for byte 0x{byte:02x}"
                );
            } else {
                // Non-UTF-8 bytes: should not panic (error is acceptable)
                let _ = result;
            }
        }
    }

    #[test]
    fn test_huffman_long_code_symbols() {
        // Symbols with the longest Huffman codes (9-30 bits) to exercise slow path.
        // Byte values 0x00-0x1f are control chars with longer codes.
        let mut input = Vec::new();
        for b in 0..=31u8 {
            input.push(b);
        }
        let encoded = encode_huffman(&input);
        let decoded = decode_huffman(&Bytes::from(encoded)).unwrap();
        assert_eq!(decoded.as_bytes(), &input[..]);
    }

    #[test]
    fn test_integer_max_valid_value() {
        // Encode and decode a large (but valid) integer.
        let value = 1_000_000_usize;
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, value, 5, 0x00);
        let mut src = buf.freeze();
        let decoded = decode_integer(&mut src, 5).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn test_integer_all_prefix_sizes() {
        for prefix in [5_u8, 6, 7, 8] {
            for &value in &[0_usize, 1, 30, 31, 127, 128, 255, 256, 65535] {
                let mut buf = BytesMut::new();
                encode_integer(&mut buf, value, prefix, 0x00);
                let mut src = buf.freeze();
                let decoded = decode_integer(&mut src, prefix).unwrap();
                assert_eq!(decoded, value, "prefix={prefix}, value={value}");
            }
        }
    }

    // =========================================================================
    // Audit Fix Tests (br-10x0x.5)
    // =========================================================================

    #[test]
    fn test_encoder_emits_size_update_on_wire() {
        // RFC 7541 §6.3: After set_max_table_size, the encoder MUST emit a
        // dynamic table size update at the start of the next header block.
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);

        // Change max table size
        encoder.set_max_table_size(256);

        // Encode a header — the size update should precede it
        let headers = vec![Header::new(":method", "GET")];
        let mut buf = BytesMut::new();
        encoder.encode(&headers, &mut buf);

        // First byte should be a dynamic table size update (0x20 prefix)
        assert_eq!(
            buf[0] & 0xe0,
            0x20,
            "first byte should be dynamic table size update prefix"
        );

        // Decode and verify: the size update should be consumed, then the header
        let mut decoder = Decoder::new();
        decoder.set_allowed_table_size(256);
        let mut src = buf.freeze();
        let decoded_headers = decoder.decode(&mut src).unwrap();
        assert_eq!(decoded_headers.len(), 1);
        assert_eq!(decoded_headers[0].name, ":method");
        assert_eq!(decoded_headers[0].value, "GET");
    }

    #[test]
    fn test_encoder_size_update_not_repeated() {
        // The size update should only be emitted once, not on subsequent blocks.
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);
        encoder.set_max_table_size(256);

        // First encode — should have size update prefix
        let mut buf1 = BytesMut::new();
        encoder.encode(&[Header::new(":method", "GET")], &mut buf1);
        assert_eq!(buf1[0] & 0xe0, 0x20, "first block should have size update");

        // Second encode — should NOT have size update prefix
        let mut buf2 = BytesMut::new();
        encoder.encode(&[Header::new(":method", "POST")], &mut buf2);
        // First byte should be indexed header (0x80 prefix) not size update
        assert_ne!(
            buf2[0] & 0xe0,
            0x20,
            "second block should not repeat size update"
        );
    }

    #[test]
    fn test_encoder_size_update_roundtrip_full() {
        // Full encoder/decoder roundtrip after a size change
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Initial encode works
        let headers1 = vec![Header::new("x-test", "value1")];
        let mut buf1 = BytesMut::new();
        encoder.encode(&headers1, &mut buf1);
        let dec1 = decoder.decode(&mut buf1.freeze()).unwrap();
        assert_eq!(dec1[0].value, "value1");

        // Change table size on both sides
        encoder.set_max_table_size(128);
        decoder.set_allowed_table_size(128);

        // Encode after size change — decoder should accept the size update
        let headers2 = vec![Header::new("x-test", "value2")];
        let mut buf2 = BytesMut::new();
        encoder.encode(&headers2, &mut buf2);
        let dec2 = decoder.decode(&mut buf2.freeze()).unwrap();
        assert_eq!(dec2[0].value, "value2");
    }

    #[test]
    fn test_encoder_emits_min_then_final_size_update_after_shrink_then_grow() {
        // RFC 7541 §4.2 requires the smallest size seen since the last block
        // to be emitted before the final size if the encoder shrinks and then
        // grows the table between header blocks.
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);

        encoder.set_max_table_size(128);
        encoder.set_max_table_size(256);

        let headers = vec![Header::new(":method", "GET")];
        let mut buf = BytesMut::new();
        encoder.encode(&headers, &mut buf);

        assert_eq!(
            buf[0] & 0xe0,
            0x20,
            "first instruction should be size update"
        );

        let mut src = buf.freeze();
        let first_update = decode_integer(&mut src, 5).unwrap();
        assert_eq!(first_update, 128);
        assert_eq!(
            src[0] & 0xe0,
            0x20,
            "second instruction should be size update"
        );
        let second_update = decode_integer(&mut src, 5).unwrap();
        assert_eq!(second_update, 256);

        let mut decoder = Decoder::new();
        decoder.set_allowed_table_size(256);
        let decoded_headers = decoder.decode(&mut src).unwrap();
        assert_eq!(decoded_headers, headers);
    }

    #[test]
    fn test_encoder_shrink_to_zero_does_not_reuse_dynamic_entries() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        let headers = vec![
            Header::new("cache-control", "gzip, deflate"),
            Header::new("cache-control", "gzip, deflate"),
        ];

        let mut initial = BytesMut::new();
        encoder.encode(&headers, &mut initial);
        let decoded_initial = decoder.decode(&mut initial.freeze()).unwrap();
        assert_eq!(decoded_initial, headers);
        assert!(encoder.dynamic_table_size() > 0);
        assert!(decoder.dynamic_table_size() > 0);

        encoder.set_max_table_size(0);
        decoder.set_allowed_table_size(0);

        let mut resized = BytesMut::new();
        encoder.encode(&headers, &mut resized);
        let decoded_resized = decoder.decode(&mut resized.freeze()).unwrap();
        assert_eq!(decoded_resized, headers);
        assert_eq!(encoder.dynamic_table_size(), 0);
        assert_eq!(decoder.dynamic_table_size(), 0);
    }

    #[test]
    fn test_integer_decode_checked_mul_overflow() {
        // On all platforms, verify that the checked_mul path catches
        // values that would silently truncate with plain checked_shl.
        // Craft input: prefix full (0x1f for 5-bit), then continuation
        // bytes that push the value beyond what fits in the platform usize.
        // 5-bit prefix full, then 4 continuation bytes (0xff = value 0x7f + continue)
        let mut data = vec![0x1f_u8];
        data.extend_from_slice(&[0xff, 0xff, 0xff, 0xff]);
        data.push(0x7f); // final byte without continuation
        let mut src = Bytes::from(data);
        // On 32-bit this MUST error (value would be ~34 GB).
        // On 64-bit the value fits, so it may succeed, but we verify no panic.
        let _ = decode_integer(&mut src, 5);
    }

    // =========================================================================
    // Audit Fix Tests: RFC 7541 §4.2 mid-block size update rejection
    // =========================================================================

    #[test]
    fn test_size_update_before_first_header_accepted() {
        // Size update at the start of a block (before any headers) is valid.
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();

        // Size update to 2048
        encode_integer(&mut buf, 2048, 5, 0x20);
        // Then an indexed header (:method: GET)
        buf.put_u8(0x82);

        let mut src = buf.freeze();
        let headers = decoder.decode(&mut src).unwrap();
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, ":method");
        assert_eq!(headers[0].value, "GET");
    }

    #[test]
    fn test_size_update_after_first_header_rejected() {
        // RFC 7541 §4.2: size update after the first header field
        // representation MUST be a COMPRESSION_ERROR.
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();

        // First: an indexed header (:method: GET)
        buf.put_u8(0x82);
        // Then: a size update (illegal mid-block)
        encode_integer(&mut buf, 2048, 5, 0x20);
        // Then: another indexed header
        buf.put_u8(0x84);

        let mut src = buf.freeze();
        let result = decoder.decode(&mut src);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.code, ErrorCode::CompressionError);
    }

    #[test]
    fn test_multiple_size_updates_then_header_ok() {
        // Multiple size updates before the first header are valid.
        let mut decoder = Decoder::new();
        let mut buf = BytesMut::new();

        // Two consecutive size updates
        encode_integer(&mut buf, 1024, 5, 0x20);
        encode_integer(&mut buf, 2048, 5, 0x20);
        // Then a header
        buf.put_u8(0x82); // :method: GET

        let mut src = buf.freeze();
        let headers = decoder.decode(&mut src).unwrap();
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, ":method");
    }

    #[test]
    fn test_size_updates_apply_intermediate_eviction_before_dynamic_lookup() {
        // RFC 7541 §4.2 requires consecutive block-start size updates to be
        // applied in-order. If an intermediate shrink evicts dynamic entries,
        // a later grow does not resurrect them before indexed lookups.
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);
        let mut decoder = Decoder::new();

        let seed_headers = vec![Header::new("x-evict-me", "value")];
        let mut seeded = BytesMut::new();
        encoder.encode(&seed_headers, &mut seeded);
        let decoded = decoder.decode(&mut seeded.freeze()).unwrap();
        assert_eq!(decoded, seed_headers);
        assert!(decoder.dynamic_table_size() > 0);

        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 0, 5, 0x20);
        encode_integer(&mut buf, 256, 5, 0x20);
        encode_integer(&mut buf, STATIC_TABLE.len() + 1, 7, 0x80);

        let mut src = buf.freeze();
        assert_compression_error(decoder.decode(&mut src));
        assert_eq!(decoder.dynamic_table_size(), 0);
        assert_eq!(decoder.dynamic_table_max_size(), 256);
    }

    // =========================================================================
    // Audit Fix Tests: String length DoS prevention
    // =========================================================================

    #[test]
    fn test_string_length_exceeds_maximum() {
        // Craft a string header with a length claiming > MAX_STRING_LENGTH.
        // The integer encodes 300000 (> 256 * 1024 = 262144).
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, 300_000, 7, 0x00); // literal string, length 300k

        let mut src = buf.freeze();
        let result = decode_string(&mut src);
        assert!(result.is_err());
    }

    #[test]
    fn test_string_length_at_maximum_boundary() {
        // A string of exactly MAX_STRING_LENGTH should be accepted
        // (if the buffer actually contains that many bytes).
        let data = vec![b'x'; MAX_STRING_LENGTH];
        let mut buf = BytesMut::new();
        encode_integer(&mut buf, MAX_STRING_LENGTH, 7, 0x00);
        buf.extend_from_slice(&data);

        let mut src = buf.freeze();
        let result = decode_string(&mut src);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), MAX_STRING_LENGTH);
    }

    #[test]
    fn header_debug_clone_eq() {
        let h = Header::new("content-type", "application/json");
        let dbg = format!("{h:?}");
        assert!(dbg.contains("content-type"));
        assert!(dbg.contains("application/json"));

        let h2 = h.clone();
        assert_eq!(h, h2);

        let h3 = Header::new("accept", "*/*");
        assert_ne!(h, h3);
    }

    #[test]
    fn static_index_exact_matches_linear_scan() {
        // Verify HashMap index returns identical results to linear scan
        for (i, &(name, value)) in STATIC_TABLE.iter().enumerate() {
            let expected = i + 1;
            assert_eq!(
                find_static(name, value),
                Some(expected),
                "exact match failed for ({name}, {value}) at index {expected}"
            );
        }
        // Non-existent exact match
        assert_eq!(find_static("x-custom", "foo"), None);
        // Name exists but value doesn't match
        assert_eq!(find_static(":method", "DELETE"), None);
    }

    #[test]
    fn static_name_index_matches_first_occurrence() {
        // Verify name-only index returns the first occurrence
        assert_eq!(find_static_name(":method"), Some(2)); // first :method
        assert_eq!(find_static_name(":path"), Some(4)); // first :path
        assert_eq!(find_static_name(":status"), Some(8)); // first :status
        assert_eq!(find_static_name(":scheme"), Some(6)); // first :scheme
        assert_eq!(find_static_name("content-type"), Some(31));
        assert_eq!(find_static_name("x-nonexistent"), None);
    }

    // =========================================================================
    // RFC 7541 Appendix C Conformance Tests
    // =========================================================================

    /// RFC 7541 Appendix C.2.1: Literal Header Field with Incremental Indexing — New Name
    #[test]
    fn test_rfc7541_c2_1_literal_incremental_new_name() {
        let mut decoder = Decoder::new();

        // RFC 7541 C.2.1: 40 0a 63 75 73 74 6f 6d 2d 6b 65 79 0d 63 75 73 74 6f 6d 2d 68 65 61 64 65 72
        let encoded = &[
            0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0d, 0x63,
            0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72,
        ];

        let mut bytes = Bytes::copy_from_slice(encoded);
        let headers = decoder
            .decode(&mut bytes)
            .expect("C.2.1 decode should work");

        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, "custom-key");
        assert_eq!(headers[0].value, "custom-header");
    }

    /// RFC 7541 Appendix C.6: Indexed Header Field
    #[test]
    fn test_rfc7541_c6_indexed_header_field() {
        let mut decoder = Decoder::new();

        // RFC 7541 C.6: Index 2 (:method: GET)
        let encoded = &[0x82];

        let mut bytes = Bytes::copy_from_slice(encoded);
        let headers = decoder.decode(&mut bytes).expect("C.6 decode should work");

        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].name, ":method");
        assert_eq!(headers[0].value, "GET");
    }

    /// RFC 7541 Appendix C.3: Multiple request sequence (dynamic table behavior)
    #[test]
    fn test_rfc7541_c3_multiple_requests() {
        let mut decoder = Decoder::new();

        // RFC 7541 C.3.1: First request (same as C.2.1)
        let encoded_1 = &[
            0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0d, 0x63,
            0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72,
        ];

        let mut bytes = Bytes::copy_from_slice(encoded_1);
        let headers_1 = decoder
            .decode(&mut bytes)
            .expect("C.3.1 decode should work");

        assert_eq!(headers_1.len(), 1);
        assert_eq!(headers_1[0].name, "custom-key");
        assert_eq!(headers_1[0].value, "custom-header");

        // RFC 7541 C.3.2: Second request (reference to dynamic table entry)
        let encoded_2 = &[0xbe];

        let mut bytes = Bytes::copy_from_slice(encoded_2);
        let headers_2 = decoder
            .decode(&mut bytes)
            .expect("C.3.2 decode should work");

        assert_eq!(headers_2.len(), 1);
        assert_eq!(headers_2[0].name, "custom-key");
        assert_eq!(headers_2[0].value, "custom-header");
    }

    /// RFC 7541 Appendix C.4: Request sequence with different values
    #[test]
    fn test_rfc7541_c4_request_sequence() {
        let mut decoder = Decoder::new();

        // RFC 7541 C.4.1: First request
        let encoded_1 = &[
            0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0d, 0x63,
            0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72,
        ];

        let mut bytes = Bytes::copy_from_slice(encoded_1);
        let headers_1 = decoder
            .decode(&mut bytes)
            .expect("C.4.1 decode should work");

        assert_eq!(headers_1.len(), 1);
        assert_eq!(headers_1[0].name, "custom-key");
        assert_eq!(headers_1[0].value, "custom-header");

        // RFC 7541 C.4.2: Second request
        let encoded_2 = &[
            0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0c, 0x63,
            0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65,
        ];

        let mut bytes = Bytes::copy_from_slice(encoded_2);
        let headers_2 = decoder
            .decode(&mut bytes)
            .expect("C.4.2 decode should work");

        assert_eq!(headers_2.len(), 1);
        assert_eq!(headers_2[0].name, "custom-key");
        assert_eq!(headers_2[0].value, "custom-value");

        // RFC 7541 C.4.3: Third request (references both dynamic table entries)
        // 0xbf = index 63 (older entry: "custom-header")
        // 0xbe = index 62 (newer entry: "custom-value")
        let encoded_3 = &[0xbf, 0xbe];

        let mut bytes = Bytes::copy_from_slice(encoded_3);
        let headers_3 = decoder
            .decode(&mut bytes)
            .expect("C.4.3 decode should work");

        assert_eq!(headers_3.len(), 2);
        // First header: index 63 (older dynamic entry)
        assert_eq!(headers_3[0].name, "custom-key");
        assert_eq!(headers_3[0].value, "custom-header");
        // Second header: index 62 (newer dynamic entry)
        assert_eq!(headers_3[1].name, "custom-key");
        assert_eq!(headers_3[1].value, "custom-value");
    }

    /// Basic round-trip test to verify encode/decode works
    #[test]
    fn test_rfc7541_round_trip_basic() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Test basic headers
        let headers = vec![
            Header::new(":method", "GET"),
            Header::new(":path", "/"),
            Header::new("custom-key", "custom-value"),
        ];

        let mut encoded = BytesMut::new();
        encoder.encode(&headers, &mut encoded);

        let mut src = encoded.freeze();
        let decoded = decoder
            .decode(&mut src)
            .expect("Round-trip decode should work");

        assert_eq!(decoded.len(), 3);
        assert_eq!(decoded[0].name, ":method");
        assert_eq!(decoded[0].value, "GET");
        assert_eq!(decoded[1].name, ":path");
        assert_eq!(decoded[1].value, "/");
        assert_eq!(decoded[2].name, "custom-key");
        assert_eq!(decoded[2].value, "custom-value");
    }

    // =========================================================================
    // RFC 7541 Appendix A Static Table Conformance Tests (Golden Tests)
    // =========================================================================

    /// Test #1: All 61 static table entries encode correctly
    #[test]
    fn conformance_static_table_all_61_entries_encode_correctly() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Test each of the 61 static table entries
        for (i, &(name, value)) in STATIC_TABLE.iter().enumerate() {
            let expected_index = i + 1;
            let header = Header::new(name, value);

            // Encode the header - should produce indexed representation
            let mut encoded = BytesMut::new();
            encoder.encode(std::slice::from_ref(&header), &mut encoded);

            // Verify it encodes as indexed (0x80 | index)
            let expected_encoded = 0x80 | expected_index;
            if expected_index <= 127 {
                assert_eq!(
                    encoded[0], expected_encoded as u8,
                    "Static table entry {} ({}, {}) should encode as indexed 0x{:02x}",
                    expected_index, name, value, expected_encoded
                );
            } else {
                // For indices > 127, integer encoding uses multiple bytes
                assert_eq!(
                    encoded[0], 0xff,
                    "Static table entry {} should start with 0xff for multi-byte encoding",
                    expected_index
                );
            }

            // Decode and verify round-trip
            let mut src = encoded.freeze();
            let decoded = decoder.decode(&mut src).expect(&format!(
                "Failed to decode static table entry {}",
                expected_index
            ));

            assert_eq!(decoded.len(), 1);
            assert_eq!(decoded[0].name, name);
            assert_eq!(decoded[0].value, value);
        }
    }

    /// Test #2: Referenced-literal vs indexed encoding selection
    #[test]
    fn conformance_referenced_literal_vs_indexed_encoding() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Test exact match -> indexed encoding
        let exact_match = Header::new(":method", "GET"); // Static table index 2
        let mut encoded = BytesMut::new();
        encoder.encode(&[exact_match], &mut encoded);

        // Should be indexed: 0x82 (0x80 | 2)
        assert_eq!(
            encoded[0], 0x82,
            "Exact static table match should use indexed encoding"
        );

        // Test name match with different value -> literal with name index
        let name_match = Header::new(":method", "DELETE"); // Name exists, value doesn't
        let mut encoded = BytesMut::new();
        encoder.encode(&[name_match], &mut encoded);

        // Should start with 0x42 (0x40 | 2) for literal with incremental indexing
        assert_eq!(
            encoded[0], 0x42,
            "Static table name match with different value should use literal with name reference"
        );

        // Verify the value "DELETE" is encoded as a literal string
        let mut src = encoded.freeze();
        let _ = src.split_to(1); // Skip the 0x42 byte

        // Next should be the string "DELETE"
        let value_str = decode_string(&mut src).expect("Should decode DELETE value");
        assert_eq!(value_str, "DELETE");

        // Test completely new header -> literal without name reference
        let new_header = Header::new("x-custom", "test-value");
        let mut encoded = BytesMut::new();
        encoder.encode(&[new_header], &mut encoded);

        // Should start with 0x40 (literal with incremental indexing, no name reference)
        assert_eq!(
            encoded[0], 0x40,
            "New header should use literal without name reference"
        );

        // Round-trip test
        let mut src = encoded.freeze();
        let decoded = decoder
            .decode(&mut src)
            .expect("Should decode custom header");
        assert_eq!(decoded[0].name, "x-custom");
        assert_eq!(decoded[0].value, "test-value");
    }

    /// Test #3: Case-insensitive name matching
    #[test]
    fn conformance_case_insensitive_name_matching() {
        let mut encoder = Encoder::new();
        encoder.set_use_huffman(false);

        // RFC 7541 Section 2.1: Header field names are case-insensitive
        // The static table contains lowercase names, but matching should work
        // with mixed case
        let test_cases = vec![
            ("Content-Type", ""),   // Should match "content-type" (index 31)
            ("CONTENT-TYPE", ""),   // Should match "content-type" (index 31)
            ("content-type", ""),   // Should match "content-type" (index 31)
            ("Content-Length", ""), // Should match "content-length" (index 28)
            ("ACCEPT", ""),         // Should match "accept" (index 19)
        ];

        for (mixed_case_name, value) in test_cases {
            let header = Header::new(mixed_case_name, value);
            let mut encoded = BytesMut::new();

            // Note: The encoder normalizes to lowercase per HTTP/2 spec
            // so we test that the static table lookup works with the normalized name
            let normalized_name = mixed_case_name.to_lowercase();

            // Find what static table index this should match
            let expected_index = find_static_name(&normalized_name)
                .expect(&format!("Should find static index for {}", normalized_name));

            encoder.encode(&[header], &mut encoded);

            // Should encode as indexed if it's an exact match (empty value case)
            let expected_encoded = 0x80 | expected_index;
            assert_eq!(
                encoded[0], expected_encoded as u8,
                "Case-insensitive name {} should match static table index {}",
                mixed_case_name, expected_index
            );
        }
    }

    /// Test #4: Dynamic table eviction under static-first policy
    #[test]
    fn conformance_dynamic_table_eviction_static_first() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Set a small dynamic table size to force eviction
        encoder.set_max_table_size(256); // Small size to force eviction
        decoder.set_allowed_table_size(256);

        // First, add several headers to fill the dynamic table
        let headers_1 = vec![
            Header::new("x-custom-1", "value-1"), // Size: 23 + 32 = 55 bytes
            Header::new("x-custom-2", "value-2"), // Size: 23 + 32 = 55 bytes
            Header::new("x-custom-3", "value-3"), // Size: 23 + 32 = 55 bytes
            Header::new("x-custom-4", "value-4"), // Size: 23 + 32 = 55 bytes
                                                  // Total: 220 bytes (within 256 limit)
        ];

        let mut encoded = BytesMut::new();
        encoder.encode(&headers_1, &mut encoded);

        let mut src = encoded.freeze();
        decoder.decode(&mut src).expect("Should decode first batch");

        // Now add one more header that should cause eviction
        let evicting_header = Header::new("x-custom-5", "value-5"); // 55 bytes

        let mut encoded = BytesMut::new();
        encoder.encode(std::slice::from_ref(&evicting_header), &mut encoded);

        let mut src = encoded.freeze();
        decoder
            .decode(&mut src)
            .expect("Should decode evicting header");

        // Verify that static table entries are still accessible
        // (they should never be evicted)
        let static_header = Header::new(":method", "GET");
        let mut encoded = BytesMut::new();
        encoder.encode(&[static_header], &mut encoded);

        // Should still encode as 0x82 (indexed)
        assert_eq!(
            encoded[0], 0x82,
            "Static table entry should remain accessible after dynamic table eviction"
        );

        // Verify old dynamic entries were evicted by trying to reference them
        // This is hard to test directly, but we can verify the table size constraint
        let large_headers = vec![
            Header::new("x-very-long-header-name-1", "very-long-value-1"),
            Header::new("x-very-long-header-name-2", "very-long-value-2"),
        ];

        let mut encoded = BytesMut::new();
        encoder.encode(&large_headers, &mut encoded);

        // Should succeed without error (proving eviction works)
        let mut src = encoded.freeze();
        let decoded = decoder
            .decode(&mut src)
            .expect("Should handle dynamic table eviction properly");
        assert_eq!(decoded.len(), 2);
    }

    /// Test #5: Never-indexed header preservation
    #[test]
    fn conformance_never_indexed_header_preservation() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        // Test sensitive headers that should never be indexed
        let sensitive_headers = vec![
            Header::new("authorization", "Bearer secret-token"),
            Header::new("cookie", "sessionid=secret123"),
            Header::new("x-api-key", "secret-api-key"),
        ];

        // Encode as never-indexed
        let mut encoded = BytesMut::new();
        encoder.encode_sensitive(&sensitive_headers, &mut encoded);

        // Decode the block
        let mut src = encoded.clone().freeze();
        let decoded = decoder
            .decode(&mut src)
            .expect("Should decode never-indexed headers");

        assert_eq!(decoded.len(), 3);
        assert_eq!(decoded[0].name, "authorization");
        assert_eq!(decoded[0].value, "Bearer secret-token");

        // Now encode the same headers again - they should NOT be found in dynamic table
        // (because they were marked never-indexed)
        let mut encoded_again = BytesMut::new();
        encoder.encode_sensitive(&sensitive_headers, &mut encoded_again);

        // The encoding should be similar (literal representation, not indexed)
        // Both encodings should start with 0x10 (never indexed literal) or similar
        for &byte in &encoded_again[0..3] {
            // Never indexed literals start with 0001xxxx pattern (0x10-0x1F)
            let is_never_indexed = (byte & 0xF0) == 0x10;
            // Or could be literal without indexing 0000xxxx (0x00-0x0F)
            let is_literal_no_index = (byte & 0xF0) == 0x00;

            assert!(
                is_never_indexed || is_literal_no_index,
                "Never-indexed header should not use indexed representation, got 0x{:02x}",
                byte
            );
        }

        // Verify the second encoding decodes to the same values
        let mut src = encoded_again.freeze();
        let decoded_again = decoder
            .decode(&mut src)
            .expect("Should decode never-indexed headers again");

        assert_eq!(
            decoded_again, decoded,
            "Never-indexed headers should decode consistently"
        );

        // Verify these headers are NOT in the dynamic table by checking
        // that subsequent regular encoding doesn't find them
        let mut encoded_regular = BytesMut::new();
        encoder.encode(&sensitive_headers[0..1], &mut encoded_regular); // Just first header

        // Should still be literal (not found in dynamic table)
        let first_byte = encoded_regular[0];
        let is_indexed = (first_byte & 0x80) != 0;
        assert!(
            !is_indexed,
            "Never-indexed header should not be found in dynamic table on subsequent encode"
        );
    }

    #[test]
    fn sensitive_exact_static_match_never_uses_indexed_representation() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        let header = Header::new(":method", "GET");
        let mut encoded = BytesMut::new();
        encoder.encode_sensitive(std::slice::from_ref(&header), &mut encoded);

        assert_eq!(
            encoded[0] & 0xF0,
            0x10,
            "sensitive headers must use the RFC 7541 never-indexed wire form, not indexed lookup"
        );
        assert_eq!(encoder.dynamic_table_size(), 0);

        let mut src = encoded.freeze();
        let decoded = decoder.decode(&mut src).expect("decode sensitive header");
        assert_eq!(decoded, vec![header]);
        assert_eq!(decoder.dynamic_table_size(), 0);
    }

    #[test]
    fn sensitive_exact_dynamic_match_never_uses_indexed_representation() {
        let mut encoder = Encoder::new();
        let mut decoder = Decoder::new();
        encoder.set_use_huffman(false);

        let header = Header::new("authorization", "Bearer secret-token");
        let mut indexed = BytesMut::new();
        encoder.encode(std::slice::from_ref(&header), &mut indexed);
        let mut indexed_src = indexed.freeze();
        let decoded = decoder
            .decode(&mut indexed_src)
            .expect("decode indexed header");
        assert_eq!(decoded, vec![header.clone()]);

        let encoder_table_before = encoder.dynamic_table_size();
        let decoder_table_before = decoder.dynamic_table_size();

        let mut sensitive = BytesMut::new();
        encoder.encode_sensitive(std::slice::from_ref(&header), &mut sensitive);
        assert_eq!(
            sensitive[0] & 0xF0,
            0x10,
            "sensitive exact matches must not collapse to indexed dynamic-table lookups"
        );

        let mut sensitive_src = sensitive.freeze();
        let decoded_sensitive = decoder
            .decode(&mut sensitive_src)
            .expect("decode sensitive header");
        assert_eq!(decoded_sensitive, vec![header]);
        assert_eq!(encoder.dynamic_table_size(), encoder_table_before);
        assert_eq!(decoder.dynamic_table_size(), decoder_table_before);
    }

    /// Additional test: Static table index bounds checking
    #[test]
    fn conformance_static_table_bounds_checking() {
        // Test get_static with various indices
        assert!(get_static(0).is_none(), "Index 0 should be invalid");
        assert!(
            get_static(1).is_some(),
            "Index 1 should be valid (:authority)"
        );
        assert!(
            get_static(61).is_some(),
            "Index 61 should be valid (www-authenticate)"
        );
        assert!(
            get_static(62).is_none(),
            "Index 62 should be invalid (beyond static table)"
        );
        assert!(get_static(1000).is_none(), "Large index should be invalid");

        // Verify the exact entries
        assert_eq!(get_static(1).unwrap(), (":authority", ""));
        assert_eq!(get_static(2).unwrap(), (":method", "GET"));
        assert_eq!(get_static(61).unwrap(), ("www-authenticate", ""));
    }

    /// Additional test: Static table completeness verification
    #[test]
    fn conformance_static_table_completeness() {
        // Verify the static table has exactly 61 entries per RFC 7541 Appendix A
        assert_eq!(
            STATIC_TABLE.len(),
            61,
            "Static table must have exactly 61 entries per RFC 7541 Appendix A"
        );

        // Verify key entries exist at expected positions
        assert_eq!(STATIC_TABLE[0], (":authority", "")); // Index 1
        assert_eq!(STATIC_TABLE[1], (":method", "GET")); // Index 2
        assert_eq!(STATIC_TABLE[2], (":method", "POST")); // Index 3
        assert_eq!(STATIC_TABLE[3], (":path", "/")); // Index 4
        assert_eq!(STATIC_TABLE[4], (":path", "/index.html")); // Index 5
        assert_eq!(STATIC_TABLE[5], (":scheme", "http")); // Index 6
        assert_eq!(STATIC_TABLE[6], (":scheme", "https")); // Index 7
        assert_eq!(STATIC_TABLE[7], (":status", "200")); // Index 8
        assert_eq!(STATIC_TABLE[60], ("www-authenticate", "")); // Index 61

        // Verify the static lookup indices work correctly
        assert_eq!(
            STATIC_EXACT_INDEX.len(),
            61,
            "Exact index should have 61 entries"
        );

        // Verify a few key lookups
        assert_eq!(find_static(":method", "GET"), Some(2));
        assert_eq!(find_static(":method", "POST"), Some(3));
        assert_eq!(find_static(":status", "200"), Some(8));
        assert_eq!(find_static("content-type", ""), Some(31));

        // Verify name-only lookups return first occurrence
        assert_eq!(find_static_name(":method"), Some(2)); // First :method
        assert_eq!(find_static_name(":path"), Some(4)); // First :path
        assert_eq!(find_static_name(":status"), Some(8)); // First :status
    }
}