asupersync 0.3.4

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
//! HTTP/1.1 codec for framed transports.
//!
//! [`Http1Codec`] implements [`Decoder`] for parsing HTTP/1.1 requests and
//! [`Encoder`] for serializing HTTP/1.1 responses, suitable for use with
//! [`Framed`](crate::codec::Framed).

use crate::bytes::BytesMut;
use crate::codec::{Decoder, Encoder};
use crate::http::h1::types::{self, Method, Request, Response, Version};
use memchr::{memchr, memchr_iter, memmem};
use std::fmt;
use std::io;

/// Maximum allowed header block size (64 KiB).
const DEFAULT_MAX_HEADERS_SIZE: usize = 64 * 1024;

/// Maximum allowed body size (16 MiB).
const DEFAULT_MAX_BODY_SIZE: usize = 16 * 1024 * 1024;

/// Maximum number of headers.
const MAX_HEADERS: usize = 128;

/// Maximum allowed request line length.
const MAX_REQUEST_LINE: usize = 8192;

/// HTTP/1.1 protocol errors.
#[derive(Debug)]
pub enum HttpError {
    /// An I/O error from the transport.
    Io(io::Error),
    /// The request line is malformed.
    BadRequestLine,
    /// A header line is malformed.
    BadHeader,
    /// Unsupported HTTP version in request.
    UnsupportedVersion,
    /// Unrecognised HTTP method.
    BadMethod,
    /// Content-Length header is not a valid integer.
    BadContentLength,
    /// Multiple Content-Length headers present.
    DuplicateContentLength,
    /// Multiple Transfer-Encoding headers present.
    DuplicateTransferEncoding,
    /// Transfer-Encoding is present but unsupported.
    BadTransferEncoding,
    /// Header name contains invalid characters.
    InvalidHeaderName,
    /// Header value contains invalid characters.
    InvalidHeaderValue,
    /// Header block exceeds the configured limit.
    HeadersTooLarge,
    /// Too many headers.
    TooManyHeaders,
    /// Too many informational responses were received before a final response.
    TooManyInformationalResponses {
        /// Number of informational responses seen.
        actual: usize,
        /// Maximum allowed informational responses.
        limit: usize,
    },
    /// Request line too long.
    RequestLineTooLong,
    /// Incomplete chunked encoding.
    BadChunkedEncoding,
    /// Body exceeds the configured limit.
    BodyTooLarge,
    /// Body exceeds the configured limit (with size details).
    BodyTooLargeDetailed {
        /// Actual body size (Content-Length or bytes received so far).
        actual: u64,
        /// Configured maximum body size.
        limit: u64,
    },
    /// Body stream was cancelled.
    BodyCancelled,
    /// Body channel closed unexpectedly.
    BodyChannelClosed,
    /// Both Content-Length and Transfer-Encoding present (RFC 7230 3.3.3 violation).
    /// This is a potential request smuggling vector.
    AmbiguousBodyLength,
    /// Trailers were provided/encountered but are not permitted in this context.
    TrailersNotAllowed,
    /// Response parsing left unread prefetched bytes when a fully-buffered
    /// response API was used.
    PrefetchedDataRemaining(usize),
}

impl fmt::Display for HttpError {
    #[allow(clippy::cast_precision_loss)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "I/O error: {e}"),
            Self::BadRequestLine => write!(f, "malformed request line"),
            Self::BadHeader => write!(f, "malformed header"),
            Self::UnsupportedVersion => write!(f, "unsupported HTTP version"),
            Self::BadMethod => write!(f, "unrecognised HTTP method"),
            Self::BadContentLength => write!(f, "invalid Content-Length"),
            Self::DuplicateContentLength => write!(f, "duplicate Content-Length"),
            Self::DuplicateTransferEncoding => write!(f, "duplicate Transfer-Encoding"),
            Self::BadTransferEncoding => write!(f, "unsupported Transfer-Encoding"),
            Self::InvalidHeaderName => write!(f, "invalid header name"),
            Self::InvalidHeaderValue => write!(f, "invalid header value"),
            Self::HeadersTooLarge => write!(f, "header block too large"),
            Self::TooManyHeaders => write!(f, "too many headers"),
            Self::TooManyInformationalResponses { actual, limit } => {
                write!(
                    f,
                    "received too many informational responses before a final response ({actual} > {limit})"
                )
            }
            Self::RequestLineTooLong => write!(f, "request line too long"),
            Self::BadChunkedEncoding => write!(f, "malformed chunked encoding"),
            Self::BodyTooLarge => write!(f, "body exceeds size limit"),
            Self::BodyTooLargeDetailed { actual, limit } => {
                #[allow(clippy::cast_precision_loss)] // display-only MB approximation
                let actual_mb = *actual as f64 / 1_048_576.0;
                #[allow(clippy::cast_precision_loss)]
                let limit_mb = *limit as f64 / 1_048_576.0;
                write!(
                    f,
                    "body size ({actual} bytes, {actual_mb:.1} MB) exceeds limit ({limit} bytes, {limit_mb:.1} MB)",
                )
            }
            Self::BodyCancelled => write!(f, "body stream cancelled"),
            Self::BodyChannelClosed => write!(f, "body stream closed"),
            Self::AmbiguousBodyLength => {
                write!(f, "both Content-Length and Transfer-Encoding present")
            }
            Self::TrailersNotAllowed => write!(f, "trailers not allowed"),
            Self::PrefetchedDataRemaining(count) => {
                write!(
                    f,
                    "response completed with {count} unread prefetched bytes; use streaming API"
                )
            }
        }
    }
}

impl std::error::Error for HttpError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for HttpError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

/// Codec state machine.
#[derive(Debug)]
enum DecodeState {
    /// Waiting for a complete request line + headers block.
    Head,
    /// Headers parsed; reading exactly `remaining` body bytes.
    Body {
        method: Method,
        uri: String,
        version: Version,
        headers: Vec<(String, String)>,
        remaining: usize,
    },
    /// Headers parsed; reading chunked transfer-encoding body.
    Chunked {
        method: Method,
        uri: String,
        version: Version,
        headers: Vec<(String, String)>,
        chunked: ChunkedBodyDecoder,
    },
    /// Codec encountered a fatal error and is permanently poisoned.
    Poisoned,
}

/// HTTP/1.1 request decoder and response encoder.
///
/// Implements [`Decoder<Item = Request>`] for parsing incoming HTTP/1.1
/// requests and [`Encoder<Response>`] for serializing outgoing responses.
///
/// # Limits
///
/// - Maximum header block size: 64 KiB (configurable via [`max_headers_size`](Self::max_headers_size))
/// - Maximum body size: 16 MiB (configurable via [`max_body_size`](Self::max_body_size))
/// - Maximum number of headers: 128
/// - Maximum request line: 8 KiB
pub struct Http1Codec {
    state: DecodeState,
    max_headers_size: usize,
    max_body_size: usize,
}

impl Http1Codec {
    /// Create a new codec with default limits.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: DecodeState::Head,
            max_headers_size: DEFAULT_MAX_HEADERS_SIZE,
            max_body_size: DEFAULT_MAX_BODY_SIZE,
        }
    }

    /// Set the maximum header block size.
    #[inline]
    #[must_use]
    pub fn max_headers_size(mut self, size: usize) -> Self {
        self.max_headers_size = size;
        self
    }

    /// Set the maximum body size.
    #[inline]
    #[must_use]
    pub fn max_body_size(mut self, size: usize) -> Self {
        self.max_body_size = size;
        self
    }
}

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

/// Find the position of `\r\n\r\n` in `buf`, returning the index of the
/// first byte after the delimiter.
#[inline]
fn find_headers_end(buf: &[u8]) -> Option<usize> {
    memmem::find(buf, b"\r\n\r\n").map(|idx| idx + 4)
}

/// Find the position of the first CRLF (`\r\n`) in `buf`.
///
/// Returns the index of `\r` when found.
#[inline]
fn find_crlf(buf: &[u8]) -> Option<usize> {
    memmem::find(buf, b"\r\n")
}

/// Collect all CRLF (`\r\n`) positions in `buf` into a pre-allocated vector.
///
/// Each returned value is the index of `\r` in a valid `\r\n` pair.
/// Used by `decode_head` to avoid repeated per-header `find_crlf` calls.
#[inline]
fn collect_crlf_positions(buf: &[u8], out: &mut smallvec::SmallVec<[usize; 32]>) {
    out.clear();
    for idx in memchr_iter(b'\n', buf) {
        if idx > 0 && buf[idx - 1] == b'\r' {
            out.push(idx - 1);
        }
    }
}

/// Valid bytes for the HTTP/1.x request-target (RFC 3986 URI + reserved/sub-delims).
///
/// Rejects control characters (including `\x00`, `\x01`, …, `\x1f`), `DEL`
/// (`0x7F`), any non-ASCII byte, and whitespace — all of which can enable
/// smuggling or header injection if silently accepted inside a path.
#[inline]
fn is_valid_request_target_byte(b: u8) -> bool {
    // RFC 3986 permits all printable ASCII except space in a URI; anything
    // outside `0x21..=0x7E` is invalid in a request-target. Space is the
    // delimiter between tokens and is already consumed by the caller, so a
    // stray space here also represents a malformed request-line.
    (0x21..=0x7E).contains(&b)
}

fn parse_request_line_bytes(line: &[u8]) -> Result<(Method, String, Version), HttpError> {
    // Reject bare CR embedded in the request line — only the terminating
    // CRLF may contain \r, and that has already been stripped. A bare \r
    // in the middle is a framing error / smuggling vector.
    if line.contains(&b'\r') {
        return Err(HttpError::BadRequestLine);
    }
    // Fast path for the overwhelmingly common HTTP/1.x wire form:
    // `METHOD SP URI SP VERSION` with no extra whitespace tokens.
    if let Some(first_sp) = memchr(b' ', line) {
        if first_sp > 0 {
            let rest = &line[first_sp + 1..];
            if let Some(second_sp_rel) = memchr(b' ', rest) {
                let second_sp = first_sp + 1 + second_sp_rel;
                if second_sp > first_sp + 1 {
                    let method_bytes = &line[..first_sp];
                    let uri_bytes = &line[first_sp + 1..second_sp];
                    let version_bytes = &line[second_sp + 1..];
                    if !version_bytes.is_empty()
                        && !version_bytes.iter().any(u8::is_ascii_whitespace)
                    {
                        let method =
                            Method::from_bytes(method_bytes).ok_or(HttpError::BadMethod)?;
                        if !uri_bytes.iter().copied().all(is_valid_request_target_byte) {
                            return Err(HttpError::BadRequestLine);
                        }
                        let version = Version::from_bytes(version_bytes)
                            .ok_or(HttpError::UnsupportedVersion)?;
                        let uri = std::str::from_utf8(uri_bytes)
                            .map_err(|_| HttpError::BadRequestLine)?;

                        validate_request_target(&method, uri)?;

                        return Ok((method, uri.to_owned(), version));
                    }
                }
            }
        }
    }

    parse_request_line_bytes_slow(line)
}

fn parse_request_line_bytes_slow(line: &[u8]) -> Result<(Method, String, Version), HttpError> {
    fn next_token_bounds(bytes: &[u8], cursor: &mut usize) -> Option<(usize, usize)> {
        let start = *cursor;
        while *cursor < bytes.len() && bytes[*cursor] != b' ' {
            *cursor += 1;
        }
        (start < *cursor).then_some((start, *cursor))
    }

    fn consume_single_space(bytes: &[u8], cursor: &mut usize) -> Result<(), HttpError> {
        if *cursor >= bytes.len() || bytes[*cursor] != b' ' {
            return Err(HttpError::BadRequestLine);
        }
        *cursor += 1;
        if *cursor >= bytes.len() || bytes[*cursor] == b' ' {
            return Err(HttpError::BadRequestLine);
        }
        Ok(())
    }

    let mut cursor = 0usize;
    let method_bounds = next_token_bounds(line, &mut cursor).ok_or(HttpError::BadRequestLine)?;
    consume_single_space(line, &mut cursor)?;
    let uri_bounds = next_token_bounds(line, &mut cursor).ok_or(HttpError::BadRequestLine)?;
    consume_single_space(line, &mut cursor)?;
    let version_bounds = next_token_bounds(line, &mut cursor).ok_or(HttpError::BadRequestLine)?;
    if cursor != line.len() {
        return Err(HttpError::BadRequestLine);
    }

    let method =
        Method::from_bytes(&line[method_bounds.0..method_bounds.1]).ok_or(HttpError::BadMethod)?;
    let uri_bytes = &line[uri_bounds.0..uri_bounds.1];
    if !uri_bytes.iter().copied().all(is_valid_request_target_byte) {
        return Err(HttpError::BadRequestLine);
    }
    let version = Version::from_bytes(&line[version_bounds.0..version_bounds.1])
        .ok_or(HttpError::UnsupportedVersion)?;
    let uri = std::str::from_utf8(uri_bytes).map_err(|_| HttpError::BadRequestLine)?;

    validate_request_target(&method, uri)?;

    Ok((method, uri.to_owned(), version))
}

fn validate_request_target(method: &Method, uri: &str) -> Result<(), HttpError> {
    if uri.is_empty() {
        return Err(HttpError::BadRequestLine);
    }

    // asterisk-form (RFC 9112 §3.2.4)
    if uri == "*" {
        if *method != Method::Options {
            return Err(HttpError::BadRequestLine);
        }
        return Ok(());
    }

    // authority-form (RFC 9112 §3.2.3)
    if *method == Method::Connect {
        if uri.starts_with('/') || uri.contains("://") {
            return Err(HttpError::BadRequestLine);
        }
        // Authority-form must be host:port
        let (host, port) = uri.rsplit_once(':').ok_or(HttpError::BadRequestLine)?;
        if host.is_empty() || port.is_empty() || !port.as_bytes().iter().all(u8::is_ascii_digit) {
            return Err(HttpError::BadRequestLine);
        }
        return Ok(());
    }

    // origin-form (RFC 9112 §3.2.1)
    if uri.starts_with('/') {
        // MUST NOT start with // (ambiguous or potential smuggling vector)
        if uri.starts_with("//") {
            return Err(HttpError::BadRequestLine);
        }
        return Ok(());
    }

    // absolute-form (RFC 9112 §3.2.2)
    if let Some((scheme, rest)) = uri.split_once("://") {
        if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphabetic()) {
            return Err(HttpError::BadRequestLine);
        }
        // absolute-form MUST have a non-empty authority. RFC 3986 defines
        // authority = [userinfo "@"] host [":" port], and RFC 9112 §3.2.2
        // requires it. `rest` starts with '/' or '?' or '#' only when the
        // authority is empty (e.g. "http:///path", "http://?q", "http://#f");
        // reject those shapes. (br-asupersync-w6u4cn)
        let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
        if authority_end == 0 {
            return Err(HttpError::BadRequestLine);
        }
        return Ok(());
    }

    // If it doesn't match any allowed form, it's invalid.
    Err(HttpError::BadRequestLine)
}

/// Validates an HTTP field-name (RFC 7230 token / tchar set).
fn is_valid_header_name(name: &str) -> bool {
    is_valid_header_name_bytes(name.as_bytes())
}

fn is_valid_header_name_bytes(name: &[u8]) -> bool {
    if name.is_empty() {
        return false;
    }
    name.iter().all(|&b| is_valid_header_name_byte(b))
}

#[inline]
fn is_valid_header_name_byte(b: u8) -> bool {
    matches!(
        b,
        b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' | b'^'
            | b'_' | b'`' | b'|' | b'~' | b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z'
    )
}

fn parse_header_line_bounds(line_bytes: &[u8]) -> Result<(usize, usize, usize), HttpError> {
    // Use memchr for SIMD-accelerated colon search.
    let colon = memchr(b':', line_bytes).ok_or(HttpError::BadHeader)?;

    // Header field names cannot be empty, and all bytes before the colon
    // must be valid tchar (RFC 7230).
    if colon == 0
        || !line_bytes[..colon]
            .iter()
            .all(|&b| is_valid_header_name_byte(b))
    {
        return Err(HttpError::InvalidHeaderName);
    }

    let mut value_start = colon + 1;
    while value_start < line_bytes.len()
        && (line_bytes[value_start] == b' ' || line_bytes[value_start] == b'\t')
    {
        value_start += 1;
    }
    let mut value_end = line_bytes.len();
    while value_end > value_start
        && (line_bytes[value_end - 1] == b' ' || line_bytes[value_end - 1] == b'\t')
    {
        value_end -= 1;
    }
    for &b in &line_bytes[value_start..value_end] {
        // Reject control characters per RFC 9110 Section 5.5.
        // Only HTAB (0x09) and visible ASCII (0x20..=0x7E) plus
        // obs-text (0x80..=0xFF) are allowed in field values.
        if b == b'\r' || b == b'\n' || b == b'\0' || (b < 0x20 && b != b'\t') || b == 0x7F {
            return Err(HttpError::InvalidHeaderValue);
        }
    }

    Ok((colon, value_start, value_end))
}

/// br-asupersync-135g0e + br-asupersync-ko0gde: returns `true` for header
/// field names that RFC 9110 §6.5.2 forbids in the trailer section. The list
/// covers framing, routing, request-modifier, authentication, payload-
/// processing, and cache-control fields that an intermediary might rely on
/// when forwarding the message. Comparison is case-insensitive per RFC 9110
/// §5.1 ("field names are case-insensitive").
fn is_forbidden_trailer(name: &str) -> bool {
    // Sorted alphabetically for review. Keep in sync with RFC 9110 §6.5.2's
    // restricted-fields table and the related security guidance in §17.13.
    const FORBIDDEN: &[&str] = &[
        // Authentication / authorization.
        "authorization",
        // Cache control.
        "age",
        "cache-control",
        // Hop-by-hop framing fields explicitly listed in RFC 9110 §6.5.2.
        // A coalescing proxy that treats trailers as headers could otherwise
        // honour a smuggled `Connection: x-secret` and strip x-secret on
        // the next hop, or terminate the connection unexpectedly.
        "connection",
        // Payload processing & message framing.
        "content-encoding",
        "content-length",
        "content-range",
        "content-type",
        // Cookies / session credentials.
        "cookie",
        // Response control data.
        "date",
        "expect",
        "expires",
        // Routing.
        "host",
        // Legacy hop-by-hop framing — same semantics as Connection.
        "keep-alive",
        // Request modifiers.
        "max-forwards",
        "pragma",
        "proxy-authenticate",
        "proxy-authorization",
        // Not in RFC 9110's table but ubiquitous on the wire and routinely
        // honoured as hop-state by proxies; share Connection's risk profile.
        "proxy-connection",
        "range",
        "retry-after",
        "set-cookie",
        // Tracking / interception.
        "te",
        // Framing-critical.
        "trailer",
        "transfer-encoding",
        "upgrade",
        "vary",
        "warning",
        "www-authenticate",
    ];
    FORBIDDEN
        .iter()
        .any(|&forbidden| name.eq_ignore_ascii_case(forbidden))
}

fn parse_header_line_bytes(line_bytes: &[u8]) -> Result<(String, String), HttpError> {
    let (colon, value_start, value_end) = parse_header_line_bounds(line_bytes)?;
    let name_bytes = &line_bytes[..colon];
    let value_bytes = &line_bytes[value_start..value_end];
    let name = std::str::from_utf8(name_bytes).map_err(|_| HttpError::BadHeader)?;

    // Header values might contain obs-text (bytes >= 0x80) which are not always valid UTF-8.
    // Fall back to Latin-1 decoding if UTF-8 validation fails.
    let value = std::str::from_utf8(value_bytes).map_or_else(
        |_| value_bytes.iter().map(|&b| b as char).collect(),
        std::borrow::ToOwned::to_owned,
    );

    Ok((name.to_owned(), value))
}

/// Parse a single `Name: Value` header line.
pub(super) fn parse_header_line(line: &str) -> Result<(String, String), HttpError> {
    let (colon, value_start, value_end) = parse_header_line_bounds(line.as_bytes())?;
    let name = &line[..colon];
    let value = &line[value_start..value_end];
    Ok((name.to_owned(), value.to_owned()))
}

/// Test-specific export of parse_header_line for conformance testing.
#[cfg(test)]
pub fn parse_header_line_test(line: &str) -> Result<(String, String), HttpError> {
    parse_header_line(line)
}

pub(super) fn validate_header_field(name: &str, value: &str) -> Result<(), HttpError> {
    if name.contains('\r') || name.contains('\n') {
        return Err(HttpError::InvalidHeaderName);
    }
    if !is_valid_header_name(name) {
        return Err(HttpError::InvalidHeaderName);
    }
    if value
        .bytes()
        .any(|b| b == b'\r' || b == b'\n' || b == b'\0' || (b < 0x20 && b != b'\t') || b == 0x7F)
    {
        return Err(HttpError::InvalidHeaderValue);
    }
    Ok(())
}

/// br-asupersync-zepgmq — Fuzz-target re-exporter for the H1
/// header-line bounds parser. `#[doc(hidden)]`; only exists for
/// direct fuzz harness access.
#[doc(hidden)]
pub fn fuzz_parse_header_line_bounds(
    line_bytes: &[u8],
) -> Result<(usize, usize, usize), HttpError> {
    parse_header_line_bounds(line_bytes)
}

/// br-asupersync-8dl9j7 — Fuzz-target re-exporter for the H1
/// chunked-encoding chunk-size-line parser.
#[doc(hidden)]
pub fn fuzz_parse_chunk_size_line(line: &[u8]) -> Result<usize, HttpError> {
    parse_chunk_size_line(line)
}

/// br-asupersync-sbc0pi — Fuzz-target re-exporter for the H1
/// request-line parser. `#[doc(hidden)]`; only exists for
/// direct fuzz harness access.
#[doc(hidden)]
pub fn fuzz_parse_request_line_bytes(line: &[u8]) -> Result<(Method, String, Version), HttpError> {
    parse_request_line_bytes(line)
}

/// Look up a header value (case-insensitive name match).
#[cfg(test)]
fn header_value<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(n, _)| n.eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_str())
}

/// Look up a header value, rejecting duplicates for security-sensitive headers.
pub(super) fn unique_header_value<'a>(
    headers: &'a [(String, String)],
    name: &str,
) -> Result<Option<&'a str>, HttpError> {
    let mut found = None;
    for (n, v) in headers {
        if n.eq_ignore_ascii_case(name) {
            if found.is_some() {
                if name.eq_ignore_ascii_case("content-length") {
                    return Err(HttpError::DuplicateContentLength);
                }
                if name.eq_ignore_ascii_case("transfer-encoding") {
                    return Err(HttpError::DuplicateTransferEncoding);
                }
                return Err(HttpError::BadHeader);
            }
            found = Some(v.as_str());
        }
    }
    Ok(found)
}

pub(super) fn require_transfer_encoding_chunked(value: &str) -> Result<(), HttpError> {
    let mut tokens = value.split(',').map(str::trim).filter(|t| !t.is_empty());
    let first = tokens.next().ok_or(HttpError::BadTransferEncoding)?;
    if tokens.next().is_some() {
        // We only support the simplest/secure subset for now: `chunked` only.
        return Err(HttpError::BadTransferEncoding);
    }
    if first.eq_ignore_ascii_case("chunked") {
        return Ok(());
    }
    Err(HttpError::BadTransferEncoding)
}

/// Append a `usize` as decimal ASCII digits to `dst`.
pub(super) fn append_decimal(dst: &mut BytesMut, mut n: usize) {
    // Stack buffer large enough for any usize (max 20 digits on 64-bit).
    let mut buf = [0u8; 20];
    let mut pos = buf.len();
    if n == 0 {
        dst.extend_from_slice(b"0");
        return;
    }
    while n > 0 {
        pos -= 1;
        buf[pos] = b'0' + (n % 10) as u8;
        n /= 10;
    }
    dst.extend_from_slice(&buf[pos..]);
}

fn upper_hex_len(mut n: usize) -> usize {
    let mut len = 1;
    while n >= 16 {
        n /= 16;
        len += 1;
    }
    len
}

pub(super) fn append_chunk_size_line(dst: &mut BytesMut, mut size: usize) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut digits = [0u8; usize::BITS as usize / 4];
    let mut written = 0usize;
    loop {
        let idx = size & 0xF;
        digits[digits.len() - 1 - written] = HEX[idx];
        written += 1;
        size >>= 4;
        if size == 0 {
            break;
        }
    }
    let start = digits.len() - written;
    dst.extend_from_slice(&digits[start..]);
    dst.extend_from_slice(b"\r\n");
}

/// Return `(Transfer-Encoding, Content-Length)` while enforcing duplicate rules.
fn transfer_and_content_length(
    headers: &[(String, String)],
) -> Result<(Option<&str>, Option<&str>), HttpError> {
    let mut transfer_encoding = None;
    let mut content_length = None;

    for (name, value) in headers {
        if name.eq_ignore_ascii_case("transfer-encoding") {
            if transfer_encoding.is_some() {
                return Err(HttpError::DuplicateTransferEncoding);
            }
            transfer_encoding = Some(value.as_str());
            continue;
        }
        if name.eq_ignore_ascii_case("content-length") {
            if content_length.is_some() {
                return Err(HttpError::DuplicateContentLength);
            }
            content_length = Some(value.as_str());
        }
    }

    Ok((transfer_encoding, content_length))
}

const HEADER_TRANSFER_ENCODING: &[u8] = b"transfer-encoding";
const HEADER_CONTENT_LENGTH: &[u8] = b"content-length";

#[inline]
fn is_transfer_encoding_name(name: &str) -> bool {
    name.as_bytes()
        .eq_ignore_ascii_case(HEADER_TRANSFER_ENCODING)
}

#[inline]
fn is_content_length_name(name: &str) -> bool {
    name.as_bytes().eq_ignore_ascii_case(HEADER_CONTENT_LENGTH)
}

enum BodyKind {
    ContentLength(usize),
    Chunked,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(not(target_arch = "wasm32"))]
pub(super) struct RequestHeadPreview {
    pub version: Version,
    pub headers: Vec<(String, String)>,
}

const MAX_CHUNK_LINE_LEN: usize = 1024;

type ChunkedDecoded = (Vec<u8>, Vec<(String, String)>);

#[derive(Debug)]
enum ChunkPhase {
    SizeLine,
    Data { remaining: usize },
    DataCrlf,
    Trailers,
}

#[derive(Debug)]
pub(super) struct ChunkedBodyDecoder {
    phase: ChunkPhase,
    body: Vec<u8>,
    trailers: Vec<(String, String)>,
    trailers_bytes: usize,
    max_body_size: usize,
    max_trailers_size: usize,
}

impl ChunkedBodyDecoder {
    pub(super) fn new(max_body_size: usize, max_trailers_size: usize) -> Self {
        Self {
            phase: ChunkPhase::SizeLine,
            body: Vec::new(),
            trailers: Vec::new(),
            trailers_bytes: 0,
            max_body_size,
            max_trailers_size,
        }
    }

    pub(super) fn decode(
        &mut self,
        src: &mut BytesMut,
    ) -> Result<Option<ChunkedDecoded>, HttpError> {
        loop {
            match self.phase {
                ChunkPhase::SizeLine => {
                    let Some(line) = split_line_crlf(src, MAX_CHUNK_LINE_LEN)? else {
                        return Ok(None);
                    };
                    let size = parse_chunk_size_line(line.as_ref())?;
                    if size == 0 {
                        self.phase = ChunkPhase::Trailers;
                        continue;
                    }

                    if self.body.len().saturating_add(size) > self.max_body_size {
                        return Err(HttpError::BodyTooLarge);
                    }

                    self.phase = ChunkPhase::Data { remaining: size };
                }

                ChunkPhase::Data { remaining } => {
                    if src.len() < remaining {
                        return Ok(None);
                    }
                    let data = src.split_to(remaining);
                    self.body.extend_from_slice(data.as_ref());
                    self.phase = ChunkPhase::DataCrlf;
                }

                ChunkPhase::DataCrlf => {
                    if src.len() < 2 {
                        return Ok(None);
                    }
                    if src.as_ref()[0] != b'\r' || src.as_ref()[1] != b'\n' {
                        return Err(HttpError::BadChunkedEncoding);
                    }
                    let _ = src.split_to(2);
                    self.phase = ChunkPhase::SizeLine;
                }

                ChunkPhase::Trailers => {
                    let Some(line) = split_line_crlf(src, self.max_trailers_size)? else {
                        return Ok(None);
                    };

                    if line.is_empty() {
                        self.phase = ChunkPhase::SizeLine;
                        self.trailers_bytes = 0;
                        return Ok(Some((
                            std::mem::take(&mut self.body),
                            std::mem::take(&mut self.trailers),
                        )));
                    }

                    self.trailers_bytes = self.trailers_bytes.saturating_add(line.len() + 2);
                    if self.trailers_bytes > self.max_trailers_size {
                        return Err(HttpError::HeadersTooLarge);
                    }

                    let (name, value) = parse_header_line_bytes(line.as_ref())?;
                    // br-asupersync-135g0e: RFC 9110 §6.5.1 forbids trailers
                    // that affect framing, routing, request modifiers, auth,
                    // payload processing, or cache control. Some middleware
                    // merges trailers into the header set, which would let a
                    // malicious trailer smuggle a Content-Length / TE override
                    // past the intermediary. Reject at the parser.
                    if is_forbidden_trailer(&name) {
                        return Err(HttpError::BadHeader);
                    }
                    self.trailers.push((name, value));
                    if self.trailers.len() > MAX_HEADERS {
                        return Err(HttpError::TooManyHeaders);
                    }
                }
            }
        }
    }
}

fn split_line_crlf(src: &mut BytesMut, max_len: usize) -> Result<Option<BytesMut>, HttpError> {
    let Some(line_end) = find_crlf(src.as_ref()) else {
        if src.len() > max_len {
            return Err(HttpError::BadChunkedEncoding);
        }
        return Ok(None);
    };

    if line_end > max_len {
        return Err(HttpError::BadChunkedEncoding);
    }

    let line = src.split_to(line_end);
    let _ = src.split_to(2); // CRLF
    Ok(Some(line))
}

pub(super) fn parse_chunk_size_line(line: &[u8]) -> Result<usize, HttpError> {
    let line = std::str::from_utf8(line).map_err(|_| HttpError::BadChunkedEncoding)?;
    // Split on ';' to separate chunk-size from optional chunk-ext (RFC 7230 §4.1).
    // Do NOT trim — chunk-size = 1*HEXDIG with no leading/trailing whitespace.
    // Trimming would mask differences from stricter proxies (request smuggling vector).
    let size_part = line.split(';').next().unwrap_or("");
    if size_part.is_empty() {
        return Err(HttpError::BadChunkedEncoding);
    }
    // Reject leading/trailing whitespace explicitly to prevent smuggling.
    if size_part
        .as_bytes()
        .first()
        .is_some_and(u8::is_ascii_whitespace)
        || size_part
            .as_bytes()
            .last()
            .is_some_and(u8::is_ascii_whitespace)
    {
        return Err(HttpError::BadChunkedEncoding);
    }
    // br-asupersync-usvn1p: RFC 9112 §7.1 — chunk-size = 1*HEXDIG (no
    // sign). Rust's usize::from_str_radix accepts '+1A' which can
    // disagree with stricter intermediaries (nginx, envoy) and create
    // a request-smuggling primitive. Reject any non-hexdigit prefix
    // before parsing.
    if size_part.is_empty() || !size_part.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(HttpError::BadChunkedEncoding);
    }
    usize::from_str_radix(size_part, 16).map_err(|_| HttpError::BadChunkedEncoding)
}

/// Parse the head (request line + headers) from `src`, splitting off the
/// consumed bytes. Returns `None` if the full header block hasn't arrived yet.
#[allow(clippy::type_complexity)]
fn decode_head_parts(
    src: &[u8],
    max_headers_size: usize,
) -> Result<
    Option<(
        usize,
        Method,
        String,
        Version,
        Vec<(String, String)>,
        BodyKind,
    )>,
    HttpError,
> {
    // Reject bare CRs in the buffered head: HTTP/1.x line terminators MUST be
    // CRLF (RFC 9112 §2.2). A `\r` followed by anything other than `\n` is a
    // framing violation (request-smuggling vector), so fail fast instead of
    // waiting for a CRLF that will never arrive. A trailing single `\r` with
    // no successor byte yet may still be completed, so we only fire when the
    // next byte is already buffered.
    //
    // br-asupersync-2ovm8z: bound the scan to the HEAD region only. The
    // previous unbounded scan over `src` would inspect body bytes (or
    // pipelined-next-request bytes) and reject any 0x0D byte as a bare-CR,
    // poisoning the connection on virtually all binary uploads (gRPC,
    // protobuf, images, octet-stream — any payload contains 0x0D in ~1/256
    // bytes). The scan must apply ONLY to head bytes.
    let head_scan_limit = match find_headers_end(src) {
        Some(end) => end, // complete head — scan exactly the head bytes
        None => src.len().min(max_headers_size),
    };
    for idx in memchr_iter(b'\r', &src[..head_scan_limit]) {
        if idx + 1 < head_scan_limit && src[idx + 1] != b'\n' {
            return Err(HttpError::BadRequestLine);
        }
    }

    let Some(end) = find_headers_end(src) else {
        if src.len() > max_headers_size {
            return Err(HttpError::HeadersTooLarge);
        }
        // Preserve request-line limit behavior for incomplete heads while
        // avoiding an extra scan on the common fully-buffered decode path.
        if src.len() > MAX_REQUEST_LINE {
            match find_crlf(src) {
                Some(line_end) if line_end > MAX_REQUEST_LINE => {
                    return Err(HttpError::RequestLineTooLong);
                }
                Some(_) => {}
                None => return Err(HttpError::RequestLineTooLong),
            }
        }
        return Ok(None);
    };

    if end > max_headers_size {
        return Err(HttpError::HeadersTooLarge);
    }

    let head = &src[..end];

    // Single-pass: collect all CRLF positions in the header block at once.
    // This replaces N+1 individual `find_crlf()` sub-slice calls with one
    // `memchr_iter` pass, eliminating repeated search setup overhead.
    let mut crlf_positions = smallvec::SmallVec::<[usize; 32]>::new();
    collect_crlf_positions(head, &mut crlf_positions);

    let request_line_end = *crlf_positions.first().ok_or(HttpError::BadRequestLine)?;
    if request_line_end > MAX_REQUEST_LINE {
        return Err(HttpError::RequestLineTooLong);
    }
    if request_line_end >= head.len() {
        return Err(HttpError::BadRequestLine);
    }
    let request_line = &head[..request_line_end];
    let (method, uri, version) = parse_request_line_bytes(request_line)?;

    let header_count = crlf_positions.len().saturating_sub(2);
    if header_count > MAX_HEADERS {
        return Err(HttpError::TooManyHeaders);
    }
    let mut headers = Vec::with_capacity(header_count);
    let mut transfer_encoding_idx = None;
    let mut content_length_idx = None;
    let mut cursor = request_line_end + 2;
    // Iterate pre-computed CRLF positions (skip the first which was request line)
    for &crlf_pos in &crlf_positions[1..] {
        if crlf_pos < cursor {
            continue;
        }
        let line_len = crlf_pos - cursor;
        if line_len == 0 {
            break;
        }
        let header = parse_header_line_bytes(&head[cursor..crlf_pos])?;
        if is_transfer_encoding_name(header.0.as_str()) {
            if transfer_encoding_idx.is_some() {
                return Err(HttpError::DuplicateTransferEncoding);
            }
            transfer_encoding_idx = Some(headers.len());
        } else if is_content_length_name(header.0.as_str()) {
            if content_length_idx.is_some() {
                return Err(HttpError::DuplicateContentLength);
            }
            content_length_idx = Some(headers.len());
        }

        headers.push(header);
        cursor = crlf_pos + 2;
    }

    let kind = match (transfer_encoding_idx, content_length_idx) {
        (Some(_), Some(_)) => return Err(HttpError::AmbiguousBodyLength),
        (Some(te_idx), None) => {
            if version == Version::Http10 {
                return Err(HttpError::BadTransferEncoding);
            }
            require_transfer_encoding_chunked(headers[te_idx].1.as_str())?;
            BodyKind::Chunked
        }
        (None, Some(cl_idx)) => {
            // br-asupersync-lbhaf2: RFC 9112 §6.1 — Content-Length is
            // 1*DIGIT (no leading sign). Rust's usize::parse() accepts
            // '+5' which can disagree with stricter intermediaries
            // (nginx, envoy) and create a request-smuggling primitive.
            // Reject any non-digit prefix before parsing.
            let cl_str = headers[cl_idx].1.trim();
            if cl_str.is_empty() || !cl_str.bytes().all(|b| b.is_ascii_digit()) {
                return Err(HttpError::BadContentLength);
            }
            let len: usize = cl_str.parse().map_err(|_| HttpError::BadContentLength)?;
            BodyKind::ContentLength(len)
        }
        (None, None) => BodyKind::ContentLength(0),
    };

    Ok(Some((end, method, uri, version, headers, kind)))
}

#[allow(clippy::type_complexity)]
fn decode_head(
    src: &mut BytesMut,
    max_headers_size: usize,
) -> Result<Option<(Method, String, Version, Vec<(String, String)>, BodyKind)>, HttpError> {
    let Some((end, method, uri, version, headers, kind)) =
        decode_head_parts(src.as_ref(), max_headers_size)?
    else {
        return Ok(None);
    };

    let _ = src.split_to(end);
    Ok(Some((method, uri, version, headers, kind)))
}

#[cfg(not(target_arch = "wasm32"))]
pub(super) fn preview_request_head(
    codec: &Http1Codec,
    src: &BytesMut,
) -> Result<Option<RequestHeadPreview>, HttpError> {
    match &codec.state {
        DecodeState::Body {
            version, headers, ..
        }
        | DecodeState::Chunked {
            version, headers, ..
        } => {
            return Ok(Some(RequestHeadPreview {
                version: *version,
                headers: headers.clone(),
            }));
        }
        DecodeState::Poisoned => return Err(HttpError::BadHeader),
        DecodeState::Head => {}
    }

    let Some((_end, _method, _uri, version, headers, _kind)) =
        decode_head_parts(src.as_ref(), codec.max_headers_size)?
    else {
        return Ok(None);
    };

    Ok(Some(RequestHeadPreview { version, headers }))
}

/// Extract the head fields from a `DecodeState::Body` or `DecodeState::Chunked`.
fn take_head(state: DecodeState) -> (Method, String, Version, Vec<(String, String)>) {
    match state {
        DecodeState::Body {
            method,
            uri,
            version,
            headers,
            ..
        }
        | DecodeState::Chunked {
            method,
            uri,
            version,
            headers,
            ..
        } => (method, uri, version, headers),
        DecodeState::Head | DecodeState::Poisoned => {
            unreachable!("take_head called in invalid state")
        }
    }
}

impl Decoder for Http1Codec {
    type Item = Request;
    type Error = HttpError;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Request>, HttpError> {
        match self.decode_inner(src) {
            Err(e) => {
                self.state = DecodeState::Poisoned;
                Err(e)
            }
            Ok(v) => Ok(v),
        }
    }
}

impl Http1Codec {
    fn decode_inner(&mut self, src: &mut BytesMut) -> Result<Option<Request>, HttpError> {
        loop {
            match &mut self.state {
                DecodeState::Poisoned => {
                    return Err(HttpError::BadHeader); // Generic error for poisoned state
                }
                state @ DecodeState::Head => {
                    let Some((method, uri, version, headers, kind)) =
                        decode_head(src, self.max_headers_size)?
                    else {
                        return Ok(None);
                    };

                    match kind {
                        BodyKind::ContentLength(0) => {
                            return Ok(Some(Request {
                                method,
                                uri,
                                version,
                                headers,
                                body: Vec::new(),
                                trailers: Vec::new(),
                                peer_addr: None,
                            }));
                        }
                        BodyKind::ContentLength(len) => {
                            // Check body size limit upfront for Content-Length
                            if len > self.max_body_size {
                                return Err(HttpError::BodyTooLarge);
                            }
                            *state = DecodeState::Body {
                                method,
                                uri,
                                version,
                                headers,
                                remaining: len,
                            };
                        }
                        BodyKind::Chunked => {
                            *state = DecodeState::Chunked {
                                method,
                                uri,
                                version,
                                headers,
                                chunked: ChunkedBodyDecoder::new(
                                    self.max_body_size,
                                    self.max_headers_size,
                                ),
                            };
                        }
                    }
                }

                DecodeState::Body { remaining, .. } => {
                    let need = *remaining;
                    if src.len() < need {
                        return Ok(None);
                    }

                    let body_bytes = src.split_to(need);
                    let old = std::mem::replace(&mut self.state, DecodeState::Head);
                    let (method, uri, version, headers) = take_head(old);

                    return Ok(Some(Request {
                        method,
                        uri,
                        version,
                        headers,
                        // br-asupersync-i5w8lh: into_vec consumes the
                        // BytesMut and moves out the underlying Vec<u8>
                        // with zero memcpy and zero allocation. The
                        // previous to_vec() copied the body again on top
                        // of the copy split_to() already paid (split_to
                        // is O(n) in the current Vec<u8>-backed BytesMut
                        // — see bytes_mut.rs split_to doc). Eliminating
                        // this second memcpy halves the per-request body
                        // copy cost on the HTTP/1 receive hot path.
                        body: body_bytes.into_vec(),
                        trailers: Vec::new(),
                        peer_addr: None,
                    }));
                }

                DecodeState::Chunked { chunked, .. } => {
                    let Some((body, trailers)) = chunked.decode(src)? else {
                        return Ok(None);
                    };

                    let old = std::mem::replace(&mut self.state, DecodeState::Head);
                    let (method, uri, version, headers) = take_head(old);

                    return Ok(Some(Request {
                        method,
                        uri,
                        version,
                        headers,
                        body,
                        trailers,
                        peer_addr: None,
                    }));
                }
            }
        }
    }
}

impl Encoder<Response> for Http1Codec {
    type Error = HttpError;

    #[allow(clippy::too_many_lines)]
    fn encode(&mut self, resp: Response, dst: &mut BytesMut) -> Result<(), HttpError> {
        let reason = if resp.reason.is_empty() {
            types::default_reason(resp.status)
        } else {
            &resp.reason
        };

        if reason.contains('\r') || reason.contains('\n') {
            return Err(HttpError::BadHeader);
        }

        let (te, cl) = transfer_and_content_length(&resp.headers)?;

        let chunked = match te {
            Some(value) => {
                require_transfer_encoding_chunked(value)?;
                true
            }
            None => false,
        };

        if chunked && cl.is_some() {
            return Err(HttpError::AmbiguousBodyLength);
        }

        if !chunked && !resp.trailers.is_empty() {
            return Err(HttpError::TrailersNotAllowed);
        }

        if !chunked {
            if let Some(cl) = cl {
                // br-asupersync-lbhaf2: same digit-only validation on the
                // encode side. Reject Content-Length values like '+5' that
                // Rust parse accepts but the spec rejects.
                let cl_str = cl.trim();
                if cl_str.is_empty() || !cl_str.bytes().all(|b| b.is_ascii_digit()) {
                    return Err(HttpError::BadContentLength);
                }
                let declared: usize = cl_str.parse().map_err(|_| HttpError::BadContentLength)?;
                // Allow empty bodies with non-zero Content-Length for HEAD responses.
                if declared != resp.body.len() && !resp.body.is_empty() {
                    return Err(HttpError::BadContentLength);
                }
            }
        }

        // Pre-validate all headers (and trailers for chunked) so the write
        // path below is infallible and we can write directly to `dst`.
        let mut has_content_length = false;
        for (name, value) in &resp.headers {
            validate_header_field(name, value)?;
            if name.eq_ignore_ascii_case("content-length") {
                has_content_length = true;
            }
        }
        if chunked {
            for (name, value) in &resp.trailers {
                validate_header_field(name, value)?;
            }
        }

        // Pre-reserve capacity for the entire response.
        let headers_bytes: usize = resp
            .headers
            .iter()
            .map(|(name, value)| name.len() + value.len() + 4)
            .sum();
        let trailers_bytes: usize = resp
            .trailers
            .iter()
            .map(|(name, value)| name.len() + value.len() + 4)
            .sum();
        let chunk_line_bytes = if chunked && !resp.body.is_empty() {
            upper_hex_len(resp.body.len()) + 2
        } else {
            0
        };
        let encoded_body_bytes = if chunked {
            chunk_line_bytes + resp.body.len() + 2 + 3 + trailers_bytes + 2
        } else {
            resp.body.len()
        };
        dst.reserve(64 + reason.len() + headers_bytes + encoded_body_bytes);

        // Write directly to dst via extend_from_slice — no fmt machinery.
        {
            // Status line: "HTTP/1.1 200 OK\r\n"
            dst.extend_from_slice(resp.version.as_str().as_bytes());
            dst.extend_from_slice(b" ");
            append_decimal(dst, resp.status as usize);
            dst.extend_from_slice(b" ");
            dst.extend_from_slice(reason.as_bytes());
            dst.extend_from_slice(b"\r\n");

            for (name, value) in &resp.headers {
                dst.extend_from_slice(name.as_bytes());
                dst.extend_from_slice(b": ");
                dst.extend_from_slice(value.as_bytes());
                dst.extend_from_slice(b"\r\n");
            }

            if chunked {
                dst.extend_from_slice(b"\r\n");
                if !resp.body.is_empty() {
                    append_chunk_size_line(dst, resp.body.len());
                    dst.extend_from_slice(&resp.body);
                    dst.extend_from_slice(b"\r\n");
                }
                dst.extend_from_slice(b"0\r\n");
                for (name, value) in &resp.trailers {
                    dst.extend_from_slice(name.as_bytes());
                    dst.extend_from_slice(b": ");
                    dst.extend_from_slice(value.as_bytes());
                    dst.extend_from_slice(b"\r\n");
                }
                dst.extend_from_slice(b"\r\n");
                return Ok(());
            }

            let suppress_content_length =
                (100..=199).contains(&resp.status) || resp.status == 204 || resp.status == 304;
            if !has_content_length && !suppress_content_length {
                dst.extend_from_slice(b"Content-Length: ");
                append_decimal(dst, resp.body.len());
                dst.extend_from_slice(b"\r\n");
            }

            dst.extend_from_slice(b"\r\n");
            if !suppress_content_length && !resp.body.is_empty() {
                dst.extend_from_slice(&resp.body);
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    fn decode_one(codec: &mut Http1Codec, data: &[u8]) -> Result<Option<Request>, HttpError> {
        let mut buf = BytesMut::from(data);
        codec.decode(&mut buf)
    }

    fn encode_one(codec: &mut Http1Codec, resp: Response) -> Vec<u8> {
        let mut buf = BytesMut::with_capacity(1024);
        codec.encode(resp, &mut buf).unwrap();
        buf.to_vec()
    }

    /// br-asupersync-2ovm8z: a complete request whose body contains a
    /// bare 0x0D byte (any binary upload — gRPC, protobuf, image — has
    /// 0x0D appearing in ~1/256 random bytes) must NOT poison the
    /// codec. Previously the bare-CR scan ran over the entire `src`
    /// buffer (head + body), rejecting any 0x0D in the body as
    /// BadRequestLine and tripping the codec into Poisoned state.
    #[test]
    fn ovm8z_body_with_bare_cr_byte_decodes_cleanly() {
        let mut codec = Http1Codec::new();
        // Build a request with Content-Length=4 and a body containing a
        // bare 0x0D (no \n successor) — the kind of byte sequence that
        // appears in any binary payload.
        let mut data = Vec::new();
        data.extend_from_slice(b"POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\n\r\n");
        data.extend_from_slice(&[0x42, 0x0D, 0x44, 0x45]); // 4-byte body with bare \r
        let mut buf = BytesMut::from(&data[..]);
        let result = codec.decode(&mut buf);
        assert!(
            result.is_ok(),
            "binary body with bare 0x0D must NOT poison the codec, got: {result:?}"
        );
        let req = result.unwrap().expect("complete request decodes");
        assert_eq!(
            AsRef::<[u8]>::as_ref(&req.body),
            &[0x42, 0x0D, 0x44, 0x45][..]
        );
    }

    /// br-asupersync-2ovm8z: a chunked request where the body chunk
    /// contains 0x0D bytes must also decode cleanly (covers the
    /// pipelined / chunked pathway).
    #[test]
    fn ovm8z_chunked_body_with_bare_cr_byte_does_not_poison() {
        let mut codec = Http1Codec::new();
        // Head with Transfer-Encoding: chunked, then a single chunk of 4
        // bytes containing a bare 0x0D.
        let mut data = Vec::new();
        data.extend_from_slice(b"POST / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n");
        data.extend_from_slice(b"4\r\n");
        data.extend_from_slice(&[0x42, 0x0D, 0x44, 0x45]);
        data.extend_from_slice(b"\r\n0\r\n\r\n");
        let mut buf = BytesMut::from(&data[..]);
        let result = codec.decode(&mut buf);
        assert!(
            result.is_ok(),
            "chunked body with bare 0x0D must decode cleanly, got: {result:?}"
        );
    }

    /// br-asupersync-2ovm8z: bare-CR within the HEAD itself must STILL
    /// be rejected (the original smuggling-defense intent).
    #[test]
    fn ovm8z_bare_cr_in_head_still_rejected() {
        let mut codec = Http1Codec::new();
        // Bare 0x0D in the request line (not followed by \n) — must be
        // rejected as BadRequestLine.
        let data = b"GET /\rsmuggle HTTP/1.1\r\nHost: x\r\n\r\n";
        let mut buf = BytesMut::from(&data[..]);
        let err = codec
            .decode(&mut buf)
            .expect_err("bare CR in head must still reject");
        assert!(matches!(err, HttpError::BadRequestLine));
    }

    #[test]
    fn decode_simple_get() {
        let mut codec = Http1Codec::new();
        let req = decode_one(&mut codec, b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
            .unwrap()
            .unwrap();
        assert_eq!(req.method, Method::Get);
        assert_eq!(req.uri, "/");
        assert_eq!(req.version, Version::Http11);
        assert_eq!(req.headers.len(), 1);
        assert_eq!(req.headers[0].0, "Host");
        assert_eq!(req.headers[0].1, "localhost");
        assert!(req.body.is_empty());
    }

    #[test]
    fn decode_post_with_body() {
        let mut codec = Http1Codec::new();
        let raw = b"POST /data HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.method, Method::Post);
        assert_eq!(req.uri, "/data");
        assert_eq!(req.body, b"hello");
    }

    #[test]
    fn decode_chunked_body() {
        let mut codec = Http1Codec::new();
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                     5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.body, b"hello world");
        assert!(req.trailers.is_empty());
    }

    #[test]
    fn decode_chunked_with_extensions() {
        let mut codec = Http1Codec::new();
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                     5;ext=1\r\nhello\r\n0\r\n\r\n";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.body, b"hello");
    }

    #[test]
    fn parse_chunk_size_line_accepts_only_bare_hex_digits() {
        let accepted: &[(&[u8], usize)] = &[
            (b"0", 0),
            (b"000f", 15),
            (b"10", 16),
            (b"A;ext=1", 10),
            (b"a;name=value", 10),
        ];
        for &(line, expected) in accepted {
            assert_eq!(
                parse_chunk_size_line(line).unwrap(),
                expected,
                "expected chunk size {expected} for {line:?}",
            );
        }

        let rejected: &[&[u8]] = &[
            b"",
            b";ext=1",
            b"+1",
            b"-1",
            b" 1",
            b"1 ",
            b"1\t",
            b"0x10",
            b"g",
            b"1\0",
            &[0xff],
            b"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
        ];
        for line in rejected {
            assert!(
                matches!(
                    parse_chunk_size_line(line),
                    Err(HttpError::BadChunkedEncoding)
                ),
                "expected BadChunkedEncoding for {line:?}",
            );
        }
    }

    #[test]
    fn decode_chunked_with_trailers() {
        let mut codec = Http1Codec::new();
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                     5\r\nhello\r\n0\r\nX-Trailer: one\r\nY-Trailer: two\r\n\r\n";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.body, b"hello");
        assert_eq!(req.trailers.len(), 2);
        assert_eq!(req.trailers[0].0, "X-Trailer");
        assert_eq!(req.trailers[0].1, "one");
    }

    /// br-asupersync-135g0e: trailers carrying RFC 9110 §6.5.1 forbidden
    /// header names must be rejected at the parser. A trailer carrying
    /// `Content-Length` or `Transfer-Encoding` is the canonical smuggling
    /// vector when downstream middleware merges trailers into the header
    /// set.
    #[test]
    fn decode_chunked_rejects_forbidden_trailers() {
        // Each entry is a forbidden trailer name. `decode_one` must reach
        // chunked-trailer parsing and return BadHeader. The set covers
        // RFC 9110 §6.5.2's restricted-fields table plus the legacy
        // hop-by-hop fields (Keep-Alive, Proxy-Connection) that share the
        // same framing-critical semantics.
        let forbidden = [
            "Content-Length",
            "Transfer-Encoding",
            "transfer-encoding",
            "TRANSFER-ENCODING",
            "Content-Encoding",
            "Content-Type",
            "Content-Range",
            "Trailer",
            "Host",
            "Authorization",
            "Cookie",
            "Set-Cookie",
            "Cache-Control",
            "Range",
            "TE",
            "Pragma",
            "Max-Forwards",
            "Expect",
            "Proxy-Authorization",
            "Proxy-Authenticate",
            "WWW-Authenticate",
            "Upgrade",
            // br-asupersync-ko0gde: hop-by-hop fields explicitly listed in
            // RFC 9110 §6.5.2's restricted-fields table. A trailer
            // `Connection: x-secret` could be coalesced into a downstream
            // proxy's header set and used as a request-smuggling primitive
            // (the proxy would then strip `x-secret` on the next hop).
            "Connection",
            "connection",
            "Keep-Alive",
            "keep-alive",
            // Not standardized but implemented by widely deployed proxies;
            // shares the same framing semantics as Connection.
            "Proxy-Connection",
            "proxy-connection",
        ];
        for name in forbidden {
            let raw = format!(
                "POST /u HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n{name}: x\r\n\r\n"
            );
            let mut codec = Http1Codec::new();
            let result = decode_one(&mut codec, raw.as_bytes());
            assert!(
                matches!(result, Err(HttpError::BadHeader)),
                "expected BadHeader for forbidden trailer {name:?}, got {result:?}"
            );
        }
    }

    /// Positive control: benign trailers must still parse after the filter
    /// is in place. Drift here would silently neuter a legitimate use case.
    #[test]
    fn decode_chunked_accepts_safe_trailers() {
        let safe = [
            "X-Trailer-Checksum",
            "X-Custom-Metadata",
            "X-Request-Id",
            "ETag",
        ];
        for name in safe {
            let raw = format!(
                "POST /u HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n{name}: ok\r\n\r\n"
            );
            let mut codec = Http1Codec::new();
            let req = decode_one(&mut codec, raw.as_bytes())
                .unwrap_or_else(|e| panic!("safe trailer {name:?} rejected: {e:?}"))
                .unwrap();
            assert_eq!(req.trailers.len(), 1, "expected one trailer for {name:?}");
            assert_eq!(req.trailers[0].0, name);
        }
    }

    #[test]
    fn decode_chunked_keeps_pipelined_next_request() {
        let mut codec = Http1Codec::new();
        let mut raw =
            b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n".to_vec();
        raw.extend_from_slice(b"GET /next HTTP/1.1\r\nX-Long: ");
        raw.extend_from_slice(&vec![b'a'; 9000]);
        raw.extend_from_slice(b"\r\n\r\n");

        let mut buf = BytesMut::from(raw.as_slice());
        let first = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(first.method, Method::Post);
        assert_eq!(first.uri, "/upload");
        assert!(first.trailers.is_empty());
        assert!(buf.as_ref().starts_with(b"GET /next HTTP/1.1\r\n"));
    }

    #[test]
    fn decode_incomplete_returns_none() {
        let mut codec = Http1Codec::new();
        let result = decode_one(&mut codec, b"GET / HTTP/1.1\r\nHost:");
        assert!(matches!(result, Ok(None)));
    }

    #[test]
    fn decode_incomplete_body_returns_none() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST /x HTTP/1.1\r\nContent-Length: 10\r\n\r\nhel",
        );
        assert!(matches!(result, Ok(None)));
    }

    #[test]
    fn preview_request_head_available_before_body_bytes() {
        let raw = b"POST /upload HTTP/1.1\r\nExpect: 100-continue\r\nContent-Length: 5\r\n\r\n";
        let mut buf = BytesMut::from(&raw[..]);
        let codec = Http1Codec::new();

        let preview = preview_request_head(&codec, &buf)
            .unwrap()
            .expect("header preview should be available before body bytes arrive");

        assert_eq!(preview.version, Version::Http11);
        assert_eq!(
            header_value(&preview.headers, "expect"),
            Some("100-continue")
        );
        assert_eq!(header_value(&preview.headers, "content-length"), Some("5"));
        assert_eq!(buf.as_ref(), raw);

        let mut codec = Http1Codec::new();
        assert!(codec.decode(&mut buf).unwrap().is_none());
        assert!(buf.is_empty(), "head bytes should move into codec state");

        let preview = preview_request_head(&codec, &buf)
            .unwrap()
            .expect("pending codec state should still expose request head");
        assert_eq!(preview.version, Version::Http11);
        assert_eq!(
            header_value(&preview.headers, "expect"),
            Some("100-continue")
        );
        assert_eq!(header_value(&preview.headers, "content-length"), Some("5"));
    }

    #[test]
    fn decode_extension_method() {
        let mut codec = Http1Codec::new();
        let req = decode_one(&mut codec, b"PURGE /cache HTTP/1.1\r\n\r\n")
            .unwrap()
            .unwrap();
        assert_eq!(req.method, Method::Extension("PURGE".into()));
    }

    #[test]
    fn parse_request_line_fast_path() {
        let (method, uri, version) = parse_request_line_bytes(b"GET /fast HTTP/1.1").unwrap();
        assert_eq!(method, Method::Get);
        assert_eq!(uri, "/fast");
        assert_eq!(version, Version::Http11);
    }

    /// br-asupersync-w6u4cn: absolute-form (RFC 9112 §3.2.2) MUST have a
    /// non-empty authority. `http:///path` parses cleanly under split_once
    /// but has no authority and must be rejected; per-RFC the authority is
    /// the substring of `rest` before the first '/', '?', or '#'.
    #[test]
    fn parse_request_line_absolute_form_rejects_empty_authority() {
        // Empty authority shapes — must all reject.
        let empty = [
            "GET http:/// HTTP/1.1",
            "GET http:///path HTTP/1.1",
            "GET http://?query HTTP/1.1",
            "GET http://#fragment HTTP/1.1",
            "GET http:// HTTP/1.1",
        ];
        for line in empty {
            assert!(
                matches!(
                    parse_request_line_bytes(line.as_bytes()),
                    Err(HttpError::BadRequestLine)
                ),
                "expected BadRequestLine for {line:?}"
            );
        }

        // Positive controls — well-formed absolute-form must still parse.
        let ok = [
            "GET http://host/path HTTP/1.1",
            "GET http://host:8080/path HTTP/1.1",
            "GET http://user@host/p HTTP/1.1",
            "GET http://host HTTP/1.1",
            "GET https://host/p?q=1 HTTP/1.1",
        ];
        for line in ok {
            let parsed = parse_request_line_bytes(line.as_bytes());
            assert!(parsed.is_ok(), "expected Ok for {line:?}, got {parsed:?}");
        }
    }

    /// RFC 9112 §3.2.3: CONNECT requests use authority-form, specifically
    /// `host:port`. The port delimiter is not enough; the port token must be
    /// numeric so invalid authority values cannot slide through as paths.
    #[test]
    fn parse_request_line_connect_authority_requires_numeric_port() {
        let ok = [
            "CONNECT example.com:443 HTTP/1.1",
            "CONNECT localhost:8080 HTTP/1.1",
            "CONNECT [2001:db8::1]:443 HTTP/1.1",
        ];
        for line in ok {
            let parsed = parse_request_line_bytes(line.as_bytes());
            assert!(parsed.is_ok(), "expected Ok for {line:?}, got {parsed:?}");
        }

        let invalid = [
            "CONNECT example.com:http HTTP/1.1",
            "CONNECT example.com:443x HTTP/1.1",
            "CONNECT example.com: HTTP/1.1",
            "CONNECT :443 HTTP/1.1",
        ];
        for line in invalid {
            assert!(
                matches!(
                    parse_request_line_bytes(line.as_bytes()),
                    Err(HttpError::BadRequestLine)
                ),
                "expected BadRequestLine for {line:?}"
            );
        }
    }

    /// Differential vs `httparse` 1.10.x default request parsing: repeated
    /// SP delimiters are rejected unless the caller explicitly enables the
    /// lenient `allow_multiple_spaces_in_request_line_delimiters(true)` mode.
    #[test]
    fn parse_request_line_rejects_multiple_spaces_like_httparse_default() {
        let line = b"GET   /slow   HTTP/1.1";
        assert!(
            matches!(
                parse_request_line_bytes(line),
                Err(HttpError::BadRequestLine)
            ),
            "default parser should reject repeated request-line delimiters",
        );
    }

    #[test]
    fn crlf_search_matches_only_complete_pairs() {
        assert_eq!(find_crlf(b"GET / HTTP/1.1\r\nHost: example.com"), Some(14));
        assert_eq!(find_crlf(b"GET / HTTP/1.1\nHost: example.com"), None);
        assert_eq!(find_crlf(b"GET / HTTP/1.1\rHost: example.com"), None);

        let mut positions = smallvec::SmallVec::<[usize; 32]>::new();
        collect_crlf_positions(b"bad\nline\r\nnext\r\n", &mut positions);
        assert_eq!(positions.as_slice(), &[8, 14]);
    }

    #[test]
    fn decode_request_line_too_long_without_crlf() {
        let mut codec = Http1Codec::new();
        let raw = vec![b'G'; MAX_REQUEST_LINE + 1];
        let result = decode_one(&mut codec, &raw);
        assert!(matches!(result, Err(HttpError::RequestLineTooLong)));
    }

    #[test]
    fn decode_unsupported_version() {
        let mut codec = Http1Codec::new();
        let result = decode_one(&mut codec, b"GET / HTTP/2.0\r\n\r\n");
        assert!(matches!(result, Err(HttpError::UnsupportedVersion)));
    }

    #[test]
    fn decode_headers_too_large() {
        let mut codec = Http1Codec::new().max_headers_size(32);
        let result = decode_one(
            &mut codec,
            b"GET / HTTP/1.1\r\nX-Large: aaaaaaaaaaaaaaa\r\n\r\n",
        );
        assert!(matches!(result, Err(HttpError::HeadersTooLarge)));
    }

    #[test]
    fn decode_too_many_headers() {
        let mut request = b"GET / HTTP/1.1\r\n".to_vec();
        for idx in 0..=MAX_HEADERS {
            request.extend_from_slice(format!("X-{idx}: value\r\n").as_bytes());
        }
        request.extend_from_slice(b"\r\n");

        let mut codec = Http1Codec::new();
        let result = decode_one(&mut codec, &request);
        assert!(matches!(result, Err(HttpError::TooManyHeaders)));
    }

    #[test]
    fn decode_bad_content_length() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST / HTTP/1.1\r\nContent-Length: abc\r\n\r\n",
        );
        assert!(matches!(result, Err(HttpError::BadContentLength)));
    }

    #[test]
    fn reject_duplicate_content_length() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: 5\r\n\r\nhello",
        );
        assert!(matches!(result, Err(HttpError::DuplicateContentLength)));
    }

    #[test]
    fn reject_duplicate_transfer_encoding() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n\r\n\
              0\r\n\r\n",
        );
        assert!(matches!(result, Err(HttpError::DuplicateTransferEncoding)));
    }

    #[test]
    fn reject_unsupported_transfer_encoding() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST / HTTP/1.1\r\nTransfer-Encoding: gzip, chunked\r\n\r\n0\r\n\r\n",
        );
        assert!(matches!(result, Err(HttpError::BadTransferEncoding)));
    }

    #[test]
    fn reject_chunked_http10() {
        let mut codec = Http1Codec::new();
        let result = decode_one(
            &mut codec,
            b"POST / HTTP/1.0\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n",
        );
        assert!(matches!(result, Err(HttpError::BadTransferEncoding)));
    }

    #[test]
    fn decode_multiple_headers() {
        let mut codec = Http1Codec::new();
        let req = decode_one(
            &mut codec,
            b"GET / HTTP/1.1\r\nHost: example.com\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n",
        )
        .unwrap()
        .unwrap();
        assert_eq!(req.headers.len(), 3);
    }

    #[test]
    fn decode_http10() {
        let mut codec = Http1Codec::new();
        let req = decode_one(&mut codec, b"GET / HTTP/1.0\r\n\r\n")
            .unwrap()
            .unwrap();
        assert_eq!(req.version, Version::Http10);
    }

    #[test]
    fn encode_simple_response() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(200, "OK", b"hello".to_vec());
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(s.contains("Content-Length: 5\r\n"));
        assert!(s.ends_with("\r\n\r\nhello"));
    }

    #[test]
    fn encode_empty_body() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(204, "No Content", Vec::new());
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(!s.contains("Content-Length"));
        assert!(s.ends_with("\r\n\r\n"));
    }

    #[test]
    fn encode_with_explicit_headers() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(200, "OK", b"{}".to_vec())
            .with_header("Content-Type", "application/json")
            .with_header("Content-Length", "2");
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.contains("Content-Type: application/json\r\n"));
        assert_eq!(s.matches("Content-Length").count(), 1);
    }

    #[test]
    fn encode_head_response_with_content_length() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(200, "OK", Vec::new()).with_header("Content-Length", "1024");
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.contains("Content-Length: 1024\r\n"));
        assert!(s.ends_with("\r\n\r\n"));
    }

    #[test]
    fn encode_default_reason_phrase() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(404, "", Vec::new());
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.starts_with("HTTP/1.1 404 Not Found\r\n"));
    }

    #[test]
    fn encode_chunked_response() {
        let mut codec = Http1Codec::new();
        let resp =
            Response::new(200, "OK", b"hello".to_vec()).with_header("Transfer-Encoding", "chunked");
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.contains("Transfer-Encoding: chunked\r\n"));
        assert!(!s.contains("Content-Length"));
        assert!(s.ends_with("5\r\nhello\r\n0\r\n\r\n"));
    }

    #[test]
    fn encode_chunked_response_with_trailers() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(200, "OK", b"hello".to_vec())
            .with_header("Transfer-Encoding", "chunked")
            .with_trailer("X-Trailer", "one");
        let bytes = encode_one(&mut codec, resp);
        let s = String::from_utf8(bytes).unwrap();
        assert!(s.ends_with("0\r\nX-Trailer: one\r\n\r\n"));
    }

    #[test]
    fn encode_trailers_without_chunked_is_error() {
        let mut codec = Http1Codec::new();
        let resp = Response::new(200, "OK", b"hello".to_vec()).with_trailer("X-Trailer", "one");
        let mut buf = BytesMut::with_capacity(256);
        let err = codec.encode(resp, &mut buf).unwrap_err();
        assert!(matches!(err, HttpError::TrailersNotAllowed));
    }

    #[test]
    fn decode_sequential_requests() {
        let mut codec = Http1Codec::new();
        let raw = b"GET /a HTTP/1.1\r\nHost: a\r\n\r\nGET /b HTTP/1.1\r\nHost: b\r\n\r\n";
        let mut buf = BytesMut::from(&raw[..]);

        let r1 = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(r1.uri, "/a");

        let r2 = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(r2.uri, "/b");
    }

    #[test]
    fn decode_body_too_large_content_length() {
        let mut codec = Http1Codec::new().max_body_size(10);
        let raw = b"POST /data HTTP/1.1\r\nContent-Length: 100\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::BodyTooLarge)));
    }

    #[test]
    fn decode_body_too_large_chunked() {
        let mut codec = Http1Codec::new().max_body_size(10);
        // Chunked body with 20 bytes total (exceeds 10 byte limit)
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                    14\r\n01234567890123456789\r\n0\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::BodyTooLarge)));
    }

    #[test]
    fn decode_body_at_limit_succeeds() {
        let mut codec = Http1Codec::new().max_body_size(5);
        let raw = b"POST /data HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.body, b"hello");
    }

    #[test]
    fn decode_chunked_body_at_limit_succeeds() {
        let mut codec = Http1Codec::new().max_body_size(11);
        // "hello world" = 11 bytes, exactly at the limit
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                     5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n";
        let req = decode_one(&mut codec, raw).unwrap().unwrap();
        assert_eq!(req.body, b"hello world");
    }

    // Security: Request smuggling protection (RFC 7230 3.3.3)
    #[test]
    fn reject_both_content_length_and_transfer_encoding() {
        let mut codec = Http1Codec::new();
        // Having both headers is a request smuggling vector
        let raw = b"POST /data HTTP/1.1\r\n\
                    Content-Length: 5\r\n\
                    Transfer-Encoding: chunked\r\n\r\n\
                    5\r\nhello\r\n0\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::AmbiguousBodyLength)));
    }

    #[test]
    fn reject_transfer_encoding_before_content_length() {
        let mut codec = Http1Codec::new();
        // Order shouldn't matter - still reject
        let raw = b"POST /data HTTP/1.1\r\n\
                    Transfer-Encoding: chunked\r\n\
                    Content-Length: 5\r\n\r\n\
                    5\r\nhello\r\n0\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::AmbiguousBodyLength)));
    }

    // Security: Chunked encoding CRLF validation
    #[test]
    fn reject_invalid_crlf_after_chunk() {
        let mut codec = Http1Codec::new();
        // Invalid: "XX" instead of "\r\n" after chunk data
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                    5\r\nhelloXX0\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::BadChunkedEncoding)));
    }

    #[test]
    fn reject_invalid_trailer_header_line() {
        let mut codec = Http1Codec::new();
        // Invalid: trailer header line missing ':'.
        let raw = b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n\
                    5\r\nhello\r\n0\r\nXX\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Err(HttpError::BadHeader)));
    }

    #[test]
    fn decode_obs_text_header_value() {
        let mut codec = Http1Codec::new();
        let raw = b"GET / HTTP/1.1\r\nTest-Header: \xff\r\n\r\n";
        let result = decode_one(&mut codec, raw);
        assert!(matches!(result, Ok(Some(_))));
    }

    /// Grammar-based fuzz test for HTTP/1.1 codec covering chunked encoding,
    /// trailers, 100-continue, HEAD body suppression, and fold pipelining.
    #[test]
    fn grammar_based_http11_features_fuzz() {
        /// HTTP/1.1 grammar-based test generator
        struct Http11Grammar {
            seed: u64,
            counter: u64,
        }

        impl Http11Grammar {
            fn new(seed: u64) -> Self {
                Self { seed, counter: 0 }
            }

            fn next_u8(&mut self) -> u8 {
                self.counter = self.counter.wrapping_add(1);
                ((self
                    .seed
                    .wrapping_add(self.counter)
                    .wrapping_mul(1103515245)
                    .wrapping_add(12345))
                    >> 16) as u8
            }

            fn next_bool(&mut self) -> bool {
                self.next_u8() & 1 == 1
            }

            fn next_choice<T: Copy>(&mut self, choices: &[T]) -> T {
                let idx = (self.next_u8() as usize) % choices.len();
                choices[idx]
            }

            /// Generate chunked encoding test case
            fn generate_chunked_request(&mut self) -> Vec<u8> {
                let mut request = Vec::new();

                // Request line
                let method = self.next_choice(&[&b"POST"[..], &b"PUT"[..], &b"PATCH"[..]]);
                request.extend_from_slice(method);
                request.extend_from_slice(b" /test HTTP/1.1\r\n");

                // Headers
                request.extend_from_slice(b"Host: example.com\r\n");
                request.extend_from_slice(b"Transfer-Encoding: chunked\r\n");

                // Expect: 100-continue (grammar condition)
                if self.next_bool() {
                    request.extend_from_slice(b"Expect: 100-continue\r\n");
                }

                request.extend_from_slice(b"\r\n");

                // Chunked body with variable chunk sizes
                let chunk_sizes = [0, 1, 5, 10, 255, 4096];
                let chunk_size = self.next_choice(&chunk_sizes);

                if chunk_size > 0 {
                    request.extend_from_slice(format!("{:x}\r\n", chunk_size).as_bytes());
                    for _ in 0..chunk_size {
                        request.push(b'A' + (self.next_u8() % 26));
                    }
                    request.extend_from_slice(b"\r\n");
                }

                // Terminal chunk
                request.extend_from_slice(b"0\r\n");

                // Trailers (grammar condition)
                if self.next_bool() {
                    let trailer_names = [
                        &b"X-Checksum"[..],
                        &b"X-Final-Status"[..],
                        &b"X-Processing-Time"[..],
                    ];
                    let trailer_name = self.next_choice(&trailer_names);
                    request.extend_from_slice(trailer_name);
                    request.extend_from_slice(b": test-value\r\n");
                }

                request.extend_from_slice(b"\r\n");
                request
            }

            /// Generate HEAD request test case for body suppression
            fn generate_head_request(&mut self) -> Vec<u8> {
                let mut request = Vec::new();

                request.extend_from_slice(b"HEAD /resource HTTP/1.1\r\n");
                request.extend_from_slice(b"Host: example.com\r\n");

                // Content-Length header that should be preserved in response
                // but body suppressed
                if self.next_bool() {
                    request.extend_from_slice(b"Accept: application/json\r\n");
                }

                request.extend_from_slice(b"\r\n");
                request
            }

            /// Generate pipelined request test case
            fn generate_pipelined_requests(&mut self) -> Vec<u8> {
                let mut requests = Vec::new();

                // First request
                requests.extend_from_slice(b"GET /first HTTP/1.1\r\n");
                requests.extend_from_slice(b"Host: example.com\r\n");
                requests.extend_from_slice(b"\r\n");

                // Second request (pipelined)
                let second_method = self.next_choice(&[&b"GET"[..], &b"HEAD"[..], &b"POST"[..]]);
                requests.extend_from_slice(second_method);
                requests.extend_from_slice(b" /second HTTP/1.1\r\n");
                requests.extend_from_slice(b"Host: example.com\r\n");

                if second_method == &b"POST"[..] {
                    requests.extend_from_slice(b"Content-Length: 4\r\n");
                    requests.extend_from_slice(b"\r\n");
                    requests.extend_from_slice(b"data");
                } else {
                    requests.extend_from_slice(b"\r\n");
                }

                requests
            }

            /// Generate folded header test case
            fn generate_folded_headers(&mut self) -> Vec<u8> {
                let mut request = Vec::new();

                request.extend_from_slice(b"GET / HTTP/1.1\r\n");
                request.extend_from_slice(b"Host: example.com\r\n");

                // Folded header (obs-fold - obsolete but sometimes encountered)
                request.extend_from_slice(b"X-Long-Header: first-part\r\n");
                request.extend_from_slice(b" second-part\r\n"); // Folded continuation

                request.extend_from_slice(b"\r\n");
                request
            }
        }

        let test_cases = [
            ("chunked_encoding", 0x1234),
            ("head_body_suppression", 0x5678),
            ("pipelined_requests", 0x9abc),
            ("folded_headers", 0xdef0),
            ("chunked_with_trailers", 0x2468),
            ("chunked_100_continue", 0xace1),
        ];

        for (test_name, seed) in &test_cases {
            let mut grammar = Http11Grammar::new(*seed);
            let mut codec = Http1Codec::new();

            let test_data = match *test_name {
                "chunked_encoding" | "chunked_with_trailers" | "chunked_100_continue" => {
                    grammar.generate_chunked_request()
                }
                "head_body_suppression" => grammar.generate_head_request(),
                "pipelined_requests" => grammar.generate_pipelined_requests(),
                "folded_headers" => grammar.generate_folded_headers(),
                _ => continue,
            };

            // Test parsing - should not panic and handle edge cases gracefully
            let result = {
                let mut buf = BytesMut::new();
                buf.extend_from_slice(&test_data);
                codec.decode(&mut buf)
            };

            match result {
                Ok(Some(request)) => {
                    // Validate grammar-specific invariants
                    match *test_name {
                        "head_body_suppression" => {
                            assert_eq!(request.method, Method::Head);
                        }
                        "chunked_encoding" | "chunked_with_trailers" | "chunked_100_continue" => {
                            // Should have chunked encoding headers
                            let has_chunked = request
                                .headers
                                .iter()
                                .any(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding"));
                            if has_chunked {
                                // Validate we can parse chunked encoding structure
                            }
                        }
                        _ => {}
                    }
                }
                Ok(None) => {
                    // Incomplete data - acceptable for fuzzing
                }
                Err(err) => {
                    // Should fail gracefully with appropriate error types
                    match err {
                        HttpError::BadRequestLine
                        | HttpError::BadHeader
                        | HttpError::UnsupportedVersion
                        | HttpError::BadMethod
                        | HttpError::BadContentLength
                        | HttpError::DuplicateContentLength
                        | HttpError::DuplicateTransferEncoding
                        | HttpError::BadTransferEncoding
                        | HttpError::InvalidHeaderName
                        | HttpError::InvalidHeaderValue
                        | HttpError::HeadersTooLarge
                        | HttpError::TooManyHeaders
                        | HttpError::RequestLineTooLong
                        | HttpError::BadChunkedEncoding
                        | HttpError::BodyTooLarge
                        | HttpError::AmbiguousBodyLength
                        | HttpError::TrailersNotAllowed => {
                            // Expected error types - codec correctly rejected malformed input
                        }
                        _ => {
                            // Unexpected error type might indicate a bug
                            println!("Test '{}' produced unexpected error: {:?}", test_name, err);
                        }
                    }
                }
            }
        }

        // Additional stress test with combined features
        let mut combined_grammar = Http11Grammar::new(0xcafe);
        for _ in 0..100 {
            let mut codec = Http1Codec::new();
            let mut request = Vec::new();

            // Grammar: Method selection
            let method = combined_grammar.next_choice(&[
                &b"GET"[..],
                &b"HEAD"[..],
                &b"POST"[..],
                &b"PUT"[..],
            ]);
            request.extend_from_slice(method);
            request.extend_from_slice(b" /combined HTTP/1.1\r\n");

            // Grammar: Header combinations
            request.extend_from_slice(b"Host: test.example\r\n");

            if method == &b"POST"[..] || method == &b"PUT"[..] {
                if combined_grammar.next_bool() {
                    // Chunked
                    request.extend_from_slice(b"Transfer-Encoding: chunked\r\n");
                    if combined_grammar.next_bool() {
                        request.extend_from_slice(b"Expect: 100-continue\r\n");
                    }
                } else {
                    // Fixed length
                    let length = combined_grammar.next_choice(&[0, 1, 10, 100]);
                    request.extend_from_slice(format!("Content-Length: {}\r\n", length).as_bytes());
                }
            }

            request.extend_from_slice(b"\r\n");

            // Test without panicking
            let mut buf = BytesMut::new();
            buf.extend_from_slice(&request);
            let _ = codec.decode(&mut buf);
        }
    }

    /// HTTP/1.1 request parsing conformance test against httparse reference implementation.
    ///
    /// This test ensures that the same byte stream produces identical (method, uri, version,
    /// headers) tuples between our implementation and the httparse reference implementation.
    /// This is Pattern 1: Differential Testing (Reference Implementation) from the
    /// testing-conformance-harnesses methodology.
    #[test]
    fn http1_codec_conformance_against_httparse() {
        /// Canonical HTTP request for conformance testing.
        #[derive(Debug, Clone)]
        struct CanonicalRequest {
            raw_bytes: Vec<u8>,
            description: String,
            expect_error: bool,
            coverage: ReferenceCoverage,
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum ReferenceCoverage {
            HttparseRequestHead,
            CodecOnly,
        }

        impl CanonicalRequest {
            fn httparse_head(raw_bytes: &[u8], description: &str, expect_error: bool) -> Self {
                Self {
                    raw_bytes: raw_bytes.to_vec(),
                    description: description.to_string(),
                    expect_error,
                    coverage: ReferenceCoverage::HttparseRequestHead,
                }
            }

            fn codec_only_error(raw_bytes: &[u8], description: &str) -> Self {
                Self {
                    raw_bytes: raw_bytes.to_vec(),
                    description: description.to_string(),
                    expect_error: true,
                    coverage: ReferenceCoverage::CodecOnly,
                }
            }
        }

        /// Parsed request tuple for comparison.
        #[derive(Debug, PartialEq, Eq)]
        struct ParsedRequest {
            method: String,
            uri: String,
            version: String,
            headers: Vec<(String, String)>,
        }

        // Test cases covering various HTTP/1.1 scenarios including chunked encoding edge cases
        let test_cases = vec![
            // Basic GET request
            CanonicalRequest::httparse_head(
                b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n",
                "Basic GET request",
                false,
            ),

            // POST with Content-Length
            CanonicalRequest::httparse_head(
                b"POST /api/v1/data HTTP/1.1\r\nHost: api.example.com\r\nContent-Type: application/json\r\nContent-Length: 13\r\n\r\n{\"test\":\"data\"}",
                "POST with Content-Length body",
                false,
            ),

            // Chunked encoding - basic
            CanonicalRequest::httparse_head(
                b"POST /upload HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n",
                "Basic chunked encoding",
                false,
            ),

            // Chunked encoding edge case: chunk extensions
            CanonicalRequest::httparse_head(
                b"POST /upload HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=value\r\nhello\r\n0\r\n\r\n",
                "Chunked encoding with extensions",
                false,
            ),

            // Chunked encoding edge case: zero-length chunks in middle
            CanonicalRequest::httparse_head(
                b"POST /stream HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nfoo\r\n0\r\n\r\n3\r\nbar\r\n0\r\n\r\n",
                "Chunked encoding with zero-length chunks",
                false,
            ),

            // Complex headers with multiple values
            CanonicalRequest::httparse_head(
                b"PUT /resource HTTP/1.1\r\nHost: example.com\r\nUser-Agent: test-client/1.0\r\nAccept: application/json, text/plain\r\nAuthorization: Bearer token123\r\nContent-Length: 0\r\n\r\n",
                "Complex headers with multiple values",
                false,
            ),

            // HTTP/1.0 version
            CanonicalRequest::httparse_head(
                b"GET /legacy HTTP/1.0\r\nHost: old.example.com\r\n\r\n",
                "HTTP/1.0 request",
                false,
            ),

            // Edge case: method with unusual but valid characters
            CanonicalRequest::httparse_head(
                b"OPTIONS * HTTP/1.1\r\nHost: example.com\r\n\r\n",
                "OPTIONS with asterisk URI",
                false,
            ),

            // Edge case: chunked with trailers
            CanonicalRequest::httparse_head(
                b"POST /data HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ntest\r\n0\r\nX-Checksum: abc123\r\n\r\n",
                "Chunked encoding with trailers",
                false,
            ),

            // Error case: malformed request line
            CanonicalRequest::httparse_head(b"GET\r\n\r\n", "Malformed request line", true),

            // Body-semantic error: httparse only validates the request head, so this
            // stays as a direct codec assertion instead of a differential verdict.
            CanonicalRequest::codec_only_error(
                b"POST /bad HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\nZZ\r\ndata\r\n",
                "Invalid chunk size",
            ),
        ];

        /// Parse request with our implementation.
        fn parse_with_our_codec(raw_bytes: &[u8]) -> Result<ParsedRequest, String> {
            let mut codec = Http1Codec::new();
            let mut buf = BytesMut::from(raw_bytes);

            match codec.decode(&mut buf) {
                Ok(Some(req)) => Ok(ParsedRequest {
                    method: format!("{:?}", req.method),
                    uri: req.uri,
                    version: format!("{:?}", req.version),
                    headers: req.headers.into_iter().collect(),
                }),
                Ok(None) => Err("Incomplete request".to_string()),
                Err(e) => Err(format!("{:?}", e)),
            }
        }

        /// Parse request with httparse reference implementation.
        fn parse_with_httparse_reference(raw_bytes: &[u8]) -> Result<ParsedRequest, String> {
            let mut headers = [httparse::Header {
                name: "",
                value: &[],
            }; 64];
            let mut req = httparse::Request::new(&mut headers);

            match req.parse(raw_bytes) {
                Ok(httparse::Status::Complete(_)) => {
                    let method = req.method.ok_or("Missing method")?.to_string();
                    let uri = req.path.ok_or("Missing path")?.to_string();
                    let version = req
                        .version
                        .map(|v| {
                            if v == 1 {
                                "Http11".to_string()
                            } else {
                                "Http10".to_string()
                            }
                        })
                        .unwrap_or_else(|| "Http11".to_string());

                    let headers: Vec<(String, String)> = req
                        .headers
                        .iter()
                        .filter(|h| !h.name.is_empty())
                        .map(|h| {
                            (
                                h.name.to_string(),
                                String::from_utf8_lossy(h.value).to_string(),
                            )
                        })
                        .collect();

                    Ok(ParsedRequest {
                        method,
                        uri,
                        version,
                        headers,
                    })
                }
                Ok(httparse::Status::Partial) => Err("Partial request".to_string()),
                Err(e) => Err(format!("httparse error: {:?}", e)),
            }
        }

        let mut conformance_failures = Vec::new();
        let mut both_error_count = 0;
        let mut both_success_count = 0;

        for test_case in &test_cases {
            let our_result = parse_with_our_codec(&test_case.raw_bytes);

            if test_case.coverage == ReferenceCoverage::CodecOnly {
                match (&our_result, test_case.expect_error) {
                    (Err(_), true) => {
                        both_error_count += 1;
                    }
                    (Ok(parsed), true) => {
                        conformance_failures.push(format!(
                            "EXPECTED CODEC ERROR but our implementation succeeded: {}\n\
                             Our result: {:?}\n\
                             Raw bytes:  {:?}",
                            test_case.description,
                            parsed,
                            String::from_utf8_lossy(&test_case.raw_bytes)
                        ));
                    }
                    (Ok(_), false) => {
                        both_success_count += 1;
                    }
                    (Err(err), false) => {
                        conformance_failures.push(format!(
                            "CODEC ERROR but expected success: {}\n\
                             Our error:  {}\n\
                             Raw bytes:  {:?}",
                            test_case.description,
                            err,
                            String::from_utf8_lossy(&test_case.raw_bytes)
                        ));
                    }
                }
                continue;
            }

            let ref_result = parse_with_httparse_reference(&test_case.raw_bytes);

            match (&our_result, &ref_result, test_case.expect_error) {
                // Both implementations succeeded - compare results
                (Ok(our_parsed), Ok(ref_parsed), false) => {
                    if our_parsed == ref_parsed {
                        both_success_count += 1;
                    } else {
                        conformance_failures.push(format!(
                            "CONFORMANCE MISMATCH: {}\n\
                             Our result:  {:?}\n\
                             Ref result:  {:?}\n\
                             Raw bytes:   {:?}",
                            test_case.description,
                            our_parsed,
                            ref_parsed,
                            String::from_utf8_lossy(&test_case.raw_bytes)
                        ));
                    }
                }

                // Both implementations failed (expected for error cases)
                (Err(_), Err(_), true) => {
                    both_error_count += 1;
                }

                // Expected error but one succeeded
                (Ok(parsed), Err(err), true) => {
                    conformance_failures.push(format!(
                        "EXPECTED ERROR but our implementation succeeded: {}\n\
                         Our result: {:?}\n\
                         Ref error:  {}\n\
                         Raw bytes:  {:?}",
                        test_case.description,
                        parsed,
                        err,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }
                (Err(err), Ok(parsed), true) => {
                    conformance_failures.push(format!(
                        "EXPECTED ERROR but reference succeeded: {}\n\
                         Our error:  {}\n\
                         Ref result: {:?}\n\
                         Raw bytes:  {:?}",
                        test_case.description,
                        err,
                        parsed,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }

                // Unexpected success/error mismatch
                (Ok(our_parsed), Err(ref_err), false) => {
                    conformance_failures.push(format!(
                        "SUCCESS/ERROR MISMATCH: {}\n\
                         Our success: {:?}\n\
                         Ref error:   {}\n\
                         Raw bytes:   {:?}",
                        test_case.description,
                        our_parsed,
                        ref_err,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }
                (Err(our_err), Ok(ref_parsed), false) => {
                    conformance_failures.push(format!(
                        "ERROR/SUCCESS MISMATCH: {}\n\
                         Our error:   {}\n\
                         Ref success: {:?}\n\
                         Raw bytes:   {:?}",
                        test_case.description,
                        our_err,
                        ref_parsed,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }
                (Err(our_err), Err(ref_err), false) => {
                    conformance_failures.push(format!(
                        "BOTH ERRORED but expected success: {}\n\
                         Our error:  {}\n\
                         Ref error:  {}\n\
                         Raw bytes:  {:?}",
                        test_case.description,
                        our_err,
                        ref_err,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }

                // Both succeeded but we expected error
                (Ok(our_parsed), Ok(ref_parsed), true) => {
                    conformance_failures.push(format!(
                        "BOTH SUCCEEDED but expected error: {}\n\
                         Our result: {:?}\n\
                         Ref result: {:?}\n\
                         Raw bytes:  {:?}",
                        test_case.description,
                        our_parsed,
                        ref_parsed,
                        String::from_utf8_lossy(&test_case.raw_bytes)
                    ));
                }
            }
        }

        // Generate conformance report
        let total_tests = test_cases.len();
        let success_rate =
            (both_success_count + both_error_count) as f64 / total_tests as f64 * 100.0;

        eprintln!(
            "HTTP/1.1 Codec Conformance Report:\n\
             - Total tests: {}\n\
             - Both succeeded: {}\n\
             - Both failed (expected): {}\n\
             - Conformance rate: {:.1}%\n\
             - Failures: {}",
            total_tests,
            both_success_count,
            both_error_count,
            success_rate,
            conformance_failures.len()
        );

        // If there are failures, create insta snapshots for debugging
        if !conformance_failures.is_empty() {
            use std::collections::BTreeMap;

            let failure_report = conformance_failures
                .into_iter()
                .enumerate()
                .map(|(i, failure)| (format!("failure_{}", i), failure))
                .collect::<BTreeMap<String, String>>();

            insta::with_settings!({
                snapshot_path => "../../tests/snapshots",
                prepend_module_to_snapshot => false,
            }, {
                insta::assert_yaml_snapshot!("http1_codec_conformance_failures", failure_report);
            });

            panic!(
                "HTTP/1.1 codec conformance test failed: {} mismatches against httparse reference.\n\
                 Check snapshot file for detailed comparison.",
                failure_report.len()
            );
        }

        // Success: perfect conformance with httparse reference
        eprintln!(
            "✅ HTTP/1.1 codec conformance test passed: {:.1}% compliance with httparse reference",
            success_rate
        );
    }
}