aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/libghostty-vt/src/terminal/stream.zig
blob: 29bdde7df66ed24a92db7b6709ac1b2bc5780fcd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
const streampkg = @This();
const std = @import("std");
const build_options = @import("terminal_options");
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const simd = @import("../simd/main.zig");
const lib = @import("lib.zig");
const Parser = @import("Parser.zig");
const ansi = @import("ansi.zig");
const charsets = @import("charsets.zig");
const device_attributes = @import("device_attributes.zig");
const device_status = @import("device_status.zig");
const csi = @import("csi.zig");
const kitty = @import("kitty.zig");
const modes = @import("modes.zig");
const osc = @import("osc.zig");
const sgr = @import("sgr.zig");
const continuationpkg = @import("stream_continuation.zig");
const UTF8Decoder = @import("UTF8Decoder.zig");
const MouseShape = @import("mouse.zig").Shape;

const log = std.log.scoped(.stream);

/// Flip this to true when you want verbose debug output for
/// debugging terminal stream issues. In addition to louder
/// output this will also disable the SIMD optimizations in
/// order to make it easier to see every byte. So if you're
/// debugging an issue in the SIMD code then you'll need to
/// do something else.
const debug = false;

/// The possible actions that can be emitted by the Stream
/// function for handling.
pub const Action = union(Key) {
    print: Print,
    print_slice: PrintSlice,
    print_repeat: usize,
    bell,
    backspace,
    horizontal_tab: u16,
    horizontal_tab_back: u16,
    linefeed,
    carriage_return,
    enquiry,
    invoke_charset: InvokeCharset,
    cursor_up: CursorMovement,
    cursor_down: CursorMovement,
    cursor_left: CursorMovement,
    cursor_right: CursorMovement,
    cursor_col: CursorMovement,
    cursor_row: CursorMovement,
    cursor_col_relative: CursorMovement,
    cursor_row_relative: CursorMovement,
    cursor_pos: CursorPos,
    cursor_style: ansi.CursorStyle,
    erase_display_below: bool,
    erase_display_above: bool,
    erase_display_complete: bool,
    erase_display_scrollback: bool,
    erase_display_scroll_complete: bool,
    erase_line_right: bool,
    erase_line_left: bool,
    erase_line_complete: bool,
    erase_line_right_unless_pending_wrap: bool,
    delete_chars: usize,
    erase_chars: usize,
    insert_lines: usize,
    insert_blanks: usize,
    delete_lines: usize,
    scroll_up: usize,
    scroll_down: usize,
    tab_clear_current,
    tab_clear_all,
    tab_set,
    tab_reset,
    index,
    next_line,
    reverse_index,
    full_reset,
    set_mode: Mode,
    reset_mode: Mode,
    save_mode: Mode,
    restore_mode: Mode,
    request_mode: Mode,
    request_mode_unknown: RawMode,
    top_and_bottom_margin: Margin,
    left_and_right_margin: Margin,
    left_and_right_margin_ambiguous,
    save_cursor,
    restore_cursor,
    modify_key_format: ansi.ModifyKeyFormat,
    mouse_shift_capture: bool,
    protected_mode_off,
    protected_mode_iso,
    protected_mode_dec,
    size_report: csi.SizeReportStyle,
    title_push: u16,
    title_pop: u16,
    xtversion,
    device_attributes: device_attributes.Req,
    device_status: DeviceStatus,
    kitty_keyboard_query,
    kitty_keyboard_push: KittyKeyboardFlags,
    kitty_keyboard_pop: u16,
    kitty_keyboard_set: KittyKeyboardFlags,
    kitty_keyboard_set_or: KittyKeyboardFlags,
    kitty_keyboard_set_not: KittyKeyboardFlags,
    dcs_hook: Parser.Action.DCS,
    dcs_put: u8,
    dcs_unhook,
    apc_start,
    apc_end: ApcEnd,
    apc_put: u8,
    apc_put_slice: ApcPutSlice,
    end_hyperlink,
    active_status_display: ansi.StatusDisplay,
    decaln,
    window_title: WindowTitle,
    report_pwd: ReportPwd,
    show_desktop_notification: ShowDesktopNotification,
    progress_report: osc.Command.ProgressReport,
    start_hyperlink: StartHyperlink,
    clipboard_contents: ClipboardContents,
    mouse_shape: MouseShape,
    configure_charset: ConfigureCharset,
    set_attribute: sgr.Attribute,
    kitty_color_report: kitty.color.OSC,
    color_operation: ColorOperation,
    semantic_prompt: SemanticPrompt,
    kitty_clipboard: KittyClipboard,
    kitty_dnd: KittyDnd,

    pub const Key = lib.Enum(
        lib.target,
        &.{
            "print",
            "print_slice",
            "print_repeat",
            "bell",
            "backspace",
            "horizontal_tab",
            "horizontal_tab_back",
            "linefeed",
            "carriage_return",
            "enquiry",
            "invoke_charset",
            "cursor_up",
            "cursor_down",
            "cursor_left",
            "cursor_right",
            "cursor_col",
            "cursor_row",
            "cursor_col_relative",
            "cursor_row_relative",
            "cursor_pos",
            "cursor_style",
            "erase_display_below",
            "erase_display_above",
            "erase_display_complete",
            "erase_display_scrollback",
            "erase_display_scroll_complete",
            "erase_line_right",
            "erase_line_left",
            "erase_line_complete",
            "erase_line_right_unless_pending_wrap",
            "delete_chars",
            "erase_chars",
            "insert_lines",
            "insert_blanks",
            "delete_lines",
            "scroll_up",
            "scroll_down",
            "tab_clear_current",
            "tab_clear_all",
            "tab_set",
            "tab_reset",
            "index",
            "next_line",
            "reverse_index",
            "full_reset",
            "set_mode",
            "reset_mode",
            "save_mode",
            "restore_mode",
            "request_mode",
            "request_mode_unknown",
            "top_and_bottom_margin",
            "left_and_right_margin",
            "left_and_right_margin_ambiguous",
            "save_cursor",
            "restore_cursor",
            "modify_key_format",
            "mouse_shift_capture",
            "protected_mode_off",
            "protected_mode_iso",
            "protected_mode_dec",
            "size_report",
            "title_push",
            "title_pop",
            "xtversion",
            "device_attributes",
            "device_status",
            "kitty_keyboard_query",
            "kitty_keyboard_push",
            "kitty_keyboard_pop",
            "kitty_keyboard_set",
            "kitty_keyboard_set_or",
            "kitty_keyboard_set_not",
            "dcs_hook",
            "dcs_put",
            "dcs_unhook",
            "apc_start",
            "apc_end",
            "apc_put",
            "apc_put_slice",
            "end_hyperlink",
            "active_status_display",
            "decaln",
            "window_title",
            "report_pwd",
            "show_desktop_notification",
            "progress_report",
            "start_hyperlink",
            "clipboard_contents",
            "mouse_shape",
            "configure_charset",
            "set_attribute",
            "kitty_color_report",
            "color_operation",
            "semantic_prompt",
            "kitty_clipboard",
            "kitty_dnd",
        },
    );

    /// C ABI functions.
    const c_union = lib.TaggedUnion(
        lib.target,
        @This(),
        // TODO: Before shipping an ABI-compatible libghostty, verify this.
        // This was just arbitrarily chosen for now.
        .{ .padding = [16]u64 },
    );
    pub const Tag = c_union.Tag;
    pub const Value = c_union.Value;
    pub const C = c_union.C;
    pub const CValue = c_union.CValue;
    pub const cval = c_union.cval;

    /// Field types
    pub const Print = struct {
        cp: u21,

        pub const C = extern struct {
            cp: u32,
        };

        pub fn cval(self: Print) Print.C {
            return .{ .cp = @intCast(self.cp) };
        }
    };

    /// A run of printable codepoints. This is emitted instead of
    /// individual print actions when the stream can decode multiple
    /// printable codepoints at once, so handlers can process them in
    /// batch with per-run rather than per-codepoint overhead (see
    /// Terminal.printSlice). A naive handler can simply loop and
    /// handle each codepoint like a print action.
    ///
    /// The slice is only valid for the duration of the handler call.
    pub const PrintSlice = struct {
        cps: []const u32,

        pub const C = extern struct {
            cps: [*]const u32,
            len: usize,
        };

        pub fn cval(self: PrintSlice) PrintSlice.C {
            return .{ .cps = self.cps.ptr, .len = self.cps.len };
        }
    };

    pub const ApcPutSlice = struct {
        bytes: []const u8,

        pub const C = extern struct {
            bytes: [*]const u8,
            len: usize,
        };

        pub fn cval(self: ApcPutSlice) ApcPutSlice.C {
            return .{ .bytes = self.bytes.ptr, .len = self.bytes.len };
        }
    };

    pub const ApcEnd = extern struct {
        /// False when CAN, SUB, or another aborting transition ended the APC.
        terminated: bool,
    };

    pub const InvokeCharset = lib.Struct(lib.target, struct {
        bank: charsets.ActiveSlot,
        charset: charsets.Slots,
        locking: bool,
    });

    pub const CursorMovement = extern struct {
        /// The value of the cursor movement. Depending on the tag of this
        /// union this may be an absolute value or it may be a relative
        /// value. For example, `cursor_up` is relative, but `cursor_row`
        /// is absolute.
        value: u16,
    };

    pub const CursorPos = extern struct {
        row: u16,
        col: u16,
    };

    pub const DeviceStatus = struct {
        request: device_status.Request,

        pub const C = u16;

        pub fn cval(self: DeviceStatus) DeviceStatus.C {
            return @bitCast(self.request);
        }
    };

    pub const Mode = struct {
        mode: modes.Mode,

        pub const C = u16;

        pub fn cval(self: Mode) Mode.C {
            return @bitCast(self.mode);
        }
    };

    pub const RawMode = extern struct {
        mode: u16,
        ansi: bool,
    };

    pub const Margin = extern struct {
        top_left: u16,
        bottom_right: u16,
    };

    pub const KittyKeyboardFlags = struct {
        flags: kitty.KeyFlags,

        pub const C = u8;

        pub fn cval(self: KittyKeyboardFlags) KittyKeyboardFlags.C {
            return @intCast(self.flags.int());
        }
    };

    pub const WindowTitle = struct {
        title: []const u8,

        pub const C = lib.String;

        pub fn cval(self: WindowTitle) WindowTitle.C {
            return .init(self.title);
        }
    };

    pub const ReportPwd = struct {
        url: []const u8,

        pub const C = lib.String;

        pub fn cval(self: ReportPwd) ReportPwd.C {
            return .init(self.url);
        }
    };

    pub const ShowDesktopNotification = struct {
        title: []const u8,
        body: []const u8,

        pub const C = extern struct {
            title: lib.String,
            body: lib.String,
        };

        pub fn cval(self: ShowDesktopNotification) ShowDesktopNotification.C {
            return .{
                .title = .init(self.title),
                .body = .init(self.body),
            };
        }
    };

    pub const StartHyperlink = struct {
        uri: []const u8,
        id: ?[]const u8,

        pub const C = extern struct {
            uri: lib.String,
            id: lib.String,
        };

        pub fn cval(self: StartHyperlink) StartHyperlink.C {
            return .{
                .uri = .init(self.uri),
                .id = .init(self.id orelse ""),
            };
        }
    };

    pub const ClipboardContents = struct {
        kind: u8,
        data: []const u8,
        terminator: osc.Terminator,

        pub const C = extern struct {
            kind: u8,
            data: lib.String,
        };

        pub fn cval(self: ClipboardContents) ClipboardContents.C {
            return .{
                .kind = self.kind,
                .data = .init(self.data),
            };
        }
    };

    pub const ConfigureCharset = lib.Struct(lib.target, struct {
        slot: charsets.Slots,
        charset: charsets.Charset,
    });

    pub const ColorOperation = struct {
        op: osc.color.Operation,
        requests: osc.color.List,
        terminator: osc.Terminator,

        pub const C = void;

        pub fn cval(_: ColorOperation) ColorOperation.C {
            return {};
        }
    };

    pub const SemanticPrompt = osc.Command.SemanticPrompt;

    pub const KittyClipboard = osc.Command.KittyClipboardProtocol;

    pub const KittyDnd = osc.Command.KittyDndProtocol;
};

/// Returns a type that can process a stream of tty control characters.
/// This will call the `vt` function on type T with the following signature:
///
///   fn(comptime action: Action.Key, value: Action.Value(action)) void
///
/// The handler type T can choose to react to whatever actions it cares
/// about in its pursuit of implementing a terminal emulator or other
/// functionality.
///
/// Note that printable text is delivered via `print_slice` actions
/// (runs of codepoints) whenever the stream can decode multiple
/// codepoints at once, and via `print` actions otherwise. Handlers
/// that care about text must handle both.
///
/// The Handler type must also have a `deinit` function.
///
/// The "comptime" key is on purpose (vs. a standard Zig tagged union)
/// because it allows the compiler to optimize away unimplemented actions.
/// e.g. you don't need to pay a conditional branching cost on every single
/// action because the Zig compiler codegens separate code paths for every
/// single action at comptime.
pub fn Stream(comptime H: type) type {
    return struct {
        const Self = @This();

        pub const Action = streampkg.Action;
        pub const Handler = H;

        const T = switch (@typeInfo(Handler)) {
            .pointer => |p| p.child,
            else => Handler,
        };

        handler: Handler,
        parser: Parser,
        utf8decoder: UTF8Decoder,
        continuation: ?continuationpkg.Tracker,

        pub const Options = struct {
            /// The handler initial value, must be set.
            handler: Handler,

            /// Allocator to use. If this is not set then the stream
            /// will be fully allocation free. There are some operations
            /// that will be dropped in this case such as OSC 52 clipboard
            /// ops.
            allocator: ?Allocator = null,

            /// Maximum size in bytes of the continuation suffix. If this is
            /// null or zero then continuation tracking is disabled. This is
            /// only applied when `allocator` is non-null; without an allocator
            /// continuation tracking is disabled. Feeding this continuation
            /// suffix into an equivalent stream at ground reconstructs the
            /// unfinished state without repeating committed terminal effects.
            /// Continuation tracking is only supported by TerminalStream.
            continuation_max_bytes: ?usize = null,
        };

        /// Initialize a stream. Without an allocator, operations that require
        /// heap allocation are dropped.
        ///
        /// As a concrete example of something that requires heap allocation,
        /// consider OSC 52 (clipboard operations) which can be arbitrarily
        /// large.
        ///
        /// This takes ownership of the handler and will call deinit
        /// when the stream is deinitialized.
        pub fn init(options: Options) Self {
            // Initialize the parser
            var parser: Parser = .init();
            if (options.allocator) |alloc| parser.osc_parser.alloc = alloc;

            // Initialize the continuation tracker if one is requested.
            var tracker: ?continuationpkg.Tracker = null;
            if (options.allocator) |alloc| {
                if (options.continuation_max_bytes) |max_bytes| {
                    if (max_bytes > 0) tracker = .init(alloc, max_bytes);
                }
            }

            return .{
                .handler = options.handler,
                .parser = parser,
                .utf8decoder = .{},
                .continuation = tracker,
            };
        }

        pub fn deinit(self: *Self) void {
            if (self.continuation) |*tracker| tracker.deinit();
            self.parser.deinit();
            self.handler.deinit();
        }

        /// Write the current continuation suffix directly to a caller-owned
        /// writer. The caller must pause and serialize access to this Stream.
        pub fn writeContinuation(
            self: *const Self,
            writer: *std.Io.Writer,
        ) (std.Io.Writer.Error || error{
            ContinuationDisabled,
            ContinuationUnavailable,
        })!void {
            const tracker = self.continuation orelse
                return error.ContinuationDisabled;
            if (tracker.broken)
                return error.ContinuationUnavailable;
            try tracker.write(writer);
        }

        /// True when no continuation suffix is needed to reproduce the
        /// stream's current parsing state.
        pub inline fn ground(self: *const Self) bool {
            // Parser ground alone is not sufficient because the UTF-8
            // decoder may have some state.
            return self.parser.state == .ground and self.utf8decoder.state == 0;
        }

        /// Update the continuation suffix after one complete feed call.
        /// Must only be called when tracking is enabled.
        fn trackContinuation(self: *Self, input: []const u8) void {
            const tracker = &self.continuation.?;

            // If we're in a ground state, we have no continuation suffix
            // to track by definition.
            if (self.ground()) {
                tracker.reset();
                return;
            }

            // Retain the part of this feed needed to replay the unfinished
            // state. When the parser is grounded here, the feed must have
            // ended inside a UTF-8 codepoint instead, because the ground
            // check above covers both state machines.
            tracker.append(
                if (self.parser.state != .ground) .vt else .utf8,
                input,
            );
        }

        /// Process a string of characters.
        pub inline fn nextSlice(self: *Self, input: []const u8) void {
            self.nextSliceUntracked(input);

            // Continuation tracking is opt-in and this branch predicts
            // perfectly, so disabled streams pay nothing else here.
            if (self.continuation != null) self.trackContinuation(input);
        }

        /// Process a string of characters, but only the shortest prefix
        /// needed to reach the ground state.
        ///
        /// The ground state is when the stream isn't in the middle of any
        /// type of sequence: UTF-8, ESC, CSI, OSC, etc. It is the stateless
        /// point of the stream.
        ///
        /// If the stream is already at ground then this consumes nothing
        /// and returns zero. A non-null return is the number of bytes consumed
        /// before reaching ground, including the byte that reaches it. A null
        /// return means the full slice was consumed without reaching ground.
        ///
        /// This is anywhere from 1% to 5% slower than nextSlice, depending
        /// on the types of inputs provided (e.g. OSC vs APC, whether it
        /// ever reaches ground, etc.).
        pub inline fn nextSliceUntilGround(
            self: *Self,
            input: []const u8,
        ) ?usize {
            const consumed = self.nextSliceUntilGroundUntracked(input);
            const consumed_len = consumed orelse input.len;
            if (self.continuation != null and consumed_len > 0) {
                self.trackContinuation(input[0..consumed_len]);
            }

            return consumed;
        }

        inline fn nextSliceUntilGroundUntracked(
            self: *Self,
            input: []const u8,
        ) ?usize {
            if (self.ground()) return 0;

            // Process UTF-8 if we're within that state.
            var offset: usize = 0;
            while (self.utf8decoder.state != 0) {
                if (offset >= input.len) return null;
                self.nextUtf8(input[offset]);
                offset += 1;
            }

            // Process non-UTF-8
            if (self.parser.state != .ground) {
                offset += self.consumeUntilGround(input[offset..]);
            }

            return if (self.ground()) offset else null;
        }

        inline fn nextSliceUntracked(self: *Self, input: []const u8) void {
            // Byte-at-a-time parsing in debug mode only. Even without
            // SIMD support (build_options.simd == false, e.g. wasm), the
            // batched path below is much faster than per-byte dispatch
            // because it decodes UTF-8 in bulk (via scalar fallbacks) and
            // hands printable runs to the handler as print_slice actions.
            if (comptime debug) {
                for (input) |c| self.nextUntracked(c);
                return;
            }

            // This is the maximum number of codepoints we can decode
            // at one time for this function call. This is somewhat arbitrary
            // so if someone can demonstrate a better number then we can switch.
            var cp_buf: [4096]u32 = undefined;

            // Split the input into chunks that fit into cp_buf.
            var i: usize = 0;
            while (true) {
                const len = @min(cp_buf.len, input.len - i);
                self.nextSliceCapped(input[i .. i + len], &cp_buf);
                i += len;
                if (i >= input.len) break;
            }
        }

        inline fn nextSliceCapped(
            self: *Self,
            input: []const u8,
            cp_buf: []u32,
        ) void {
            assert(input.len <= cp_buf.len);

            var offset: usize = 0;

            // If the scalar UTF-8 decoder was in the middle of processing
            // a code sequence, we continue until it's not.
            while (self.utf8decoder.state != 0) {
                if (offset >= input.len) return;
                self.nextUtf8(input[offset]);
                offset += 1;
            }
            if (offset >= input.len) return;

            // If we're not in the ground state then we process until
            // we are. This can happen if the last chunk of input put us
            // in the middle of a control sequence.
            offset += self.consumeUntilGround(input[offset..]);
            if (offset >= input.len) return;
            offset += self.consumeAllEscapes(input[offset..]);

            // If we're in the ground state then we can use SIMD to process
            // input until we see an ESC (0x1B), since all other characters
            // up to that point are just UTF-8.
            while (self.parser.state == .ground and offset < input.len) {
                const res = simd.vt.utf8DecodeUntilControlSeq(input[offset..], cp_buf);
                const cps = cp_buf[0..res.decoded];

                // Hand runs of printable codepoints to the handler as
                // print_slice actions so it can process them with
                // per-run rather than per-codepoint overhead.
                var i: usize = 0;
                while (i < cps.len) {
                    const cp = cps[i];
                    // C0 and UTF-8-decoded C1 controls never enter
                    // printable runs. A codepoint is one of those
                    // exactly when it has no bit set outside 0x9F:
                    // bits 0-4 and bit 7 cover 0x00-0x1F and
                    // 0x80-0x9F and nothing else, so a single
                    // AND-test classifies both ranges.
                    if ((cp & ~@as(u32, 0x9F)) == 0) {
                        @branchHint(.unlikely);
                        if (cp <= 0x1F) {
                            // C0 controls execute rather than print.
                            self.execute(@intCast(cp));
                        } else {
                            // C1 controls decoded from UTF-8 are ignored.
                            logUnsupportedOnce(
                                "ignoring UTF-8-decoded C1 controls, first: 0x{x}",
                                .{cp},
                                0x80,
                            );
                        }
                        i += 1;
                        continue;
                    }

                    // Find the end of the printable run. This is an
                    // early-exit search loop that LLVM won't
                    // auto-vectorize, and printable runs dominate real
                    // input, so scan several codepoints at a time
                    // manually (same idiom as the printSliceFill run
                    // scan).
                    var end = i + 1;
                    scan: {
                        if (simd.lanes(u32)) |lanes| {
                            const V = @Vector(lanes, u32);
                            // Non-printable (C0 or decoded C1) is
                            // equivalent to "no bit outside 0x9F is
                            // set": one AND-test per lane.
                            const mask: V = @splat(~@as(u32, 0x9F));
                            const zero: V = @splat(0);
                            while (end + lanes <= cps.len) {
                                const v: V = cps[end..][0..lanes].*;
                                const stop = (v & mask) == zero;
                                if (@reduce(.Or, stop)) {
                                    const bits: std.meta.Int(.unsigned, lanes) = @bitCast(stop);
                                    end += @ctz(bits);
                                    break :scan;
                                }
                                end += lanes;
                            }
                        }
                        while (end < cps.len and (cps[end] & ~@as(u32, 0x9F)) != 0) end += 1;
                    }
                    self.handler.vt(.print_slice, .{ .cps = cps[i..end] });
                    i = end;
                }
                // Consume the bytes we just processed.
                offset += res.consumed;

                if (offset >= input.len) return;

                // If our offset is NOT an escape then we must have a
                // partial UTF-8 sequence. In that case, we pass it off
                // to the scalar parser.
                if (input[offset] != 0x1B) {
                    const rem = input[offset..];
                    for (rem) |c| self.nextUtf8(c);
                    return;
                }

                // Process control sequences until we run out.
                offset += self.consumeAllEscapes(input[offset..]);
            }
        }

        /// Parses back-to-back escape sequences until none are left.
        /// Returns the number of bytes consumed from the provided input.
        ///
        /// Expects input to start with 0x1B, use consumeUntilGround first
        /// if the stream may be in the middle of an escape sequence.
        inline fn consumeAllEscapes(self: *Self, input: []const u8) usize {
            var offset: usize = 0;
            while (input[offset] == 0x1B) {
                self.parser.state = .escape;
                self.parser.clear();
                offset += 1;
                offset += self.consumeUntilGround(input[offset..]);
                if (offset >= input.len) return input.len;
            }
            return offset;
        }

        /// Parses escape sequences until the parser reaches the ground state.
        /// Returns the number of bytes consumed from the provided input.
        inline fn consumeUntilGround(self: *Self, input: []const u8) usize {
            var offset: usize = 0;
            while (self.parser.state != .ground) {
                if (offset >= input.len) return input.len;

                // Fast path for CSI entry: "ESC [" is by far the most
                // common escape sequence prefix, so handle the '[' and
                // the byte that follows it here rather than paying a
                // nextNonUtf8 call for each.
                if (self.parser.state == .escape and input[offset] == '[') {
                    self.parser.state = .csi_entry;
                    offset += 1;
                    continue;
                }

                if (comptime !@hasDecl(T, "vtRaw")) {
                    if (self.parser.state == .csi_entry) {
                        if (self.csiEntryByte(input[offset])) {
                            offset += 1;
                            continue;
                        }
                    }

                    // Bulk-consume CSI parameter bytes. This can't be
                    // used for handlers with a vtRaw hook because it
                    // dispatches the CSI directly (see nextNonUtf8).
                    if (self.parser.state == .csi_param) {
                        offset += self.consumeCsiParams(input[offset..]);
                        if (offset >= input.len) return input.len;
                        // If we're still in csi_param then the next byte
                        // isn't a parameter byte; let nextNonUtf8 below
                        // handle it. Otherwise re-check our state.
                        if (self.parser.state != .csi_param) continue;
                    }

                    // Bulk-consume APC string bytes into a single slice.
                    // APC payloads (e.g. Kitty graphics) can be megabytes
                    // of base64 data, so per-byte dispatch is far too slow.
                    // This can't be used for handlers with a vtRaw hook
                    // because it dispatches the slice directly.
                    if (self.parser.state == .sos_pm_apc_string) {
                        offset += self.consumeApcString(input[offset..]);
                        if (offset >= input.len) return input.len;

                        // Fast-path normal string termination. This matches
                        // Parser.next's exit and entry actions while avoiding
                        // the generic action loop for every completed APC.
                        switch (input[offset]) {
                            std.ascii.control_code.esc => {
                                self.parser.clear();
                                self.parser.state = .escape;
                                self.handler.vt(.apc_end, .{ .terminated = true });
                                offset += 1;
                                continue;
                            },
                            0x9C => {
                                self.parser.state = .ground;
                                self.handler.vt(.apc_end, .{ .terminated = true });
                                offset += 1;
                                continue;
                            },
                            else => {},
                        }

                        // Aborting transitions need the scalar path so the
                        // handler can distinguish them from terminators.
                    }

                    // Bulk-consume OSC string bytes into the OSC parser.
                    // OSC payloads (e.g. OSC 52 clipboard operations and
                    // the kitty clipboard protocol) can be megabytes of
                    // base64 data, so per-byte dispatch is far too slow.
                    // This can't be used for handlers with a vtRaw hook
                    // because the bytes never produce osc_put actions.
                    if (self.parser.state == .osc_string) {
                        offset += self.consumeOscString(input[offset..]);
                        if (offset >= input.len) return input.len;

                        // Fast-path normal string termination. This matches
                        // Parser.next's exit and entry actions while avoiding
                        // the generic action loop for every completed OSC.
                        switch (input[offset]) {
                            // The sequence should be terminated by a full
                            // ST ("ESC \"); the "\" that should follow is
                            // dispatched as a normal escape sequence.
                            std.ascii.control_code.esc => {
                                if (self.parser.osc_parser.end(
                                    std.ascii.control_code.esc,
                                )) |cmd| self.oscDispatch(cmd.*);
                                self.parser.clear();
                                self.parser.state = .escape;
                                offset += 1;
                                continue;
                            },
                            // BEL terminates the string directly.
                            std.ascii.control_code.bel => {
                                if (self.parser.osc_parser.end(
                                    std.ascii.control_code.bel,
                                )) |cmd| self.oscDispatch(cmd.*);
                                self.parser.state = .ground;
                                offset += 1;
                                continue;
                            },
                            // CAN/SUB abort and ignored C0 bytes go
                            // through the state machine below.
                            else => {},
                        }
                    }
                }

                self.nextNonUtf8(input[offset]);
                offset += 1;
            }
            return offset;
        }

        /// Fast path for a byte in the csi_entry state, the state right
        /// after "ESC [". Virtually every CSI sequence spends exactly
        /// one byte in this state, on either a digit, a private marker,
        /// or a final byte. Returns true if the byte was fully handled;
        /// false means the caller must process it through the general
        /// state machine.
        ///
        /// Must not be used by handlers with a vtRaw hook because the
        /// final byte case dispatches the CSI directly.
        inline fn csiEntryByte(self: *Self, c: u8) bool {
            comptime assert(!@hasDecl(T, "vtRaw"));
            assert(self.parser.state == .csi_entry);
            switch (c) {
                // First parameter digit.
                '0'...'9' => {
                    self.parser.state = .csi_param;
                    // param_acc is zero (cleared on escape entry)
                    // so accumulating is just the digit value.
                    self.parser.param_acc = c - '0';
                    self.parser.param_acc_idx = 1;
                },
                // An empty first parameter.
                ';' => {
                    self.parser.state = .csi_param;
                    self.parser.params[0] = 0;
                    self.parser.params_idx = 1;
                },
                // Private marker (e.g. '?' in "ESC [ ? 2004 h").
                0x3C...0x3F => {
                    self.parser.state = .csi_param;
                    self.parser.collect(c);
                },
                // A final byte: a parameterless CSI.
                0x40...0x7E => self.csiDispatchFinal(c),
                // Defer to the state machine for anything else
                // (C0 controls, intermediates, colon).
                else => return false,
            }
            return true;
        }

        /// Bulk-consume CSI parameter bytes (digits and separators)
        /// and, if reached, the final byte (dispatching the CSI).
        /// Returns the number of bytes consumed. Stops at the first
        /// byte that isn't handled here, leaving the parser in the
        /// csi_param state so the caller can process that byte.
        fn consumeCsiParams(self: *Self, input: []const u8) usize {
            const p = &self.parser;
            assert(p.state == .csi_param);

            // Accumulate parser state in locals for the hot loop.
            var acc = p.param_acc;
            var acc_idx = p.param_acc_idx;
            var idx = p.params_idx;

            var offset: usize = 0;
            while (offset < input.len) {
                const c = input[offset];
                switch (c) {
                    // A parameter digit.
                    '0'...'9' => {
                        if (idx < Parser.MAX_PARAMS) {
                            acc *|= 10;
                            acc +|= c - '0';
                            acc_idx |= 1;
                        }
                        offset += 1;
                    },

                    // A parameter separator.
                    ':', ';' => {
                        if (idx < Parser.MAX_PARAMS) {
                            p.params[idx] = acc;
                            if (c == ':') p.params_sep.set(idx);
                            idx += 1;
                            acc = 0;
                            acc_idx = 0;
                        }
                        offset += 1;
                    },

                    // A final byte: dispatch the CSI.
                    0x40...0x7E => {
                        p.param_acc = acc;
                        p.param_acc_idx = acc_idx;
                        p.params_idx = idx;
                        self.csiDispatchFinal(c);
                        return offset + 1;
                    },

                    // Anything else (C0 controls, intermediates, etc.)
                    // is handled by the caller.
                    else => break,
                }
            }

            p.param_acc = acc;
            p.param_acc_idx = acc_idx;
            p.params_idx = idx;
            return offset;
        }

        /// Bulk-consume APC string bytes and dispatch them as a single
        /// apc_put_slice action. Returns the number of bytes consumed.
        /// Stops at the first byte that is not an apc_put byte in the
        /// parse table, leaving it for the caller to process through
        /// the state machine. CAN, SUB, ESC, and most C1 bytes exit
        /// or abort the string state; 0xA0-0xFF are ignored by the
        /// table (not payload), so they can't be bulk-consumed either.
        ///
        /// Must not be used by handlers with a vtRaw hook because it
        /// dispatches the slice directly.
        fn consumeApcString(self: *Self, input: []const u8) usize {
            comptime assert(!@hasDecl(T, "vtRaw"));
            assert(self.parser.state == .sos_pm_apc_string);

            var end: usize = 0;
            if (comptime std.simd.suggestVectorLength(u8)) |vector_len| {
                const ByteVector = @Vector(vector_len, u8);
                while (end + vector_len <= input.len) {
                    const bytes: ByteVector = input[end..][0..vector_len].*;
                    const invalid = (bytes == @as(ByteVector, @splat(0x18))) |
                        (bytes == @as(ByteVector, @splat(0x1A))) |
                        (bytes == @as(ByteVector, @splat(0x1B))) |
                        (bytes >= @as(ByteVector, @splat(0x80)));
                    if (@reduce(.Or, invalid)) break;
                    end += vector_len;
                }
            }
            while (end < input.len) {
                switch (input[end]) {
                    // Not apc_put bytes: CAN/SUB/ESC and most C1 exit
                    // or abort the state; 0xA0-0xFF are ignored by it.
                    0x18, 0x1A, 0x1B, 0x80...0xFF => break,
                    // Everything else is an apc_put byte.
                    else => end += 1,
                }
            }

            if (end > 0) self.handler.vt(
                .apc_put_slice,
                .{ .bytes = input[0..end] },
            );
            return end;
        }

        /// Bulk-consume OSC string bytes into the OSC parser. Returns
        /// the number of bytes consumed. Stops at the first byte that
        /// is not an osc_put byte in the parse table, leaving it for
        /// the caller to process through the state machine. Every byte
        /// >= 0x20 is an osc_put byte; bytes below either terminate or
        /// abort the string (BEL, CAN, SUB, ESC) or are ignored.
        ///
        /// Must not be used by handlers with a vtRaw hook because the
        /// consumed bytes never produce osc_put actions.
        fn consumeOscString(self: *Self, input: []const u8) usize {
            comptime assert(!@hasDecl(T, "vtRaw"));
            assert(self.parser.state == .osc_string);

            var end: usize = 0;
            if (comptime std.simd.suggestVectorLength(u8)) |vector_len| {
                const ByteVector = @Vector(vector_len, u8);
                while (end + vector_len <= input.len) {
                    const bytes: ByteVector = input[end..][0..vector_len].*;
                    const stop = bytes < @as(ByteVector, @splat(0x20));
                    if (@reduce(.Or, stop)) break;
                    end += vector_len;
                }
            }
            while (end < input.len) {
                switch (input[end]) {
                    // Not osc_put bytes: BEL/CAN/SUB/ESC terminate or
                    // abort the state; other C0 bytes are ignored by it.
                    0x00...0x1F => break,
                    // Everything else is an osc_put byte.
                    else => end += 1,
                }
            }

            if (end > 0) self.parser.osc_parser.nextSlice(input[0..end]);
            return end;
        }

        /// Like nextSlice but takes one byte and is necessarily a scalar
        /// operation that can't use SIMD. Prefer nextSlice if you can and
        /// try to get multiple bytes at once.
        pub inline fn next(self: *Self, c: u8) void {
            self.nextUntracked(c);
            if (self.continuation != null) self.trackContinuation(&.{c});
        }

        inline fn nextUntracked(self: *Self, c: u8) void {
            // The scalar path can be responsible for decoding UTF-8.
            if (self.parser.state == .ground) {
                self.nextUtf8(c);
                return;
            }

            self.nextNonUtf8(c);
        }

        /// Process the next byte and print as necessary.
        ///
        /// This assumes we're in the UTF-8 decoding state. If we may not
        /// be in the UTF-8 decoding state call nextSlice or next.
        inline fn nextUtf8(self: *Self, c: u8) void {
            assert(self.parser.state == .ground);

            const res = self.utf8decoder.next(c);
            const consumed = res[1];
            if (res[0]) |codepoint| {
                self.handleCodepoint(codepoint);
            }
            if (!consumed) {
                // We optimize for the scenario where the text being
                // printed in the terminal ISN'T full of ill-formed
                // UTF-8 sequences.
                @branchHint(.unlikely);

                const retry = self.utf8decoder.next(c);
                // It should be impossible for the decoder
                // to not consume the byte twice in a row.
                assert(retry[1] == true);
                if (retry[0]) |codepoint| {
                    self.handleCodepoint(codepoint);
                }
            }
        }

        /// To be called whenever the utf-8 decoder produces a codepoint.
        ///
        /// This function is abstracted this way to handle the case where
        /// the decoder emits a 0x1B after rejecting an ill-formed sequence.
        inline fn handleCodepoint(self: *Self, c: u21) void {
            // We need to increase the eval branch limit because a lot of
            // tests end up running almost completely at comptime due to
            // a chain of inline functions.
            @setEvalBranchQuota(200_000);

            // C0 control or a C1 control decoded from UTF-8: exactly
            // the codepoints with no bit set outside 0x9F (bits 0-4
            // and bit 7 cover 0x00-0x1F and 0x80-0x9F and nothing
            // else), so the printable fast path stays a single
            // AND-test.
            if ((c & ~@as(u21, 0x9F)) == 0) {
                @branchHint(.unlikely);

                // ESC
                if (c == 0x1B) {
                    self.parser.state = .escape;
                    self.parser.clear();
                    return;
                }

                // Ignore C1 that came via UTF-8 decoding, matching xterm.
                if (c > 0x1F) {
                    logUnsupportedOnce(
                        "ignoring UTF-8-decoded C1 controls, first: 0x{x}",
                        .{c},
                        0x80,
                    );
                    return;
                }

                self.execute(@intCast(c));
                return;
            }
            self.print(@intCast(c));
        }

        /// Process the next character and call any callbacks if necessary.
        ///
        /// This assumes that we're not in the UTF-8 decoding state. If
        /// we may be in the UTF-8 decoding state call nextSlice or next.
        fn nextNonUtf8(self: *Self, c: u8) void {
            assert(self.parser.state != .ground);

            // Fast path for CSI entry.
            if (self.parser.state == .escape and c == '[') {
                self.parser.state = .csi_entry;
                return;
            }

            // The fast paths below dispatch actions directly rather than
            // going through Parser.next, so they'd bypass a handler's
            // vtRaw hook. Handlers with vtRaw (e.g. the inspector) use
            // the general path for anything that produces an action.
            const has_vt_raw = comptime @hasDecl(T, "vtRaw");

            // Fast path for CSI params.
            if (self.parser.state == .csi_param) csi_param: {
                // csi_param is the most common parser state
                // other than ground by a fairly wide margin.
                //
                // ref: https://github.com/qwerasd205/asciinema-stats
                @branchHint(.likely);
                switch (c) {
                    // A C0 escape (yes, this is valid):
                    0x00...0x0F => self.execute(c),
                    // We ignore C0 escapes > 0xF since execute
                    // doesn't have processing for them anyway:
                    0x10...0x17, 0x19, 0x1C...0x1F => {},
                    // We don't currently have any handling for
                    // 0x18 or 0x1A, but they should still move
                    // the parser state to ground.
                    0x18, 0x1A => self.parser.state = .ground,
                    // A parameter digit:
                    '0'...'9' => if (self.parser.params_idx < Parser.MAX_PARAMS) {
                        self.parser.param_acc *|= 10;
                        self.parser.param_acc +|= c - '0';
                        // The parser's CSI param action uses param_acc_idx
                        // to decide if there's a final param that needs to
                        // be consumed or not, but it doesn't matter really
                        // what it is as long as it's not 0.
                        self.parser.param_acc_idx |= 1;
                    },
                    // A parameter separator:
                    ':', ';' => if (self.parser.params_idx < Parser.MAX_PARAMS) {
                        self.parser.params[self.parser.params_idx] = self.parser.param_acc;
                        if (c == ':') self.parser.params_sep.set(self.parser.params_idx);
                        self.parser.params_idx += 1;

                        self.parser.param_acc = 0;
                        self.parser.param_acc_idx = 0;
                    },
                    // A final byte: dispatch the CSI directly.
                    0x40...0x7E => if (comptime !has_vt_raw) {
                        self.csiDispatchFinal(c);
                    } else break :csi_param,
                    // Explicitly ignored:
                    0x7F => {},
                    // Defer to the state machine to
                    // handle any other characters:
                    else => break :csi_param,
                }
                return;
            }

            // Fast path for CSI entry, the state right after "ESC [".
            if (comptime !has_vt_raw) {
                if (self.parser.state == .csi_entry) {
                    if (self.csiEntryByte(c)) return;
                }
            }

            // We explicitly inline this call here for performance reasons.
            //
            // We do this rather than mark Parser.next as inline because doing
            // that causes weird behavior in some tests- I'm not sure if they
            // miscompile or it's just very counter-intuitive comptime stuff,
            // but regardless, this is the easy solution.
            const actions = @call(.always_inline, Parser.next, .{ &self.parser, c });

            for (actions) |action_opt| {
                const action = action_opt orelse continue;
                if (comptime debug) log.info("action: {f}", .{action});

                // A handler can expose this to get the raw action before
                // it is further parsed. If this returns `true` then we skip
                // processing ourselves.
                if (@hasDecl(T, "vtRaw")) {
                    const skip = self.handler.vtRaw(action) catch |err| err: {
                        log.warn("error handling action manually err={} action={f}", .{
                            err,
                            action,
                        });
                        // Always skip erroneous actions because we can't
                        // be sure...
                        break :err true;
                    };

                    if (skip) continue;
                }

                switch (action) {
                    .print => |p| self.print(p),
                    .execute => |code| self.execute(code),
                    .csi_dispatch => |csi_action| self.csiDispatch(csi_action),
                    .esc_dispatch => |esc| self.escDispatch(esc),
                    .osc_dispatch => |cmd| self.oscDispatch(cmd),
                    .dcs_hook => |dcs| self.handler.vt(.dcs_hook, dcs),
                    .dcs_put => |code| self.handler.vt(.dcs_put, code),
                    .dcs_unhook => self.handler.vt(.dcs_unhook, {}),
                    .apc_start => self.handler.vt(.apc_start, {}),
                    .apc_put => |code| self.handler.vt(.apc_put, code),
                    .apc_end => self.handler.vt(.apc_end, .{
                        .terminated = c == std.ascii.control_code.esc or c == 0x9C,
                    }),
                }
            }
        }

        /// Finalize and dispatch a CSI directly from parser state for
        /// the fast paths in nextNonUtf8, without going through
        /// Parser.next. This must match the behavior of the parser's
        /// csi_dispatch action.
        fn csiDispatchFinal(self: *Self, c: u8) void {
            const p = &self.parser;
            p.state = .ground;

            // Ignore sequences with too many parameters, matching the
            // parser's behavior of dropping the dispatch entirely.
            if (p.params_idx >= Parser.MAX_PARAMS) {
                @branchHint(.unlikely);
                return;
            }

            // Finalize the last parameter if we have one.
            if (p.param_acc_idx > 0) {
                p.params[p.params_idx] = p.param_acc;
                p.params_idx += 1;
            }

            const action: Parser.Action.CSI = .{
                .intermediates = p.intermediates[0..p.intermediates_idx],
                .params = p.params[0..p.params_idx],
                .params_sep = p.params_sep,
                .final = c,
            };

            // We only allow colon or mixed separators for the 'm' command.
            if (c != 'm' and p.params_sep.count() > 0) {
                @branchHint(.cold);
                log.warn(
                    "CSI colon or mixed separators only allowed for 'm' command, got: {f}",
                    .{action},
                );
                return;
            }

            if (comptime debug) log.info("action: {f}", .{Parser.Action{ .csi_dispatch = action }});
            self.csiDispatch(action);
        }

        inline fn print(self: *Self, c: u21) void {
            self.handler.vt(.print, .{ .cp = c });
        }

        inline fn execute(self: *Self, c: u8) void {
            // If the character is > 0x7F, it's a C1 (8-bit) control,
            // which is strictly equivalent to `ESC` plus `c - 0x40`.
            if (c > 0x7F) {
                @branchHint(.unlikely);
                log.info("executing C1 0x{x} as ESC {c}", .{ c, c - 0x40 });
                self.escDispatch(.{
                    .intermediates = &.{},
                    .final = c - 0x40,
                });
                return;
            }

            const c0: ansi.C0 = @enumFromInt(c);
            if (comptime debug) log.info("execute: {f}", .{c0});
            switch (c0) {
                // We ignore SOH/STX: https://github.com/microsoft/terminal/issues/10786
                .NUL, .SOH, .STX => {},

                .ENQ => self.handler.vt(.enquiry, {}),
                .BEL => self.handler.vt(.bell, {}),
                .BS => self.handler.vt(.backspace, {}),
                .HT => self.handler.vt(.horizontal_tab, 1),
                .LF, .VT, .FF => self.handler.vt(.linefeed, {}),
                .CR => self.handler.vt(.carriage_return, {}),
                .SO => self.handler.vt(.invoke_charset, .{ .bank = .GL, .charset = .G1, .locking = false }),
                .SI => self.handler.vt(.invoke_charset, .{ .bank = .GL, .charset = .G0, .locking = false }),

                else => logUnsupportedOnce("invalid C0 character, ignoring: 0x{x}", .{c}, c),
            }
        }

        inline fn csiDispatch(self: *Self, input: Parser.Action.CSI) void {
            // The branch hints here are based on real world data
            // which indicates that the most common CSI finals are:
            //
            // 1. m
            // 2. H
            // 3. K
            // 4. A
            // 5. C
            // 6. X
            // 7. l
            // 8. h
            // 9. r
            //
            // Together, these 9 finals make up about 96% of all
            // CSI sequences encountered in real world scenarios.
            //
            // Additionally, within the prongs, unlikely branch
            // hints have been added to branches that deal with
            // invalid sequences/commands, this is in order to
            // optimize for the happy path where we're getting
            // valid data from the program we're running.
            //
            // ref: https://github.com/qwerasd205/asciinema-stats

            switch (input.final) {
                // CUU - Cursor Up
                'A', 'k' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        0 => self.handler.vt(.cursor_up, .{
                            .value = switch (input.params.len) {
                                0 => 1,
                                1 => input.params[0],
                                else => {
                                    @branchHint(.unlikely);
                                    log.warn("invalid cursor up command: {f}", .{input});
                                    return;
                                },
                            },
                        }),

                        else => log.warn(
                            "ignoring unimplemented CSI A with intermediates: {s}",
                            .{input.intermediates},
                        ),
                    }
                },

                // CUD - Cursor Down
                'B' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_down, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                @branchHint(.unlikely);
                                log.warn("invalid cursor down command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI B with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // CUF - Cursor Right
                'C' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        0 => self.handler.vt(.cursor_right, .{
                            .value = switch (input.params.len) {
                                0 => 1,
                                1 => input.params[0],
                                else => {
                                    @branchHint(.unlikely);
                                    log.warn("invalid cursor right command: {f}", .{input});
                                    return;
                                },
                            },
                        }),

                        else => log.warn(
                            "ignoring unimplemented CSI C with intermediates: {s}",
                            .{input.intermediates},
                        ),
                    }
                },

                // CUB - Cursor Left
                'D', 'j' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_left, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                @branchHint(.unlikely);
                                log.warn("invalid cursor left command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI D with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // CNL - Cursor Next Line
                'E' => switch (input.intermediates.len) {
                    0 => {
                        self.handler.vt(.cursor_down, .{
                            .value = switch (input.params.len) {
                                0 => 1,
                                1 => input.params[0],
                                else => {
                                    @branchHint(.unlikely);
                                    log.warn("invalid cursor up command: {f}", .{input});
                                    return;
                                },
                            },
                        });
                        self.handler.vt(.carriage_return, {});
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI E with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // CPL - Cursor Previous Line
                'F' => switch (input.intermediates.len) {
                    0 => {
                        self.handler.vt(.cursor_up, .{
                            .value = switch (input.params.len) {
                                0 => 1,
                                1 => input.params[0],
                                else => {
                                    @branchHint(.unlikely);
                                    log.warn("invalid cursor down command: {f}", .{input});
                                    return;
                                },
                            },
                        });
                        self.handler.vt(.carriage_return, {});
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI F with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // HPA - Cursor Horizontal Position Absolute
                // TODO: test
                'G', '`' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_col, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                @branchHint(.unlikely);
                                log.warn("invalid HPA command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI G with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // CUP - Set Cursor Position.
                // TODO: test
                'H', 'f' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        0 => {
                            const pos: streampkg.Action.CursorPos = switch (input.params.len) {
                                0 => .{ .row = 1, .col = 1 },
                                1 => .{ .row = input.params[0], .col = 1 },
                                2 => .{ .row = input.params[0], .col = input.params[1] },
                                else => {
                                    @branchHint(.unlikely);
                                    log.warn("invalid CUP command: {f}", .{input});
                                    return;
                                },
                            };
                            self.handler.vt(.cursor_pos, pos);
                        },

                        else => log.warn(
                            "ignoring unimplemented CSI H with intermediates: {s}",
                            .{input.intermediates},
                        ),
                    }
                },

                // CHT - Cursor Horizontal Tabulation
                'I' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.horizontal_tab, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid horizontal tab command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI I with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Erase Display
                'J' => {
                    const protected_: ?bool = switch (input.intermediates.len) {
                        0 => false,
                        1 => if (input.intermediates[0] == '?') true else null,
                        else => null,
                    };

                    const protected = protected_ orelse {
                        log.warn("invalid erase display command: {f}", .{input});
                        return;
                    };

                    const mode_: ?csi.EraseDisplay = switch (input.params.len) {
                        0 => .below,
                        1 => std.enums.fromInt(csi.EraseDisplay, input.params[0]),
                        else => null,
                    };

                    const mode = mode_ orelse {
                        log.warn("invalid erase display command: {f}", .{input});
                        return;
                    };

                    switch (mode) {
                        .below => self.handler.vt(.erase_display_below, protected),
                        .above => self.handler.vt(.erase_display_above, protected),
                        .complete => self.handler.vt(.erase_display_complete, protected),
                        .scrollback => self.handler.vt(.erase_display_scrollback, protected),
                        .scroll_complete => self.handler.vt(.erase_display_scroll_complete, protected),
                    }
                },

                // Erase Line
                'K' => {
                    @branchHint(.likely);
                    const protected_: ?bool = switch (input.intermediates.len) {
                        0 => false,
                        1 => if (input.intermediates[0] == '?') true else null,
                        else => null,
                    };

                    const protected = protected_ orelse {
                        @branchHint(.unlikely);
                        log.warn("invalid erase line command: {f}", .{input});
                        return;
                    };

                    const mode_: ?csi.EraseLine = switch (input.params.len) {
                        0 => .right,
                        1 => if (input.params[0] < 3) @enumFromInt(input.params[0]) else null,
                        else => null,
                    };

                    const mode = mode_ orelse {
                        @branchHint(.unlikely);
                        log.warn("invalid erase line command: {f}", .{input});
                        return;
                    };

                    switch (mode) {
                        .right => self.handler.vt(.erase_line_right, protected),
                        .left => self.handler.vt(.erase_line_left, protected),
                        .complete => self.handler.vt(.erase_line_complete, protected),
                        .right_unless_pending_wrap => self.handler.vt(.erase_line_right_unless_pending_wrap, protected),
                        _ => {
                            @branchHint(.unlikely);
                            log.warn("invalid erase line mode: {}", .{mode});
                        },
                    }
                },

                // IL - Insert Lines
                // TODO: test
                'L' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.insert_lines, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid IL command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI L with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // DL - Delete Lines
                // TODO: test
                'M' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.delete_lines, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid DL command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI M with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Delete Character (DCH)
                'P' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.delete_chars, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid delete characters command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI P with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Scroll Up (SD)

                'S' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.scroll_up, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid scroll up command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI S with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Scroll Down (SD)
                'T' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.scroll_down, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid scroll down command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI T with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Cursor Tabulation Control
                'W' => switch (input.intermediates.len) {
                    0 => {
                        if (input.params.len == 0 or
                            (input.params.len == 1 and input.params[0] == 0))
                        {
                            self.handler.vt(.tab_set, {});
                            return;
                        }

                        switch (input.params.len) {
                            0 => unreachable,

                            1 => switch (input.params[0]) {
                                0 => unreachable,

                                2 => self.handler.vt(.tab_clear_current, {}),

                                5 => self.handler.vt(.tab_clear_all, {}),

                                else => {},
                            },

                            else => {},
                        }

                        log.warn("invalid cursor tabulation control: {f}", .{input});
                        return;
                    },

                    1 => if (input.intermediates[0] == '?' and
                        input.params.len == 1 and
                        input.params[0] == 5)
                    {
                        self.handler.vt(.tab_reset, {});
                    } else log.warn("invalid cursor tabulation control: {f}", .{input}),

                    else => log.warn(
                        "ignoring unimplemented CSI W with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Erase Characters (ECH)
                'X' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        0 => self.handler.vt(.erase_chars, switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                @branchHint(.unlikely);
                                log.warn("invalid erase characters command: {f}", .{input});
                                return;
                            },
                        }),

                        else => log.warn(
                            "ignoring unimplemented CSI X with intermediates: {s}",
                            .{input.intermediates},
                        ),
                    }
                },

                // CHT - Cursor Horizontal Tabulation Back
                'Z' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.horizontal_tab_back, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid horizontal tab back command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI Z with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // HPR - Cursor Horizontal Position Relative
                'a' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_col_relative, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                log.warn("invalid HPR command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI a with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // Repeat Previous Char (REP)
                'b' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.print_repeat, switch (input.params.len) {
                        0 => 1,
                        1 => input.params[0],
                        else => {
                            log.warn("invalid print repeat command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI b with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // c - Device Attributes (DA1)
                'c' => {
                    const req: ?device_attributes.Req = switch (input.intermediates.len) {
                        0 => .primary,
                        1 => switch (input.intermediates[0]) {
                            '>' => .secondary,
                            '=' => .tertiary,
                            else => null,
                        },
                        else => null,
                    };

                    if (req) |r| {
                        self.handler.vt(.device_attributes, r);
                    } else {
                        logUnsupportedOnce(
                            "invalid device attributes command: {f}",
                            .{input},
                            if (input.params.len > 0) input.params[0] else 0,
                        );
                        return;
                    }
                },

                // VPA - Cursor Vertical Position Absolute
                'd' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_row, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                log.warn("invalid VPA command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI d with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // VPR - Cursor Vertical Position Relative
                'e' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.cursor_row_relative, .{
                        .value = switch (input.params.len) {
                            0 => 1,
                            1 => input.params[0],
                            else => {
                                log.warn("invalid VPR command: {f}", .{input});
                                return;
                            },
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI e with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // TBC - Tab Clear
                // TODO: test
                'g' => switch (input.intermediates.len) {
                    0 => {
                        const mode: csi.TabClear = switch (input.params.len) {
                            1 => std.enums.fromInt(csi.TabClear, input.params[0]) orelse {
                                log.warn("invalid tab clear mode: {}", .{input.params[0]});
                                return;
                            },
                            else => {
                                log.warn("invalid tab clear command: {f}", .{input});
                                return;
                            },
                        };
                        switch (mode) {
                            .current => self.handler.vt(.tab_clear_current, {}),
                            .all => self.handler.vt(.tab_clear_all, {}),
                            _ => log.warn("unknown tab clear mode: {}", .{mode}),
                        }
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI g with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                // SM - Set Mode
                'h' => mode: {
                    @branchHint(.likely);
                    const ansi_mode = ansi: {
                        if (input.intermediates.len == 0) break :ansi true;
                        if (input.intermediates.len == 1 and
                            input.intermediates[0] == '?') break :ansi false;

                        log.warn("invalid set mode command: {f}", .{input});
                        break :mode;
                    };

                    for (input.params) |mode_int| {
                        if (modes.modeFromInt(mode_int, ansi_mode)) |mode| {
                            self.handler.vt(.set_mode, .{ .mode = mode });
                        } else {
                            logUnsupportedOnce("unimplemented mode: {}", .{mode_int}, mode_int);
                        }
                    }
                },

                // RM - Reset Mode
                'l' => mode: {
                    @branchHint(.likely);
                    const ansi_mode = ansi: {
                        if (input.intermediates.len == 0) break :ansi true;
                        if (input.intermediates.len == 1 and
                            input.intermediates[0] == '?') break :ansi false;

                        log.warn("invalid set mode command: {f}", .{input});
                        break :mode;
                    };

                    for (input.params) |mode_int| {
                        if (modes.modeFromInt(mode_int, ansi_mode)) |mode| {
                            self.handler.vt(.reset_mode, .{ .mode = mode });
                        } else {
                            logUnsupportedOnce("unimplemented mode: {}", .{mode_int}, mode_int);
                        }
                    }
                },

                // SGR - Select Graphic Rendition
                'm' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        0 => {
                            // This is the most common case.
                            @branchHint(.likely);
                            // log.info("parse SGR params={any}", .{input.params});
                            var p: sgr.Parser = .{
                                .params = input.params,
                                .params_sep = input.params_sep,
                            };
                            while (p.next()) |attr| {
                                // log.info("SGR attribute: {}", .{attr});
                                self.handler.vt(.set_attribute, attr);
                            }
                        },

                        1 => switch (input.intermediates[0]) {
                            '>' => blk: {
                                if (input.params.len == 0) {
                                    // Reset
                                    self.handler.vt(.modify_key_format, .legacy);
                                    break :blk;
                                }

                                var format: ansi.ModifyKeyFormat = switch (input.params[0]) {
                                    0 => .legacy,
                                    1 => .cursor_keys,
                                    2 => .function_keys,
                                    4 => .other_keys_none,
                                    else => {
                                        @branchHint(.unlikely);
                                        log.warn("invalid setModifyKeyFormat: {f}", .{input});
                                        break :blk;
                                    },
                                };

                                if (input.params.len > 2) {
                                    @branchHint(.unlikely);
                                    log.warn("invalid setModifyKeyFormat: {f}", .{input});
                                    break :blk;
                                }

                                if (input.params.len == 2) {
                                    switch (format) {
                                        // We don't support any of the subparams yet for these.
                                        .legacy => {},
                                        .cursor_keys => {},
                                        .function_keys => {},

                                        // We only support the numeric form.
                                        .other_keys_none => switch (input.params[1]) {
                                            2 => format = .other_keys_numeric,
                                            else => {},
                                        },
                                        .other_keys_numeric_except => {},
                                        .other_keys_numeric => {},
                                    }
                                }

                                self.handler.vt(.modify_key_format, format);
                            },

                            else => logUnsupportedOnce(
                                "unknown CSI m with intermediate: {}",
                                .{input.intermediates[0]},
                                input.intermediates[0],
                            ),
                        },

                        else => {
                            // Nothing, but I wanted a place to put this comment:
                            // there are others forms of CSI m that have intermediates.
                            // `vim --clean` uses `CSI ? 4 m` and I don't know what
                            // that means.
                            log.warn(
                                "ignoring unimplemented CSI m with intermediates: {s}",
                                .{input.intermediates},
                            );
                        },
                    }
                },

                // TODO: test
                'n' => {
                    // Handle deviceStatusReport first
                    if (input.intermediates.len == 0 or
                        input.intermediates[0] == '?')
                    {
                        if (input.params.len != 1) {
                            log.warn("invalid device status report command: {f}", .{input});
                            return;
                        }

                        const question = question: {
                            if (input.intermediates.len == 0) break :question false;
                            if (input.intermediates.len == 1 and
                                input.intermediates[0] == '?') break :question true;

                            log.warn("invalid set mode command: {f}", .{input});
                            return;
                        };

                        const req = device_status.reqFromInt(input.params[0], question) orelse {
                            log.warn("invalid device status report command: {f}", .{input});
                            return;
                        };

                        self.handler.vt(.device_status, .{ .request = req });
                        return;
                    }

                    // Handle other forms of CSI n
                    switch (input.intermediates.len) {
                        0 => unreachable, // handled above

                        1 => switch (input.intermediates[0]) {
                            '>' => {
                                // This isn't strictly correct. CSI > n has parameters that
                                // control what exactly is being disabled. However, we
                                // only support reverting back to modify other keys in
                                // numeric except format.
                                self.handler.vt(.modify_key_format, .other_keys_numeric_except);
                            },

                            else => log.warn(
                                "unknown CSI n with intermediate: {}",
                                .{input.intermediates[0]},
                            ),
                        },

                        else => log.warn(
                            "ignoring unimplemented CSI n with intermediates: {s}",
                            .{input.intermediates},
                        ),
                    }
                },

                // DECRQM - Request Mode
                'p' => switch (input.intermediates.len) {
                    2 => decrqm: {
                        const ansi_mode = ansi: {
                            switch (input.intermediates.len) {
                                1 => if (input.intermediates[0] == '$') break :ansi true,
                                2 => if (input.intermediates[0] == '?' and
                                    input.intermediates[1] == '$') break :ansi false,
                                else => {},
                            }

                            log.warn(
                                "ignoring unimplemented CSI p with intermediates: {s}",
                                .{input.intermediates},
                            );
                            break :decrqm;
                        };

                        if (input.params.len != 1) {
                            log.warn("invalid DECRQM command: {f}", .{input});
                            break :decrqm;
                        }

                        const mode_raw = input.params[0];
                        const mode = modes.modeFromInt(mode_raw, ansi_mode);
                        if (mode) |m| {
                            self.handler.vt(.request_mode, .{ .mode = m });
                        } else {
                            self.handler.vt(.request_mode_unknown, .{
                                .mode = mode_raw,
                                .ansi = ansi_mode,
                            });
                        }
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI p with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                'q' => switch (input.intermediates.len) {
                    1 => switch (input.intermediates[0]) {
                        // DECSCUSR - Select Cursor Style
                        // TODO: test
                        ' ' => {
                            const style: ansi.CursorStyle = switch (input.params.len) {
                                0 => .default,
                                1 => switch (input.params[0]) {
                                    0 => .default,
                                    1 => .blinking_block,
                                    2 => .steady_block,
                                    3 => .blinking_underline,
                                    4 => .steady_underline,
                                    5 => .blinking_bar,
                                    6 => .steady_bar,
                                    else => {
                                        log.warn("invalid cursor style value: {}", .{input.params[0]});
                                        return;
                                    },
                                },
                                else => {
                                    log.warn("invalid set cursor style command: {f}", .{input});
                                    return;
                                },
                            };
                            self.handler.vt(.cursor_style, style);
                        },

                        // DECSCA
                        '"' => {
                            const mode_: ?ansi.ProtectedMode = switch (input.params.len) {
                                else => null,
                                0 => .off,
                                1 => switch (input.params[0]) {
                                    0, 2 => .off,
                                    1 => .dec,
                                    else => null,
                                },
                            };

                            const mode = mode_ orelse {
                                log.warn("invalid set protected mode command: {f}", .{input});
                                return;
                            };

                            switch (mode) {
                                .off => self.handler.vt(.protected_mode_off, {}),
                                .iso => self.handler.vt(.protected_mode_iso, {}),
                                .dec => self.handler.vt(.protected_mode_dec, {}),
                            }
                        },

                        // XTVERSION
                        '>' => self.handler.vt(.xtversion, {}),
                        else => {
                            log.warn(
                                "ignoring unimplemented CSI q with intermediates: {s}",
                                .{input.intermediates},
                            );
                        },
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI p with intermediates: {s}",
                        .{input.intermediates},
                    ),
                },

                'r' => {
                    @branchHint(.likely);
                    switch (input.intermediates.len) {
                        // DECSTBM - Set Top and Bottom Margins
                        0 => switch (input.params.len) {
                            0 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = 0, .bottom_right = 0 }),
                            1 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = input.params[0], .bottom_right = 0 }),
                            2 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = input.params[0], .bottom_right = input.params[1] }),
                            else => {
                                @branchHint(.unlikely);
                                log.warn("invalid DECSTBM command: {f}", .{input});
                            },
                        },

                        1 => switch (input.intermediates[0]) {
                            // Restore Mode
                            '?' => {
                                for (input.params) |mode_int| {
                                    if (modes.modeFromInt(mode_int, false)) |mode| {
                                        self.handler.vt(.restore_mode, .{ .mode = mode });
                                    } else {
                                        log.warn(
                                            "unimplemented restore mode: {}",
                                            .{mode_int},
                                        );
                                    }
                                }
                            },

                            else => log.warn(
                                "unknown CSI s with intermediate: {f}",
                                .{input},
                            ),
                        },

                        else => log.warn(
                            "ignoring unimplemented CSI s with intermediates: {f}",
                            .{input},
                        ),
                    }
                },

                's' => switch (input.intermediates.len) {
                    // DECSLRM
                    0 => switch (input.params.len) {
                        // CSI S is ambiguous with zero params so we defer
                        // to our handler to do the proper logic. If mode 69
                        // is set, then we should invoke DECSLRM, otherwise
                        // we should invoke SC.
                        0 => self.handler.vt(.left_and_right_margin_ambiguous, {}),
                        1 => self.handler.vt(.left_and_right_margin, .{ .top_left = input.params[0], .bottom_right = 0 }),
                        2 => self.handler.vt(.left_and_right_margin, .{ .top_left = input.params[0], .bottom_right = input.params[1] }),
                        else => log.warn("invalid DECSLRM command: {f}", .{input}),
                    },

                    1 => switch (input.intermediates[0]) {
                        '?' => {
                            for (input.params) |mode_int| {
                                if (modes.modeFromInt(mode_int, false)) |mode| {
                                    self.handler.vt(.save_mode, .{ .mode = mode });
                                } else {
                                    log.warn(
                                        "unimplemented save mode: {}",
                                        .{mode_int},
                                    );
                                }
                            }
                        },

                        // XTSHIFTESCAPE
                        '>' => capture: {
                            const capture = switch (input.params.len) {
                                0 => false,
                                1 => switch (input.params[0]) {
                                    0 => false,
                                    1 => true,
                                    else => {
                                        log.warn("invalid XTSHIFTESCAPE command: {f}", .{input});
                                        break :capture;
                                    },
                                },
                                else => {
                                    log.warn("invalid XTSHIFTESCAPE command: {f}", .{input});
                                    break :capture;
                                },
                            };

                            self.handler.vt(.mouse_shift_capture, capture);
                        },

                        else => log.warn(
                            "unknown CSI s with intermediate: {f}",
                            .{input},
                        ),
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI s with intermediates: {f}",
                        .{input},
                    ),
                },

                // XTWINOPS
                't' => switch (input.intermediates.len) {
                    0 => {
                        if (input.params.len > 0) {
                            switch (input.params[0]) {
                                14 => if (input.params.len == 1) {
                                    // report the text area size in pixels
                                    self.handler.vt(.size_report, .csi_14_t);
                                } else log.warn(
                                    "ignoring CSI 14 t with extra parameters: {f}",
                                    .{input},
                                ),
                                16 => if (input.params.len == 1) {
                                    // report cell size in pixels
                                    self.handler.vt(.size_report, .csi_16_t);
                                } else log.warn(
                                    "ignoring CSI 16 t with extra parameters: {f}",
                                    .{input},
                                ),
                                18 => if (input.params.len == 1) {
                                    // report screen size in characters
                                    self.handler.vt(.size_report, .csi_18_t);
                                } else log.warn(
                                    "ignoring CSI 18 t with extra parameters: {f}",
                                    .{input},
                                ),
                                21 => if (input.params.len == 1) {
                                    // report window title
                                    self.handler.vt(.size_report, .csi_21_t);
                                } else log.warn(
                                    "ignoring CSI 21 t with extra parameters: {f}",
                                    .{input},
                                ),
                                inline 22, 23 => |number| if ((input.params.len == 2 or
                                    input.params.len == 3) and
                                    // we only support window title
                                    (input.params[1] == 0 or
                                        input.params[1] == 2))
                                {
                                    // push/pop title
                                    const index: u16 = if (input.params.len == 3)
                                        input.params[2]
                                    else
                                        0;
                                    switch (number) {
                                        22 => self.handler.vt(.title_push, index),
                                        23 => self.handler.vt(.title_pop, index),
                                        else => @compileError("unreachable"),
                                    }
                                } else logUnsupportedOnce(
                                    "ignoring CSI 22/23 t with extra parameters: {f}",
                                    .{input},
                                    input.params[0],
                                ),
                                else => logUnsupportedOnce(
                                    "ignoring CSI t with unimplemented parameter: {f}",
                                    .{input},
                                    input.params[0],
                                ),
                            }
                        } else log.err(
                            "ignoring CSI t with no parameters: {f}",
                            .{input},
                        );
                    },
                    else => log.warn(
                        "ignoring unimplemented CSI t with intermediates: {f}",
                        .{input},
                    ),
                },

                'u' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.restore_cursor, {}),

                    // Kitty keyboard protocol
                    1 => switch (input.intermediates[0]) {
                        '?' => self.handler.vt(.kitty_keyboard_query, {}),

                        '>' => push: {
                            const flags: u5 = if (input.params.len == 1)
                                std.math.cast(u5, input.params[0]) orelse {
                                    log.warn("invalid pushKittyKeyboard command: {f}", .{input});
                                    break :push;
                                }
                            else
                                0;

                            self.handler.vt(.kitty_keyboard_push, .{ .flags = @as(kitty.KeyFlags, @bitCast(flags)) });
                        },

                        '<' => {
                            const number: u16 = if (input.params.len == 1)
                                input.params[0]
                            else
                                1;

                            self.handler.vt(.kitty_keyboard_pop, number);
                        },

                        '=' => set: {
                            const flags: u5 = if (input.params.len >= 1)
                                std.math.cast(u5, input.params[0]) orelse {
                                    log.warn("invalid setKittyKeyboard command: {f}", .{input});
                                    break :set;
                                }
                            else
                                0;

                            const number: u16 = if (input.params.len >= 2)
                                input.params[1]
                            else
                                1;

                            const action_tag: streampkg.Action.Tag = switch (number) {
                                1 => .kitty_keyboard_set,
                                2 => .kitty_keyboard_set_or,
                                3 => .kitty_keyboard_set_not,
                                else => {
                                    log.warn("invalid setKittyKeyboard command: {f}", .{input});
                                    break :set;
                                },
                            };

                            const kitty_flags: streampkg.Action.KittyKeyboardFlags = .{ .flags = @as(kitty.KeyFlags, @bitCast(flags)) };
                            switch (action_tag) {
                                .kitty_keyboard_set => self.handler.vt(.kitty_keyboard_set, kitty_flags),
                                .kitty_keyboard_set_or => self.handler.vt(.kitty_keyboard_set_or, kitty_flags),
                                .kitty_keyboard_set_not => self.handler.vt(.kitty_keyboard_set_not, kitty_flags),
                                else => unreachable,
                            }
                        },

                        else => log.warn(
                            "unknown CSI s with intermediate: {f}",
                            .{input},
                        ),
                    },

                    else => log.warn(
                        "ignoring unimplemented CSI u: {f}",
                        .{input},
                    ),
                },

                // ICH - Insert Blanks
                '@' => switch (input.intermediates.len) {
                    0 => self.handler.vt(.insert_blanks, switch (input.params.len) {
                        0 => 1,
                        1 => @max(1, input.params[0]),
                        else => {
                            @branchHint(.unlikely);
                            log.warn("invalid ICH command: {f}", .{input});
                            return;
                        },
                    }),

                    else => log.warn(
                        "ignoring unimplemented CSI @: {f}",
                        .{input},
                    ),
                },

                // DECSASD - Select Active Status Display
                '}' => decsasd: {
                    // Verify we're getting a DECSASD command
                    if (input.intermediates.len != 1 or input.intermediates[0] != '$') {
                        log.warn("unimplemented CSI callback: {f}", .{input});
                        break :decsasd;
                    }
                    if (input.params.len != 1) {
                        log.warn("unimplemented CSI callback: {f}", .{input});
                        break :decsasd;
                    }

                    const display: ansi.StatusDisplay = switch (input.params[0]) {
                        0 => .main,
                        1 => .status_line,
                        else => {
                            log.warn("unimplemented CSI callback: {f}", .{input});
                            break :decsasd;
                        },
                    };

                    self.handler.vt(.active_status_display, display);
                },

                else => log.warn("unimplemented CSI action: {f}", .{input}),
            }
        }

        inline fn oscDispatch(self: *Self, cmd: osc.Command) void {
            // The branch hints here are based on real world data
            // which indicates that the most common OSC commands are:
            //
            // 1. hyperlink_end
            // 2. change_window_title
            // 3. change_window_icon
            // 4. hyperlink_start
            // 5. report_pwd
            // 6. color_operation
            // 7. semantic_prompt
            //
            // Together, these 7 commands make up about 96% of all
            // OSC commands encountered in real world scenarios.
            //
            // Additionally, within the prongs, unlikely branch
            // hints have been added to branches that deal with
            // invalid sequences/commands, this is in order to
            // optimize for the happy path where we're getting
            // valid data from the program we're running.
            //
            // ref: https://github.com/qwerasd205/asciinema-stats

            switch (cmd) {
                .semantic_prompt => |sp| {
                    @branchHint(.likely);
                    self.handler.vt(.semantic_prompt, sp);
                },

                .change_window_title => |title| {
                    @branchHint(.likely);
                    if (!std.unicode.utf8ValidateSlice(title)) {
                        @branchHint(.unlikely);
                        log.warn("change title request: invalid utf-8, ignoring request", .{});
                        return;
                    }

                    self.handler.vt(.window_title, .{ .title = title });
                },

                .change_window_icon => |icon| {
                    @branchHint(.likely);
                    logUnsupportedOnce(
                        "OSC 1 (change icon) received and ignored icon={s}",
                        .{icon},
                        0,
                    );
                },

                .clipboard_contents => |clip| {
                    self.handler.vt(.clipboard_contents, .{
                        .kind = clip.kind,
                        .data = clip.data,
                        .terminator = clip.terminator,
                    });
                },

                .report_pwd => |v| {
                    @branchHint(.likely);
                    self.handler.vt(.report_pwd, .{ .url = v.value });
                },

                .mouse_shape => |v| {
                    const shape = MouseShape.fromString(v.value) orelse {
                        @branchHint(.unlikely);
                        log.warn("unknown cursor shape: {s}", .{v.value});
                        return;
                    };

                    self.handler.vt(.mouse_shape, shape);
                },

                .color_operation => |v| {
                    @branchHint(.likely);
                    self.handler.vt(.color_operation, .{
                        .op = v.op,
                        .requests = v.requests,
                        .terminator = v.terminator,
                    });
                },

                .kitty_color_protocol => |v| {
                    self.handler.vt(.kitty_color_report, v);
                },

                .show_desktop_notification => |v| {
                    self.handler.vt(.show_desktop_notification, .{
                        .title = v.title,
                        .body = v.body,
                    });
                },

                .hyperlink_start => |v| {
                    @branchHint(.likely);
                    self.handler.vt(.start_hyperlink, .{
                        .uri = v.uri,
                        .id = v.id,
                    });
                },

                .hyperlink_end => {
                    @branchHint(.likely);
                    self.handler.vt(.end_hyperlink, {});
                },

                .conemu_progress_report => |v| {
                    self.handler.vt(.progress_report, v);
                },

                .kitty_clipboard_protocol => |v| {
                    self.handler.vt(.kitty_clipboard, v);
                },

                .kitty_dnd_protocol => |v| {
                    self.handler.vt(.kitty_dnd, v);
                },

                .conemu_sleep,
                .conemu_show_message_box,
                .conemu_change_tab_title,
                .conemu_wait_input,
                .conemu_guimacro,
                .conemu_comment,
                .conemu_xterm_emulation,
                .conemu_output_environment_variable,
                .conemu_run_process,
                .kitty_text_sizing,
                .kitty_desktop_notification,
                .context_signal,
                => {
                    log.debug("unimplemented OSC callback: {}", .{cmd});
                },

                .invalid => {
                    @branchHint(.cold);
                    // This is an invalid internal state, not an invalid OSC
                    // string being parsed. We shouldn't see this.
                    log.warn("invalid OSC, should never happen", .{});
                },
            }
        }

        inline fn configureCharset(
            self: *Self,
            intermediates: []const u8,
            set: charsets.Charset,
        ) void {
            if (intermediates.len != 1) {
                log.warn("invalid charset intermediate: {any}", .{intermediates});
                return;
            }

            const slot: charsets.Slots = switch (intermediates[0]) {
                // TODO: support slots '-', '.', '/'

                '(' => .G0,
                ')' => .G1,
                '*' => .G2,
                '+' => .G3,
                else => {
                    @branchHint(.unlikely);
                    log.warn("invalid charset intermediate: {any}", .{intermediates});
                    return;
                },
            };

            self.handler.vt(.configure_charset, .{
                .slot = slot,
                .charset = set,
            });
        }

        inline fn escDispatch(
            self: *Self,
            action: Parser.Action.ESC,
        ) void {
            // The branch hints here are based on real world data
            // which indicates that the most common ESC finals are:
            //
            // 1. B
            // 2. \
            // 3. 0
            // 4. M
            // 5. 8
            // 6. 7
            // 7. >
            // 8. =
            //
            // Together, these 8 finals make up nearly 99% of all
            // ESC sequences encountered in real world scenarios.
            //
            // Additionally, within the prongs, unlikely branch
            // hints have been added to branches that deal with
            // invalid sequences/commands, this is in order to
            // optimize for the happy path where we're getting
            // valid data from the program we're running.
            //
            // ref: https://github.com/qwerasd205/asciinema-stats

            switch (action.final) {
                // Charsets
                'B' => {
                    @branchHint(.likely);
                    self.configureCharset(action.intermediates, .ascii);
                },
                'A' => self.configureCharset(action.intermediates, .british),
                '0' => {
                    @branchHint(.likely);
                    self.configureCharset(action.intermediates, .dec_special);
                },

                // DECSC - Save Cursor
                '7' => {
                    @branchHint(.likely);
                    switch (action.intermediates.len) {
                        0 => self.handler.vt(.save_cursor, {}),
                        else => {
                            @branchHint(.unlikely);
                            log.warn("invalid command: {f}", .{action});
                            return;
                        },
                    }
                },

                '8' => blk: {
                    @branchHint(.likely);
                    switch (action.intermediates.len) {
                        // DECRC - Restore Cursor
                        0 => {
                            self.handler.vt(.restore_cursor, {});
                            break :blk {};
                        },

                        1 => switch (action.intermediates[0]) {
                            // DECALN - Fill Screen with E
                            '#' => {
                                self.handler.vt(.decaln, {});
                                break :blk {};
                            },

                            else => {},
                        },

                        else => {}, // fall through
                    }

                    logUnsupportedOnce(
                        "unimplemented ESC action: {f}",
                        .{action},
                        action.final,
                    );
                },

                // IND - Index
                'D' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.index, {}),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid index command: {f}", .{action});
                        return;
                    },
                },

                // NEL - Next Line
                'E' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.next_line, {}),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid next line command: {f}", .{action});
                        return;
                    },
                },

                // HTS - Horizontal Tab Set
                'H' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.tab_set, {}),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid tab set command: {f}", .{action});
                        return;
                    },
                },

                // RI - Reverse Index
                'M' => {
                    @branchHint(.likely);
                    switch (action.intermediates.len) {
                        0 => self.handler.vt(.reverse_index, {}),
                        else => {
                            @branchHint(.unlikely);
                            log.warn("invalid reverse index command: {f}", .{action});
                            return;
                        },
                    }
                },

                // SS2 - Single Shift 2
                'N' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GL,
                        .charset = .G2,
                        .locking = true,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid single shift 2 command: {f}", .{action});
                        return;
                    },
                },

                // SS3 - Single Shift 3
                'O' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GL,
                        .charset = .G3,
                        .locking = true,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid single shift 3 command: {f}", .{action});
                        return;
                    },
                },

                // SPA - Start of Guarded Area
                'V' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.protected_mode_iso, {}),
                    else => log.warn("unimplemented ESC callback: {f}", .{action}),
                },

                // EPA - End of Guarded Area
                'W' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.protected_mode_off, {}),
                    else => log.warn("unimplemented ESC callback: {f}", .{action}),
                },

                // DECID
                'Z' => if (action.intermediates.len == 0) {
                    self.handler.vt(.device_attributes, .primary);
                } else log.warn("unimplemented ESC callback: {f}", .{action}),

                // RIS - Full Reset
                'c' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.full_reset, {}),
                    else => {
                        log.warn("invalid full reset command: {f}", .{action});
                        return;
                    },
                },

                // LS2 - Locking Shift 2
                'n' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GL,
                        .charset = .G2,
                        .locking = false,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid single shift 2 command: {f}", .{action});
                        return;
                    },
                },

                // LS3 - Locking Shift 3
                'o' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GL,
                        .charset = .G3,
                        .locking = false,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid single shift 3 command: {f}", .{action});
                        return;
                    },
                },

                // LS1R - Locking Shift 1 Right
                '~' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GR,
                        .charset = .G1,
                        .locking = false,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid locking shift 1 right command: {f}", .{action});
                        return;
                    },
                },

                // LS2R - Locking Shift 2 Right
                '}' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GR,
                        .charset = .G2,
                        .locking = false,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid locking shift 2 right command: {f}", .{action});
                        return;
                    },
                },

                // LS3R - Locking Shift 3 Right
                '|' => switch (action.intermediates.len) {
                    0 => self.handler.vt(.invoke_charset, .{
                        .bank = .GR,
                        .charset = .G3,
                        .locking = false,
                    }),
                    else => {
                        @branchHint(.unlikely);
                        log.warn("invalid locking shift 3 right command: {f}", .{action});
                        return;
                    },
                },

                // Set application keypad mode
                '=' => {
                    @branchHint(.likely);
                    switch (action.intermediates.len) {
                        0 => self.handler.vt(.set_mode, .{ .mode = .keypad_keys }),
                        else => log.warn("unimplemented setMode: {f}", .{action}),
                    }
                },

                // Reset application keypad mode
                '>' => {
                    @branchHint(.likely);
                    switch (action.intermediates.len) {
                        0 => self.handler.vt(.reset_mode, .{ .mode = .keypad_keys }),
                        else => log.warn("unimplemented setMode: {f}", .{action}),
                    }
                },

                // Sets ST (string terminator). We don't have to do anything
                // because our parser always accepts ST.
                '\\' => {
                    @branchHint(.likely);
                },

                else => logUnsupportedOnce(
                    "unimplemented ESC action: {f}",
                    .{action},
                    action.final,
                ),
            }
        }
    };
}

/// Logs an unsupported-input message at most once per distinct key
/// per process.
///
/// These messages are emitted in response to input that the terminal
/// application controls, so a misbehaving (or merely chatty) program
/// can trigger the same message millions of times, e.g. by toggling
/// an unimplemented mode on every frame. Each log call has a real
/// throughput cost (formatting plus a blocking write per message)
/// while adding no diagnostic value beyond the first occurrence.
///
/// The keys seen so far are tracked in a small fixed table (64 bytes)
/// instantiated per (format, argument type) tuple, i.e. roughly per
/// call site. Real streams only ever produce a handful of distinct
/// unsupported values per site, so if the table ever fills, messages
/// for further new values are suppressed as well: by that point the
/// log already shows this class of problem and unbounded distinct
/// values would flood it anyway.
fn logUnsupportedOnce(
    comptime format: []const u8,
    args: anytype,
    key: u16,
) void {
    // u32 slots so every u16 key is representable alongside an empty
    // sentinel and so 32-bit targets (e.g. wasm32) have native
    // atomics.
    const empty = std.math.maxInt(u32);
    const Static = struct {
        var seen: [16]u32 = @splat(empty);
    };

    // The atomics make concurrent streams safe: slots are only ever
    // claimed, never changed, so the scan can stop at the first empty
    // slot. The worst case race is a benign duplicate message.
    for (&Static.seen) |*slot| {
        const cur = @atomicLoad(u32, slot, .acquire);
        if (cur == key) return; // already logged
        if (cur != empty) continue; // other key, keep scanning

        // Empty slot: claim it for this key and log below.
        const actual = @cmpxchgStrong(
            u32,
            slot,
            empty,
            key,
            .acq_rel,
            .acquire,
        ) orelse break;

        // Lost the race: suppress if it was to the same key, keep
        // scanning otherwise.
        if (actual == key) return;
    } else return; // table full: suppress new values too

    log.warn(format, args);
}

test Action {
    // Forces the C type to be reified when the target is C, ensuring
    // all our types are C ABI compatible.
    _ = Action.C;
}

test "stream: print" {
    const H = struct {
        c: ?u21 = 0,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .print => self.c = value.cp,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.next('x');
    try testing.expectEqual(@as(u21, 'x'), s.handler.c.?);
}

test "simd: print invalid utf-8" {
    const H = struct {
        c: ?u21 = 0,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .print => self.c = value.cp,
                .print_slice => self.c = @intCast(value.cps[value.cps.len - 1]),
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice(&.{0xFF});
    try testing.expectEqual(@as(u21, 0xFFFD), s.handler.c.?);
}

test "simd: complete incomplete utf-8" {
    const H = struct {
        c: ?u21 = null,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .print => self.c = value.cp,
                .print_slice => self.c = @intCast(value.cps[value.cps.len - 1]),
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice(&.{0xE0}); // 3 byte
    try testing.expect(s.handler.c == null);
    s.nextSlice(&.{0xA0}); // still incomplete
    try testing.expect(s.handler.c == null);
    s.nextSlice(&.{0x80});
    try testing.expectEqual(@as(u21, 0x800), s.handler.c.?);
}

test "stream: ground state C0 controls are executed, not printed" {
    const H = struct {
        buf: [128]u21 = undefined,
        len: usize = 0,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .print => {
                    self.buf[self.len] = value.cp;
                    self.len += 1;
                },
                .print_slice => for (value.cps) |cp| {
                    self.buf[self.len] = @intCast(cp);
                    self.len += 1;
                },
                else => {},
            }
        }
    };

    // Every C0 control except ESC must never produce a print action
    // in the ground state. ESC is excluded because it begins an
    // escape sequence rather than executing.
    for (0..0x20) |c| {
        if (c == 0x1B) continue;

        // Scalar path.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            s.next('A');
            s.next(@intCast(c));
            s.next('B');
            try testing.expectEqual(@as(usize, 2), s.handler.len);
            try testing.expectEqual(@as(u21, 'A'), s.handler.buf[0]);
            try testing.expectEqual(@as(u21, 'B'), s.handler.buf[1]);
        }

        // Batched path.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            s.nextSlice(&.{ 'A', 'B', @intCast(c), 'C', 'D' });
            try testing.expectEqual(@as(usize, 4), s.handler.len);
            for ("ABCD", 0..) |expected, i| {
                try testing.expectEqual(@as(u21, expected), s.handler.buf[i]);
            }
        }

        // Batched path with a run long enough to exercise the
        // vectorized printable-run scan on either side of the control.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            var input: [65]u8 = @splat('A');
            input[32] = @intCast(c);
            s.nextSlice(&input);
            try testing.expectEqual(@as(usize, 64), s.handler.len);
            for (s.handler.buf[0..s.handler.len]) |cp| {
                try testing.expectEqual(@as(u21, 'A'), cp);
            }
        }
    }
}

test "stream: ground state UTF-8-decoded C1 controls are ignored" {
    const H = struct {
        buf: [128]u21 = undefined,
        len: usize = 0,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .print => {
                    self.buf[self.len] = value.cp;
                    self.len += 1;
                },
                .print_slice => for (value.cps) |cp| {
                    self.buf[self.len] = @intCast(cp);
                    self.len += 1;
                },
                else => {},
            }
        }
    };

    // Every C1 control that arrives as well-formed UTF-8 (a two byte
    // 0xC2-lead sequence) must be dropped: not printed and not
    // interpreted as a control (e.g. U+009B must not start a CSI).
    for (0x80..0xA0) |c| {
        const enc: [2]u8 = .{ 0xC2, @intCast(c) };

        // Scalar path.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            s.next('A');
            s.next(enc[0]);
            s.next(enc[1]);
            s.next('B');
            try testing.expectEqual(@as(usize, 2), s.handler.len);
            try testing.expectEqual(@as(u21, 'A'), s.handler.buf[0]);
            try testing.expectEqual(@as(u21, 'B'), s.handler.buf[1]);
        }

        // Batched path.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            s.nextSlice(&.{ 'A', 'B', enc[0], enc[1], 'C', 'D' });
            try testing.expectEqual(@as(usize, 4), s.handler.len);
            for ("ABCD", 0..) |expected, i| {
                try testing.expectEqual(@as(u21, expected), s.handler.buf[i]);
            }
        }

        // Batched path with a run long enough to exercise the
        // vectorized printable-run scan on either side of the control.
        {
            var s: Stream(H) = .init(.{ .handler = .{} });
            var input: [66]u8 = @splat('A');
            input[32] = enc[0];
            input[33] = enc[1];
            s.nextSlice(&input);
            try testing.expectEqual(@as(usize, 64), s.handler.len);
            for (s.handler.buf[0..s.handler.len]) |cp| {
                try testing.expectEqual(@as(u21, 'A'), cp);
            }
        }
    }

    // U+00A0 (NBSP), just past the C1 range, must still print.
    {
        var s: Stream(H) = .init(.{ .handler = .{} });
        s.nextSlice(&.{ 0xC2, 0xA0 });
        try testing.expectEqual(@as(usize, 1), s.handler.len);
        try testing.expectEqual(@as(u21, 0xA0), s.handler.buf[0]);
    }

    // A codepoint whose continuation byte falls in the C1 range must
    // still print: "Ü" is 0xC3 0x9C.
    {
        var s: Stream(H) = .init(.{ .handler = .{} });
        s.nextSlice("Ü");
        try testing.expectEqual(@as(usize, 1), s.handler.len);
        try testing.expectEqual(@as(u21, 0xDC), s.handler.buf[0]);
    }

    // A raw C1 byte is ill-formed UTF-8, not a decoded C1: it must
    // still produce a U+FFFD replacement.
    {
        var s: Stream(H) = .init(.{ .handler = .{} });
        s.nextSlice(&.{0x9B});
        try testing.expectEqual(@as(usize, 1), s.handler.len);
        try testing.expectEqual(@as(u21, 0xFFFD), s.handler.buf[0]);
    }
}

test "stream: cursor right (CUF)" {
    const H = struct {
        amount: u16 = 0,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .cursor_right => self.amount = value.value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[C");
    try testing.expectEqual(@as(u16, 1), s.handler.amount);

    s.nextSlice("\x1B[5C");
    try testing.expectEqual(@as(u16, 5), s.handler.amount);

    s.handler.amount = 0;
    s.nextSlice("\x1B[5;4C");
    try testing.expectEqual(@as(u16, 0), s.handler.amount);

    s.handler.amount = 0;
    s.nextSlice("\x1b[?3C");
    try testing.expectEqual(@as(u16, 0), s.handler.amount);
}

test "stream: dec set mode (SM) and reset mode (RM)" {
    const H = struct {
        mode: modes.Mode = @as(modes.Mode, @enumFromInt(1)),

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .set_mode => self.mode = value.mode,
                .reset_mode => self.mode = @as(modes.Mode, @enumFromInt(1)),
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[?6h");
    try testing.expectEqual(@as(modes.Mode, .origin), s.handler.mode);

    s.nextSlice("\x1B[?6l");
    try testing.expectEqual(@as(modes.Mode, @enumFromInt(1)), s.handler.mode);

    s.handler.mode = @as(modes.Mode, @enumFromInt(1));
    s.nextSlice("\x1B[6 h");
    try testing.expectEqual(@as(modes.Mode, @enumFromInt(1)), s.handler.mode);
}

test "stream: ansi set mode (SM) and reset mode (RM)" {
    const H = struct {
        mode: ?modes.Mode = null,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .set_mode => self.mode = value.mode,
                .reset_mode => self.mode = null,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[4h");
    try testing.expectEqual(@as(modes.Mode, .insert), s.handler.mode.?);

    s.nextSlice("\x1B[4l");
    try testing.expect(s.handler.mode == null);

    s.handler.mode = null;
    s.nextSlice("\x1B[>5h");
    try testing.expect(s.handler.mode == null);
}

test "stream: ansi set mode (SM) and reset mode (RM) with unknown value" {
    const H = struct {
        mode: ?modes.Mode = null,

        pub fn setMode(self: *@This(), mode: modes.Mode, v: bool) !void {
            self.mode = null;
            if (v) self.mode = mode;
        }

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            _ = self;
            _ = value;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[6h");
    try testing.expect(s.handler.mode == null);

    s.nextSlice("\x1B[6l");
    try testing.expect(s.handler.mode == null);
}

test "stream: restore mode" {
    const H = struct {
        const Self = @This();
        called: bool = false,

        pub fn vt(
            self: *Self,
            comptime action: Stream(Self).Action.Tag,
            value: Stream(Self).Action.Value(action),
        ) void {
            _ = value;
            switch (action) {
                .top_and_bottom_margin => self.called = true,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[?42r") |c| s.next(c);
    try testing.expect(!s.handler.called);
}

test "stream: pop kitty keyboard with no params defaults to 1" {
    const H = struct {
        const Self = @This();
        n: u16 = 0,

        pub fn vt(
            self: *Self,
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .kitty_keyboard_pop => self.n = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[<u") |c| s.next(c);
    try testing.expectEqual(@as(u16, 1), s.handler.n);
}

test "stream: DECSCA" {
    const H = struct {
        const Self = @This();
        v: ?ansi.ProtectedMode = null,

        pub fn vt(
            self: *Self,
            comptime action: Stream(Self).Action.Tag,
            value: Stream(Self).Action.Value(action),
        ) void {
            _ = value;
            switch (action) {
                .protected_mode_off => self.v = .off,
                .protected_mode_iso => self.v = .iso,
                .protected_mode_dec => self.v = .dec,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    {
        for ("\x1B[\"q") |c| s.next(c);
        try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?);
    }
    {
        for ("\x1B[0\"q") |c| s.next(c);
        try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?);
    }
    {
        for ("\x1B[2\"q") |c| s.next(c);
        try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?);
    }
    {
        for ("\x1B[1\"q") |c| s.next(c);
        try testing.expectEqual(ansi.ProtectedMode.dec, s.handler.v.?);
    }
}

test "stream: DECED, DECSED" {
    const H = struct {
        const Self = @This();
        mode: ?csi.EraseDisplay = null,
        protected: ?bool = null,

        pub fn vt(
            self: *Self,
            comptime action: anytype,
            value: anytype,
        ) void {
            switch (action) {
                .erase_display_below => {
                    self.mode = .below;
                    self.protected = value;
                },
                .erase_display_above => {
                    self.mode = .above;
                    self.protected = value;
                },
                .erase_display_complete => {
                    self.mode = .complete;
                    self.protected = value;
                },
                .erase_display_scrollback => {
                    self.mode = .scrollback;
                    self.protected = value;
                },
                .erase_display_scroll_complete => {
                    self.mode = .scroll_complete;
                    self.protected = value;
                },
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    {
        for ("\x1B[?J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?0J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?1J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.above, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?2J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.complete, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?3J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }

    {
        for ("\x1B[J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[0J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[1J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.above, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[2J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.complete, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[3J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        // Invalid and ignored by the handler
        for ("\x1B[>0J") |c| s.next(c);
        try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
}

test "stream: DECEL, DECSEL" {
    const H = struct {
        const Self = @This();
        mode: ?csi.EraseLine = null,
        protected: ?bool = null,

        pub fn vt(
            self: *Self,
            comptime action: anytype,
            value: anytype,
        ) void {
            switch (action) {
                .erase_line_right => {
                    self.mode = .right;
                    self.protected = value;
                },
                .erase_line_left => {
                    self.mode = .left;
                    self.protected = value;
                },
                .erase_line_complete => {
                    self.mode = .complete;
                    self.protected = value;
                },
                .erase_line_right_unless_pending_wrap => {
                    self.mode = .right_unless_pending_wrap;
                    self.protected = value;
                },
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    {
        for ("\x1B[?K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?0K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?1K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.left, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }
    {
        for ("\x1B[?2K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?);
        try testing.expect(s.handler.protected.?);
    }

    {
        for ("\x1B[K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[0K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[1K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.left, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        for ("\x1B[2K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
    {
        // Invalid and ignored by the handler
        for ("\x1B[<1K") |c| s.next(c);
        try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?);
        try testing.expect(!s.handler.protected.?);
    }
}

test "stream: DECSCUSR" {
    const H = struct {
        style: ?ansi.CursorStyle = null,

        pub fn vt(
            self: *@This(),
            comptime action: Stream(@This()).Action.Tag,
            value: Stream(@This()).Action.Value(action),
        ) void {
            switch (action) {
                .cursor_style => self.style = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[ q");
    try testing.expect(s.handler.style.? == .default);

    s.nextSlice("\x1B[1 q");
    try testing.expect(s.handler.style.? == .blinking_block);

    // Invalid and ignored by the handler
    s.nextSlice("\x1B[?0 q");
    try testing.expect(s.handler.style.? == .blinking_block);
}

test "stream: DECSCUSR without space" {
    const H = struct {
        style: ?ansi.CursorStyle = null,

        pub fn vt(
            self: *@This(),
            comptime action: Stream(@This()).Action.Tag,
            value: Stream(@This()).Action.Value(action),
        ) void {
            switch (action) {
                .cursor_style => self.style = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[q");
    try testing.expect(s.handler.style == null);

    s.nextSlice("\x1B[1q");
    try testing.expect(s.handler.style == null);
}

test "stream: XTSHIFTESCAPE" {
    const H = struct {
        escape: ?bool = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .mouse_shift_capture => self.escape = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[>2s");
    try testing.expect(s.handler.escape == null);

    s.nextSlice("\x1B[>s");
    try testing.expect(s.handler.escape.? == false);

    s.nextSlice("\x1B[>0s");
    try testing.expect(s.handler.escape.? == false);

    s.nextSlice("\x1B[>1s");
    try testing.expect(s.handler.escape.? == true);

    // Invalid and ignored by the handler
    s.nextSlice("\x1B[1 s");
    try testing.expect(s.handler.escape.? == true);
}

test "stream: change window title with invalid utf-8" {
    const H = struct {
        seen: bool = false,

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = value;
            switch (action) {
                .window_title => self.seen = true,
                else => {},
            }
        }
    };

    {
        var s: Stream(H) = .init(.{ .handler = .{} });
        s.nextSlice("\x1b]2;abc\x1b\\");
        try testing.expect(s.handler.seen);
    }

    {
        var s: Stream(H) = .init(.{ .handler = .{} });
        s.nextSlice("\x1b]2;abc\xc0\x1b\\");
        try testing.expect(!s.handler.seen);
    }
}

test "stream: osc 52 large payload in chunks" {
    const alloc = testing.allocator;

    const H = struct {
        const Self = @This();
        data: std.ArrayListUnmanaged(u8) = .empty,
        kind: u8 = 0,
        terminator: ?osc.Terminator = null,
        count: usize = 0,

        pub fn vt(
            self: *Self,
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .clipboard_contents => {
                    self.count += 1;
                    self.kind = value.kind;
                    self.terminator = value.terminator;
                    self.data.appendSlice(
                        testing.allocator,
                        value.data,
                    ) catch @panic("OOM");
                },
                else => {},
            }
        }
    };

    // A payload that far exceeds the fixed buffer so the allocating
    // capture is used, fed in chunk sizes that don't align with the
    // sequence so the bulk path sees every kind of boundary.
    const prefix = "\x1b]52;c;";
    const payload_len = 150_000;
    var input: std.ArrayListUnmanaged(u8) = .empty;
    defer input.deinit(alloc);
    try input.appendSlice(alloc, prefix);
    for (0..payload_len) |i| try input.append(
        alloc,
        'A' + @as(u8, @intCast(i % 26)),
    );
    try input.appendSlice(alloc, "\x1b\\");

    var s: Stream(H) = .init(.{ .handler = .{}, .allocator = alloc });
    defer s.parser.deinit();
    defer s.handler.data.deinit(alloc);

    var i: usize = 0;
    while (i < input.items.len) {
        const end = @min(i + 4093, input.items.len);
        s.nextSlice(input.items[i..end]);
        i = end;
    }

    try testing.expectEqual(@as(usize, 1), s.handler.count);
    try testing.expectEqual(@as(u8, 'c'), s.handler.kind);
    try testing.expectEqual(osc.Terminator.st, s.handler.terminator.?);
    try testing.expectEqualSlices(
        u8,
        input.items[prefix.len .. prefix.len + payload_len],
        s.handler.data.items,
    );
}

test "stream: osc bulk path matches per-byte path" {
    const alloc = testing.allocator;

    // Records every dispatch relevant to OSC processing in a
    // normalized text form so streams fed different ways can be
    // compared byte-for-byte.
    const H = struct {
        const Self = @This();
        alloc: Allocator,
        journal: std.ArrayListUnmanaged(u8) = .empty,

        fn record(self: *Self, comptime fmt: []const u8, args: anytype) void {
            const s = std.fmt.allocPrint(
                self.alloc,
                fmt,
                args,
            ) catch @panic("OOM");
            defer self.alloc.free(s);
            self.journal.appendSlice(self.alloc, s) catch @panic("OOM");
        }

        pub fn vt(
            self: *Self,
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            switch (action) {
                .clipboard_contents => self.record(
                    "clip kind={c} term={s} data={s}\n",
                    .{ value.kind, @tagName(value.terminator), value.data },
                ),
                .kitty_clipboard => self.record(
                    "kitty meta={s} payload={?s}\n",
                    .{ value.metadata, value.payload },
                ),
                .window_title => self.record(
                    "title {s}\n",
                    .{value.title},
                ),
                // Normalize prints to per-codepoint so the per-byte
                // and slice paths journal identically.
                .print => self.record("print {u}\n", .{value.cp}),
                .print_slice => for (value.cps) |cp| self.record(
                    "print {u}\n",
                    .{@as(u21, @intCast(cp))},
                ),
                else => {},
            }
        }
    };

    const cases = [_][]const u8{
        "\x1b]52;c;aGVsbG8=\x1b\\",
        "\x1b]52;c;aGVsbG8=\x07",
        "\x1b]52;;aGVsbG8=\x07",
        // Ignored C0 byte embedded in the payload.
        "\x1b]52;c;aGVs\x01bG8=\x07",
        // CAN and SUB aborts.
        "\x1b]52;c;aGVsbG8=\x18",
        "\x1b]52;c;aGVsbG8=\x1a",
        // C1 byte embedded in the payload is data.
        "\x1b]0;ab\x9ccd\x07",
        // Terminated with trailing printable text.
        "\x1b]0;a title\x07x",
        // Back-to-back sequences.
        "\x1b]2;another title\x1b\\\x1b]0;t2\x07",
        "\x1b]5522;type=write;aGVsbG8=\x1b\\",
        // Invalid OSC number.
        "\x1b]999;junk\x07",
        // Exceeds the fixed buffer: allocating capture.
        "\x1b]52;c;" ++ "y" ** 3000 ++ "\x1b\\",
        // Exceeds the fixed buffer: overflow, no dispatch.
        "\x1b]0;" ++ "x" ** 3000 ++ "\x07",
    };

    for (cases) |case| {
        // Reference: byte-at-a-time.
        var ref: Stream(H) = .init(.{
            .handler = .{ .alloc = alloc },
            .allocator = alloc,
        });
        defer ref.parser.deinit();
        defer ref.handler.journal.deinit(alloc);
        for (case) |c| ref.next(c);

        // The whole slice at once.
        {
            var s: Stream(H) = .init(.{
                .handler = .{ .alloc = alloc },
                .allocator = alloc,
            });
            defer s.parser.deinit();
            defer s.handler.journal.deinit(alloc);
            s.nextSlice(case);
            try testing.expectEqualSlices(
                u8,
                ref.handler.journal.items,
                s.handler.journal.items,
            );
        }

        // Split into two slices at every possible boundary.
        for (0..case.len + 1) |split| {
            var s: Stream(H) = .init(.{
                .handler = .{ .alloc = alloc },
                .allocator = alloc,
            });
            defer s.parser.deinit();
            defer s.handler.journal.deinit(alloc);
            s.nextSlice(case[0..split]);
            s.nextSlice(case[split..]);
            try testing.expectEqualSlices(
                u8,
                ref.handler.journal.items,
                s.handler.journal.items,
            );
        }
    }
}

test "stream: insert characters" {
    const H = struct {
        const Self = @This();
        called: bool = false,

        pub fn vt(
            self: *Self,
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = value;
            switch (action) {
                .insert_blanks => self.called = true,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[42@") |c| s.next(c);
    try testing.expect(s.handler.called);

    s.handler.called = false;
    for ("\x1B[?42@") |c| s.next(c);
    try testing.expect(!s.handler.called);
}

test "stream: insert characters explicit zero clamps to 1" {
    const H = struct {
        const Self = @This();
        value: ?usize = null,

        pub fn vt(
            self: *Self,
            comptime action: anytype,
            value: anytype,
        ) void {
            switch (action) {
                .insert_blanks => self.value = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[0@") |c| s.next(c);
    try testing.expectEqual(@as(usize, 1), s.handler.value.?);
}

test "stream: SCOSC" {
    const H = struct {
        const Self = @This();
        called: bool = false,

        pub fn vt(
            self: *Self,
            comptime action: Stream(Self).Action.Tag,
            value: Stream(Self).Action.Value(action),
        ) void {
            _ = value;
            switch (action) {
                .left_and_right_margin => @panic("bad"),
                .left_and_right_margin_ambiguous => self.called = true,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[s") |c| s.next(c);
    try testing.expect(s.handler.called);
}

test "stream: SCORC" {
    const H = struct {
        const Self = @This();
        called: bool = false,

        pub fn vt(
            self: *Self,
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            _ = value;
            switch (action) {
                .restore_cursor => self.called = true,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    for ("\x1B[u") |c| s.next(c);
    try testing.expect(s.handler.called);
}

test "stream: too many csi params" {
    const H = struct {
        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = self;
            _ = value;
            switch (action) {
                .cursor_right => unreachable,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1C");
}

test "stream: csi param too long" {
    const H = struct {
        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = self;
            _ = action;
            _ = value;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    s.nextSlice("\x1B[1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111C");
}

test "stream: send report with CSI t" {
    const H = struct {
        style: ?csi.SizeReportStyle = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .size_report => self.style = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[14t");
    try testing.expectEqual(csi.SizeReportStyle.csi_14_t, s.handler.style);

    s.nextSlice("\x1b[16t");
    try testing.expectEqual(csi.SizeReportStyle.csi_16_t, s.handler.style);

    s.nextSlice("\x1b[18t");
    try testing.expectEqual(csi.SizeReportStyle.csi_18_t, s.handler.style);

    s.nextSlice("\x1b[21t");
    try testing.expectEqual(csi.SizeReportStyle.csi_21_t, s.handler.style);
}

test "stream: invalid CSI t" {
    const H = struct {
        style: ?csi.SizeReportStyle = null,

        pub fn sendSizeReport(self: *@This(), style: csi.SizeReportStyle) void {
            self.style = style;
        }

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = self;
            _ = action;
            _ = value;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[19t");
    try testing.expectEqual(null, s.handler.style);
}

test "stream: CSI t push title" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_push => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[22;0t");
    try testing.expectEqual(@as(u16, 0), s.handler.index.?);
}

test "stream: CSI t push title with explicit window" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_push => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[22;2t");
    try testing.expectEqual(@as(u16, 0), s.handler.index.?);
}

test "stream: CSI t push title with explicit icon" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_push => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[22;1t");
    try testing.expectEqual(null, s.handler.index);
}

test "stream: CSI t push title with index" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_push => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[22;0;5t");
    try testing.expectEqual(@as(u16, 5), s.handler.index.?);
}

test "stream: CSI t pop title" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_pop => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[23;0t");
    try testing.expectEqual(@as(u16, 0), s.handler.index.?);
}

test "stream: CSI t pop title with explicit window" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_pop => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[23;2t");
    try testing.expectEqual(@as(u16, 0), s.handler.index.?);
}

test "stream: CSI t pop title with explicit icon" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_pop => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[23;1t");
    try testing.expectEqual(null, s.handler.index);
}

test "stream: CSI t pop title with index" {
    const H = struct {
        index: ?u16 = null,

        pub fn vt(
            self: *@This(),
            comptime action: streampkg.Action.Tag,
            value: streampkg.Action.Value(action),
        ) void {
            switch (action) {
                .title_pop => self.index = value,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[23;0;5t");
    try testing.expectEqual(@as(u16, 5), s.handler.index.?);
}

test "stream CSI W clear tab stops" {
    const H = struct {
        action: ?Action.Key = null,

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = value;
            self.action = action;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[2W");
    try testing.expectEqual(Action.Key.tab_clear_current, s.handler.action.?);

    s.nextSlice("\x1b[5W");
    try testing.expectEqual(Action.Key.tab_clear_all, s.handler.action.?);
}

test "stream CSI W tab set" {
    const H = struct {
        action: ?Action.Key = null,

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = value;
            self.action = action;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[W");
    try testing.expectEqual(Action.Key.tab_set, s.handler.action.?);

    s.handler.action = null;
    s.nextSlice("\x1b[0W");
    try testing.expectEqual(Action.Key.tab_set, s.handler.action.?);

    s.handler.action = null;
    s.nextSlice("\x1b[>W");
    try testing.expect(s.handler.action == null);

    s.handler.action = null;
    s.nextSlice("\x1b[99W");
    try testing.expect(s.handler.action == null);
}

test "stream CSI ? W reset tab stops" {
    const H = struct {
        action: ?Action.Key = null,

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            _ = value;
            self.action = action;
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    s.nextSlice("\x1b[?2W");
    try testing.expect(s.handler.action == null);

    s.nextSlice("\x1b[?5W");
    try testing.expectEqual(Action.Key.tab_reset, s.handler.action.?);

    // Invalid and ignored by the handler
    s.handler.action = null;
    s.nextSlice("\x1b[?1;2;3W");
    try testing.expect(s.handler.action == null);
}

test "stream: SGR with 17+ parameters for underline color" {
    const H = struct {
        attrs: ?sgr.Attribute = null,
        called: bool = false,

        pub fn vt(
            self: *@This(),
            comptime action: anytype,
            value: anytype,
        ) void {
            switch (action) {
                .set_attribute => {
                    self.attrs = value;
                    self.called = true;
                },
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });

    // Kakoune-style SGR with underline color as 17th parameter
    // This tests the fix where param 17 was being dropped
    s.nextSlice("\x1b[4:3;38;2;51;51;51;48;2;170;170;170;58;2;255;97;136;0m");
    try testing.expect(s.handler.called);
}

test "stream: tab clear with overflowing param" {
    // Regression test for a fuzz crash: CSI with a parameter value that
    // saturates to 65535 (u16 max) causes @enumFromInt to panic when
    // converting to TabClear (enum(u8)).
    const H = struct {
        called: bool = false,

        pub fn vt(
            self: *@This(),
            comptime action: Action.Tag,
            value: Action.Value(action),
        ) void {
            _ = value;
            switch (action) {
                .tab_clear_current, .tab_clear_all => self.called = true,
                else => {},
            }
        }
    };

    var s: Stream(H) = .init(.{ .handler = .{} });
    // This is the exact input from the fuzz crash (minus the mode byte):
    // CSI with a huge numeric param that saturates to 65535, followed by 'g'.
    s.nextSlice("\x1b[388888888888888888888888888888888888g\x1b[0m");
}

/// A test handler that accumulates APC bytes regardless of whether they
/// arrive per-byte (apc_put) or in bulk (apc_put_slice).
const ApcTestHandler = struct {
    buf: [256]u8 = undefined,
    len: usize = 0,
    slices: usize = 0,
    puts: usize = 0,
    started: usize = 0,
    ended: usize = 0,

    pub fn vt(
        self: *@This(),
        comptime action: Action.Tag,
        value: Action.Value(action),
    ) void {
        switch (action) {
            .apc_start => self.started += 1,
            .apc_end => self.ended += 1,
            .apc_put => {
                self.buf[self.len] = value;
                self.len += 1;
                self.puts += 1;
            },
            .apc_put_slice => {
                @memcpy(self.buf[self.len..][0..value.bytes.len], value.bytes);
                self.len += value.bytes.len;
                self.slices += 1;
            },
            else => {},
        }
    }
};

test "stream: apc bulk slice" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    s.nextSlice("\x1b_Gf=24,s=10,v=20;aGVsbG8=\x1b\\");

    try testing.expectEqual(@as(usize, 1), s.handler.started);
    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings(
        "Gf=24,s=10,v=20;aGVsbG8=",
        s.handler.buf[0..s.handler.len],
    );

    // With SIMD enabled the body must arrive as a single slice.
    if (comptime build_options.simd and !debug) {
        try testing.expectEqual(@as(usize, 1), s.handler.slices);
        try testing.expectEqual(@as(usize, 0), s.handler.puts);
    }
}

test "stream: apc bulk slice C1 ST" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    s.nextSlice("\x1b_Gpayload\x9c");

    try testing.expectEqual(@as(usize, 1), s.handler.started);
    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings(
        "Gpayload",
        s.handler.buf[0..s.handler.len],
    );
}

test "stream: apc bulk slice split across inputs" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    s.nextSlice("\x1b_Gf=24,s=10");
    s.nextSlice(",v=20;aGVs");
    s.nextSlice("bG8=\x1b\\");

    try testing.expectEqual(@as(usize, 1), s.handler.started);
    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings(
        "Gf=24,s=10,v=20;aGVsbG8=",
        s.handler.buf[0..s.handler.len],
    );
}

test "stream: apc bulk slice keeps C0 bytes as data" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    // BEL does not terminate an APC string; it is payload data.
    s.nextSlice("\x1b_Gx\x07y\x1b\\");

    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings("Gx\x07y", s.handler.buf[0..s.handler.len]);
}

test "stream: apc aborted by CAN" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    // CAN (0x18) aborts the APC string via the anywhere => ground
    // transition. Exiting the sos_pm_apc_string state emits apc_end,
    // and the trailing bytes are printed, not treated as APC data.
    s.nextSlice("\x1b_Gabcdefghijklmnopqrstuvwxyz0123456789\x18def");

    try testing.expectEqual(@as(usize, 1), s.handler.started);
    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings(
        "Gabcdefghijklmnopqrstuvwxyz0123456789",
        s.handler.buf[0..s.handler.len],
    );
}

test "stream: apc scalar path matches" {
    var s: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
    for ("\x1b_Gf=24;aGVsbG8=\x1b\\") |c| s.next(c);

    try testing.expectEqual(@as(usize, 1), s.handler.started);
    try testing.expectEqual(@as(usize, 1), s.handler.ended);
    try testing.expectEqualStrings(
        "Gf=24;aGVsbG8=",
        s.handler.buf[0..s.handler.len],
    );
}

test "stream: apc vector boundaries match scalar path" {
    const positions = [_]usize{ 15, 16, 17, 31, 32, 33, 63, 64, 65 };
    const controls = [_]u8{ 0x18, 0x1A, 0x1B, 0x80, 0xFF };

    for (positions) |position| for (controls) |control| {
        var input: [96]u8 = undefined;
        input[0..3].* = "\x1b_G".*;
        @memset(input[3 .. 3 + position], 'a');
        input[3 + position] = control;
        input[4 + position] = '\\';
        const bytes = input[0 .. 5 + position];

        var bulk: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
        bulk.nextSlice(bytes);
        var scalar: Stream(ApcTestHandler) = .init(.{ .handler = .{} });
        for (bytes) |byte| scalar.next(byte);

        try testing.expectEqual(scalar.handler.started, bulk.handler.started);
        try testing.expectEqual(scalar.handler.ended, bulk.handler.ended);
        try testing.expectEqualStrings(
            scalar.handler.buf[0..scalar.handler.len],
            bulk.handler.buf[0..bulk.handler.len],
        );
    };
}

const ContinuationTestHandler = struct {
    committed: usize = 0,
    apc_active: bool = false,
    apc_buf: [256]u8 = undefined,
    apc_len: usize = 0,
    dcs_active: bool = false,

    pub fn deinit(_: *@This()) void {}

    pub fn vt(
        self: *@This(),
        comptime action: Action.Tag,
        value: Action.Value(action),
    ) void {
        switch (action) {
            .apc_start => self.apc_active = true,
            .apc_put => {
                self.apc_buf[self.apc_len] = value;
                self.apc_len += 1;
            },
            .apc_put_slice => {
                @memcpy(
                    self.apc_buf[self.apc_len..][0..value.bytes.len],
                    value.bytes,
                );
                self.apc_len += value.bytes.len;
            },
            .dcs_hook => self.dcs_active = true,
            .dcs_put => {},
            .apc_end => {
                self.apc_active = false;
                self.apc_len = 0;
                self.committed += 1;
            },
            .dcs_unhook => {
                self.dcs_active = false;
                self.committed += 1;
            },
            .print => self.committed += 1,
            .print_slice => self.committed += value.cps.len,
            .print_repeat => self.committed += value,
            else => self.committed += 1,
        }
    }
};

const ContinuationNullHandler = struct {
    pub fn deinit(_: *@This()) void {}

    pub fn vt(
        _: *@This(),
        comptime _: Action.Tag,
        _: anytype,
    ) void {}
};

test "stream: nextSliceUntilGround stops at the earliest boundary" {
    const S = Stream(ContinuationTestHandler);
    var stream: S = .init(.{ .handler = .{} });
    defer stream.deinit();

    stream.nextSlice("\x1b[31");
    try testing.expect(!stream.ground());
    stream.handler.committed = 0;

    const input = "mABC\x1b[";
    const consumed = stream.nextSliceUntilGround(input).?;
    try testing.expectEqual(@as(usize, 1), consumed);
    try testing.expect(stream.ground());
    try testing.expectEqual(@as(usize, 1), stream.handler.committed);

    // The suffix was not inspected by the handler and can be processed after
    // the caller performs work at the boundary.
    stream.nextSlice(input[consumed..]);
    try testing.expect(!stream.ground());
    try testing.expectEqual(Parser.State.csi_entry, stream.parser.state);
    try testing.expectEqual(@as(usize, 4), stream.handler.committed);
}

test "stream: nextSliceUntilGround consumes all input without a boundary" {
    const S = Stream(ContinuationNullHandler);
    var stream: S = .init(.{ .handler = .{} });
    defer stream.deinit();

    try testing.expectEqual(
        @as(?usize, 0),
        stream.nextSliceUntilGround("unprocessed"),
    );
    try testing.expect(stream.ground());

    stream.nextSlice("\x1b[");
    try testing.expectEqual(
        @as(?usize, null),
        stream.nextSliceUntilGround("123"),
    );
    try testing.expect(!stream.ground());

    // A boundary on the final byte is distinguishable from exhausting the
    // input while still pending.
    try testing.expectEqual(
        @as(?usize, 1),
        stream.nextSliceUntilGround("m"),
    );
    try testing.expect(stream.ground());
}

test "stream: nextSliceUntilGround handles UTF-8 boundaries" {
    const S = Stream(ContinuationTestHandler);

    // A completed codepoint is committed synchronously, and the printable
    // suffix remains untouched.
    var valid: S = .init(.{ .handler = .{} });
    defer valid.deinit();
    valid.nextSlice(&.{0xF0});
    const valid_input = [_]u8{ 0x9F, 0x98, 0x84, 'X' };
    try testing.expectEqual(
        @as(?usize, 3),
        valid.nextSliceUntilGround(&valid_input),
    );
    try testing.expect(valid.ground());
    try testing.expectEqual(@as(usize, 1), valid.handler.committed);

    // A malformed continuation emits the replacement codepoint and retries
    // the same byte. Ground is observed after that complete byte operation.
    var malformed: S = .init(.{ .handler = .{} });
    defer malformed.deinit();
    malformed.nextSlice(&.{ 0xE0, 0xA0 });
    try testing.expectEqual(
        @as(?usize, 1),
        malformed.nextSliceUntilGround("A!"),
    );
    try testing.expect(malformed.ground());
    try testing.expectEqual(@as(usize, 2), malformed.handler.committed);

    // If the retried byte is ESC, the stream has begun VT state at the end of
    // that byte and must continue to the following ground boundary.
    var retry_escape: S = .init(.{ .handler = .{} });
    defer retry_escape.deinit();
    retry_escape.nextSlice(&.{ 0xE0, 0xA0 });
    try testing.expectEqual(
        @as(?usize, 3),
        retry_escape.nextSliceUntilGround("\x1b[mX"),
    );
    try testing.expect(retry_escape.ground());
}

test "stream: nextSliceUntilGround handles aborts and bulk strings" {
    const S = Stream(ContinuationTestHandler);

    var aborted: S = .init(.{ .handler = .{} });
    defer aborted.deinit();
    aborted.nextSlice("\x1b[123");
    try testing.expectEqual(
        @as(?usize, 1),
        aborted.nextSliceUntilGround(&.{ 0x18, 'X' }),
    );
    try testing.expect(aborted.ground());

    var apc: S = .init(.{ .handler = .{} });
    defer apc.deinit();
    apc.nextSlice("\x1b_Gseed");
    var input: [131]u8 = undefined;
    @memset(input[0..128], 'a');
    input[128..130].* = "\x1b\\".*;
    input[130] = 'X';
    try testing.expectEqual(
        @as(?usize, 130),
        apc.nextSliceUntilGround(&input),
    );
    try testing.expect(apc.ground());
}

test "stream: nextSliceUntilGround tracks only the consumed prefix" {
    const S = Stream(ContinuationNullHandler);
    var stream: S = .init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 64,
    });
    defer stream.deinit();

    stream.nextSlice("\x1b[31");
    try testing.expectEqual(
        @as(?usize, 1),
        stream.nextSliceUntilGround("mX\x1b["),
    );

    var buf: [64]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&buf);
    try stream.writeContinuation(&writer);
    try testing.expectEqual(@as(usize, 0), writer.buffered().len);

    stream.nextSlice("\x1b[");
    try testing.expectEqual(
        @as(?usize, null),
        stream.nextSliceUntilGround("123"),
    );
    var pending_writer: std.Io.Writer = .fixed(&buf);
    try stream.writeContinuation(&pending_writer);
    try testing.expectEqualStrings("\x1b[123", pending_writer.buffered());
}

test "stream: continuation lifecycle" {
    const S = Stream(ContinuationTestHandler);

    var disabled: S = .init(.{ .handler = .{} });
    defer disabled.deinit();
    var disabled_buf: [1]u8 = undefined;
    var disabled_writer: std.Io.Writer = .fixed(&disabled_buf);
    try testing.expectError(
        error.ContinuationDisabled,
        disabled.writeContinuation(&disabled_writer),
    );

    var zero_capacity: S = .init(.{
        .handler = .{},
        .continuation_max_bytes = 0,
    });
    defer zero_capacity.deinit();
    var zero_capacity_buf: [1]u8 = undefined;
    var zero_capacity_writer: std.Io.Writer = .fixed(&zero_capacity_buf);
    try testing.expectError(
        error.ContinuationDisabled,
        zero_capacity.writeContinuation(&zero_capacity_writer),
    );
    var no_allocator: S = .init(.{
        .handler = .{},
        .continuation_max_bytes = 64,
    });
    defer no_allocator.deinit();
    var no_allocator_buf: [1]u8 = undefined;
    var no_allocator_writer: std.Io.Writer = .fixed(&no_allocator_buf);
    try testing.expectError(
        error.ContinuationDisabled,
        no_allocator.writeContinuation(&no_allocator_writer),
    );

    var tracked = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 64,
    });
    defer tracked.deinit();

    tracked.nextSlice("complete input");
    var empty_buf: [1]u8 = undefined;
    var empty_writer: std.Io.Writer = .fixed(&empty_buf);
    try tracked.writeContinuation(&empty_writer);
    try testing.expectEqual(@as(usize, 0), empty_writer.end);

    tracked.nextSlice("\x1b[");
    var short_buf: [1]u8 = undefined;
    var short_writer: std.Io.Writer = .fixed(&short_buf);
    try testing.expectError(
        error.WriteFailed,
        tracked.writeContinuation(&short_writer),
    );

    var failing = testing.FailingAllocator.init(testing.allocator, .{
        .fail_index = 0,
    });
    var failing_stream = Stream(ContinuationNullHandler).init(.{
        .allocator = failing.allocator(),
        .handler = .{},
        .continuation_max_bytes = 64,
    });
    defer failing_stream.deinit();
    failing_stream.nextSlice("\x1b[");
    var unavailable_buf: [1]u8 = undefined;
    var unavailable_writer: std.Io.Writer = .fixed(&unavailable_buf);
    try testing.expectError(
        error.ContinuationUnavailable,
        failing_stream.writeContinuation(&unavailable_writer),
    );
}

test "stream: continuation suffixes are replay safe" {
    const Case = struct {
        input: []const u8,
        expected: []const u8,
    };
    const cases = [_]Case{
        .{ .input = "text\x1b", .expected = "\x1b" },
        .{ .input = "text\x1b[12;", .expected = "\x1b[12;" },
        .{ .input = "text\x1b[1\x07;2", .expected = "\x1b[1;2" },
        .{ .input = "text\x1b]2;hello", .expected = "\x1b]2;hello" },
        .{ .input = "text\x1b_Gabc", .expected = "\x1b_Gabc" },
        .{ .input = "text\x1bP+qabc", .expected = "\x1bP+qabc" },
        .{ .input = "text\xE0\xA0\xF0", .expected = "\xF0" },
        .{ .input = "text\x1b[12\x1b", .expected = "\x1b" },
        .{
            .input = "text\x1b[12\x9D2;title",
            .expected = "\x1b[12\x9D2;title",
        },
    };

    const S = Stream(ContinuationTestHandler);
    for (cases) |case| {
        var stream = S.init(.{
            .allocator = testing.allocator,
            .handler = .{},
            .continuation_max_bytes = 1024,
        });
        defer stream.deinit();
        stream.nextSlice(case.input);

        var buf: [1024]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try stream.writeContinuation(&writer);
        try testing.expectEqualStrings(case.expected, writer.buffered());
    }
}

test "stream: continuation reconstructs every unfinished VT state" {
    const Case = struct {
        input: []const u8,
        state: Parser.State,
    };
    const cases = [_]Case{
        .{ .input = "\x1b", .state = .escape },
        .{ .input = "\x1b(", .state = .escape_intermediate },
        .{ .input = "\x1b[", .state = .csi_entry },
        .{ .input = "\x1b[1", .state = .csi_param },
        .{ .input = "\x1b[1$", .state = .csi_intermediate },
        .{ .input = "\x1b[:", .state = .csi_ignore },
        .{ .input = "\x1bP", .state = .dcs_entry },
        .{ .input = "\x1bP1", .state = .dcs_param },
        .{ .input = "\x1bP1$", .state = .dcs_intermediate },
        .{ .input = "\x1bP1q", .state = .dcs_passthrough },
        .{ .input = "\x1bP:", .state = .dcs_ignore },
        .{ .input = "\x1b]2;title", .state = .osc_string },
        .{ .input = "\x1b_Gpayload", .state = .sos_pm_apc_string },
    };
    const S = Stream(ContinuationTestHandler);

    for (cases) |case| {
        var source = S.init(.{
            .allocator = testing.allocator,
            .handler = .{},
            .continuation_max_bytes = 1024,
        });
        defer source.deinit();
        source.nextSlice(case.input);
        try testing.expectEqual(case.state, source.parser.state);

        var buf: [1024]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try source.writeContinuation(&writer);

        var restored = S.init(.{
            .allocator = testing.allocator,
            .handler = .{},
            .continuation_max_bytes = 1024,
        });
        defer restored.deinit();
        restored.nextSlice(writer.buffered());
        try testing.expectEqual(@as(usize, 0), restored.handler.committed);
        try testing.expectEqual(source.parser.state, restored.parser.state);
        try testing.expectEqual(source.utf8decoder.state, restored.utf8decoder.state);
    }

    // Parser ground is still unfinished while the UTF-8 decoder is waiting
    // for the remaining bytes of a codepoint.
    var utf8 = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 4,
    });
    defer utf8.deinit();
    utf8.next(0xF0);
    try testing.expectEqual(Parser.State.ground, utf8.parser.state);
    try testing.expect(utf8.utf8decoder.state != 0);
    var utf8_buf: [4]u8 = undefined;
    var utf8_writer: std.Io.Writer = .fixed(&utf8_buf);
    try utf8.writeContinuation(&utf8_writer);
    try testing.expectEqualSlices(u8, &.{0xF0}, utf8_writer.buffered());
}

test "stream: continuation is chunking-independent and idempotent" {
    const S = Stream(ContinuationTestHandler);
    const input = "committed\x1b[1\x07;2";

    var bulk = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer bulk.deinit();
    bulk.nextSlice(input);

    var scalar = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer scalar.deinit();
    for (input) |c| scalar.next(c);

    var bulk_buf: [1024]u8 = undefined;
    var bulk_writer: std.Io.Writer = .fixed(&bulk_buf);
    try bulk.writeContinuation(&bulk_writer);
    var scalar_buf: [1024]u8 = undefined;
    var scalar_writer: std.Io.Writer = .fixed(&scalar_buf);
    try scalar.writeContinuation(&scalar_writer);
    try testing.expectEqualStrings(
        bulk_writer.buffered(),
        scalar_writer.buffered(),
    );

    var restored = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer restored.deinit();
    restored.nextSlice(bulk_writer.buffered());
    try testing.expectEqual(@as(usize, 0), restored.handler.committed);

    var restored_buf: [1024]u8 = undefined;
    var restored_writer: std.Io.Writer = .fixed(&restored_buf);
    try restored.writeContinuation(&restored_writer);
    try testing.expectEqualStrings(
        bulk_writer.buffered(),
        restored_writer.buffered(),
    );

    bulk.handler.committed = 0;
    restored.handler.committed = 0;
    bulk.nextSlice("mZ");
    restored.next('m');
    restored.next('Z');
    try testing.expectEqual(bulk.handler.committed, restored.handler.committed);
}

test "stream: continuation rebuilds APC handler input" {
    const S = Stream(ContinuationTestHandler);
    var source = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer source.deinit();
    source.nextSlice("committed\x1b_Gabc");

    var continuation: [1024]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&continuation);
    try source.writeContinuation(&writer);

    var restored = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer restored.deinit();
    restored.nextSlice(writer.buffered());
    try testing.expectEqual(@as(usize, 0), restored.handler.committed);
    try testing.expect(restored.handler.apc_active);
    try testing.expectEqualStrings(
        source.handler.apc_buf[0..source.handler.apc_len],
        restored.handler.apc_buf[0..restored.handler.apc_len],
    );

    source.handler.committed = 0;
    restored.handler.committed = 0;
    source.nextSlice("\x1b\\");
    restored.nextSlice("\x1b\\");
    try testing.expectEqual(source.handler.committed, restored.handler.committed);
    try testing.expect(!source.handler.apc_active);
    try testing.expect(!restored.handler.apc_active);
}

test "stream: continuation cap and recovery" {
    const S = Stream(ContinuationTestHandler);

    // The raw feed exceeds the cap, but only the unfinished three-byte
    // CSI suffix is retained.
    var seeded = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 4,
    });
    defer seeded.deinit();
    seeded.nextSlice("committed text\x1b[1");
    var seeded_buf: [4]u8 = undefined;
    var seeded_writer: std.Io.Writer = .fixed(&seeded_buf);
    try seeded.writeContinuation(&seeded_writer);
    try testing.expectEqualStrings("\x1b[1", seeded_writer.buffered());

    var exceeded = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 4,
    });
    defer exceeded.deinit();
    exceeded.nextSlice("\x1b[123");
    var unavailable_buf: [1]u8 = undefined;
    var unavailable_writer: std.Io.Writer = .fixed(&unavailable_buf);
    try testing.expectError(
        error.ContinuationUnavailable,
        exceeded.writeContinuation(&unavailable_writer),
    );

    // Completing the CSI reaches ground and recovers without rebuilding the
    // Stream. A later unfinished sequence is tracked normally.
    exceeded.nextSlice("mtext\x1b[");
    var recovered_buf: [4]u8 = undefined;
    var recovered_writer: std.Io.Writer = .fixed(&recovered_buf);
    try exceeded.writeContinuation(&recovered_writer);
    try testing.expectEqualStrings("\x1b[", recovered_writer.buffered());

    // A fresh ESC seed also recovers broken tracking even when the stream
    // never reaches ground: the ESC abandons the previous unfinished
    // state and everything after it is retained.
    exceeded.nextSlice("\x1b[123");
    var reexceeded_buf: [1]u8 = undefined;
    var reexceeded_writer: std.Io.Writer = .fixed(&reexceeded_buf);
    try testing.expectError(
        error.ContinuationUnavailable,
        exceeded.writeContinuation(&reexceeded_writer),
    );
    exceeded.nextSlice("\x1b]0;");
    var seed_buf: [4]u8 = undefined;
    var seed_writer: std.Io.Writer = .fixed(&seed_buf);
    try exceeded.writeContinuation(&seed_writer);
    try testing.expectEqualStrings("\x1b]0;", seed_writer.buffered());
}

test "stream: continuation spans multiple bulk feeds" {
    const S = Stream(ContinuationTestHandler);

    // An unfinished APC grows across feeds that contain no new seed.
    var apc = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer apc.deinit();
    apc.nextSlice("text\x1b_Gab");
    apc.nextSlice("cd");
    apc.nextSlice("ef");
    var apc_buf: [16]u8 = undefined;
    var apc_writer: std.Io.Writer = .fixed(&apc_buf);
    try apc.writeContinuation(&apc_writer);
    try testing.expectEqualStrings("\x1b_Gabcdef", apc_writer.buffered());

    // An incomplete UTF-8 sequence grows across feeds of its
    // continuation bytes.
    var utf8 = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 1024,
    });
    defer utf8.deinit();
    utf8.nextSlice("text\xF0");
    utf8.nextSlice("\x9F");
    var utf8_buf: [4]u8 = undefined;
    var utf8_writer: std.Io.Writer = .fixed(&utf8_buf);
    try utf8.writeContinuation(&utf8_writer);
    try testing.expectEqualSlices(u8, "\xF0\x9F", utf8_writer.buffered());

    // A later feed with its own seed drops everything retained earlier.
    utf8.nextSlice("\x98\x84 done \x1b[38;5");
    var seed_buf: [8]u8 = undefined;
    var seed_writer: std.Io.Writer = .fixed(&seed_buf);
    try utf8.writeContinuation(&seed_writer);
    try testing.expectEqualStrings("\x1b[38;5", seed_writer.buffered());
}

test "stream: continuation exact cap and large unfinished string" {
    const S = Stream(ContinuationNullHandler);

    var exact = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = 5,
    });
    defer exact.deinit();
    exact.nextSlice("\x1b[123");
    var exact_buf: [5]u8 = undefined;
    var exact_writer: std.Io.Writer = .fixed(&exact_buf);
    try exact.writeContinuation(&exact_writer);
    try testing.expectEqualStrings("\x1b[123", exact_writer.buffered());

    const payload_len = 12 * 1024;
    const input = try testing.allocator.alloc(u8, payload_len);
    defer testing.allocator.free(input);
    input[0..3].* = "\x1b_G".*;
    @memset(input[3..], 'A');

    var large = S.init(.{
        .allocator = testing.allocator,
        .handler = .{},
        .continuation_max_bytes = payload_len,
    });
    defer large.deinit();
    large.nextSlice(input);
    const large_buf = try testing.allocator.alloc(u8, payload_len);
    defer testing.allocator.free(large_buf);
    var large_writer: std.Io.Writer = .fixed(large_buf);
    try large.writeContinuation(&large_writer);
    try testing.expectEqualSlices(u8, input, large_writer.buffered());
}

test "stream: continuation allocation failure recovers" {
    var failing = testing.FailingAllocator.init(testing.allocator, .{});
    const alloc = failing.allocator();
    const S = Stream(ContinuationNullHandler);
    var stream = S.init(.{
        .allocator = alloc,
        .handler = .{},
        .continuation_max_bytes = 16 * 1024,
    });
    defer stream.deinit();

    var input = try testing.allocator.alloc(u8, 12 * 1024);
    defer testing.allocator.free(input);
    input[0..2].* = "\x1b[".*;
    @memset(input[2..], '1');

    failing.fail_index = failing.alloc_index;
    stream.nextSlice(input);
    var unavailable_buf: [1]u8 = undefined;
    var unavailable_writer: std.Io.Writer = .fixed(&unavailable_buf);
    try testing.expectError(
        error.ContinuationUnavailable,
        stream.writeContinuation(&unavailable_writer),
    );

    failing.fail_index = std.math.maxInt(usize);
    stream.next('m');
    var recovered_buf: [1]u8 = undefined;
    var recovered_writer: std.Io.Writer = .fixed(&recovered_buf);
    try stream.writeContinuation(&recovered_writer);
    try testing.expectEqual(@as(usize, 0), recovered_writer.end);
}

test "stream: continuation every-byte cuts preserve future behavior" {
    const corpora = [_][]const u8{
        "plain \xF0\x9F\x98\x84 utf8",
        "bad \xE0\xA0\xF0\x9F\x98\x84 utf8",
        "\x1b[1\x07;2mstyled\x1b[0m",
        "\x1b]2;window title\x1b\\text",
        "\x1bP$qm\x1b\\text",
        "\x1b_Ga=q;payload\x1b\\text",
        "\x1b_25a1;s\x1b\\text",
        "\x1b]2;first\x1b\\\x1b_Gsecond",
        "\x1b[12\x9D2;title\x1b\\text",
        "\x1b[12\x18text\x1b[1\x1Atext",
    };
    const S = Stream(ContinuationTestHandler);

    for (corpora) |corpus| for (0..corpus.len + 1) |cut| {
        var source = S.init(.{
            .allocator = testing.allocator,
            .handler = .{},
            .continuation_max_bytes = 64 * 1024,
        });
        defer source.deinit();
        source.nextSlice(corpus[0..cut]);

        var continuation: [64 * 1024]u8 = undefined;
        var continuation_writer: std.Io.Writer = .fixed(&continuation);
        try source.writeContinuation(&continuation_writer);

        var restored = S.init(.{
            .allocator = testing.allocator,
            .handler = .{},
            .continuation_max_bytes = 64 * 1024,
        });
        defer restored.deinit();
        restored.nextSlice(continuation_writer.buffered());
        try testing.expectEqual(@as(usize, 0), restored.handler.committed);
        try testing.expectEqual(source.handler.apc_active, restored.handler.apc_active);
        try testing.expectEqual(source.handler.dcs_active, restored.handler.dcs_active);
        if (source.handler.apc_active) {
            try testing.expectEqualStrings(
                source.handler.apc_buf[0..source.handler.apc_len],
                restored.handler.apc_buf[0..restored.handler.apc_len],
            );
        }

        var reexport: [64 * 1024]u8 = undefined;
        var reexport_writer: std.Io.Writer = .fixed(&reexport);
        try restored.writeContinuation(&reexport_writer);
        try testing.expectEqualStrings(
            continuation_writer.buffered(),
            reexport_writer.buffered(),
        );

        source.handler.committed = 0;
        restored.handler.committed = 0;
        source.nextSlice(corpus[cut..]);
        var offset = cut;
        var partition = cut +% corpus.len +% 1;
        while (offset < corpus.len) {
            partition = partition *% 1664525 +% 1013904223;
            const len = @min(1 + partition % 7, corpus.len - offset);
            restored.nextSlice(corpus[offset..][0..len]);
            offset += len;
        }
        try testing.expectEqual(source.handler.committed, restored.handler.committed);
        try testing.expectEqual(source.handler.apc_active, restored.handler.apc_active);
        try testing.expectEqual(source.handler.dcs_active, restored.handler.dcs_active);

        var source_final: [64]u8 = undefined;
        var source_final_writer: std.Io.Writer = .fixed(&source_final);
        try source.writeContinuation(&source_final_writer);
        var restored_final: [64]u8 = undefined;
        var restored_final_writer: std.Io.Writer = .fixed(&restored_final);
        try restored.writeContinuation(&restored_final_writer);
        try testing.expectEqualStrings(
            source_final_writer.buffered(),
            restored_final_writer.buffered(),
        );
    };
}