zenith-net 0.1.0

Zenith 网络地址与传输层抽象:L2-L4 协议解析、TCP/UDP/QUIC 状态机、来源准入引擎、单队列 Worker 数据面循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
//! QUIC 核心协议实现(RFC 9000)
//!
//! 设计目标:Worker 本地无锁单所有者、零堆分配热路径、硬上限预分配。
//!
//! 模块覆盖:
//! - 包头解析(Long Header / Short Header,Version Negotiation,Retry)
//! - 连接管理(CID 路由、地址验证、Retry Token 三倍防放大)
//! - 可靠性基础(Packet Number 单调、ACK 帧处理、PTO 定时)
//! - 流管理(连接/流级流控、Stream 状态管理、预分配流表)
//! - 关闭流程(正常关闭、排空、超时回收)

use crate::error::NetError;
use crate::packet::IpVersion;
use crate::source_admission::IpAddr;
use crate::transport::{TimerAction, TimerType, TimerWheel};

/// QUIC 版本(当前支持 RFC 9000)
pub const QUIC_VERSION_1: u32 = 1;

/// 最大 CID 长度(字节)
pub const MAX_CID_LEN: usize = 20;

/// 最大 Token 长度(字节,Retry Token)
pub const MAX_TOKEN_LEN: usize = 255;

/// 最小 QUIC 包头长度(Short Header 最短:1 字节)
pub const MIN_QUIC_HEADER_LEN: usize = 1;

/// Retry Integrity Tag 长度(字节,RFC 9000 §17.2.5.1)
pub const RETRY_INTEGRITY_TAG_LEN: usize = 16;

/// 最大流 ID(预分配上限,必须为 4 的倍数 + 3)
pub const MAX_STREAM_ID: u64 = 0x0000_FFFF_FFFF;

/// QUIC 连接最大并发数(预分配硬上限)
pub const MAX_QUIC_CONNECTIONS: usize = 1024;

/// QUIC 每连接最大流数(活动流计数硬上限)
pub const MAX_STREAMS_PER_CONN: usize = 128;

/// QUIC 流表预分配槽位数
///
/// 流 ID 直接作为流表索引(RFC 9000 §2.1:低 2 位为类型位,同类型流 ID 步长为 4)。
/// 最多 MAX_STREAMS_PER_CONN 条同类型流时,其最大流 ID < MAX_STREAMS_PER_CONN * 4,
/// 故槽位数取 MAX_STREAMS_PER_CONN * 4,保证无碰撞且覆盖全部合法流 ID。
pub const QUIC_STREAM_TABLE_SIZE: usize = MAX_STREAMS_PER_CONN * 4;

/// QUIC 包头类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuicHeaderType {
    /// Long Header(包含 Version / DCID / SCID / Token / Length)
    Long,
    /// Short Header(已建立连接的数据包)
    Short,
    /// Version Negotiation
    VersionNegotiation,
    /// Retry
    Retry,
}

/// QUIC 长包头帧类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LongFrameType {
    /// Initial
    Initial,
    /// Handshake
    Handshake,
    /// 0-RTT
    ZeroRtt,
}

/// QUIC 包头(解析结果,Copy 语义,零堆分配)
#[derive(Debug, Clone, Copy)]
pub struct QuicHeader {
    /// 包头类型
    pub header_type: QuicHeaderType,
    /// 版本(仅 Long Header)
    pub version: u32,
    /// 目标 CID
    pub dcid: [u8; MAX_CID_LEN],
    /// 目标 CID 实际长度
    pub dcid_len: u8,
    /// 源 CID
    pub scid: [u8; MAX_CID_LEN],
    /// 源 CID 实际长度
    pub scid_len: u8,
    /// 包头包号
    pub packet_number: u64,
    /// Token(Retry / Initial)
    pub token: [u8; MAX_TOKEN_LEN],
    /// Token 实际长度
    pub token_len: u8,
    /// 长包头帧类型
    pub long_frame: LongFrameType,
    /// 包头标志字节(第一字节)
    pub first_byte: u8,
    /// Length 字段值(Long Header:包号长度 + 密文长度,RFC 9000 §17.2)
    pub length: u64,
}

impl QuicHeader {
    /// 创建空包头
    pub const fn empty() -> Self {
        Self {
            header_type: QuicHeaderType::Short,
            version: 0,
            dcid: [0u8; MAX_CID_LEN],
            dcid_len: 0,
            scid: [0u8; MAX_CID_LEN],
            scid_len: 0,
            packet_number: 0,
            token: [0u8; MAX_TOKEN_LEN],
            token_len: 0,
            long_frame: LongFrameType::Initial,
            first_byte: 0,
            length: 0,
        }
    }

    /// 是否为 Long Header
    #[inline]
    pub fn is_long_header(&self) -> bool {
        self.header_type == QuicHeaderType::Long
            || self.header_type == QuicHeaderType::VersionNegotiation
            || self.header_type == QuicHeaderType::Retry
    }

    /// 是否为 Initial(可能携带 Token)
    #[inline]
    pub fn is_initial(&self) -> bool {
        self.header_type == QuicHeaderType::Long
            && self.long_frame == LongFrameType::Initial
    }

    /// 是否已包含有效 Token
    #[inline]
    pub fn has_token(&self) -> bool {
        self.token_len > 0
    }

    /// 比较 Packet Number(处理 62-bit 回绕)
    #[inline]
    pub fn compare_packet_number(a: u64, b: u64) -> i32 {
        use std::cmp::Ordering;
        match a.cmp(&b) {
            Ordering::Equal => 0,
            Ordering::Greater => {
                if a - b < (1u64 << 61) {
                    1
                } else {
                    -1
                }
            }
            Ordering::Less => {
                if b - a < (1u64 << 61) {
                    -1
                } else {
                    1
                }
            }
        }
    }
}

/// QUIC 连接状态机
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QuicConnState {
    /// 初始(等待 Initial)
    Initial,
    /// 握手中
    Handshake,
    /// 已建立(数据传输)
    Established,
    /// 关闭中
    Closing,
    /// 已关闭(终态)
    Closed,
}

/// QUIC 流状态
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QuicStreamState {
    /// 空闲(未使用)
    Idle,
    /// 打开(双向可读写)
    Open,
    /// 半关闭本地(本地已发 FIN)
    HalfClosedLocal,
    /// 半关闭远端(远端已发 FIN)
    HalfClosedRemote,
    /// 已关闭
    Closed,
}

/// QUIC 流元数据(固定长度,零堆分配)
#[derive(Debug, Clone, Copy)]
pub struct QuicStream {
    /// 流 ID
    pub stream_id: u64,
    /// 流状态
    pub state: QuicStreamState,
    /// 最大允许本地偏移(流控)
    pub max_local_offset: u64,
    /// 远端已通知的最大偏移
    pub max_remote_offset: u64,
    /// 本地已提交的偏移
    pub local_offset: u64,
    /// 远端已提交的偏移
    pub remote_offset: u64,
    /// 是否为单向流
    pub is_uni: bool,
}

impl QuicStream {
    const fn empty() -> Self {
        Self {
            stream_id: 0,
            state: QuicStreamState::Idle,
            max_local_offset: 0,
            max_remote_offset: 0,
            local_offset: 0,
            remote_offset: 0,
            is_uni: false,
        }
    }

    /// 从流 ID 初始化
    pub fn new(stream_id: u64, is_uni: bool) -> Self {
        Self {
            stream_id,
            state: QuicStreamState::Open,
            max_local_offset: 0,
            max_remote_offset: 0,
            local_offset: 0,
            remote_offset: 0,
            is_uni,
        }
    }

    /// 计算流表索引(流 ID 直接作为预分配数组索引)
    ///
    /// RFC 9000 §2.1:流 ID 低 2 位编码类型(client/server × bidi/uni),
    /// 故 0、1、2、3 是四条不同的流。旧实现 `stream_id / 4` 会把它们映射到
    /// 同一槽位造成碰撞;直接以流 ID 为索引可保证每条流落到唯一槽位。
    #[inline]
    pub fn remote_idx(stream_id: u64) -> usize {
        stream_id as usize
    }
}

/// QUIC 连接(单 Owner,预分配固定容量流表)
pub struct QuicConnection {
    /// 连接状态
    pub state: QuicConnState,
    /// 源 CID(本地)
    pub scid: [u8; MAX_CID_LEN],
    /// 源 CID 有效长度(字节)
    pub scid_len: u8,
    /// 目标 CID(对端)
    pub dcid: [u8; MAX_CID_LEN],
    /// 目标 CID 有效长度(字节)
    pub dcid_len: u8,
    /// 上一次收到的 Token(Retry 防放大)
    pub retry_token: [u8; MAX_TOKEN_LEN],
    /// Retry Token 有效长度(字节)
    pub retry_token_len: u8,
    /// Token 验证次数(超过 3 次拒绝)
    pub token_attempts: u8,
    /// 远端地址
    pub remote_addr: IpAddr,
    /// 远端端口
    pub remote_port: u16,
    /// 本地地址
    pub local_addr: IpAddr,
    /// 本地端口
    pub local_port: u16,
    /// IP 版本
    pub ip_version: IpVersion,
    /// 最大 Packet Number(远端可见)
    pub max_pn_seen: u64,
    /// 远端通知的最大流 ID(接收方向)
    pub max_remote_stream_id: u64,
    /// 本地双向流计数
    pub next_local_bidi_id: u64,
    /// 本地单向流计数
    pub next_local_uni_id: u64,
    /// 流表(预分配,按流 ID 直接索引)
    pub streams: Vec<QuicStream>,
    /// 已用流数
    pub stream_count: usize,
    /// PTO(毫秒)
    pub pto_ms: u64,
    /// 是否地址已验证
    pub address_verified: bool,
    /// 本连接累计接收字节数(防放大)
    pub bytes_received: u64,
    /// 本连接累计发送字节数(防放大)
    pub bytes_sent: u64,
    // ── 连接迁移(RFC 9000 §9)─────────────────────────────────────
    /// 路径验证状态
    pub path_validation: PathValidationState,
    /// 待验证的 PATH_CHALLENGE 数据(8 字节随机数)
    pub path_challenge_data: u64,
    /// 迁移目标远端地址(连接迁移进行中)
    pub migration_remote_addr: IpAddr,
    /// 迁移目标远端端口
    pub migration_remote_port: u16,
    /// 新路径上已发送字节数(迁移 anti-amplification 限制)
    pub migration_bytes_sent: u64,
    /// 新路径上已接收字节数
    pub migration_bytes_received: u64,
}

impl core::fmt::Debug for QuicConnection {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("QuicConnection")
            .field("state", &self.state)
            .field("stream_count", &self.stream_count)
            .field("bytes_received", &self.bytes_received)
            .field("address_verified", &self.address_verified)
            .finish()
    }
}

impl QuicConnection {
    /// 创建新连接
    pub fn new(
        scid: &[u8],
        dcid: &[u8],
        remote_addr: IpAddr,
        remote_port: u16,
        local_addr: IpAddr,
        local_port: u16,
        ip_version: IpVersion,
    ) -> Self {
        let mut scid_buf = [0u8; MAX_CID_LEN];
        let scid_len = scid.len().min(MAX_CID_LEN) as u8;
        scid_buf[..scid_len as usize].copy_from_slice(&scid[..scid_len as usize]);

        let mut dcid_buf = [0u8; MAX_CID_LEN];
        let dcid_len = dcid.len().min(MAX_CID_LEN) as u8;
        dcid_buf[..dcid_len as usize].copy_from_slice(&dcid[..dcid_len as usize]);

        Self {
            state: QuicConnState::Initial,
            scid: scid_buf,
            scid_len,
            dcid: dcid_buf,
            dcid_len,
            retry_token: [0u8; MAX_TOKEN_LEN],
            retry_token_len: 0,
            token_attempts: 0,
            remote_addr,
            remote_port,
            local_addr,
            local_port,
            ip_version,
            max_pn_seen: 0,
            max_remote_stream_id: 0,
            next_local_bidi_id: 0,
            next_local_uni_id: 0,
            streams: vec![QuicStream::empty(); QUIC_STREAM_TABLE_SIZE],
            stream_count: 0,
            pto_ms: 1000,
            address_verified: false,
            bytes_received: 0,
            bytes_sent: 0,
            path_validation: PathValidationState::Idle,
            path_challenge_data: 0,
            migration_remote_addr: remote_addr,
            migration_remote_port: remote_port,
            migration_bytes_sent: 0,
            migration_bytes_received: 0,
        }
    }

    /// 查找/创建远端流(按远端发起的流 ID)
    pub fn get_or_create_remote_stream(&mut self, stream_id: u64) -> Option<&mut QuicStream> {
        let idx = QuicStream::remote_idx(stream_id);
        if idx >= self.streams.len() {
            return None;
        }
        let entry = &mut self.streams[idx];
        if entry.state == QuicStreamState::Idle {
            entry.stream_id = stream_id;
            entry.state = QuicStreamState::Open;
            entry.is_uni = (stream_id & 0x02) != 0;
            self.stream_count += 1;
        }
        Some(entry)
    }

    /// 获取本地流(若已创建)
    pub fn get_local_stream(&mut self, stream_id: u64) -> Option<&mut QuicStream> {
        let idx = QuicStream::remote_idx(stream_id);
        if idx >= self.streams.len() {
            return None;
        }
        let entry = &mut self.streams[idx];
        if entry.state == QuicStreamState::Idle {
            return None;
        }
        Some(entry)
    }

    /// 申请新的本地流 ID
    ///
    /// # 规范(RFC 9000 §2.1)
    /// 客户端发起的流 ID(初始化时):
    /// - 双向:0, 4, 8, ... (stream_idx * 4)
    /// - 单向:2, 6, 10, ... (stream_idx * 4 + 2)
    pub fn alloc_local_stream_id(&mut self, is_uni: bool) -> Option<u64> {
        if self.stream_count >= MAX_STREAMS_PER_CONN {
            return None;
        }
        // 计算下一个流 ID(计数器暂不前移,待越界检查通过后再提交,避免状态不一致)
        let (id, idx) = if is_uni {
            let idx = self.next_local_uni_id;
            (idx.checked_mul(4)?.checked_add(2)?, idx)
        } else {
            let idx = self.next_local_bidi_id;
            (idx.checked_mul(4)?, idx)
        };
        // 流 ID 直接作为流表索引,须确保槽位在预分配范围内(防御性越界检查)
        let slot = QuicStream::remote_idx(id);
        if slot >= self.streams.len() {
            return None;
        }
        // 越界检查通过后提交计数器前移
        if is_uni {
            self.next_local_uni_id = idx.checked_add(1)?;
        } else {
            self.next_local_bidi_id = idx.checked_add(1)?;
        }
        self.streams[slot] = QuicStream::new(id, is_uni);
        self.stream_count += 1;
        Some(id)
    }

    /// 验证 Token(防放大攻击)
    ///
    /// 规则:
    /// - 同一连接最多接受 3 次 Token 验证(三倍防放大)
    /// - Token 长度必须 > 0 且 <= MAX_TOKEN_LEN
    /// - 使用恒定时间比较,避免时序侧信道泄露
    pub fn verify_token(&mut self, token: &[u8]) -> Result<bool, NetError> {
        if token.is_empty() || token.len() > MAX_TOKEN_LEN {
            return Ok(false);
        }
        if self.retry_token_len == 0 {
            return Ok(false);
        }
        if self.token_attempts >= 3 {
            return Err(NetError::ResourceLimit(
                "quic: token verification attempts exceeded".to_string(),
            ));
        }
        self.token_attempts += 1;
        let len = self.retry_token_len as usize;
        // 恒定时间比较,避免时序攻击
        let ok = token.len() == len && constant_time_eq(&token[..len], &self.retry_token[..len]);
        if ok {
            self.address_verified = true;
        }
        Ok(ok)
    }

    /// 收到一个包后更新 Packet Number(回绕安全)
    pub fn observe_packet_number(&mut self, pn: u64) {
        if QuicHeader::compare_packet_number(pn, self.max_pn_seen) > 0 {
            self.max_pn_seen = pn;
        }
    }

    /// 记录接收字节(放大检测)
    pub fn record_rx_bytes(&mut self, n: u64) {
        self.bytes_received = self.bytes_received.saturating_add(n);
    }
    /// 记录发送字节(放大检测)
    pub fn record_tx_bytes(&mut self, n: u64) {
        self.bytes_sent = self.bytes_sent.saturating_add(n);
    }

    /// 判断是否疑似放大攻击(RFC 9000 §8.1:地址未验证前发送字节不得超过接收字节的 3 倍)
    #[inline]
    pub fn is_amplification_risk(&self) -> bool {
        !self.address_verified && self.bytes_sent > self.bytes_received.saturating_mul(3)
    }

    // ── 连接迁移(RFC 9000 §9)─────────────────────────────────────

    /// 发起连接迁移:生成 PATH_CHALLENGE 并切换到新路径
    ///
    /// # 参数
    /// * `new_addr` - 迁移目标远端地址
    /// * `new_port` - 迁移目标远端端口
    /// * `challenge_data` - 8 字节随机挑战数据(须密码学随机)
    ///
    /// # 返回
    /// * `PathChallengeFrame` - 待发送的路径挑战帧
    pub fn initiate_path_migration(
        &mut self,
        new_addr: IpAddr,
        new_port: u16,
        challenge_data: u64,
    ) -> PathChallengeFrame {
        self.migration_remote_addr = new_addr;
        self.migration_remote_port = new_port;
        self.path_challenge_data = challenge_data;
        self.migration_bytes_sent = 0;
        self.migration_bytes_received = 0;
        self.path_validation = PathValidationState::ChallengeSent;
        PathChallengeFrame::new(challenge_data)
    }

    /// 处理收到的 PATH_CHALLENGE(RFC 9000 §9.3)
    ///
    /// 对端发起路径验证时,本端须回传 PATH_RESPONSE。
    /// 使用恒定时间比较以防时序侧信道(§4.9)。
    ///
    /// # 返回
    /// * `Some(PathResponseFrame)` - 须回传的路径响应帧
    pub fn handle_path_challenge(&self, data: u64) -> PathResponseFrame {
        PathResponseFrame::new(data)
    }

    /// 处理收到的 PATH_RESPONSE(RFC 9000 §9.3)
    ///
    /// 验证响应数据与本端发出的 PATH_CHALLENGE 一致(恒定时间比较)。
    /// 验证通过则完成迁移,将 remote_addr/port 更新为新路径。
    ///
    /// # 返回
    /// * `true` - 路径验证成功,迁移完成
    /// * `false` - 数据不匹配或无进行中的迁移
    pub fn handle_path_response(&mut self, data: u64) -> bool {
        if self.path_validation != PathValidationState::ChallengeSent {
            return false;
        }
        // 恒定时间比较防时序侧信道(§4.9):
        // 复用 zenith-core 统一实现(#[inline(never)] 防内联时序泄漏),
        // 取代内联手写 XOR 循环(统一入口原则)
        if zenith_foundation::ct_compare::constant_time_eq_u64(self.path_challenge_data, data) {
            // 验证成功:提交迁移到新路径
            self.remote_addr = self.migration_remote_addr;
            self.remote_port = self.migration_remote_port;
            self.path_validation = PathValidationState::Validated;
            true
        } else {
            self.path_validation = PathValidationState::Failed;
            false
        }
    }

    /// 迁移是否进行中
    #[inline]
    pub fn is_migration_in_progress(&self) -> bool {
        matches!(self.path_validation, PathValidationState::ChallengeSent)
    }

    /// 迁移 anti-amplification 检查(RFC 9000 §9.4)
    ///
    /// 在新路径地址验证完成前,发送量不得超过接收量的 3 倍。
    #[inline]
    pub fn migration_amplification_limit_reached(&self) -> bool {
        self.path_validation == PathValidationState::ChallengeSent
            && self.migration_bytes_sent
                >= self.migration_bytes_received.saturating_mul(3)
    }

    /// 记录迁移期间新路径发送字节(anti-amplification)
    #[inline]
    pub fn record_migration_tx_bytes(&mut self, n: u64) {
        self.migration_bytes_sent = self.migration_bytes_sent.saturating_add(n);
    }

    /// 记录迁移期间新路径接收字节
    #[inline]
    pub fn record_migration_rx_bytes(&mut self, n: u64) {
        self.migration_bytes_received = self.migration_bytes_received.saturating_add(n);
    }

    /// 重置路径验证状态(迁移完成或失败后回到 Idle)
    #[inline]
    pub fn reset_path_validation(&mut self) {
        self.path_validation = PathValidationState::Idle;
        self.path_challenge_data = 0;
        self.migration_bytes_sent = 0;
        self.migration_bytes_received = 0;
    }

    /// 开始关闭流程
    pub fn start_close(&mut self) {
        self.state = QuicConnState::Closing;
    }

    /// 结束关闭
    pub fn finish_close(&mut self) {
        self.state = QuicConnState::Closed;
    }

    /// 是否已关闭
    #[inline]
    pub fn is_closed(&self) -> bool {
        self.state == QuicConnState::Closed
    }

    /// 是否可以发送数据(Established 状态)
    #[inline]
    pub fn can_send_data(&self) -> bool {
        matches!(self.state, QuicConnState::Established)
    }
}

/// QUIC 连接分配参数
///
/// 将 `QuicConnectionTable::allocate` 所需的多个参数封装为单个结构体,
/// 避免函数签名过长(clippy::too_many_arguments)。
#[derive(Debug, Clone, Copy)]
pub struct QuicConnParams<'a> {
    /// 源 CID(本地)
    pub scid: &'a [u8],
    /// 目标 CID(对端)
    pub dcid: &'a [u8],
    /// 远端地址
    pub remote_addr: IpAddr,
    /// 远端端口
    pub remote_port: u16,
    /// 本地地址
    pub local_addr: IpAddr,
    /// 本地端口
    pub local_port: u16,
    /// IP 版本
    pub ip_version: IpVersion,
}

/// QUIC 连接表(预分配固定容量,无锁单 Owner)
pub struct QuicConnectionTable {
    /// 预分配连接池
    conns: Vec<Option<QuicConnection>>,
    /// 空闲索引栈
    free_stack: Vec<usize>,
    /// 活动连接数
    active: usize,
}

impl core::fmt::Debug for QuicConnectionTable {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("QuicConnectionTable")
            .field("active", &self.active)
            .field("capacity", &self.conns.len())
            .finish()
    }
}

impl QuicConnectionTable {
    /// 创建连接表
    pub fn new(capacity: usize) -> Self {
        let cap = capacity.clamp(16, MAX_QUIC_CONNECTIONS);
        Self {
            conns: (0..cap).map(|_| None).collect(),
            free_stack: (0..cap).rev().collect(),
            active: 0,
        }
    }

    /// 当前活动数
    #[inline]
    pub fn active_count(&self) -> usize {
        self.active
    }

    /// 容量
    #[inline]
    pub fn capacity(&self) -> usize {
        self.conns.len()
    }

    /// 根据 DCID 查找连接
    ///
    /// 使用恒定时间比较避免侧信道泄露;仅比较 `dcid_len` 范围内的字节,
    /// 其余填充字节不参与比较(与 RFC 9000 §17.2 对 DCID 的语义一致)。
    ///
    /// # 已知限制
    /// 当前实现对连接表做 O(n) 线性扫描。在单线程 Worker 场景下连接数通常远低于
    /// 上限(容量预分配固定数组),线性扫描的开销可接受。若未来连接数显著增长,
    /// 可考虑引入 `dcid_index: FxHashMap<Vec<u8>, usize>` 哈希索引实现 O(1) 查找,
    /// 再用 `constant_time_eq` 验证候选 DCID 以保持时序安全性。
    pub fn find_by_dcid(&self, dcid: &[u8]) -> Option<usize> {
        if dcid.is_empty() || dcid.len() > MAX_CID_LEN {
            return None;
        }
        for (idx, entry) in self.conns.iter().enumerate() {
            if let Some(c) = entry {
                let len = c.dcid_len as usize;
                if len == dcid.len()
                    && constant_time_eq(&c.dcid[..len], &dcid[..len])
                {
                    return Some(idx);
                }
            }
        }
        None
    }

    /// 分配新连接,返回索引
    pub fn allocate(&mut self, params: QuicConnParams<'_>) -> Result<usize, NetError> {
        let idx = self
            .free_stack
            .pop()
            .ok_or_else(|| NetError::ResourceLimit("quic: connection table full".to_string()))?;
        let conn = QuicConnection::new(
            params.scid,
            params.dcid,
            params.remote_addr,
            params.remote_port,
            params.local_addr,
            params.local_port,
            params.ip_version,
        );
        self.conns[idx] = Some(conn);
        self.active += 1;
        Ok(idx)
    }

    /// 回收连接
    pub fn release(&mut self, idx: usize) {
        if idx < self.conns.len() && self.conns[idx].is_some() {
            self.conns[idx] = None;
            self.free_stack.push(idx);
            self.active = self.active.saturating_sub(1);
        }
    }

    /// 获取连接可变引用
    pub fn get(&mut self, idx: usize) -> Option<&mut QuicConnection> {
        self.conns.get_mut(idx).and_then(|x| x.as_mut())
    }

    /// 遍历处理所有到期连接(调用回调)
    pub fn for_each_conn_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(usize, &mut QuicConnection),
    {
        for (idx, entry) in self.conns.iter_mut().enumerate() {
            if let Some(c) = entry {
                f(idx, c);
            }
        }
    }

    /// 处理所有连接的定时器推进(返回到期动作)
    pub fn tick(
        &mut self,
        wheel: &mut TimerWheel,
        elapsed_ms: u64,
    ) -> Vec<(usize, TimerAction)> {
        let expired = wheel.advance(elapsed_ms);
        let mut results = Vec::with_capacity(expired.len());
        for action in expired {
            if matches!(
                action.timer_type,
                TimerType::QuicPto | TimerType::QuicCloseTimeout
            ) {
                results.push((action.target_idx, action));
            }
        }
        results
    }
}

/// QUIC 动作(Worker 处理 QUIC 包后的输出)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuicAction {
    /// 新建连接
    NewConnection {
        /// 连接索引
        conn_idx: usize,
    },
    /// 数据到达
    DataReceived {
        /// 连接索引
        conn_idx: usize,
        /// 流 ID
        stream_id: u64,
    },
    /// 连接关闭
    ConnectionClosed {
        /// 连接索引
        conn_idx: usize,
    },
    /// 放大攻击拦截
    AmplificationBlocked {
        /// 连接索引
        conn_idx: usize,
    },
    /// 无效包丢弃
    InvalidPacket,
}

/// 解析 QUIC 包头
///
/// # 规范
/// First Byte 语义:
/// - 最高位(0x80)必须为 1(Long Header),否则为 Short Header
/// - Long Header: 0x80 (I) | 0x40 (1/R) | 0x30 (TT) | 0x0F (PPPP)
/// - Short Header: 0x40 (S) | 0x30 (KK) | 0x0F (PPPP)
pub fn parse_quic_header(input: &[u8]) -> Option<QuicHeader> {
    parse_quic_header_with_dcid_len(input, 8)
}

/// 解析 QUIC 包头(指定服务器 DCID 长度)
///
/// Short Header 不编码 DCID 长度,需从连接状态推断。
/// 本函数接受服务器选择的 SCID 长度(即对端发送 Short Header 时的 DCID 长度)。
pub fn parse_quic_header_with_dcid_len(input: &[u8], server_scid_len: usize) -> Option<QuicHeader> {
    if input.len() < MIN_QUIC_HEADER_LEN {
        return None;
    }
    let first = input[0];
    let mut off = 1;
    let mut hdr = QuicHeader::empty();
    hdr.first_byte = first;

    let is_long = (first & 0x80) != 0;
    if is_long {
        // Long Header
        if input.len() < 6 {
            return None;
        }
        let version = u32::from_be_bytes([input[1], input[2], input[3], input[4]]);
        hdr.version = version;
        hdr.header_type = if version == 0 {
            QuicHeaderType::VersionNegotiation
        } else {
            QuicHeaderType::Long
        };
        // RFC 9000 §17.2:Fixed Bit (0x40) 必须为 1。
        // 唯一例外是 Version Negotiation 包(version == 0,首字节 Unused 位全 0)。
        // 攻击者篡改该位为 0 时 fail-closed 丢弃,避免伪造包头进入后续处理。
        if version != 0 && (first & 0x40) == 0 {
            return None;
        }
        off = 5;

        // DCID 长度 + DCID
        if input.len() <= off {
            return None;
        }
        let dcid_len = input[off] as usize;
        off += 1;
        if dcid_len > MAX_CID_LEN || input.len() < off + dcid_len {
            return None;
        }
        hdr.dcid_len = dcid_len as u8;
        hdr.dcid[..dcid_len].copy_from_slice(&input[off..off + dcid_len]);
        off += dcid_len;

        // SCID 长度 + SCID
        if input.len() <= off {
            return None;
        }
        let scid_len = input[off] as usize;
        off += 1;
        if scid_len > MAX_CID_LEN || input.len() < off + scid_len {
            return None;
        }
        hdr.scid_len = scid_len as u8;
        hdr.scid[..scid_len].copy_from_slice(&input[off..off + scid_len]);
        off += scid_len;

        // 长包类型 TT(RFC 9000 §17.2:bits 5-4,0=Initial、1=0-RTT、2=Handshake、3=Retry)
        // 仅 version != 0 时有意义(Version Negotiation 包的 TT 位无类型语义)
        let tt = (first & 0x30) >> 4;
        if version != 0 {
            // Retry 包(RFC 9000 §17.2.5):无 Token 长度前缀、无 Length 字段、无包号;
            // 剩余字节 = Retry Token + 16 字节 Retry Integrity Tag
            if tt == 3 {
                hdr.header_type = QuicHeaderType::Retry;
                let remaining = input.len().saturating_sub(off);
                if remaining >= RETRY_INTEGRITY_TAG_LEN {
                    let token_len = (remaining - RETRY_INTEGRITY_TAG_LEN).min(MAX_TOKEN_LEN);
                    hdr.token[..token_len].copy_from_slice(&input[off..off + token_len]);
                    hdr.token_len = token_len as u8;
                }
                return Some(hdr);
            }

            hdr.long_frame = match tt {
                0 => LongFrameType::Initial,
                1 => LongFrameType::ZeroRtt,
                // tt == 2(tt == 3 已在上方返回)
                _ => LongFrameType::Handshake,
            };

            // Token 仅存在于 Initial 包(TT=0,RFC 9000 §17.2.2)
            if tt == 0 {
                if input.len() <= off {
                    return None;
                }
                let token_len = input[off] as usize;
                off += 1;
                if token_len > MAX_TOKEN_LEN || input.len() < off + token_len {
                    return None;
                }
                hdr.token_len = token_len as u8;
                hdr.token[..token_len].copy_from_slice(&input[off..off + token_len]);
                off += token_len;
            }

            // Length 字段(Initial/0-RTT/Handshake 均存在,变长,最大 8 字节)。
            // 值 = 包号长度 + 密文长度,存储供调用方切分合并包(RFC 9000 §12.2)。
            if input.len() <= off {
                return Some(hdr);
            }
            let (length, _) = parse_varint(&input[off..])?;
            hdr.length = length;
        }
    } else {
        // Short Header:bit 7 为 0 表示 Short Header
        // RFC 9000 §17.3:
        //   Bit 7: 0 (Short Header 标识)
        //   Bit 6: S (Server 为 0,Client 为 1)
        //   Bits 5-4: Reserved (必须为 0)
        //   Bits 1-0: PPN (Packet Number 长度减 1)
        hdr.header_type = QuicHeaderType::Short;
        // Short Header 不编码 DCID 长度,使用服务器配置的 SCID 长度
        let dcid_len = server_scid_len.min(MAX_CID_LEN);
        if input.len() < off + dcid_len {
            return None;
        }
        hdr.dcid_len = dcid_len as u8;
        hdr.dcid[..dcid_len].copy_from_slice(&input[off..off + dcid_len]);
        off += dcid_len;
        let pn_len = (first & 0x03) as usize + 1;
        if input.len() < off + pn_len {
            return None;
        }
        let mut pn: u64 = 0;
        for i in 0..pn_len {
            pn = (pn << 8) | (input[off + i] as u64);
        }
        hdr.packet_number = pn;
    }

    Some(hdr)
}

/// QUIC 变长度整数解析(RFC 9000 §16)
///
/// **唯一来源约定**:本函数是 zenith-net 内 varint 解码的唯一实现,
/// 编码来源为 [`super::quic_server::encode_varint`](quic_server.rs 顶部
/// re-export 本函数),两者共同覆盖 RFC 9000 §16(解码语义经
/// `test_varint_encode_decode` 往返测试与 §A.1 已知值锁定)。
/// zenith-http3 帧层的 varint 属应用层(RFC 9114 复用 §16 同一编码),
/// 与 zenith-net 无依赖关系,不构成第三份实现。
pub fn parse_varint(input: &[u8]) -> Option<(u64, usize)> {
    if input.is_empty() {
        return None;
    }
    let first = input[0];
    let len_tag = first >> 6;
    let len = 1usize << len_tag;
    if input.len() < len {
        return None;
    }
    let mut v: u64 = (first & 0x3F) as u64;
    for &b in input.iter().take(len).skip(1) {
        v = (v << 8) | (b as u64);
    }
    Some((v, len))
}

// ─── QUIC 帧类型枚举(RFC 9000 §19)───────────────────────────────

/// QUIC 帧类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum QuicFrameType {
    /// 填充帧(Padding, 0x00)
    Padding = 0x00,
    /// 探测帧(Ping, 0x01)
    Ping = 0x01,
    /// 确认帧(ACK, 0x02)
    Ack = 0x02,
    /// 带 ECN 的确认帧(ACK with ECN, 0x03)
    AckEcn = 0x03,
    /// 流重置帧(RESET_STREAM, 0x04)
    RstStream = 0x04,
    /// 停止发送帧(STOP_SENDING, 0x05, RFC 9000 §19.2)
    StopSending = 0x05,
    /// 连接级流控上限帧(MAX_DATA, 0x10)
    MaxData = 0x10,
    /// 流级流控上限帧(MAX_STREAM_DATA, 0x11)
    MaxStreamData = 0x11,
    /// 新连接 ID 帧(NEW_CONNECTION_ID, 0x18)
    NewConnectionId = 0x18,
    /// 退役连接 ID 帧(RETIRE_CONNECTION_ID, 0x19)
    RetireConnectionId = 0x19,
    /// 路径挑战帧(PATH_CHALLENGE, 0x1a, RFC 9000 §19.17)
    PathChallenge = 0x1a,
    /// 路径响应帧(PATH_RESPONSE, 0x1b, RFC 9000 §19.18)
    PathResponse = 0x1b,
    /// 流数据帧(STREAM, 0x08)
    Stream = 0x08,
    /// 连接关闭帧(CONNECTION_CLOSE, 0x1c)
    ConnectionClose = 0x1c,
}

impl QuicFrameType {
    /// 从帧类型字节解析(处理前缀匹配)
    pub fn from_byte(byte: u8) -> Option<Self> {
        match byte {
            0x00 => Some(QuicFrameType::Padding),
            0x01 => Some(QuicFrameType::Ping),
            0x02 | 0x03 => Some(QuicFrameType::Ack),
            0x04 => Some(QuicFrameType::RstStream),
            0x05 => Some(QuicFrameType::StopSending),
            0x08..=0x0F => Some(QuicFrameType::Stream),
            0x10 => Some(QuicFrameType::MaxData),
            0x11 => Some(QuicFrameType::MaxStreamData),
            0x18 => Some(QuicFrameType::NewConnectionId),
            0x19 => Some(QuicFrameType::RetireConnectionId),
            0x1a => Some(QuicFrameType::PathChallenge),
            0x1b => Some(QuicFrameType::PathResponse),
            0x1C | 0x1D => Some(QuicFrameType::ConnectionClose),
            _ => None,
        }
    }
}

// ─── 帧结构体(Copy 语义,固定容量数组)──────────────────────────

/// 最大 ACK 范围数(固定容量,零堆分配)
pub const MAX_ACK_RANGES: usize = 8;

/// 最大 STREAM 帧数据长度(固定容量)
pub const MAX_STREAM_DATA_LEN: usize = 1024;

/// 最大连接关闭原因短语长度
pub const MAX_REASON_PHRASE_LEN: usize = 255;

/// ACK 帧(RFC 9000 §19.3)
#[derive(Debug, Clone, Copy)]
pub struct AckFrame {
    /// 已确认的最大数据包号
    pub largest_acknowledged: u64,
    /// ACK 延迟(微秒)
    pub ack_delay: u64,
    /// ACK 范围块数量
    pub ack_range_count: u8,
    /// 第一个 ACK 范围(连续确认的包数)
    pub first_ack_range: u64,
    /// 后续 ACK 范围块(gap + length)
    pub ranges: [u64; MAX_ACK_RANGES],
}

impl AckFrame {
    /// 创建全零的空 ACK 帧
    pub const fn empty() -> Self {
        Self {
            largest_acknowledged: 0,
            ack_delay: 0,
            ack_range_count: 0,
            first_ack_range: 0,
            ranges: [0u64; MAX_ACK_RANGES],
        }
    }
}

/// STREAM 帧(RFC 9000 §19.4)
#[derive(Debug, Clone, Copy)]
pub struct StreamFrame {
    /// 流 ID
    pub stream_id: u64,
    /// 数据偏移量
    pub offset: u64,
    /// 有效数据长度
    pub length: u64,
    /// 是否带 FIN 标志
    pub fin: bool,
    /// 数据负载(固定容量)
    pub data: [u8; MAX_STREAM_DATA_LEN],
}

impl StreamFrame {
    /// 创建全零的空 STREAM 帧
    pub const fn empty() -> Self {
        Self {
            stream_id: 0,
            offset: 0,
            length: 0,
            fin: false,
            data: [0u8; MAX_STREAM_DATA_LEN],
        }
    }
}

/// CONNECTION_CLOSE 帧(RFC 9000 §19.6)
#[derive(Debug, Clone, Copy)]
pub struct ConnectionCloseFrame {
    /// 错误码
    pub error_code: u64,
    /// 关闭原因短语(固定容量)
    pub reason_phrase: [u8; MAX_REASON_PHRASE_LEN],
    /// 原因短语有效长度
    pub reason_len: u8,
    /// 是否为应用层关闭(true=应用层,false=传输层)
    pub is_app_close: bool,
}

impl ConnectionCloseFrame {
    /// 创建全零的空 CONNECTION_CLOSE 帧
    pub const fn empty() -> Self {
        Self {
            error_code: 0,
            reason_phrase: [0u8; MAX_REASON_PHRASE_LEN],
            reason_len: 0,
            is_app_close: false,
        }
    }
}

/// RST_STREAM 帧(RFC 9000 §19.5)
#[derive(Debug, Clone, Copy)]
pub struct RstStreamFrame {
    /// 流 ID
    pub stream_id: u64,
    /// 错误码
    pub error_code: u64,
}

impl RstStreamFrame {
    /// 创建全零的空 RST_STREAM 帧
    pub const fn empty() -> Self {
        Self {
            stream_id: 0,
            error_code: 0,
        }
    }
}

/// STOP_SENDING 帧(RFC 9000 §19.2)
///
/// 请求对端停止在某条流上发送数据。负载与 RST_STREAM 不同:
/// 仅含 Stream ID 与应用协议错误码,不含 Final Size。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StopSendingFrame {
    /// 流 ID
    pub stream_id: u64,
    /// 应用协议错误码
    pub error_code: u64,
}

impl StopSendingFrame {
    /// 创建全零的空 STOP_SENDING 帧
    pub const fn empty() -> Self {
        Self {
            stream_id: 0,
            error_code: 0,
        }
    }
}

/// MAX_DATA 帧(RFC 9000 §19.7)
#[derive(Debug, Clone, Copy)]
pub struct MaxDataFrame {
    /// 连接级最大数据量
    pub max_data: u64,
}

impl MaxDataFrame {
    /// 创建全零的空 MAX_DATA 帧
    pub const fn empty() -> Self {
        Self { max_data: 0 }
    }
}

/// MAX_STREAM_DATA 帧(RFC 9000 §19.8)
#[derive(Debug, Clone, Copy)]
pub struct MaxStreamDataFrame {
    /// 流 ID
    pub stream_id: u64,
    /// 流级最大数据量
    pub max_stream_data: u64,
}

impl MaxStreamDataFrame {
    /// 创建全零的空 MAX_STREAM_DATA 帧
    pub const fn empty() -> Self {
        Self {
            stream_id: 0,
            max_stream_data: 0,
        }
    }
}

/// PATH_CHALLENGE 帧(RFC 9000 §19.17)
///
/// 连接迁移路径验证:发送 8 字节随机挑战数据,对端须回 PATH_RESPONSE。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PathChallengeFrame {
    /// 8 字节路径挑战数据
    pub data: u64,
}

impl PathChallengeFrame {
    /// 创建路径挑战帧
    #[inline]
    pub const fn new(data: u64) -> Self {
        Self { data }
    }

    /// 编码到缓冲区(帧类型 0x1a + 8 字节 data,共 9 字节)
    pub fn encode(&self, out: &mut [u8]) -> Option<usize> {
        if out.len() < 9 {
            return None;
        }
        out[0] = 0x1a;
        out[1..9].copy_from_slice(&self.data.to_be_bytes());
        Some(9)
    }
}

/// PATH_RESPONSE 帧(RFC 9000 §19.18)
///
/// 对 PATH_CHALLENGE 的响应,须回传相同的 8 字节数据。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PathResponseFrame {
    /// 8 字节路径响应数据(须与 PATH_CHALLENGE.data 一致)
    pub data: u64,
}

impl PathResponseFrame {
    /// 创建路径响应帧
    #[inline]
    pub const fn new(data: u64) -> Self {
        Self { data }
    }

    /// 编码到缓冲区(帧类型 0x1b + 8 字节 data,共 9 字节)
    pub fn encode(&self, out: &mut [u8]) -> Option<usize> {
        if out.len() < 9 {
            return None;
        }
        out[0] = 0x1b;
        out[1..9].copy_from_slice(&self.data.to_be_bytes());
        Some(9)
    }
}

/// 路径验证状态(RFC 9000 §9)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathValidationState {
    /// 空闲,无进行中的路径验证
    Idle,
    /// 已发送 PATH_CHALLENGE,等待 PATH_RESPONSE
    ChallengeSent,
    /// 路径验证成功,迁移完成
    Validated,
    /// 路径验证失败
    Failed,
}

// ─── 帧解析函数 ────────────────────────────────────────────────────

/// 解析 ACK 帧(RFC 9000 §19.3)
///
/// ACK Frame {
///   Type (i) = 0x02..0x03,
///   Largest Acknowledged (i),
///   ACK Delay (i),
///   ACK Range Count (i),
///   First ACK Range (i),
///   ACK Range (..) ...,
///   [ECN Count (i), ...]
/// }
pub fn parse_ack_frame(input: &[u8]) -> Option<AckFrame> {
    if input.len() < 5 {
        return None;
    }
    let mut off = 0;
    off += 1;

    let (largest_acknowledged, n) = parse_varint(&input[off..])?;
    off += n;
    let (ack_delay, n) = parse_varint(&input[off..])?;
    off += n;
    let (ack_range_count, n) = parse_varint(&input[off..])?;
    off += n;
    let (first_ack_range, n) = parse_varint(&input[off..])?;
    off += n;

    // 先以完整 u64 判界,再窄化为 u8:若先 `as u8` 截断,count≥256 会回绕
    // (256→0、300→44)绕过 MAX_ACK_RANGES 上限检查 → 越界/畸形帧被接受。
    if ack_range_count > MAX_ACK_RANGES as u64 {
        return None;
    }
    let ack_range_count = ack_range_count as u8;
    if ack_range_count as usize > MAX_ACK_RANGES {
        return None;
    }

    let mut ranges = [0u64; MAX_ACK_RANGES];
    // RFC 9000 §19.3:首个 ACK range 的最小编号 = largest_acknowledged - first_ack_range
    let mut smallest = largest_acknowledged.checked_sub(first_ack_range)?;
    for slot in ranges.iter_mut().take(ack_range_count as usize) {
        let (gap, n) = parse_varint(&input[off..])?;
        off += n;
        let (length, n) = parse_varint(&input[off..])?;
        off += n;
        // RFC 9000 §19.3.1:本 range 的最大编号 = 上一 range 最小编号 - gap - 2,
        // 最小编号 = 最大编号 - length。必须累积(相对上一 range 边界),
        // 而非每次相对 largest_acknowledged 计算(>1 range 时语义错误)。
        let this_largest = smallest.checked_sub(gap.checked_add(2)?)?;
        let this_smallest = this_largest.checked_sub(length)?;
        *slot = this_smallest;
        smallest = this_smallest;
    }

    Some(AckFrame {
        largest_acknowledged,
        ack_delay,
        ack_range_count,
        first_ack_range,
        ranges,
    })
}

/// 解析 STREAM 帧(RFC 9000 §19.4)
///
/// STREAM Frame {
///   Type (i) = 0x08..0x0F,
///   Stream ID (i),
///   [Offset (i)],
///   [Length (i)],
///   Fin Bit (0x01),
///   Data (..),
/// }
pub fn parse_stream_frame(input: &[u8]) -> Option<StreamFrame> {
    if input.len() < 2 {
        return None;
    }
    let type_byte = input[0];
    let off_bit = (type_byte & 0x04) != 0;
    let len_bit = (type_byte & 0x02) != 0;
    let fin_bit = (type_byte & 0x01) != 0;
    let mut off = 1;

    let (stream_id, n) = parse_varint(&input[off..])?;
    off += n;

    let offset = if off_bit {
        let (v, n) = parse_varint(&input[off..])?;
        off += n;
        v
    } else {
        0
    };

    let length = if len_bit {
        let (v, n) = parse_varint(&input[off..])?;
        off += n;
        v
    } else {
        (input.len() - off) as u64
    };

    if length as usize > MAX_STREAM_DATA_LEN {
        return None;
    }
    if input.len() < off + length as usize {
        return None;
    }

    let mut data = [0u8; MAX_STREAM_DATA_LEN];
    data[..length as usize].copy_from_slice(&input[off..off + length as usize]);

    Some(StreamFrame {
        stream_id,
        offset,
        length,
        fin: fin_bit,
        data,
    })
}

/// 解析 CONNECTION_CLOSE 帧(RFC 9000 §19.6)
///
/// CONNECTION_CLOSE Frame {
///   Type (i) = 0x1c..0x1d,
///   Error Code (i),
///   Reason Phrase Length (i),
///   Reason Phrase (..),
/// }
pub fn parse_connection_close_frame(input: &[u8]) -> Option<ConnectionCloseFrame> {
    if input.len() < 3 {
        return None;
    }
    let type_byte = input[0];
    let is_app_close = (type_byte & 0x01) != 0;
    let mut off = 1;

    let (error_code, n) = parse_varint(&input[off..])?;
    off += n;

    let (reason_len, n) = parse_varint(&input[off..])?;
    off += n;

    if reason_len > MAX_REASON_PHRASE_LEN as u64 {
        return None;
    }
    if input.len() < off + reason_len as usize {
        return None;
    }

    let mut reason_phrase = [0u8; MAX_REASON_PHRASE_LEN];
    reason_phrase[..reason_len as usize].copy_from_slice(&input[off..off + reason_len as usize]);

    Some(ConnectionCloseFrame {
        error_code,
        reason_phrase,
        reason_len: reason_len as u8,
        is_app_close,
    })
}

/// 解析 RST_STREAM 帧(RFC 9000 §19.5)
///
/// RST_STREAM Frame {
///   Type (i) = 0x04..0x05,
///   Stream ID (i),
///   Application Protocol Error Code (i),
/// }
pub fn parse_rst_stream_frame(input: &[u8]) -> Option<RstStreamFrame> {
    if input.len() < 3 {
        return None;
    }
    let mut off = 1;

    let (stream_id, n) = parse_varint(&input[off..])?;
    off += n;

    let (error_code, _) = parse_varint(&input[off..])?;

    Some(RstStreamFrame {
        stream_id,
        error_code,
    })
}

/// 解析 STOP_SENDING 帧(RFC 9000 §19.2)
///
/// STOP_SENDING Frame {
///   Type (i) = 0x05,
///   Stream ID (i),
///   Application Protocol Error Code (i),
/// }
pub fn parse_stop_sending_frame(input: &[u8]) -> Option<StopSendingFrame> {
    if input.len() < 3 {
        return None;
    }
    let mut off = 1;

    let (stream_id, n) = parse_varint(&input[off..])?;
    off += n;

    let (error_code, _) = parse_varint(&input[off..])?;

    Some(StopSendingFrame {
        stream_id,
        error_code,
    })
}

/// 解析 MAX_DATA 帧(RFC 9000 §19.7)
///
/// MAX_DATA Frame {
///   Type (i) = 0x10,
///   Maximum Data (i),
/// }
pub fn parse_max_data_frame(input: &[u8]) -> Option<MaxDataFrame> {
    if input.len() < 2 {
        return None;
    }
    let (max_data, _) = parse_varint(&input[1..])?;
    Some(MaxDataFrame { max_data })
}

/// 解析 MAX_STREAM_DATA 帧(RFC 9000 §19.8)
///
/// MAX_STREAM_DATA Frame {
///   Type (i) = 0x11,
///   Stream ID (i),
///   Maximum Stream Data (i),
/// }
pub fn parse_max_stream_data_frame(input: &[u8]) -> Option<MaxStreamDataFrame> {
    if input.len() < 3 {
        return None;
    }
    let mut off = 1;

    let (stream_id, n) = parse_varint(&input[off..])?;
    off += n;

    let (max_stream_data, _) = parse_varint(&input[off..])?;

    Some(MaxStreamDataFrame {
        stream_id,
        max_stream_data,
    })
}

/// 解析 PATH_CHALLENGE 帧(RFC 9000 §19.17)
///
/// PATH_CHALLENGE Frame {
///   Type (i) = 0x1a,
///   Data (64),
/// }
pub fn parse_path_challenge_frame(input: &[u8]) -> Option<PathChallengeFrame> {
    if input.len() < 9 || input[0] != 0x1a {
        return None;
    }
    let data = u64::from_be_bytes([
        input[1], input[2], input[3], input[4], input[5], input[6], input[7], input[8],
    ]);
    Some(PathChallengeFrame { data })
}

/// 解析 PATH_RESPONSE 帧(RFC 9000 §19.18)
///
/// PATH_RESPONSE Frame {
///   Type (i) = 0x1b,
///   Data (64),
/// }
pub fn parse_path_response_frame(input: &[u8]) -> Option<PathResponseFrame> {
    if input.len() < 9 || input[0] != 0x1b {
        return None;
    }
    let data = u64::from_be_bytes([
        input[1], input[2], input[3], input[4], input[5], input[6], input[7], input[8],
    ]);
    Some(PathResponseFrame { data })
}

// ─── 拥塞控制基础(RFC 9002 / BBR 简化版)──────────────────────────

/// 拥塞控制状态
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CongestionState {
    /// 慢启动:cwnd 线性增长
    SlowStart,
    /// 拥塞避免:cwnd 加性增乘性减
    CongestionAvoidance,
    /// 恢复:检测到丢包后的恢复阶段
    Recovery,
}

/// 拥塞控制器(简化版 Reno/CUBIC)
#[derive(Debug, Clone, Copy)]
pub struct CongestionController {
    /// 拥塞窗口(字节)
    pub cwnd: u64,
    /// 在途字节数
    pub in_flight: u64,
    /// 平滑 RTT(微秒)
    pub srtt: u64,
    /// RTT 方差(微秒)
    pub rtt_var: u64,
    /// PTO 连续超时计数
    pub pto_count: u32,
    state: CongestionState,
    ssthresh: u64,
    min_rtt: u64,
}

impl CongestionController {
    /// 默认初始拥塞窗口(10 包 * 1460 字节)
    const INITIAL_CWND: u64 = 14_600;
    /// 最大拥塞窗口上限(16MB)
    const MAX_CWND: u64 = 16 * 1024 * 1024;
    /// 最小窗口(2 个包)
    const MIN_CWND: u64 = 2 * 1460;

    /// 创建新的拥塞控制器
    pub fn new() -> Self {
        Self {
            cwnd: Self::INITIAL_CWND,
            in_flight: 0,
            srtt: 0,
            rtt_var: 0,
            pto_count: 0,
            state: CongestionState::SlowStart,
            ssthresh: u64::MAX,
            min_rtt: u64::MAX,
        }
    }

    /// 当前拥塞控制状态
    #[inline]
    pub fn state(&self) -> CongestionState {
        self.state
    }

    /// 空闲可用字节数
    #[inline]
    pub fn available_bytes(&self) -> u64 {
        self.cwnd.saturating_sub(self.in_flight)
    }

    /// 记录发送字节
    #[inline]
    pub fn on_send(&mut self, bytes: u64) {
        self.in_flight = self.in_flight.saturating_add(bytes);
    }

    /// 收到 ACK,返回可新增加的拥塞窗口字节数
    pub fn on_ack(&mut self, acked_bytes: u64, rtt_us: u64) -> u64 {
        self.in_flight = self.in_flight.saturating_sub(acked_bytes);
        self.update_rtt(rtt_us);

        let old_cwnd = self.cwnd;
        match self.state {
            CongestionState::SlowStart => {
                self.cwnd = self.cwnd.saturating_add(acked_bytes.min(1460));
                if self.cwnd >= self.ssthresh {
                    self.state = CongestionState::CongestionAvoidance;
                }
            }
            CongestionState::CongestionAvoidance => {
                let increment = acked_bytes * 1460 / self.cwnd.max(1);
                self.cwnd = self.cwnd.saturating_add(increment.max(1));
            }
            CongestionState::Recovery => {
                if self.in_flight == 0 {
                    self.state = CongestionState::CongestionAvoidance;
                }
            }
        }
        self.cwnd = self.cwnd.min(Self::MAX_CWND);
        self.cwnd - old_cwnd
    }

    /// 丢包处理
    pub fn on_loss(&mut self, lost_bytes: u64) {
        self.in_flight = self.in_flight.saturating_sub(lost_bytes);
        match self.state {
            CongestionState::Recovery => {}
            _ => {
                self.state = CongestionState::Recovery;
                self.ssthresh = self.cwnd * 7 / 10;
                self.cwnd = self.ssthresh.max(Self::MIN_CWND);
            }
        }
    }

    /// 超时处理(进入慢启动)
    pub fn on_timeout(&mut self) {
        self.pto_count += 1;
        self.ssthresh = self.cwnd * 3 / 4;
        self.cwnd = Self::INITIAL_CWND;
        self.in_flight = 0;
        self.state = CongestionState::SlowStart;
    }

    /// 更新 RTT 估计
    fn update_rtt(&mut self, rtt_us: u64) {
        if self.min_rtt == u64::MAX || rtt_us < self.min_rtt {
            self.min_rtt = rtt_us;
        }
        if self.srtt == 0 {
            self.srtt = rtt_us;
            self.rtt_var = rtt_us / 2;
        } else {
            let delta = self.srtt.abs_diff(rtt_us);
            self.srtt = (self.srtt * 7 + rtt_us) / 8;
            self.rtt_var = (self.rtt_var * 3 + delta) / 4;
        }
    }

    /// 计算 PTO(微秒)
    pub fn pto_us(&self) -> u64 {
        if self.srtt == 0 {
            100_000
        } else {
            let base = self.srtt + (self.rtt_var * 4).max(1000);
            let multiplier = 1u64.checked_shl(self.pto_count.min(10)).unwrap_or(1 << 10);
            base * multiplier
        }
    }

    /// 重置 PTO 计数器
    pub fn reset_pto(&mut self) {
        self.pto_count = 0;
    }
}

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

// ─── 恒定时间字节比较(避免侧信道泄露)────────────────────────────
// 委托 zenith-core 统一实现(AGENT.md §4.9 时序安全,禁止重复造轮子)
use zenith_foundation::ct_compare::constant_time_eq;

// ─── 测试 ──────────────────────────────────────────────────────────

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

    #[test]
    fn test_quic_header_empty() {
        let hdr = QuicHeader::empty();
        assert_eq!(hdr.header_type, QuicHeaderType::Short);
        assert!(!hdr.is_long_header());
        assert!(!hdr.has_token());
    }

    #[test]
    fn test_parse_short_header() {
        // Short Header: first byte = 0x43 (S | 011 -> PPN len = 4 bytes)
        // DCID = 8 bytes (server SCID length, default)
        // packet number = 0x11223344
        let input: [u8; 13] = [
            0x43,
            0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, // 8-byte DCID
            0x11, 0x22, 0x33, 0x44, // packet number
        ];
        let hdr = parse_quic_header(&input).unwrap();
        assert_eq!(hdr.header_type, QuicHeaderType::Short);
        assert_eq!(hdr.dcid_len, 8);
        assert_eq!(&hdr.dcid[..8], &[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11]);
        assert_eq!(hdr.packet_number, 0x11223344);
        assert!(!hdr.is_long_header());
    }

    #[test]
    fn test_parse_long_initial_with_token() {
        // Initial with Token: first = 0xC1 (I=1, Fixed=1, TT=00, PPN=01)
        // version = 1
        // dcid = [1,2,3,4,5] (len 5)
        // scid = [6,7,8,9] (len 4)
        // token = [0xAA, 0xBB] (len 2)
        let mut input = Vec::new();
        input.push(0xC1);
        input.extend_from_slice(&1u32.to_be_bytes());
        input.push(5);
        input.extend_from_slice(&[1u8, 2, 3, 4, 5]);
        input.push(4);
        input.extend_from_slice(&[6u8, 7, 8, 9]);
        input.push(2);
        input.extend_from_slice(&[0xAA, 0xBB]);
        // 长度字段(1 字节 varint)
        input.push(0x04);

        let hdr = parse_quic_header(&input).unwrap();
        assert_eq!(hdr.header_type, QuicHeaderType::Long);
        assert_eq!(hdr.long_frame, LongFrameType::Initial);
        assert_eq!(hdr.version, 1);
        assert_eq!(hdr.dcid_len, 5);
        assert_eq!(&hdr.dcid[..5], &[1, 2, 3, 4, 5]);
        assert_eq!(hdr.scid_len, 4);
        assert_eq!(&hdr.scid[..4], &[6, 7, 8, 9]);
        assert_eq!(hdr.token_len, 2);
        assert_eq!(&hdr.token[..2], &[0xAA, 0xBB]);
        assert!(hdr.is_initial());
        assert!(hdr.has_token());
    }

    #[test]
    fn test_parse_version_negotiation() {
        // Version Negotiation: first = 0x82 (I=1, R=0, TT=00, PPN=10)
        let mut input = Vec::new();
        input.push(0x82);
        input.extend_from_slice(&0u32.to_be_bytes()); // version = 0
        input.push(3);
        input.extend_from_slice(&[0x11, 0x22, 0x33]);
        input.push(3);
        input.extend_from_slice(&[0x44, 0x55, 0x66]);
        input.push(0);
        // 长度字段
        input.push(0x08);

        let hdr = parse_quic_header(&input).unwrap();
        assert_eq!(hdr.header_type, QuicHeaderType::VersionNegotiation);
        assert_eq!(hdr.version, 0);
    }

    /// 构造最小长包(version=1,dcid/scid 长度为 0)
    fn build_long_packet(first: u8) -> Vec<u8> {
        let mut v = vec![first];
        v.extend_from_slice(&1u32.to_be_bytes());
        v.push(0); // dcid len = 0
        v.push(0); // scid len = 0
        v
    }

    #[test]
    fn test_long_header_tt_bits_rfc9000() {
        // 回归:旧实现 `(first & 0xC0) >> 5` 对真实长包头(bit7=1)恒判 Initial。
        // RFC 9000 §17.2:TT 位为 bits 5-4(0=Initial、1=0-RTT、2=Handshake、3=Retry)。

        // TT=0 → Initial(补 1 字节 Token 长度 + 1 字节 Length)
        let mut init = build_long_packet(0xC0);
        init.push(0); // token len = 0
        init.push(0); // length = 0
        let h = parse_quic_header(&init).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Long);
        assert_eq!(h.long_frame, LongFrameType::Initial);
        assert!(h.is_initial());

        // TT=1 → 0-RTT
        let h = parse_quic_header(&build_long_packet(0xD0)).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Long);
        assert_eq!(h.long_frame, LongFrameType::ZeroRtt);

        // TT=2 → Handshake(不得误判为 Initial 或 Retry)
        let h = parse_quic_header(&build_long_packet(0xE0)).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Long);
        assert_eq!(h.long_frame, LongFrameType::Handshake);

        // TT=3 → Retry
        let h = parse_quic_header(&build_long_packet(0xF0)).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Retry);
    }

    #[test]
    fn test_retry_detection_tt3_only() {
        // 回归:旧 Retry 条件 `(first & 0xE0) == 0xE0 && (first & 0x10) == 0`
        // 会把 Handshake(0xE*,TT=2)误判为 Retry。
        let h = parse_quic_header(&build_long_packet(0xE3)).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Long);
        assert_eq!(h.long_frame, LongFrameType::Handshake);

        // TT=3 + version!=0 → Retry;Token = 剩余字节减去 16 字节 Integrity Tag
        let mut pkt = build_long_packet(0xF0);
        pkt.extend_from_slice(&[0x42; 8]); // Retry Token(8 字节)
        pkt.extend_from_slice(&[0u8; RETRY_INTEGRITY_TAG_LEN]); // Integrity Tag
        let h = parse_quic_header(&pkt).unwrap();
        assert_eq!(h.header_type, QuicHeaderType::Retry);
        assert_eq!(h.token_len, 8);
        assert_eq!(&h.token[..8], &[0x42; 8]);
    }

    #[test]
    fn test_token_gating_only_initial() {
        // 回归:旧门控 `(first & 0x20)` 恰好命中 TT 高位,
        // 把真正的 Initial(TT=0)排除在外、却对 0-RTT(TT=1)解析 Token。

        // Initial(TT=0):解析 Token 字段
        let mut init = build_long_packet(0xC1);
        init.push(2); // token len = 2
        init.extend_from_slice(&[0xAA, 0xBB]);
        init.push(4); // length = 4
        let h = parse_quic_header(&init).unwrap();
        assert!(h.is_initial());
        assert_eq!(h.token_len, 2);
        assert_eq!(&h.token[..2], &[0xAA, 0xBB]);
        assert_eq!(h.length, 4);

        // 0-RTT(TT=1):无 Token 字段,相同字节流的首个 varint 是 Length
        let mut zrtt = build_long_packet(0xD1);
        zrtt.push(2); // length = 2(而非 token len)
        zrtt.extend_from_slice(&[0xAA, 0xBB]);
        let h = parse_quic_header(&zrtt).unwrap();
        assert_eq!(h.long_frame, LongFrameType::ZeroRtt);
        assert_eq!(h.token_len, 0, "0-RTT 不得解析 Token 字段");
        assert_eq!(h.length, 2, "0-RTT 的首个 varint 应解析为 Length");
    }

    #[test]
    fn test_amplification_risk_direction_rfc9000() {
        // 回归:旧实现方向写反(rx > 3*tx 报警),接收多发送少时误报。
        // RFC 9000 §8.1:地址未验证前 tx 不得超过 3*rx。
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();

        // 接收多、发送少:旧实现误报,修正后不报
        c.record_rx_bytes(500);
        c.record_tx_bytes(100);
        assert!(!c.is_amplification_risk(), "tx <= 3*rx 不应触发");

        // tx 恰好等于 3*rx:仍在预算内
        c.record_tx_bytes(1400);
        assert!(!c.is_amplification_risk(), "tx == 3*rx 仍在预算内");

        // tx 超过 3*rx:触发
        c.record_tx_bytes(1);
        assert!(c.is_amplification_risk(), "tx > 3*rx 必须触发");

        // 地址验证通过后不再触发
        c.address_verified = true;
        assert!(!c.is_amplification_risk());

        conns.release(idx);
    }

    #[test]
    fn test_quic_connection_lifecycle() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8, 2, 3, 4],
                dcid: &[5u8, 6, 7, 8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 12345,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        assert_eq!(conns.active_count(), 1);

        let c = conns.get(idx).unwrap();
        assert_eq!(c.state, QuicConnState::Initial);

        let sid = c.alloc_local_stream_id(false).unwrap();
        assert_eq!(sid, 0);
        let sid2 = c.alloc_local_stream_id(true).unwrap();
        assert_eq!(sid2, 2);

        conns.release(idx);
        assert_eq!(conns.active_count(), 0);
    }

    #[test]
    fn test_quic_token_amplification() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8, 2, 3],
                dcid: &[4u8, 5, 6],
                remote_addr: IpAddr::V4([192, 168, 1, 1]),
                remote_port: 443,
                local_addr: IpAddr::V4([10, 0, 0, 1]),
                local_port: 0,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();

        // 设置 Retry Token
        c.retry_token[..4].copy_from_slice(&[0x11, 0x22, 0x33, 0x44]);
        c.retry_token_len = 4;

        // 第 1 次验证通过
        assert!(c.verify_token(&[0x11, 0x22, 0x33, 0x44]).unwrap());
        assert!(c.address_verified);

        conns.release(idx);
    }

    #[test]
    fn test_quic_token_exceed_limit() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        c.retry_token[0] = 0xAA;
        c.retry_token_len = 1;

        // 前 3 次(含正确值后的尝试)
        for _ in 0..3 {
            let _ = c.verify_token(&[0xFF]);
        }
        // 第 4 次超限
        let res = c.verify_token(&[0xAA]);
        assert!(res.is_err());
    }

    #[test]
    fn test_stream_id_remote_idx() {
        // 流 ID 直接作为流表索引(RFC 9000 §2.1:低 2 位为类型位)。
        // 同类型流 ID 步长为 4,跨类型流 ID 不得映射到同一槽位。
        assert_eq!(QuicStream::remote_idx(0), 0);
        assert_eq!(QuicStream::remote_idx(4), 4);
        assert_eq!(QuicStream::remote_idx(8), 8);
    }

    #[test]
    fn test_quic_stream_state_transitions() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        let s = c.get_or_create_remote_stream(8).unwrap();
        assert_eq!(s.state, QuicStreamState::Open);
        assert_eq!(s.stream_id, 8);
        assert!(!s.is_uni);

        s.state = QuicStreamState::Closed;
        assert_eq!(s.state, QuicStreamState::Closed);

        conns.release(idx);
    }

    #[test]
    fn test_packet_number_compare() {
        assert!(QuicHeader::compare_packet_number(10, 5) > 0);
        assert!(QuicHeader::compare_packet_number(5, 10) < 0);
        assert_eq!(QuicHeader::compare_packet_number(10, 10), 0);
        // 回绕
        assert!(QuicHeader::compare_packet_number(1, u64::MAX) > 0);
        assert!(QuicHeader::compare_packet_number(u64::MAX, 1) < 0);
    }

    #[test]
    fn test_quic_conn_amplification_detection() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        // RFC 9000 §8.1:tx > 3*rx 才触发(rx=100,tx=400 > 300)
        c.record_rx_bytes(100);
        c.record_tx_bytes(400);
        assert!(c.is_amplification_risk());

        c.address_verified = true;
        assert!(!c.is_amplification_risk());

        conns.release(idx);
    }

    #[test]
    fn test_quic_find_by_dcid_basic() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8, 2, 3],
                dcid: &[4u8, 5, 6, 7, 8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        // 完全匹配
        let found = conns.find_by_dcid(&[4u8, 5, 6, 7, 8]);
        assert_eq!(found, Some(idx));
        // 长度不同
        assert_eq!(conns.find_by_dcid(&[4u8, 5, 6, 7]), None);
        // 内容不同
        assert_eq!(conns.find_by_dcid(&[4u8, 5, 6, 7, 9]), None);
        // 空 DCID
        assert_eq!(conns.find_by_dcid(&[]), None);
    }

    #[test]
    fn test_quic_find_by_dcid_no_panic_on_short_slice() {
        // 回归测试:旧实现使用 `dcid[..c.dcid.len()]` 会在 dcid 短于 20 字节时越界 panic
        let mut conns = QuicConnectionTable::new(4);
        let _ = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[4u8, 5, 6], // 短 DCID(3 字节,< MAX_CID_LEN=20)
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        // 不应 panic,应正常返回 Some 或 None
        let res = conns.find_by_dcid(&[4u8, 5, 6]);
        assert!(res.is_some());
    }

    #[test]
    fn test_constant_time_eq_basic() {
        assert!(constant_time_eq(b"", b""));
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"ab"));
        assert!(!constant_time_eq(b"abc", b"abcd"));
        assert!(!constant_time_eq(b"abc", b""));
    }

    #[test]
    fn test_quic_verify_token_constant_time() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        c.retry_token[..6].copy_from_slice(b"SECRET");
        c.retry_token_len = 6;
        // 正确 Token
        assert!(c.verify_token(b"SECRET").unwrap());
        assert!(c.address_verified);
        // 错误 Token(不应 panic,应返回 false)
        c.address_verified = false;
        c.token_attempts = 0;
        assert!(!c.verify_token(b"WRONG1").unwrap());
        assert!(!c.address_verified);
        // 长度不一致的 Token(不应 panic)
        c.token_attempts = 0;
        assert!(!c.verify_token(b"SEC").unwrap());
        assert!(!c.verify_token(b"SECRETS").unwrap());
        conns.release(idx);
    }

    #[test]
    fn test_quic_close_lifecycle() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        c.state = QuicConnState::Established;
        assert_eq!(c.state, QuicConnState::Established);

        c.start_close();
        assert_eq!(c.state, QuicConnState::Closing);

        c.finish_close();
        assert!(c.is_closed());
        conns.release(idx);
    }

    #[test]
    fn test_quic_conn_table_full() {
        // 预分配容量为 4 的连接表(小于 MIN_CONN_CAPACITY 会被提升到 16)
        let mut conns = QuicConnectionTable::new(4);
        let cap = conns.capacity();
        // 填满整个连接表
        for i in 0..cap as u8 {
            let _ = conns.allocate(QuicConnParams {
                scid: &[i],
                dcid: &[i + 1],
                remote_addr: IpAddr::V4([10, 0, 0, i]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            });
        }
        let res = conns.allocate(QuicConnParams {
            scid: &[99u8],
            dcid: &[100u8],
            remote_addr: IpAddr::V4([10, 0, 0, 99]),
            remote_port: 0,
            local_addr: IpAddr::V4([127, 0, 0, 1]),
            local_port: 8443,
            ip_version: IpVersion::V4,
        });
        assert!(res.is_err());
    }

    #[test]
    fn test_quic_for_each_conn() {
        let mut conns = QuicConnectionTable::new(4);
        for i in 0..3u8 {
            let _ = conns.allocate(QuicConnParams {
                scid: &[i],
                dcid: &[i + 1],
                remote_addr: IpAddr::V4([10, 0, 0, i]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            });
        }
        let mut count = 0;
        conns.for_each_conn_mut(|_, c| {
            c.pto_ms = 500;
            count += 1;
        });
        assert_eq!(count, 3);
    }

    // ─── 帧类型枚举测试 ────────────────────────────────────────────

    #[test]
    fn test_frame_type_from_byte() {
        assert_eq!(QuicFrameType::from_byte(0x00), Some(QuicFrameType::Padding));
        assert_eq!(QuicFrameType::from_byte(0x01), Some(QuicFrameType::Ping));
        assert_eq!(QuicFrameType::from_byte(0x02), Some(QuicFrameType::Ack));
        assert_eq!(QuicFrameType::from_byte(0x03), Some(QuicFrameType::Ack));
        assert_eq!(QuicFrameType::from_byte(0x04), Some(QuicFrameType::RstStream));
        assert_eq!(QuicFrameType::from_byte(0x05), Some(QuicFrameType::StopSending));
        assert_eq!(QuicFrameType::from_byte(0x08), Some(QuicFrameType::Stream));
        assert_eq!(QuicFrameType::from_byte(0x0F), Some(QuicFrameType::Stream));
        assert_eq!(QuicFrameType::from_byte(0x10), Some(QuicFrameType::MaxData));
        assert_eq!(QuicFrameType::from_byte(0x11), Some(QuicFrameType::MaxStreamData));
        assert_eq!(QuicFrameType::from_byte(0x18), Some(QuicFrameType::NewConnectionId));
        assert_eq!(QuicFrameType::from_byte(0x19), Some(QuicFrameType::RetireConnectionId));
        assert_eq!(QuicFrameType::from_byte(0x1C), Some(QuicFrameType::ConnectionClose));
        assert_eq!(QuicFrameType::from_byte(0x1D), Some(QuicFrameType::ConnectionClose));
        assert_eq!(QuicFrameType::from_byte(0xFF), None);
    }

    // ─── ACK 帧解析测试 ────────────────────────────────────────────

    #[test]
    fn test_parse_ack_frame_empty_ranges() {
        // ACK 帧: type=0x02, largest_acknowledged=42, ack_delay=0, range_count=0, first_range=0
        let input = [0x02, 42, 0, 0, 0];
        let frame = parse_ack_frame(&input).unwrap();
        assert_eq!(frame.largest_acknowledged, 42);
        assert_eq!(frame.ack_delay, 0);
        assert_eq!(frame.ack_range_count, 0);
        assert_eq!(frame.first_ack_range, 0);
    }

    #[test]
    fn test_parse_ack_frame_with_ranges() {
        // ACK 帧: type=0x02, largest=50, delay=1000, count=1, first_range=10
        // range: gap=5, length=3
        // varint 编码:
        //   50 (1字节): [50]
        //   1000 (2字节): [0x43, 0xE8]
        //   1 (1字节): [1]
        //   10 (1字节): [10]
        //   5 (1字节): [5]
        //   3 (1字节): [3]
        let input = [
            0x02, // type
            50,   // largest_acknowledged
            0x43, 0xE8, // ack_delay = 1000
            1,    // range_count
            10,   // first_range
            5,    // gap
            3,    // length
        ];

        let frame = parse_ack_frame(&input).unwrap();
        assert_eq!(frame.largest_acknowledged, 50);
        assert_eq!(frame.ack_delay, 1000);
        assert_eq!(frame.ack_range_count, 1);
        assert_eq!(frame.first_ack_range, 10);
        // RFC 9000 §19.3:首个 range 最小编号 = 50 - 10 = 40;
        // 本 range 最小编号 = 40 - (gap 5 + 2) - length 3 = 30
        assert_eq!(frame.ranges[0], 30);
    }

    #[test]
    fn test_parse_ack_frame_too_short() {
        let input = [0x02, 1, 2];
        assert!(parse_ack_frame(&input).is_none());
    }

    #[test]
    fn test_parse_ack_frame_exceeds_max_ranges() {
        // range_count = MAX_ACK_RANGES + 1 = 9
        let input = [0x02, 100, 0, 9, 50];
        assert!(parse_ack_frame(&input).is_none());
    }

    // ─── STREAM 帧解析测试 ─────────────────────────────────────────

    #[test]
    fn test_parse_stream_frame_basic() {
        // STREAM 帧: type=0x08 (无 offset, 无 length, 无 FIN)
        // stream_id=0, data="hello"
        let input = [0x08, 0, b'h', b'e', b'l', b'l', b'o'];
        let frame = parse_stream_frame(&input).unwrap();
        assert_eq!(frame.stream_id, 0);
        assert_eq!(frame.offset, 0);
        assert_eq!(frame.length, 5);
        assert!(!frame.fin);
        assert_eq!(&frame.data[..5], b"hello");
    }

    #[test]
    fn test_parse_stream_frame_with_offset_and_fin() {
        // STREAM 帧: type=0x0F (0x08 | 0x04 | 0x02 | 0x01: offset=yes, length=yes, fin=yes)
        // stream_id=4, offset=1000, length=3, data="abc"
        // varint 编码:
        //   4 (1字节): [4]
        //   1000 (2字节): [0x43, 0xE8]
        //   3 (1字节): [3]
        let input = [
            0x0F, // type: offset=yes, length=yes, fin=yes
            4,    // stream_id
            0x43, 0xE8, // offset = 1000
            3,    // length
            b'a', b'b', b'c', // data
        ];

        let frame = parse_stream_frame(&input).unwrap();
        assert_eq!(frame.stream_id, 4);
        assert_eq!(frame.offset, 1000);
        assert_eq!(frame.length, 3);
        assert!(frame.fin);
        assert_eq!(&frame.data[..3], b"abc");
    }

    #[test]
    fn test_parse_stream_frame_too_short() {
        let input = [0x08];
        assert!(parse_stream_frame(&input).is_none());
    }

    #[test]
    fn test_parse_stream_frame_exceeds_max_data() {
        // 构造一个超过 MAX_STREAM_DATA_LEN 的 STREAM 帧
        // 使用 length 位 (0x0A) 来指定长度为 MAX_STREAM_DATA_LEN + 1
        // MAX_STREAM_DATA_LEN = 1024, 1025 的 varint 编码为 2 字节: [0x44, 0x01]
        let input = [
            0x0A, // type: length=yes, fin=no (0x08 | 0x02)
            0,    // stream_id
            0x44, 0x01, // length = 1025 (MAX_STREAM_DATA_LEN + 1)
            0, 0, 0, 0, 0, 0, 0, 0, // 填充
        ];
        assert!(parse_stream_frame(&input).is_none());
    }

    // ─── CONNECTION_CLOSE 帧解析测试 ──────────────────────────────

    #[test]
    fn test_parse_connection_close_frame() {
        // CONNECTION_CLOSE 帧: type=0x1C (非应用关闭)
        // error_code=256, reason="test"
        // varint 编码:
        //   256 (2字节): [0x41, 0x00]
        //   4 (1字节): [4]
        let input = [
            0x1C, // type
            0x41, 0x00, // error_code = 256
            4,    // reason_len
            b't', b'e', b's', b't', // reason = "test"
        ];

        let frame = parse_connection_close_frame(&input).unwrap();
        assert_eq!(frame.error_code, 256);
        assert_eq!(frame.reason_len, 4);
        assert_eq!(&frame.reason_phrase[..4], b"test");
        assert!(!frame.is_app_close);
    }

    #[test]
    fn test_parse_connection_close_frame_app_close() {
        // CONNECTION_CLOSE 帧: type=0x1D (应用关闭)
        // error_code=50, reason_len=0
        let input = [0x1D, 50, 0];
        let frame = parse_connection_close_frame(&input).unwrap();
        assert_eq!(frame.error_code, 50);
        assert_eq!(frame.reason_len, 0);
        assert!(frame.is_app_close);
    }

    #[test]
    fn test_parse_connection_close_frame_too_short() {
        let input = [0x1C, 1];
        assert!(parse_connection_close_frame(&input).is_none());
    }

    #[test]
    fn test_parse_connection_close_frame_reason_too_long() {
        let mut input = vec![0u8; 5];
        input[0] = 0x1C;
        input[1] = 0; // error_code = 0
        input[2] = 0xC0; // reason_len > 255 (varint indicating > 255)
        input[3] = 0x80;
        input[4] = 0x01;
        assert!(parse_connection_close_frame(&input).is_none());
    }

    // ─── RST_STREAM 帧解析测试 ────────────────────────────────────

    #[test]
    fn test_parse_rst_stream_frame() {
        // RST_STREAM 帧: type=0x04, stream_id=10, error_code=257
        // varint 编码:
        //   10 (1字节): [10]
        //   257 (2字节): [0x41, 0x01]
        let input = [
            0x04, // type
            10,   // stream_id
            0x41, 0x01, // error_code = 257
        ];

        let frame = parse_rst_stream_frame(&input).unwrap();
        assert_eq!(frame.stream_id, 10);
        assert_eq!(frame.error_code, 257);
    }

    #[test]
    fn test_parse_rst_stream_frame_too_short() {
        let input = [0x04, 5];
        assert!(parse_rst_stream_frame(&input).is_none());
    }

    // ─── MAX_DATA 帧解析测试 ──────────────────────────────────────

    #[test]
    fn test_parse_max_data_frame() {
        // MAX_DATA: type=0x10, max_data=1000
        // 1000 (2字节): [0x43, 0xE8]
        let input = [0x10, 0x43, 0xE8];
        let frame = parse_max_data_frame(&input).unwrap();
        assert_eq!(frame.max_data, 1000);
    }

    #[test]
    fn test_parse_max_data_frame_simple() {
        // MAX_DATA: type=0x10, max_data=50 (1字节 varint,范围 0-63)
        let input = [0x10, 50];
        let frame = parse_max_data_frame(&input).unwrap();
        assert_eq!(frame.max_data, 50);
    }

    #[test]
    fn test_parse_max_data_frame_too_short() {
        let input = [0x10];
        assert!(parse_max_data_frame(&input).is_none());
    }

    // ─── MAX_STREAM_DATA 帧解析测试 ───────────────────────────────

    #[test]
    fn test_parse_max_stream_data_frame() {
        // MAX_STREAM_DATA: type=0x11, stream_id=5, max_stream_data=2000
        // varint 编码:
        //   5 (1字节): [5]
        //   2000 (2字节): [0x47, 0xD0]
        let input = [
            0x11, // type
            5,    // stream_id
            0x47, 0xD0, // max_stream_data = 2000
        ];

        let frame = parse_max_stream_data_frame(&input).unwrap();
        assert_eq!(frame.stream_id, 5);
        assert_eq!(frame.max_stream_data, 2000);
    }

    #[test]
    fn test_parse_max_stream_data_frame_too_short() {
        let input = [0x11, 1];
        assert!(parse_max_stream_data_frame(&input).is_none());
    }

    // ─── 拥塞控制测试 ──────────────────────────────────────────────

    #[test]
    fn test_congestion_controller_initial() {
        let cc = CongestionController::new();
        assert_eq!(cc.cwnd, CongestionController::INITIAL_CWND);
        assert_eq!(cc.in_flight, 0);
        assert_eq!(cc.state(), CongestionState::SlowStart);
        assert_eq!(cc.available_bytes(), CongestionController::INITIAL_CWND);
    }

    #[test]
    fn test_congestion_controller_default() {
        let cc = CongestionController::default();
        assert_eq!(cc.cwnd, CongestionController::INITIAL_CWND);
        assert_eq!(cc.state(), CongestionState::SlowStart);
    }

    #[test]
    fn test_congestion_send_and_available() {
        let mut cc = CongestionController::new();
        cc.on_send(5000);
        assert_eq!(cc.in_flight, 5000);
        assert_eq!(cc.available_bytes(), CongestionController::INITIAL_CWND - 5000);
    }

    #[test]
    fn test_congestion_slow_start() {
        let mut cc = CongestionController::new();
        let initial_cwnd = cc.cwnd;

        // 模拟慢启动: 每次 ACK 增加 cwnd
        cc.on_ack(1460, 100_000); // ack 1 packet
        assert!(cc.cwnd > initial_cwnd);
        assert_eq!(cc.state(), CongestionState::SlowStart);
    }

    #[test]
    fn test_congestion_congestion_avoidance() {
        let mut cc = CongestionController::new();
        // 设置 ssthresh 通过 on_loss
        cc.on_send(20_000);
        cc.on_loss(15_000); // 触发 Recovery 状态,设置 ssthresh = cwnd * 7/10

        // 恢复后 ACK 所有剩余字节,使 in_flight 变为 0
        cc.on_ack(5000, 100_000); // in_flight 变为 0,状态转为 CongestionAvoidance
        assert_eq!(cc.state(), CongestionState::CongestionAvoidance);
    }

    #[test]
    fn test_congestion_loss() {
        let mut cc = CongestionController::new();
        cc.on_send(14_600); // 发送初始窗口
        cc.on_loss(7_300); // 丢包一半

        assert_eq!(cc.state(), CongestionState::Recovery);
        assert!(cc.cwnd < CongestionController::INITIAL_CWND);
        assert_eq!(cc.in_flight, 7_300);
    }

    #[test]
    fn test_congestion_timeout() {
        let mut cc = CongestionController::new();
        cc.on_send(10_000);
        cc.on_timeout();

        assert_eq!(cc.state(), CongestionState::SlowStart);
        assert_eq!(cc.cwnd, CongestionController::INITIAL_CWND);
        assert_eq!(cc.in_flight, 0);
        assert_eq!(cc.pto_count, 1);

        cc.on_timeout();
        assert_eq!(cc.pto_count, 2);
    }

    #[test]
    fn test_congestion_pto_calculation() {
        let mut cc = CongestionController::new();
        // 未测量 RTT 时返回默认值
        assert_eq!(cc.pto_us(), 100_000);

        cc.on_ack(1460, 50_000); // 测量 RTT
        assert!(cc.srtt > 0);
        let pto = cc.pto_us();
        assert!(pto > 50_000);

        cc.on_timeout();
        let pto2 = cc.pto_us();
        assert!(pto2 > pto); // PTO 指数退避
    }

    #[test]
    fn test_congestion_pto_reset() {
        let mut cc = CongestionController::new();
        cc.on_timeout();
        cc.on_timeout();
        assert_eq!(cc.pto_count, 2);
        cc.reset_pto();
        assert_eq!(cc.pto_count, 0);
    }

    #[test]
    fn test_congestion_recovery_to_avoidance() {
        let mut cc = CongestionController::new();
        cc.on_send(5000);
        cc.on_loss(2000);
        assert_eq!(cc.state(), CongestionState::Recovery);

        // 恢复完成(in_flight 归零后进入拥塞避免)
        cc.on_ack(3000, 100_000);
        assert_eq!(cc.in_flight, 0);
        assert_eq!(cc.state(), CongestionState::CongestionAvoidance);
    }

    #[test]
    fn test_congestion_max_cwnd_limit() {
        let mut cc = CongestionController::new();
        // 大量 ACK 推动 cwnd 增长
        for _ in 0..10000 {
            cc.on_ack(1460, 50_000);
        }
        assert!(cc.cwnd <= CongestionController::MAX_CWND);
    }

    #[test]
    fn test_constant_time_eq_empty_slices() {
        assert!(constant_time_eq(b"", b""));
    }

    #[test]
    fn test_constant_time_eq_single_byte() {
        assert!(constant_time_eq(b"A", b"A"));
        assert!(!constant_time_eq(b"A", b"B"));
    }

    #[test]
    fn test_constant_time_eq_first_byte_diff() {
        assert!(!constant_time_eq(b"abc", b"xbc"));
    }

    #[test]
    fn test_constant_time_eq_middle_byte_diff() {
        assert!(!constant_time_eq(b"abcdef", b"abXdef"));
    }

    #[test]
    fn test_constant_time_eq_last_byte_diff() {
        assert!(!constant_time_eq(b"abcdef", b"abcdeX"));
    }

    #[test]
    fn test_constant_time_eq_all_bytes_max() {
        let a = [0xFFu8; 32];
        let b = [0xFFu8; 32];
        assert!(constant_time_eq(&a, &b));
    }

    #[test]
    fn test_constant_time_eq_all_bytes_zero() {
        let a = [0x00u8; 32];
        let b = [0x00u8; 32];
        assert!(constant_time_eq(&a, &b));
    }

    #[test]
    fn test_constant_time_eq_zeros_vs_ones() {
        let a = [0x00u8; 32];
        let b = [0x01u8; 32];
        assert!(!constant_time_eq(&a, &b));
    }

    #[test]
    fn test_constant_time_eq_left_shorter() {
        assert!(!constant_time_eq(b"ab", b"abc"));
    }

    #[test]
    fn test_constant_time_eq_right_shorter() {
        assert!(!constant_time_eq(b"abc", b"ab"));
    }

    #[test]
    fn test_dcid_len_zero() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[],
                dcid: &[],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        assert_eq!(c.dcid_len, 0);
        assert_eq!(c.scid_len, 0);

        let found = conns.find_by_dcid(&[]);
        assert_eq!(found, None);

        conns.release(idx);
    }

    #[test]
    fn test_dcid_len_boundary_20() {
        let dcid = [0xAAu8; 20];
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[],
                dcid: &dcid,
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        assert_eq!(c.dcid_len, 20);

        let found = conns.find_by_dcid(&dcid);
        assert_eq!(found, Some(idx));

        conns.release(idx);
    }

    #[test]
    fn test_dcid_len_one_byte() {
        let dcid = [0x42u8; 1];
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[],
                dcid: &dcid,
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();

        let found = conns.find_by_dcid(&[0x42]);
        assert_eq!(found, Some(idx));
        assert_eq!(conns.find_by_dcid(&[0x43]), None);

        conns.release(idx);
    }

    #[test]
    fn test_quic_header_copy() {
        let hdr = QuicHeader::empty();
        let hdr2 = hdr;
        assert_eq!(hdr2.header_type, QuicHeaderType::Short);
    }

    #[test]
    fn test_quic_long_frame_types() {
        assert_eq!(LongFrameType::Initial as u8, 0);
        assert_eq!(LongFrameType::Handshake as u8, 1);
        assert_eq!(LongFrameType::ZeroRtt as u8, 2);
    }

    #[test]
    fn test_quic_conn_state_transitions() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();

        assert_eq!(c.state, QuicConnState::Initial);

        c.state = QuicConnState::Handshake;
        assert_eq!(c.state, QuicConnState::Handshake);

        c.state = QuicConnState::Established;
        assert_eq!(c.state, QuicConnState::Established);
        assert!(c.can_send_data());

        c.start_close();
        assert_eq!(c.state, QuicConnState::Closing);

        c.finish_close();
        assert!(c.is_closed());

        conns.release(idx);
    }

    #[test]
    fn test_quic_stream_id_bidirectional() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();

        let sid1 = c.alloc_local_stream_id(false).unwrap();
        assert_eq!(sid1, 0);
        let sid2 = c.alloc_local_stream_id(false).unwrap();
        assert_eq!(sid2, 4);
        let sid3 = c.alloc_local_stream_id(false).unwrap();
        assert_eq!(sid3, 8);

        conns.release(idx);
    }

    #[test]
    fn test_quic_stream_id_unidirectional() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();

        let sid1 = c.alloc_local_stream_id(true).unwrap();
        assert_eq!(sid1, 2);
        let sid2 = c.alloc_local_stream_id(true).unwrap();
        assert_eq!(sid2, 6);

        conns.release(idx);
    }

    #[test]
    fn test_congestion_state_enum() {
        let states = vec![
            CongestionState::SlowStart,
            CongestionState::CongestionAvoidance,
            CongestionState::Recovery,
        ];
        for state in states {
            let _ = format!("{:?}", state);
        }
    }

    #[test]
    fn test_quic_conn_table_capacity() {
        let conns = QuicConnectionTable::new(4);
        assert!(conns.capacity() >= 4);
    }

    #[test]
    fn test_quic_conn_active_count() {
        let mut conns = QuicConnectionTable::new(16);
        assert_eq!(conns.active_count(), 0);

        let idx1 = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        assert_eq!(conns.active_count(), 1);

        let idx2 = conns
            .allocate(QuicConnParams {
                scid: &[3u8],
                dcid: &[4u8],
                remote_addr: IpAddr::V4([10, 0, 0, 2]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        assert_eq!(conns.active_count(), 2);

        conns.release(idx1);
        assert_eq!(conns.active_count(), 1);

        conns.release(idx2);
        assert_eq!(conns.active_count(), 0);
    }

    #[test]
    fn test_verify_token_zero_attempts() {
        let mut conns = QuicConnectionTable::new(4);
        let idx = conns
            .allocate(QuicConnParams {
                scid: &[1u8],
                dcid: &[2u8],
                remote_addr: IpAddr::V4([10, 0, 0, 1]),
                remote_port: 0,
                local_addr: IpAddr::V4([127, 0, 0, 1]),
                local_port: 8443,
                ip_version: IpVersion::V4,
            })
            .unwrap();
        let c = conns.get(idx).unwrap();
        c.retry_token[..4].copy_from_slice(b"test");
        c.retry_token_len = 4;

        assert_eq!(c.token_attempts, 0);
        assert!(!c.address_verified);

        conns.release(idx);
    }

    // ── 连接迁移测试(RFC 9000 §9)──────────────────────────────────

    #[test]
    fn test_path_challenge_frame_type() {
        assert_eq!(QuicFrameType::from_byte(0x1a), Some(QuicFrameType::PathChallenge));
        assert_eq!(QuicFrameType::from_byte(0x1b), Some(QuicFrameType::PathResponse));
    }

    #[test]
    fn test_path_challenge_encode_decode() {
        let frame = PathChallengeFrame::new(0xDEADBEEFCAFEBABE);
        let mut buf = [0u8; 16];
        let n = frame.encode(&mut buf).unwrap();
        assert_eq!(n, 9);
        assert_eq!(buf[0], 0x1a);

        let decoded = parse_path_challenge_frame(&buf[..n]).unwrap();
        assert_eq!(decoded.data, 0xDEADBEEFCAFEBABE);
        assert_eq!(decoded, frame);
    }

    #[test]
    fn test_path_response_encode_decode() {
        let frame = PathResponseFrame::new(0x0123456789ABCDEF);
        let mut buf = [0u8; 16];
        let n = frame.encode(&mut buf).unwrap();
        assert_eq!(n, 9);
        assert_eq!(buf[0], 0x1b);

        let decoded = parse_path_response_frame(&buf[..n]).unwrap();
        assert_eq!(decoded.data, 0x0123456789ABCDEF);
        assert_eq!(decoded, frame);
    }

    #[test]
    fn test_parse_path_challenge_too_short() {
        assert!(parse_path_challenge_frame(&[0x1a, 0x01, 0x02]).is_none());
        assert!(parse_path_challenge_frame(&[0x00; 9]).is_none()); // wrong type
    }

    #[test]
    fn test_path_migration_initiate_and_validate() {
        let mut conn = QuicConnection::new(
            &[1, 2, 3, 4],
            &[5, 6, 7, 8],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        assert!(!conn.is_migration_in_progress());
        assert_eq!(conn.path_validation, PathValidationState::Idle);

        // 发起迁移到新地址
        let challenge = conn.initiate_path_migration(
            IpAddr::V4([192, 168, 1, 100]),
            5443,
            0xAAAABBBBCCCCDDDD,
        );
        assert!(conn.is_migration_in_progress());
        assert_eq!(conn.path_validation, PathValidationState::ChallengeSent);
        assert_eq!(challenge.data, 0xAAAABBBBCCCCDDDD);

        // 收到正确的 PATH_RESPONSE -> 迁移成功
        let ok = conn.handle_path_response(0xAAAABBBBCCCCDDDD);
        assert!(ok);
        assert_eq!(conn.path_validation, PathValidationState::Validated);
        // 远端地址已更新为新路径
        assert_eq!(conn.remote_addr, IpAddr::V4([192, 168, 1, 100]));
        assert_eq!(conn.remote_port, 5443);
    }

    #[test]
    fn test_path_migration_wrong_response_rejected() {
        let mut conn = QuicConnection::new(
            &[1, 2, 3, 4],
            &[5, 6, 7, 8],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        conn.initiate_path_migration(
            IpAddr::V4([192, 168, 1, 100]),
            5443,
            0xAAAABBBBCCCCDDDD,
        );

        // 错误的响应数据 -> 迁移失败
        let ok = conn.handle_path_response(0x1111222233334444);
        assert!(!ok);
        assert_eq!(conn.path_validation, PathValidationState::Failed);
        // 远端地址未变更
        assert_eq!(conn.remote_addr, IpAddr::V4([10, 0, 0, 1]));
        assert_eq!(conn.remote_port, 4433);
    }

    #[test]
    fn test_path_response_without_challenge_ignored() {
        let mut conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        // 无进行中的迁移,PATH_RESPONSE 应被忽略
        let ok = conn.handle_path_response(0xDEADBEEF);
        assert!(!ok);
        assert_eq!(conn.path_validation, PathValidationState::Idle);
    }

    #[test]
    fn test_handle_path_challenge_returns_response() {
        let conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        let response = conn.handle_path_challenge(0xCAFEBABE12345678);
        assert_eq!(response.data, 0xCAFEBABE12345678);
    }

    #[test]
    fn test_migration_anti_amplification() {
        let mut conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        conn.initiate_path_migration(
            IpAddr::V4([192, 168, 1, 100]),
            5443,
            0xAAAABBBBCCCCDDDD,
        );

        // 新路径接收 100 字节
        conn.record_migration_rx_bytes(100);
        // 可发送最多 300 字节(3x anti-amplification)
        conn.record_migration_tx_bytes(299);
        assert!(!conn.migration_amplification_limit_reached());

        // 达到 3x 限制
        conn.record_migration_tx_bytes(1);
        assert!(conn.migration_amplification_limit_reached());
    }

    #[test]
    fn test_reset_path_validation() {
        let mut conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        conn.initiate_path_migration(
            IpAddr::V4([192, 168, 1, 100]),
            5443,
            0xAAAABBBBCCCCDDDD,
        );
        conn.record_migration_tx_bytes(500);
        conn.record_migration_rx_bytes(200);

        conn.reset_path_validation();
        assert_eq!(conn.path_validation, PathValidationState::Idle);
        assert_eq!(conn.path_challenge_data, 0);
        assert_eq!(conn.migration_bytes_sent, 0);
        assert_eq!(conn.migration_bytes_received, 0);
    }

    // ── 流表索引碰撞修复测试(RFC 9000 §2.1)────────────────────────

    #[test]
    fn test_remote_idx_no_collision_across_types() {
        // RFC 9000 §2.1:流 ID 低 2 位编码类型,0/1/2/3 是四条不同的流。
        // 旧实现 `stream_id / 4` 把 0、1、2、3 全部映射到槽 0,造成碰撞。
        // 修复后流 ID 直接作为索引,四条流须落到不同槽位。
        assert_ne!(QuicStream::remote_idx(0), QuicStream::remote_idx(1));
        assert_ne!(QuicStream::remote_idx(0), QuicStream::remote_idx(2));
        assert_ne!(QuicStream::remote_idx(0), QuicStream::remote_idx(3));
        assert_ne!(QuicStream::remote_idx(1), QuicStream::remote_idx(2));
        // 流 0 与流 2(客户端双向 vs 客户端单向)须映射到不同槽位
        assert_ne!(QuicStream::remote_idx(0), QuicStream::remote_idx(2));
        // 同类型流保持步长 4 的索引间隔
        assert_eq!(QuicStream::remote_idx(4) - QuicStream::remote_idx(0), 4);
    }

    #[test]
    fn test_alloc_local_bidi_then_uni_no_conflict() {
        let mut conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        let bidi = conn.alloc_local_stream_id(false).unwrap();
        let uni = conn.alloc_local_stream_id(true).unwrap();
        assert_eq!(bidi, 0);
        assert_eq!(uni, 2);
        // 双向流与单向流须占用不同槽位,单向流不得覆盖双向流
        {
            let b = conn.get_local_stream(bidi).unwrap();
            assert_eq!(b.stream_id, 0);
            assert!(!b.is_uni);
        }
        {
            let u = conn.get_local_stream(uni).unwrap();
            assert_eq!(u.stream_id, 2);
            assert!(u.is_uni);
        }
    }

    #[test]
    fn test_remote_stream_slot_bounds_check_none() {
        let mut conn = QuicConnection::new(
            &[1],
            &[2],
            IpAddr::V4([10, 0, 0, 1]),
            4433,
            IpAddr::V4([10, 0, 0, 2]),
            8443,
            IpVersion::V4,
        );
        // 流 ID 超出预分配流表范围时须返回 None(防御性越界检查)
        let overflow = conn.streams.len() as u64;
        assert!(conn.get_or_create_remote_stream(overflow).is_none());
        assert!(conn.get_local_stream(overflow).is_none());
        // 合法范围内的流 ID 仍可正常创建
        assert!(conn.get_or_create_remote_stream(4).is_some());
    }

    // ── STOP_SENDING 帧类型修复测试(RFC 9000 §19.2)────────────────

    #[test]
    fn test_frame_type_stop_sending() {
        // RFC 9000 §19.2:0x04 = RESET_STREAM,0x05 = STOP_SENDING(不同帧)
        assert_eq!(QuicFrameType::from_byte(0x04), Some(QuicFrameType::RstStream));
        assert_eq!(QuicFrameType::from_byte(0x05), Some(QuicFrameType::StopSending));
        assert_ne!(
            QuicFrameType::from_byte(0x05),
            Some(QuicFrameType::RstStream)
        );
    }

    #[test]
    fn test_parse_stop_sending_frame() {
        // STOP_SENDING 帧: type=0x05, stream_id=10, error_code=257
        // varint 编码:
        //   10 (1字节): [10]
        //   257 (2字节): [0x41, 0x01]
        let input = [
            0x05, // type
            10,   // stream_id
            0x41, 0x01, // error_code = 257
        ];
        let frame = parse_stop_sending_frame(&input);
        assert!(frame.is_some(), "STOP_SENDING 帧应解析成功");
        let frame = frame.unwrap();
        assert_eq!(frame.stream_id, 10);
        assert_eq!(frame.error_code, 257);
    }

    #[test]
    fn test_parse_stop_sending_frame_too_short() {
        assert!(parse_stop_sending_frame(&[0x05, 5]).is_none());
    }
}