deno_core 0.398.0

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

use std::cell::Cell;
use std::cell::RefCell;
use std::ffi::c_char;
use std::ffi::c_void;
use std::future::poll_fn;
use std::rc::Rc;
use std::task::Poll;

use super::tcp::AF_INET;
use super::tcp::sockaddr_in;
use crate::JsRuntime;
use crate::PollEventLoopOptions;
use crate::uv_compat::*;

fn assert_ok(status: i32) {
  assert_eq!(status, 0);
}

async fn run_test(f: impl AsyncFnOnce(&mut JsRuntime, *mut uv_loop_t)) {
  let mut runtime = JsRuntime::new(Default::default());
  let uv_loop = runtime
    .uv_loop_ptr()
    .expect("JsRuntime should have a uv loop");
  f(&mut runtime, uv_loop).await;
}

/// Tick the event loop once with a real waker (so tokio's reactor works).
async fn tick(runtime: &mut JsRuntime) {
  poll_fn(|cx| {
    let _ = runtime.poll_event_loop(cx, PollEventLoopOptions::default());
    Poll::Ready(())
  })
  .await;
}

// ========== Loop lifecycle ==========

#[tokio::test(flavor = "current_thread")]
async fn loop_init_and_close() {
  let uv_loop = Box::into_raw(Box::<uv_loop_t>::new_uninit());
  unsafe {
    assert_ok(uv_loop_init(uv_loop.cast()));
    assert_ok(uv_loop_close(uv_loop.cast()));
    let _ = Box::from_raw(uv_loop);
  }
}

#[tokio::test(flavor = "current_thread")]
async fn uv_now_returns_nonzero_after_delay() {
  run_test(async |_runtime, uv_loop| {
    let t1 = unsafe { uv_now(uv_loop) };
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    let t2 = unsafe { uv_now(uv_loop) };
    assert!(t2 >= t1);
  })
  .await;
}

// ========== Timer tests ==========

#[tokio::test(flavor = "current_thread")]
async fn timer_init_sets_fields() {
  run_test(async |_runtime, uv_loop| {
    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    unsafe {
      assert_ok(uv_timer_init(uv_loop, timer.as_mut_ptr()));
      let timer = timer.assume_init_ref();
      assert_eq!(timer.r#type, uv_handle_type::UV_TIMER);
      assert_eq!(timer.loop_, uv_loop);
      assert!(timer.data.is_null());
      assert_eq!(uv_is_active(timer as *const _ as *const uv_handle_t), 0);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn timer_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn timer_cb(handle: *mut uv_timer_t) {
      let fired = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      fired.set(true);
      // Re-leak so the Rc lives until the test checks it.
      let _ = Rc::into_raw(fired);
    }

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    unsafe {
      uv_timer_init(uv_loop, timer.as_mut_ptr());
      let timer = timer.as_mut_ptr();
      (*timer).data = fired_ptr as *mut c_void;
      uv_timer_start(timer, timer_cb, 0, 0);
      assert_eq!(uv_is_active(timer as *const uv_handle_t), 1);
    }

    // Tick the event loop so timers fire.
    tick(runtime).await;

    assert!(fired.get());

    // Clean up the leaked Rc.
    unsafe {
      Rc::from_raw(fired_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn timer_repeat() {
  run_test(async |runtime, uv_loop| {
    let count = Rc::new(Cell::new(0u32));
    let count_ptr = Rc::into_raw(count.clone());

    unsafe extern "C" fn timer_cb(handle: *mut uv_timer_t) {
      let count = unsafe { Rc::from_raw((*handle).data as *const Cell<u32>) };
      count.set(count.get() + 1);
      let _ = Rc::into_raw(count);
    }

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      (*timer_ptr).data = count_ptr as *mut c_void;
      // repeat every 1ms, first fire at 0ms
      uv_timer_start(timer_ptr, timer_cb, 0, 1);
    }

    // Tick a few times with small delays.
    for _ in 0..5 {
      tick(runtime).await;
      tokio::time::sleep(std::time::Duration::from_millis(2)).await;
    }

    let final_count = count.get();
    assert!(
      final_count >= 2,
      "Expected repeat timer to fire at least twice, got {final_count}"
    );

    unsafe {
      uv_timer_stop(timer_ptr);
    }

    // Clean up.
    unsafe {
      Rc::from_raw(count_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn timer_stop_prevents_firing() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn timer_cb(handle: *mut uv_timer_t) {
      let fired = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      fired.set(true);
      let _ = Rc::into_raw(fired);
    }

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      (*timer_ptr).data = fired_ptr as *mut c_void;
      uv_timer_start(timer_ptr, timer_cb, 10, 0);
      uv_timer_stop(timer_ptr);
      assert_eq!(uv_is_active(timer_ptr as *const uv_handle_t), 0);
    }

    tick(runtime).await;
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    tick(runtime).await;

    assert!(!fired.get());

    unsafe {
      Rc::from_raw(fired_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn timer_again_requires_repeat() {
  run_test(async |_runtime, uv_loop| {
    unsafe extern "C" fn noop_cb(_: *mut uv_timer_t) {}

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);

      // uv_timer_again on a never-started timer returns UV_EINVAL
      // (because cb is None).
      let status = uv_timer_again(timer_ptr);
      assert_eq!(status, UV_EINVAL);

      // Start with repeat = 0
      uv_timer_start(timer_ptr, noop_cb, 100, 0);
      // uv_timer_again with repeat=0 is a no-op (returns 0), matching libuv.
      let status = uv_timer_again(timer_ptr);
      assert_ok(status);

      // Set repeat, then again should succeed and restart the timer
      uv_timer_set_repeat(timer_ptr, 50);
      assert_eq!(uv_timer_get_repeat(timer_ptr), 50);
      let status = uv_timer_again(timer_ptr);
      assert_ok(status);

      uv_timer_stop(timer_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn timer_get_set_repeat() {
  run_test(async |_runtime, uv_loop| {
    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      assert_eq!(uv_timer_get_repeat(timer_ptr), 0);
      uv_timer_set_repeat(timer_ptr, 42);
      assert_eq!(uv_timer_get_repeat(timer_ptr), 42);
    }
  })
  .await;
}

// ========== Idle tests ==========

#[tokio::test(flavor = "current_thread")]
async fn idle_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn idle_cb(handle: *mut uv_idle_t) {
      let fired = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      fired.set(true);
      let _ = Rc::into_raw(fired);
    }

    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let idle_ptr = idle.as_mut_ptr();
    unsafe {
      uv_idle_init(uv_loop, idle_ptr);
      (*idle_ptr).data = fired_ptr as *mut c_void;
      uv_idle_start(idle_ptr, idle_cb);
      assert_eq!(uv_is_active(idle_ptr as *const uv_handle_t), 1);
    }

    tick(runtime).await;
    assert!(fired.get());

    unsafe {
      uv_idle_stop(idle_ptr);
      assert_eq!(uv_is_active(idle_ptr as *const uv_handle_t), 0);
      Rc::from_raw(fired_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn idle_stop_prevents_further_callbacks() {
  run_test(async |runtime, uv_loop| {
    let count = Rc::new(Cell::new(0u32));
    let count_ptr = Rc::into_raw(count.clone());

    unsafe extern "C" fn idle_cb(handle: *mut uv_idle_t) {
      let count = unsafe { Rc::from_raw((*handle).data as *const Cell<u32>) };
      count.set(count.get() + 1);
      let _ = Rc::into_raw(count);
    }

    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let idle_ptr = idle.as_mut_ptr();
    unsafe {
      uv_idle_init(uv_loop, idle_ptr);
      (*idle_ptr).data = count_ptr as *mut c_void;
      uv_idle_start(idle_ptr, idle_cb);
    }

    tick(runtime).await;
    let after_first = count.get();
    assert!(after_first >= 1);

    unsafe { uv_idle_stop(idle_ptr) };

    tick(runtime).await;
    assert_eq!(count.get(), after_first, "idle should not fire after stop");

    unsafe {
      Rc::from_raw(count_ptr);
    }
  })
  .await;
}

// ========== Prepare tests ==========

#[tokio::test(flavor = "current_thread")]
async fn prepare_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn prepare_cb(handle: *mut uv_prepare_t) {
      let fired = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      fired.set(true);
      let _ = Rc::into_raw(fired);
    }

    let mut prepare = std::mem::MaybeUninit::<uv_prepare_t>::uninit();
    let prepare_ptr = prepare.as_mut_ptr();
    unsafe {
      uv_prepare_init(uv_loop, prepare_ptr);
      (*prepare_ptr).data = fired_ptr as *mut c_void;
      uv_prepare_start(prepare_ptr, prepare_cb);
      assert_eq!(uv_is_active(prepare_ptr as *const uv_handle_t), 1);
    }

    tick(runtime).await;
    assert!(fired.get());

    unsafe {
      uv_prepare_stop(prepare_ptr);
      assert_eq!(uv_is_active(prepare_ptr as *const uv_handle_t), 0);
      Rc::from_raw(fired_ptr);
    }
  })
  .await;
}

// ========== Check tests ==========

#[tokio::test(flavor = "current_thread")]
async fn check_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn check_cb(handle: *mut uv_check_t) {
      let fired = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      fired.set(true);
      let _ = Rc::into_raw(fired);
    }

    let mut check = std::mem::MaybeUninit::<uv_check_t>::uninit();
    let check_ptr = check.as_mut_ptr();
    unsafe {
      uv_check_init(uv_loop, check_ptr);
      (*check_ptr).data = fired_ptr as *mut c_void;
      uv_check_start(check_ptr, check_cb);
      assert_eq!(uv_is_active(check_ptr as *const uv_handle_t), 1);
    }

    tick(runtime).await;
    assert!(fired.get());

    unsafe {
      uv_check_stop(check_ptr);
      assert_eq!(uv_is_active(check_ptr as *const uv_handle_t), 0);
      Rc::from_raw(fired_ptr);
    }
  })
  .await;
}

// ========== uv_close tests ==========

#[tokio::test(flavor = "current_thread")]
async fn close_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      (*timer_ptr).data = closed_ptr as *mut c_void;
      assert_eq!(uv_is_closing(timer_ptr as *const uv_handle_t), 0);
      uv_close(timer_ptr as *mut uv_handle_t, Some(close_cb));
      assert_eq!(uv_is_closing(timer_ptr as *const uv_handle_t), 1);
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn close_without_callback() {
  run_test(async |runtime, uv_loop| {
    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let idle_ptr = idle.as_mut_ptr();
    unsafe {
      uv_idle_init(uv_loop, idle_ptr);
      uv_close(idle_ptr as *mut uv_handle_t, None);
      assert_eq!(uv_is_closing(idle_ptr as *const uv_handle_t), 1);
    }
    // Should not crash.
    tick(runtime).await;
  })
  .await;
}

// ========== uv_ref / uv_unref ==========

#[tokio::test(flavor = "current_thread")]
async fn ref_unref_toggle() {
  run_test(async |_runtime, uv_loop| {
    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      let handle = timer_ptr as *mut uv_handle_t;
      // Timer starts ref'd by default.
      assert_ne!((*handle).flags & 0x2, 0); // UV_HANDLE_REF

      uv_unref(handle);
      assert_eq!((*handle).flags & 0x2, 0);

      uv_ref(handle);
      assert_ne!((*handle).flags & 0x2, 0);
    }
  })
  .await;
}

// ========== uv_ip4_addr ==========

#[tokio::test(flavor = "current_thread")]
async fn ip4_addr_parses_correctly() {
  let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
  let ip = std::ffi::CString::new("127.0.0.1").unwrap();
  unsafe {
    assert_ok(uv_ip4_addr(ip.as_ptr(), 8080, addr.as_mut_ptr()));
    let addr = addr.assume_init_ref();
    assert_eq!(addr.sin_family as i32, AF_INET);
    assert_eq!(u16::from_be(addr.sin_port), 8080);
    // 127.0.0.1 in network byte order
    let expected = u32::from(std::net::Ipv4Addr::new(127, 0, 0, 1)).to_be();
    assert_eq!(addr.sin_addr.s_addr, expected);
  }
}

#[tokio::test(flavor = "current_thread")]
async fn ip4_addr_invalid_string() {
  let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
  let ip = std::ffi::CString::new("not-an-ip").unwrap();
  unsafe {
    let status = uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
    assert_eq!(status, UV_EINVAL);
  }
}

// ========== TCP init ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_init_sets_fields() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      assert_ok(uv_tcp_init(uv_loop, tcp_ptr));
      let tcp = tcp.assume_init_ref();
      assert_eq!(tcp.r#type, uv_handle_type::UV_TCP);
      assert_eq!(tcp.loop_, uv_loop);
      assert!(tcp.data.is_null());
    }
  })
  .await;
}

// ========== TCP bind / listen / accept ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_bind_and_listen() {
  run_test(async |_runtime, uv_loop| {
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());

      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));

      unsafe extern "C" fn on_connection(_: *mut uv_stream_t, _: i32) {}

      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(on_connection),
      ));

      assert_eq!(uv_is_active(server_ptr as *const uv_handle_t), 1);

      // Verify getsockname works after listen
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      assert_ok(uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      ));
      let name = name.assume_init_ref();
      let port = u16::from_be(name.sin_port);
      assert!(port > 0, "Expected OS-assigned port > 0, got {port}");

      uv_close(server_ptr as *mut uv_handle_t, None);
    }
  })
  .await;
}

// ========== TCP connect + I/O ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_connect_and_echo() {
  run_test(async |runtime, uv_loop| {
    // --- Set up a server ---
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();

    unsafe extern "C" fn on_connection(server: *mut uv_stream_t, status: i32) {
      assert_eq!(status, 0);
      // We don't accept here; the test drives accept manually.
      let _ = server;
    }

    let server_port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());

      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));

      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(on_connection),
      ));

      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      server_port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // --- Connect a client ---
    let connected = Rc::new(Cell::new(false));
    let connected_ptr = Rc::into_raw(connected.clone());

    unsafe extern "C" fn on_connect(req: *mut uv_connect_t, status: i32) {
      assert_eq!(status, 0);
      let connected = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      connected.set(true);
      let _ = Rc::into_raw(connected);
    }

    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut connect_req = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    let connect_req_ptr = connect_req.as_mut_ptr();

    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      uv_tcp_nodelay(client_ptr, 1);

      (*connect_req_ptr).data = connected_ptr as *mut c_void;

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), server_port as i32, addr.as_mut_ptr());

      assert_ok(uv_tcp_connect(
        connect_req_ptr,
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(on_connect),
      ));
    }

    // Poll until connected.
    for _ in 0..100 {
      tick(runtime).await;
      if connected.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(connected.get(), "Client should have connected");

    // Clean up.
    unsafe {
      uv_close(client_ptr as *mut uv_handle_t, None);
      uv_close(server_ptr as *mut uv_handle_t, None);
      Rc::from_raw(connected_ptr);
    }
    tick(runtime).await;
  })
  .await;
}

// ========== TCP nodelay ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_nodelay() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      // Should not error even without a stream.
      assert_ok(uv_tcp_nodelay(tcp_ptr, 1));
      assert_ok(uv_tcp_nodelay(tcp_ptr, 0));
    }
  })
  .await;
}

// ========== TCP keepalive / simultaneous_accepts (no-ops) ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_keepalive_is_noop() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      assert_ok(uv_tcp_keepalive(tcp_ptr, 1, 60));
      assert_ok(uv_tcp_simultaneous_accepts(tcp_ptr, 1));
    }
  })
  .await;
}

// ========== uv_read_stop ==========

#[tokio::test(flavor = "current_thread")]
async fn read_stop_clears_reading() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);

      unsafe extern "C" fn alloc_cb(
        _: *mut uv_handle_t,
        _: usize,
        _: *mut uv_buf_t,
      ) {
      }
      unsafe extern "C" fn read_cb(
        _: *mut uv_stream_t,
        _: isize,
        _: *const uv_buf_t,
      ) {
      }

      uv_read_start(tcp_ptr as *mut uv_stream_t, Some(alloc_cb), Some(read_cb));
      assert_eq!(uv_is_active(tcp_ptr as *const uv_handle_t), 1);

      uv_read_stop(tcp_ptr as *mut uv_stream_t);
      assert_eq!(uv_is_active(tcp_ptr as *const uv_handle_t), 0);
    }
  })
  .await;
}

// ========== uv_try_write without stream ==========

#[tokio::test(flavor = "current_thread")]
async fn try_write_no_stream_returns_ebadf() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      let data = b"hello";
      let result = uv_try_write(tcp_ptr as *mut uv_stream_t, data);
      assert_eq!(result, UV_EBADF);
    }
  })
  .await;
}

// ========== new_* constructors ==========

#[test]
fn new_tcp_constructor() {
  let tcp = new_tcp();
  assert_eq!(tcp.r#type, uv_handle_type::UV_TCP);
  assert!(tcp.data.is_null());
  assert!(tcp.loop_.is_null());
}

#[test]
fn new_write_constructor() {
  let w = new_write();
  assert_eq!(w.r#type, 0);
  assert!(w.data.is_null());
  assert!(w.handle.is_null());
}

#[test]
fn new_connect_constructor() {
  let c = new_connect();
  assert_eq!(c.r#type, 0);
  assert!(c.data.is_null());
  assert!(c.handle.is_null());
}

#[test]
fn new_shutdown_constructor() {
  let s = new_shutdown();
  assert_eq!(s.r#type, 0);
  assert!(s.data.is_null());
  assert!(s.handle.is_null());
}

// ========== Phase ordering ==========

#[tokio::test(flavor = "current_thread")]
async fn phase_ordering_idle_prepare_check() {
  run_test(async |runtime, uv_loop| {
    // Verify that idle runs before prepare, and prepare before check,
    // by recording the order callbacks fire in.
    let order = Rc::new(RefCell::new(Vec::<&'static str>::new()));

    let order_idle = Rc::into_raw(order.clone());
    let order_prepare = Rc::into_raw(order.clone());
    let order_check = Rc::into_raw(order.clone());

    unsafe extern "C" fn idle_cb(handle: *mut uv_idle_t) {
      let order = unsafe {
        Rc::from_raw((*handle).data as *const RefCell<Vec<&'static str>>)
      };
      order.borrow_mut().push("idle");
      let _ = Rc::into_raw(order);
    }
    unsafe extern "C" fn prepare_cb(handle: *mut uv_prepare_t) {
      let order = unsafe {
        Rc::from_raw((*handle).data as *const RefCell<Vec<&'static str>>)
      };
      order.borrow_mut().push("prepare");
      let _ = Rc::into_raw(order);
    }
    unsafe extern "C" fn check_cb(handle: *mut uv_check_t) {
      let order = unsafe {
        Rc::from_raw((*handle).data as *const RefCell<Vec<&'static str>>)
      };
      order.borrow_mut().push("check");
      let _ = Rc::into_raw(order);
    }

    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let mut prepare = std::mem::MaybeUninit::<uv_prepare_t>::uninit();
    let mut check = std::mem::MaybeUninit::<uv_check_t>::uninit();

    unsafe {
      uv_idle_init(uv_loop, idle.as_mut_ptr());
      (*idle.as_mut_ptr()).data = order_idle as *mut c_void;
      uv_idle_start(idle.as_mut_ptr(), idle_cb);

      uv_prepare_init(uv_loop, prepare.as_mut_ptr());
      (*prepare.as_mut_ptr()).data = order_prepare as *mut c_void;
      uv_prepare_start(prepare.as_mut_ptr(), prepare_cb);

      uv_check_init(uv_loop, check.as_mut_ptr());
      (*check.as_mut_ptr()).data = order_check as *mut c_void;
      uv_check_start(check.as_mut_ptr(), check_cb);
    }

    tick(runtime).await;

    let phases = order.borrow();
    // The runtime runs: timers -> idle -> prepare -> I/O -> check -> close
    // (matching libuv's phase ordering)
    assert!(
      phases.len() >= 3,
      "Expected at least 3 phases, got {:?}",
      *phases
    );

    // Find first occurrence of each.
    let idle_idx = phases.iter().position(|&s| s == "idle").unwrap();
    let prepare_idx = phases.iter().position(|&s| s == "prepare").unwrap();
    let check_idx = phases.iter().position(|&s| s == "check").unwrap();

    assert!(
      idle_idx < prepare_idx,
      "idle should run before prepare: {:?}",
      *phases
    );
    assert!(
      prepare_idx < check_idx,
      "prepare should run before check: {:?}",
      *phases
    );

    unsafe {
      uv_idle_stop(idle.as_mut_ptr());
      uv_prepare_stop(prepare.as_mut_ptr());
      uv_check_stop(check.as_mut_ptr());

      Rc::from_raw(order_idle);
      Rc::from_raw(order_prepare);
      Rc::from_raw(order_check);
    }
  })
  .await;
}

// ========== idle_start on already-active handle is no-op ==========

#[tokio::test(flavor = "current_thread")]
async fn idle_start_already_active_is_noop() {
  run_test(async |runtime, uv_loop| {
    let count = Rc::new(Cell::new(0u32));
    let count_ptr = Rc::into_raw(count.clone());

    unsafe extern "C" fn cb_a(handle: *mut uv_idle_t) {
      let c = unsafe { Rc::from_raw((*handle).data as *const Cell<u32>) };
      c.set(c.get() + 1);
      let _ = Rc::into_raw(c);
    }
    unsafe extern "C" fn cb_b(_handle: *mut uv_idle_t) {
      // This should never be called -- libuv ignores the new cb.
      panic!(
        "cb_b should not be called; uv_idle_start on active handle is a no-op"
      );
    }

    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let idle_ptr = idle.as_mut_ptr();
    unsafe {
      uv_idle_init(uv_loop, idle_ptr);
      (*idle_ptr).data = count_ptr as *mut c_void;
      uv_idle_start(idle_ptr, cb_a);
    }

    tick(runtime).await;
    assert!(count.get() >= 1);

    // Calling uv_idle_start on an already-active handle is a no-op in libuv.
    // The original callback (cb_a) should keep firing, NOT cb_b.
    let before = count.get();
    unsafe {
      uv_idle_start(idle_ptr, cb_b);
    }

    tick(runtime).await;
    // cb_a should still be firing (if cb_b fired, it would panic).
    assert!(count.get() > before, "original callback should keep firing");

    unsafe {
      uv_idle_stop(idle_ptr);
      Rc::from_raw(count_ptr);
    }
  })
  .await;
}

// ========== Idle stop is idempotent ==========

#[tokio::test(flavor = "current_thread")]
async fn idle_stop_when_not_active_is_noop() {
  run_test(async |_runtime, uv_loop| {
    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    unsafe {
      uv_idle_init(uv_loop, idle.as_mut_ptr());
      // Stop without start should not crash.
      assert_ok(uv_idle_stop(idle.as_mut_ptr()));
    }
  })
  .await;
}

// ========== Event loop keeps running with alive handles ==========

#[tokio::test(flavor = "current_thread")]
async fn event_loop_pending_with_active_timer() {
  run_test(async |runtime, uv_loop| {
    unsafe extern "C" fn noop_cb(_: *mut uv_timer_t) {}

    let mut timer = std::mem::MaybeUninit::<uv_timer_t>::uninit();
    let timer_ptr = timer.as_mut_ptr();
    unsafe {
      uv_timer_init(uv_loop, timer_ptr);
      uv_timer_start(timer_ptr, noop_cb, 100_000, 0);
    }

    // With an active timer, poll_event_loop should return Pending.
    let result = poll_fn(|cx| {
      let poll = runtime.poll_event_loop(cx, PollEventLoopOptions::default());
      Poll::Ready(poll)
    })
    .await;

    assert!(result.is_pending(), "Should be pending with active timer");

    unsafe {
      uv_timer_stop(timer_ptr);
    }
  })
  .await;
}

// ========== Close on each handle type ==========

#[tokio::test(flavor = "current_thread")]
async fn close_idle_handle() {
  run_test(async |runtime, uv_loop| {
    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    unsafe extern "C" fn idle_cb(_: *mut uv_idle_t) {}

    let mut idle = std::mem::MaybeUninit::<uv_idle_t>::uninit();
    let idle_ptr = idle.as_mut_ptr();
    unsafe {
      uv_idle_init(uv_loop, idle_ptr);
      (*idle_ptr).data = closed_ptr as *mut c_void;
      uv_idle_start(idle_ptr, idle_cb);
      uv_close(idle_ptr as *mut uv_handle_t, Some(close_cb));
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn close_prepare_handle() {
  run_test(async |runtime, uv_loop| {
    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    unsafe extern "C" fn prepare_cb(_: *mut uv_prepare_t) {}

    let mut prepare = std::mem::MaybeUninit::<uv_prepare_t>::uninit();
    let prepare_ptr = prepare.as_mut_ptr();
    unsafe {
      uv_prepare_init(uv_loop, prepare_ptr);
      (*prepare_ptr).data = closed_ptr as *mut c_void;
      uv_prepare_start(prepare_ptr, prepare_cb);
      uv_close(prepare_ptr as *mut uv_handle_t, Some(close_cb));
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn close_check_handle() {
  run_test(async |runtime, uv_loop| {
    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    unsafe extern "C" fn check_cb(_: *mut uv_check_t) {}

    let mut check = std::mem::MaybeUninit::<uv_check_t>::uninit();
    let check_ptr = check.as_mut_ptr();
    unsafe {
      uv_check_init(uv_loop, check_ptr);
      (*check_ptr).data = closed_ptr as *mut c_void;
      uv_check_start(check_ptr, check_cb);
      uv_close(check_ptr as *mut uv_handle_t, Some(close_cb));
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn close_tcp_handle() {
  run_test(async |runtime, uv_loop| {
    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      (*tcp_ptr).data = closed_ptr as *mut c_void;
      uv_close(tcp_ptr as *mut uv_handle_t, Some(close_cb));
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

// ========== TCP getsockname / getpeername edge cases ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_getsockname_no_bind_returns_einval() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      let status = uv_tcp_getsockname(
        tcp_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      assert_eq!(status, UV_EINVAL);
    }
  })
  .await;
}

#[tokio::test(flavor = "current_thread")]
async fn tcp_getpeername_no_stream_returns_enotconn() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      let status = uv_tcp_getpeername(
        tcp_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      assert_eq!(status, UV_ENOTCONN);
    }
  })
  .await;
}

// ========== TCP shutdown drains write queue first ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_shutdown_waits_for_write_queue_to_drain() {
  run_test(async |runtime, uv_loop| {
    use std::cell::RefCell;

    // Track ordering of callbacks.
    let order = Rc::new(RefCell::new(Vec::<&'static str>::new()));

    // --- Server: bind + listen ---
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();

    unsafe extern "C" fn on_connection(_: *mut uv_stream_t, _: i32) {}

    let server_port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());

      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));

      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(on_connection),
      ));

      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      server_port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // --- Client: connect ---
    let connected = Rc::new(Cell::new(false));
    let connected_ptr = Rc::into_raw(connected.clone());

    unsafe extern "C" fn on_connect(req: *mut uv_connect_t, status: i32) {
      assert_eq!(status, 0);
      let connected = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      connected.set(true);
      let _ = Rc::into_raw(connected);
    }

    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut connect_req = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    let connect_req_ptr = connect_req.as_mut_ptr();

    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      (*connect_req_ptr).data = connected_ptr as *mut c_void;

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), server_port as i32, addr.as_mut_ptr());

      assert_ok(uv_tcp_connect(
        connect_req_ptr,
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(on_connect),
      ));
    }

    // Poll until connected.
    for _ in 0..100 {
      tick(runtime).await;
      if connected.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(connected.get(), "Client should have connected");

    // --- Accept on server side ---
    let mut accepted = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let accepted_ptr = accepted.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, accepted_ptr);
    }
    tick(runtime).await;
    unsafe {
      assert_ok(uv_accept(
        server_ptr as *mut uv_stream_t,
        accepted_ptr as *mut uv_stream_t,
      ));
    }

    // Start reading on accepted socket so the client's writes can drain.
    unsafe extern "C" fn alloc_cb(
      _: *mut uv_handle_t,
      size: usize,
      buf: *mut uv_buf_t,
    ) {
      let mut v = Vec::<u8>::with_capacity(size);
      unsafe {
        (*buf).base = v.as_mut_ptr().cast();
        (*buf).len = size;
      }
      std::mem::forget(v);
    }
    unsafe extern "C" fn drain_read_cb(
      _: *mut uv_stream_t,
      _nread: isize,
      buf: *const uv_buf_t,
    ) {
      unsafe {
        if !(*buf).base.is_null() && (*buf).len > 0 {
          drop(Vec::<u8>::from_raw_parts((*buf).base.cast(), 0, (*buf).len));
        }
      }
    }
    unsafe {
      uv_read_start(
        accepted_ptr as *mut uv_stream_t,
        Some(alloc_cb),
        Some(drain_read_cb),
      );
    }

    // --- Write large buffer + immediate shutdown ---
    let order_write = Rc::into_raw(order.clone());
    let order_shutdown = Rc::into_raw(order.clone());

    unsafe extern "C" fn write_cb(req: *mut uv_write_t, status: i32) {
      assert_eq!(status, 0);
      let order = unsafe {
        Rc::from_raw((*req).data as *const RefCell<Vec<&'static str>>)
      };
      order.borrow_mut().push("write");
      let _ = Rc::into_raw(order);
    }

    unsafe extern "C" fn shutdown_cb(req: *mut uv_shutdown_t, _status: i32) {
      let order = unsafe {
        Rc::from_raw((*req).data as *const RefCell<Vec<&'static str>>)
      };
      order.borrow_mut().push("shutdown");
      let _ = Rc::into_raw(order);
    }

    // 2 MB – large enough to exceed kernel TCP buffers, ensuring
    // the write is partially queued when uv_shutdown is called.
    let write_data = vec![0x42u8; 2 * 1024 * 1024];
    let mut write_req = std::mem::MaybeUninit::<uv_write_t>::uninit();
    let write_req_ptr = write_req.as_mut_ptr();
    let mut shutdown_req = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    let shutdown_req_ptr = shutdown_req.as_mut_ptr();

    unsafe {
      (*write_req_ptr).data = order_write as *mut c_void;
      (*shutdown_req_ptr).data = order_shutdown as *mut c_void;

      let buf = uv_buf_t {
        base: write_data.as_ptr() as *mut _,
        len: write_data.len(),
      };

      assert_ok(uv_write(
        write_req_ptr,
        client_ptr as *mut uv_stream_t,
        &buf,
        1,
        Some(write_cb),
      ));

      // Shutdown while writes are (likely) still queued.
      assert_ok(uv_shutdown(
        shutdown_req_ptr,
        client_ptr as *mut uv_stream_t,
        Some(shutdown_cb),
      ));
    }

    // Tick until both callbacks fire.
    for _ in 0..2000 {
      tick(runtime).await;
      if order.borrow().len() >= 2 {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }

    {
      let phases = order.borrow();
      assert!(
        phases.len() >= 2,
        "Expected both write and shutdown callbacks, got {:?}",
        *phases
      );

      let write_idx = phases
        .iter()
        .position(|&s| s == "write")
        .expect("write cb should have fired");
      let shutdown_idx = phases
        .iter()
        .position(|&s| s == "shutdown")
        .expect("shutdown cb should have fired");
      assert!(
        write_idx < shutdown_idx,
        "write should complete before shutdown: {:?}",
        *phases
      );
    }

    // Clean up.
    unsafe {
      uv_close(client_ptr as *mut uv_handle_t, None);
      uv_close(server_ptr as *mut uv_handle_t, None);
      uv_close(accepted_ptr as *mut uv_handle_t, None);
      Rc::from_raw(connected_ptr);
      Rc::from_raw(order_write);
      Rc::from_raw(order_shutdown);
    }
    tick(runtime).await;
  })
  .await;
}

// ========== TCP shutdown without stream ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_shutdown_no_stream() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    let mut req = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    let req_ptr = req.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      // uv_shutdown returns UV_ENOTCONN when no stream is attached
      // (matching libuv which returns error code, not callback).
      let status = uv_shutdown(req_ptr, tcp_ptr as *mut uv_stream_t, None);
      assert_eq!(status, UV_ENOTCONN);
    }
  })
  .await;
}

// ========== Deferred bind error: EADDRINUSE reported at listen ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_bind_eaddrinuse_deferred_to_listen() {
  run_test(async |_runtime, uv_loop| {
    // Server A: bind + listen to get a real port.
    let mut server_a = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_a_ptr = server_a.as_mut_ptr();

    unsafe extern "C" fn noop_conn(_: *mut uv_stream_t, _: i32) {}

    let port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_a_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(
        server_a_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_a_ptr as *mut uv_stream_t,
        128,
        Some(noop_conn),
      ));

      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_a_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // Server B: bind to same port — bind returns 0 (deferred),
    // but listen should report EADDRINUSE.
    let mut server_b = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_b_ptr = server_b.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, server_b_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), port as i32, addr.as_mut_ptr());
      let bind_status =
        uv_tcp_bind(server_b_ptr, addr.as_ptr() as *const c_void, 0, 0);
      assert_eq!(bind_status, 0, "bind should defer the error");

      let listen_status =
        uv_listen(server_b_ptr as *mut uv_stream_t, 128, Some(noop_conn));
      assert_eq!(
        listen_status, UV_EADDRINUSE,
        "listen should report the deferred EADDRINUSE"
      );

      uv_close(server_a_ptr as *mut uv_handle_t, None);
      uv_close(server_b_ptr as *mut uv_handle_t, None);
    }
  })
  .await;
}

// ========== TCP connect returns UV_EALREADY on duplicate ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_connect_returns_ealready() {
  run_test(async |_runtime, uv_loop| {
    // Set up a server to connect to.
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();

    unsafe extern "C" fn noop_conn(_: *mut uv_stream_t, _: i32) {}
    unsafe extern "C" fn noop_connect(_: *mut uv_connect_t, _: i32) {}

    let port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(noop_conn),
      ));
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // Client: connect, then try to connect again.
    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut req1 = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    let mut req2 = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), port as i32, addr.as_mut_ptr());

      assert_ok(uv_tcp_connect(
        req1.as_mut_ptr(),
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(noop_connect),
      ));

      let status = uv_tcp_connect(
        req2.as_mut_ptr(),
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(noop_connect),
      );
      assert_eq!(status, UV_EALREADY);

      uv_close(client_ptr as *mut uv_handle_t, None);
      uv_close(server_ptr as *mut uv_handle_t, None);
    }
  })
  .await;
}

// ========== TCP shutdown returns UV_EALREADY on duplicate ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_shutdown_returns_ealready() {
  run_test(async |runtime, uv_loop| {
    // Server
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();
    unsafe extern "C" fn noop_conn(_: *mut uv_stream_t, _: i32) {}

    let port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(noop_conn),
      ));
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // Client: connect, wait for connection, then double-shutdown.
    let connected = Rc::new(Cell::new(false));
    let connected_ptr = Rc::into_raw(connected.clone());

    unsafe extern "C" fn on_connect(req: *mut uv_connect_t, status: i32) {
      assert_eq!(status, 0);
      let c = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      c.set(true);
      let _ = Rc::into_raw(c);
    }

    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut connect_req = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      (*connect_req.as_mut_ptr()).data = connected_ptr as *mut c_void;
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), port as i32, addr.as_mut_ptr());
      assert_ok(uv_tcp_connect(
        connect_req.as_mut_ptr(),
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(on_connect),
      ));
    }

    // Poll until connected.
    for _ in 0..100 {
      tick(runtime).await;
      if connected.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(connected.get(), "client should be connected");

    // First shutdown succeeds, second returns EALREADY.
    let mut req1 = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    let mut req2 = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    unsafe {
      assert_ok(uv_shutdown(
        req1.as_mut_ptr(),
        client_ptr as *mut uv_stream_t,
        None,
      ));
      let status =
        uv_shutdown(req2.as_mut_ptr(), client_ptr as *mut uv_stream_t, None);
      assert_eq!(status, UV_EALREADY);

      uv_close(client_ptr as *mut uv_handle_t, None);
      uv_close(server_ptr as *mut uv_handle_t, None);
    }
    // Clean up Rc leak.
    unsafe { drop(Rc::from_raw(connected_ptr)) };
  })
  .await;
}

// ========== read_start on closing handle returns UV_EINVAL ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_read_start_on_closing_handle() {
  run_test(async |_runtime, uv_loop| {
    unsafe extern "C" fn noop_alloc(
      _: *mut uv_handle_t,
      _: usize,
      _: *mut uv_buf_t,
    ) {
    }
    unsafe extern "C" fn noop_read(
      _: *mut uv_stream_t,
      _: isize,
      _: *const uv_buf_t,
    ) {
    }

    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      uv_close(tcp_ptr as *mut uv_handle_t, None);

      let status = uv_read_start(
        tcp_ptr as *mut uv_stream_t,
        Some(noop_alloc),
        Some(noop_read),
      );
      assert_eq!(status, UV_EINVAL);
    }
  })
  .await;
}

// ========== shutdown on closing handle returns UV_ENOTCONN ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_shutdown_on_closing_handle() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    let mut req = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      uv_close(tcp_ptr as *mut uv_handle_t, None);

      let status =
        uv_shutdown(req.as_mut_ptr(), tcp_ptr as *mut uv_stream_t, None);
      assert_eq!(status, UV_ENOTCONN);
    }
  })
  .await;
}

// ========== getsockname works after bind, before listen ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_getsockname_after_bind_before_listen() {
  run_test(async |_runtime, uv_loop| {
    let mut tcp = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let tcp_ptr = tcp.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, tcp_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(tcp_ptr, addr.as_ptr() as *const c_void, 0, 0));

      // getsockname should resolve the ephemeral port from the
      // pre-created socket, even before listen/connect.
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      assert_ok(uv_tcp_getsockname(
        tcp_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      ));
      let port = u16::from_be(name.assume_init_ref().sin_port);
      assert!(port > 0, "Expected OS-assigned port > 0, got {port}");

      uv_close(tcp_ptr as *mut uv_handle_t, None);
    }
  })
  .await;
}

// ========== close cancels pending writes with UV_ECANCELED ==========

#[tokio::test(flavor = "current_thread")]
async fn tcp_close_cancels_pending_writes() {
  run_test(async |runtime, uv_loop| {
    // Server
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();
    unsafe extern "C" fn noop_conn(_: *mut uv_stream_t, _: i32) {}

    let port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(noop_conn),
      ));
      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // Client: connect, write, then close — write should be canceled.
    let connected = Rc::new(Cell::new(false));
    let connected_ptr = Rc::into_raw(connected.clone());

    unsafe extern "C" fn on_connect(req: *mut uv_connect_t, status: i32) {
      assert_eq!(status, 0);
      let c = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      c.set(true);
      let _ = Rc::into_raw(c);
    }

    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut connect_req = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      (*connect_req.as_mut_ptr()).data = connected_ptr as *mut c_void;
      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), port as i32, addr.as_mut_ptr());
      assert_ok(uv_tcp_connect(
        connect_req.as_mut_ptr(),
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(on_connect),
      ));
    }

    for _ in 0..100 {
      tick(runtime).await;
      if connected.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(connected.get(), "client should be connected");

    // Queue a write, then immediately close.
    let write_status = Rc::new(Cell::new(None::<i32>));
    let write_status_ptr = Rc::into_raw(write_status.clone());

    unsafe extern "C" fn on_write(req: *mut uv_write_t, status: i32) {
      let s = unsafe { Rc::from_raw((*req).data as *const Cell<Option<i32>>) };
      s.set(Some(status));
      let _ = Rc::into_raw(s);
    }

    let mut write_req = std::mem::MaybeUninit::<uv_write_t>::uninit();
    let msg = b"hello";
    unsafe {
      (*write_req.as_mut_ptr()).data = write_status_ptr as *mut c_void;
      let buf = uv_buf_t {
        base: msg.as_ptr() as *mut c_char,
        len: msg.len(),
      };
      assert_ok(uv_write(
        write_req.as_mut_ptr(),
        client_ptr as *mut uv_stream_t,
        &buf,
        1,
        Some(on_write),
      ));

      // Close immediately — should cancel pending write.
      uv_close(client_ptr as *mut uv_handle_t, None);
    }

    // Tick to let close cleanup fire.
    for _ in 0..5 {
      tick(runtime).await;
    }

    assert_eq!(
      write_status.get(),
      Some(UV_ECANCELED),
      "write callback should fire with UV_ECANCELED on close"
    );

    unsafe {
      uv_close(server_ptr as *mut uv_handle_t, None);
      drop(Rc::from_raw(connected_ptr));
      drop(Rc::from_raw(write_status_ptr));
    }
  })
  .await;
}

// ========== TTY tests ==========

/// Helper: create a PTY pair and return (master_fd, slave_fd).
/// The slave fd is a real TTY that `isatty()` returns true for.
#[cfg(unix)]
unsafe fn open_pty_pair() -> (i32, i32) {
  unsafe {
    let fdm = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY);
    assert!(fdm >= 0, "posix_openpt failed");
    assert_eq!(libc::grantpt(fdm), 0, "grantpt failed");
    assert_eq!(libc::unlockpt(fdm), 0, "unlockpt failed");
    let slave_name = libc::ptsname(fdm);
    assert!(!slave_name.is_null(), "ptsname failed");
    let fds = libc::open(slave_name, libc::O_RDWR | libc::O_NOCTTY);
    assert!(fds >= 0, "open(ptsname) failed");
    (fdm, fds)
  }
}

/// RAII guard to close a file descriptor.
#[cfg(unix)]
struct FdGuard(i32);
#[cfg(unix)]
impl Drop for FdGuard {
  fn drop(&mut self) {
    unsafe { libc::close(self.0) };
  }
}

#[cfg(unix)]
unsafe fn set_errno(val: i32) {
  #[cfg(target_os = "macos")]
  unsafe {
    *libc::__error() = val;
  }
  #[cfg(target_os = "linux")]
  unsafe {
    *libc::__errno_location() = val;
  }
}

#[cfg(unix)]
fn get_errno() -> i32 {
  std::io::Error::last_os_error()
    .raw_os_error()
    .unwrap_or_default()
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_init_sets_fields() {
  run_test(async |_runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
      let tty = tty.assume_init_ref();
      assert_eq!(tty.r#type, uv_handle_type::UV_TTY);
      assert_eq!(tty.loop_, uv_loop);
      assert!(tty.data.is_null());
      assert_eq!(tty.mode, uv_tty_mode_t::UV_TTY_MODE_NORMAL);
      // uv_tty_init reopens slave fds so internal_fd may differ from the
      // original fd.
      assert!(tty.internal_fd >= 0);
      assert!(tty.internal_reactor.is_some());

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(_runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_init_rejects_non_tty() {
  run_test(async |_runtime, uv_loop| {
    // A regular file fd should be rejected (UV_FILE -> UV_EINVAL).
    let path = c"/dev/null";
    let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY) };
    assert!(fd >= 0);
    let _guard = FdGuard(fd);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    unsafe {
      let status = uv_tty_init(uv_loop, tty.as_mut_ptr(), fd, 0);
      assert_eq!(status, UV_EINVAL);
    }
  })
  .await;
}

// Regression test for https://github.com/denoland/deno/issues/32802
// On macOS, /dev/tty is a kqueue-incompatible device. uv_tty_init must
// succeed via the select(2) fallback rather than returning EINVAL.
// We also do a write through the handle to verify the fallback I/O path.
#[cfg(target_os = "macos")]
#[tokio::test(flavor = "current_thread")]
async fn tty_init_dev_tty_select_fallback() {
  run_test(async |runtime, uv_loop| {
    // Open /dev/tty directly — this produces an fd that kqueue rejects.
    let fd = unsafe { libc::open(c"/dev/tty".as_ptr(), libc::O_RDWR) };
    if fd < 0 {
      // No controlling terminal (e.g., CI without a PTY). Skip.
      return;
    }
    let _fd_guard = FdGuard(fd);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      // This is the core assertion: init must succeed, not EINVAL.
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fd, 0));
    }

    // Verify the select fallback was used.
    unsafe {
      let tty_ref = tty.assume_init_ref();
      assert!(tty_ref.internal_reactor.is_some());
      assert!(matches!(
        tty_ref.internal_reactor,
        Some(tty::TtyReactor::SelectFallback(_))
      ));
    }

    // Write through the handle to exercise the fallback I/O path.
    let write_done = Rc::new(Cell::new(false));
    let write_done_ptr = Rc::into_raw(write_done.clone());

    unsafe extern "C" fn write_cb(req: *mut uv_write_t, status: i32) {
      assert_eq!(status, 0);
      let done = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      done.set(true);
      let _ = Rc::into_raw(done);
    }

    let payload = b"\n";
    let mut write_req = std::mem::MaybeUninit::<uv_write_t>::uninit();
    let write_req_ptr = write_req.as_mut_ptr();
    unsafe {
      (*write_req_ptr).data = write_done_ptr as *mut c_void;
      let buf = uv_buf_t {
        base: payload.as_ptr() as *mut _,
        len: payload.len(),
      };
      assert_ok(uv_write(
        write_req_ptr,
        tty_ptr as *mut uv_stream_t,
        &buf,
        1,
        Some(write_cb),
      ));
    }

    // Tick until write completes.
    for _ in 0..50 {
      tick(runtime).await;
      if write_done.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
    assert!(write_done.get(), "write callback should have fired");

    // Also verify read_start doesn't panic. We can't easily feed data
    // to /dev/tty from a test, so just start and immediately stop.
    unsafe extern "C" fn alloc_cb(
      _: *mut uv_handle_t,
      size: usize,
      buf: *mut uv_buf_t,
    ) {
      let mut v = Vec::<u8>::with_capacity(size);
      unsafe {
        (*buf).base = v.as_mut_ptr().cast();
        (*buf).len = size;
      }
      std::mem::forget(v);
    }

    unsafe extern "C" fn read_cb(
      _handle: *mut uv_stream_t,
      _nread: isize,
      buf: *const uv_buf_t,
    ) {
      unsafe {
        if !(*buf).base.is_null() && (*buf).len > 0 {
          drop(Vec::<u8>::from_raw_parts((*buf).base.cast(), 0, (*buf).len));
        }
      }
    }

    unsafe {
      assert_ok(uv_read_start(
        tty_ptr as *mut uv_stream_t,
        Some(alloc_cb),
        Some(read_cb),
      ));
    }

    // One tick to register interest.
    tick(runtime).await;

    // Stop reading and clean up.
    unsafe {
      uv_read_stop(tty_ptr as *mut uv_stream_t);
      uv_close(tty_ptr as *mut uv_handle_t, None);
      Rc::from_raw(write_done_ptr);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_get_winsize() {
  run_test(async |_runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    // Set a known window size on the master side.
    unsafe {
      let ws = libc::winsize {
        ws_row: 42,
        ws_col: 120,
        ws_xpixel: 0,
        ws_ypixel: 0,
      };
      assert_eq!(libc::ioctl(fdm, libc::TIOCSWINSZ, &ws), 0);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));

      let mut width: i32 = 0;
      let mut height: i32 = 0;
      assert_ok(uv_tty_get_winsize(tty_ptr, &mut width, &mut height));
      assert_eq!(width, 120);
      assert_eq!(height, 42);

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(_runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_set_mode_raw_and_back() {
  run_test(async |_runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));

      // Normal -> Raw
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_RAW));
      assert_eq!((*tty_ptr).mode, uv_tty_mode_t::UV_TTY_MODE_RAW);

      // Idempotent: setting same mode again is ok.
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_RAW));

      // Back to normal.
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_NORMAL));
      assert_eq!((*tty_ptr).mode, uv_tty_mode_t::UV_TTY_MODE_NORMAL);

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(_runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_set_mode_io() {
  run_test(async |_runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));

      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_IO));
      assert_eq!((*tty_ptr).mode, uv_tty_mode_t::UV_TTY_MODE_IO);

      // Back to normal.
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_NORMAL));

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(_runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_write_and_read_through_pty() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };

    // Put slave in raw mode so writes pass through without line buffering
    // or echo processing getting in the way.
    unsafe {
      let mut term: libc::termios = std::mem::zeroed();
      libc::tcgetattr(fds, &mut term);
      libc::cfmakeraw(&mut term);
      libc::tcsetattr(fds, libc::TCSANOW, &term);
    }

    // Set master non-blocking for reading.
    unsafe {
      let flags = libc::fcntl(fdm, libc::F_GETFL);
      libc::fcntl(fdm, libc::F_SETFL, flags | libc::O_NONBLOCK);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
    }

    // Write "hello" through the TTY handle.
    let write_done = Rc::new(Cell::new(false));
    let write_done_ptr = Rc::into_raw(write_done.clone());

    unsafe extern "C" fn write_cb(req: *mut uv_write_t, status: i32) {
      assert_eq!(status, 0);
      let done = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      done.set(true);
      let _ = Rc::into_raw(done);
    }

    let payload = b"hello";
    let mut write_req = std::mem::MaybeUninit::<uv_write_t>::uninit();
    let write_req_ptr = write_req.as_mut_ptr();
    unsafe {
      (*write_req_ptr).data = write_done_ptr as *mut c_void;
      let buf = uv_buf_t {
        base: payload.as_ptr() as *mut _,
        len: payload.len(),
      };
      assert_ok(uv_write(
        write_req_ptr,
        tty_ptr as *mut uv_stream_t,
        &buf,
        1,
        Some(write_cb),
      ));
    }

    // Tick until write completes.
    for _ in 0..50 {
      tick(runtime).await;
      if write_done.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(write_done.get(), "write callback should have fired");

    // Read from master fd — data written to the slave should appear here.
    let mut buf = [0u8; 64];
    let n = unsafe { libc::read(fdm, buf.as_mut_ptr() as *mut _, buf.len()) };
    assert!(n > 0, "Expected data on master fd, got {n}");
    assert_eq!(&buf[..n as usize], b"hello");

    // Clean up.
    unsafe {
      uv_close(tty_ptr as *mut uv_handle_t, None);
      Rc::from_raw(write_done_ptr);
      libc::close(fdm);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_read_from_pty() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };

    // Put slave in raw mode.
    unsafe {
      let mut term: libc::termios = std::mem::zeroed();
      libc::tcgetattr(fds, &mut term);
      libc::cfmakeraw(&mut term);
      libc::tcsetattr(fds, libc::TCSANOW, &term);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
    }

    let received = Rc::new(Cell::new(Vec::<u8>::new()));
    let received_ptr = Rc::into_raw(received.clone());

    unsafe extern "C" fn alloc_cb(
      _: *mut uv_handle_t,
      size: usize,
      buf: *mut uv_buf_t,
    ) {
      let mut v = Vec::<u8>::with_capacity(size);
      unsafe {
        (*buf).base = v.as_mut_ptr().cast();
        (*buf).len = size;
      }
      std::mem::forget(v);
    }

    unsafe extern "C" fn read_cb(
      handle: *mut uv_stream_t,
      nread: isize,
      buf: *const uv_buf_t,
    ) {
      unsafe {
        let tty = handle as *const uv_tty_t;
        let received = Rc::from_raw((*tty).data as *const Cell<Vec<u8>>);
        if nread > 0 {
          let data = std::slice::from_raw_parts(
            (*buf).base as *const u8,
            nread as usize,
          );
          let mut v = received.take();
          v.extend_from_slice(data);
          received.set(v);
        }
        let _ = Rc::into_raw(received);

        // Free the alloc'd buffer.
        if !(*buf).base.is_null() && (*buf).len > 0 {
          drop(Vec::<u8>::from_raw_parts((*buf).base.cast(), 0, (*buf).len));
        }
      }
    }

    unsafe {
      (*tty_ptr).data = received_ptr as *mut c_void;
      assert_ok(uv_read_start(
        tty_ptr as *mut uv_stream_t,
        Some(alloc_cb),
        Some(read_cb),
      ));
    }

    // Write to the master fd — it should arrive at the slave's read callback.
    unsafe {
      libc::write(fdm, b"world".as_ptr() as *const _, 5);
    }

    // Tick until data is received.
    for _ in 0..100 {
      tick(runtime).await;
      let snapshot = received.take();
      let done = !snapshot.is_empty();
      received.set(snapshot); // put it back
      if done {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }

    let data = received.take();
    assert!(
      !data.is_empty(),
      "Expected to receive data from master write"
    );
    // The data might include terminal processing, but should contain "world".
    let s = String::from_utf8_lossy(&data);
    assert!(
      s.contains("world"),
      "Expected 'world' in received data, got: {s:?}"
    );

    // Clean up.
    unsafe {
      uv_close(tty_ptr as *mut uv_handle_t, None);
      Rc::from_raw(received_ptr);
      libc::close(fdm);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_close_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let closed = Rc::new(Cell::new(false));
    let closed_ptr = Rc::into_raw(closed.clone());

    unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) {
      let closed = unsafe { Rc::from_raw((*handle).data as *const Cell<bool>) };
      closed.set(true);
      let _ = Rc::into_raw(closed);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
      (*tty_ptr).data = closed_ptr as *mut c_void;
      uv_close(tty_ptr as *mut uv_handle_t, Some(close_cb));
    }

    tick(runtime).await;
    assert!(closed.get());

    unsafe {
      Rc::from_raw(closed_ptr);
    }
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_shutdown_fires_callback() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let shutdown_done = Rc::new(Cell::new(false));
    let shutdown_done_ptr = Rc::into_raw(shutdown_done.clone());

    unsafe extern "C" fn shutdown_cb(req: *mut uv_shutdown_t, status: i32) {
      assert_eq!(status, 0);
      let done = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      done.set(true);
      let _ = Rc::into_raw(done);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    let mut req = std::mem::MaybeUninit::<uv_shutdown_t>::uninit();
    let req_ptr = req.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
      (*req_ptr).data = shutdown_done_ptr as *mut c_void;
      assert_ok(uv_shutdown(
        req_ptr,
        tty_ptr as *mut uv_stream_t,
        Some(shutdown_cb),
      ));
    }

    for _ in 0..50 {
      tick(runtime).await;
      if shutdown_done.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(shutdown_done.get(), "shutdown callback should have fired");

    unsafe {
      uv_close(tty_ptr as *mut uv_handle_t, None);
      Rc::from_raw(shutdown_done_ptr);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[test]
fn tty_guess_handle_detects_pty() {
  let (fdm, fds) = unsafe { open_pty_pair() };
  let _fdm_guard = FdGuard(fdm);
  let _fds_guard = FdGuard(fds);

  assert_eq!(uv_guess_handle(fds), uv_handle_type::UV_TTY);
  // A pipe fd should be detected as UV_NAMED_PIPE.
  let mut pipe_fds = [0i32; 2];
  unsafe { libc::pipe(pipe_fds.as_mut_ptr()) };
  let _r = FdGuard(pipe_fds[0]);
  let _w = FdGuard(pipe_fds[1]);
  assert_eq!(uv_guess_handle(pipe_fds[0]), uv_handle_type::UV_NAMED_PIPE);
  // A regular file should be UV_FILE.
  let file_fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) };
  assert!(file_fd >= 0);
  let _f = FdGuard(file_fd);
  assert_eq!(uv_guess_handle(file_fd), uv_handle_type::UV_FILE);
}

#[test]
fn new_tty_constructor() {
  let tty = new_tty();
  assert_eq!(tty.r#type, uv_handle_type::UV_TTY);
  assert!(tty.data.is_null());
  assert!(tty.loop_.is_null());
  assert_eq!(tty.mode, uv_tty_mode_t::UV_TTY_MODE_NORMAL);
}

#[cfg(unix)]
#[test]
fn tty_reset_mode_when_no_tty_modified() {
  // Should succeed (no-op) when no TTY has entered raw mode.
  assert_ok(uv_tty_reset_mode());
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_reset_mode_restores_termios() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    // Capture the original termios before any mode changes.
    let mut orig_termios: libc::termios = unsafe { std::mem::zeroed() };
    assert_eq!(unsafe { libc::tcgetattr(fds, &mut orig_termios) }, 0);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));

      // Enter raw mode — this should save original termios globally.
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_RAW));

      // Verify terminal is actually in raw mode (ECHO should be off).
      let mut raw_termios: libc::termios = std::mem::zeroed();
      assert_eq!(libc::tcgetattr(fds, &mut raw_termios), 0);
      assert_eq!(
        raw_termios.c_lflag & libc::ECHO,
        0,
        "ECHO should be off in raw mode"
      );

      // Reset via the global reset function.
      assert_ok(uv_tty_reset_mode());

      // Verify termios is restored to original.
      let mut after_termios: libc::termios = std::mem::zeroed();
      assert_eq!(libc::tcgetattr(fds, &mut after_termios), 0);
      assert_eq!(
        after_termios.c_lflag & libc::ECHO,
        orig_termios.c_lflag & libc::ECHO,
        "ECHO flag should be restored after reset_mode"
      );
      assert_eq!(
        after_termios.c_lflag & libc::ICANON,
        orig_termios.c_lflag & libc::ICANON,
        "ICANON flag should be restored after reset_mode"
      );

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_reset_mode_preserves_errno() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };
    let _fdm_guard = FdGuard(fdm);

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
      assert_ok(uv_tty_set_mode(tty_ptr, uv_tty_mode_t::UV_TTY_MODE_RAW));

      // Set errno to a known sentinel value.
      set_errno(42);

      // reset_mode should preserve errno.
      assert_ok(uv_tty_reset_mode());

      assert_eq!(get_errno(), 42, "uv_tty_reset_mode should preserve errno");

      // Clean up errno.
      set_errno(0);

      uv_close(tty_ptr as *mut uv_handle_t, None);
    }
    tick(runtime).await;
  })
  .await;
}

#[cfg(unix)]
#[test]
fn tty_guess_handle_negative_fd() {
  assert_eq!(uv_guess_handle(-1), uv_handle_type::UV_UNKNOWN_HANDLE);
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn tty_read_stop() {
  run_test(async |runtime, uv_loop| {
    let (fdm, fds) = unsafe { open_pty_pair() };

    // Put slave in raw mode.
    unsafe {
      let mut term: libc::termios = std::mem::zeroed();
      libc::tcgetattr(fds, &mut term);
      libc::cfmakeraw(&mut term);
      libc::tcsetattr(fds, libc::TCSANOW, &term);
    }

    let mut tty = std::mem::MaybeUninit::<uv_tty_t>::uninit();
    let tty_ptr = tty.as_mut_ptr();
    unsafe {
      assert_ok(uv_tty_init(uv_loop, tty_ptr, fds, 0));
    }

    unsafe extern "C" fn alloc_cb(
      _: *mut uv_handle_t,
      size: usize,
      buf: *mut uv_buf_t,
    ) {
      let mut v = Vec::<u8>::with_capacity(size);
      unsafe {
        (*buf).base = v.as_mut_ptr().cast();
        (*buf).len = size;
      }
      std::mem::forget(v);
    }

    unsafe extern "C" fn read_cb(
      _handle: *mut uv_stream_t,
      _nread: isize,
      buf: *const uv_buf_t,
    ) {
      unsafe {
        if !(*buf).base.is_null() && (*buf).len > 0 {
          drop(Vec::<u8>::from_raw_parts((*buf).base.cast(), 0, (*buf).len));
        }
      }
    }

    // Start then immediately stop reads.
    unsafe {
      assert_ok(uv_read_start(
        tty_ptr as *mut uv_stream_t,
        Some(alloc_cb),
        Some(read_cb),
      ));
      assert!((*tty_ptr).internal_reading);

      assert_ok(uv_read_stop(tty_ptr as *mut uv_stream_t));
      assert!(!(*tty_ptr).internal_reading);
    }

    // Write to master — should NOT trigger read callback since reads are stopped.
    unsafe {
      libc::write(fdm, b"nope".as_ptr() as *const _, 4);
    }
    tick(runtime).await;

    unsafe {
      uv_close(tty_ptr as *mut uv_handle_t, None);
      libc::close(fdm);
    }
    tick(runtime).await;
  })
  .await;
}

// ========== Regression: uv_write must not fire callbacks synchronously ==========

/// Regression test for https://github.com/denoland/deno/issues/32891
///
/// uv_write must never fire the write callback synchronously. Doing so causes
/// re-entrancy panics when callers (e.g. StreamWrap ops) hold an OpState borrow
/// during the call to uv_write. This test verifies that the callback is deferred
/// to the event loop (poll_tcp_handle/run_io) rather than firing inline.
#[tokio::test(flavor = "current_thread")]
async fn uv_write_callback_is_deferred() {
  run_test(async |runtime, uv_loop| {
    let fired = Rc::new(Cell::new(false));
    let fired_ptr = Rc::into_raw(fired.clone());

    unsafe extern "C" fn write_cb(req: *mut uv_write_t, status: i32) {
      assert_eq!(status, 0);
      let fired = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      fired.set(true);
      let _ = Rc::into_raw(fired);
    }

    // --- Set up a server ---
    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();

    unsafe extern "C" fn on_connection(server: *mut uv_stream_t, _status: i32) {
      let _ = server;
    }

    let server_port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());

      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        1,
        Some(on_connection),
      ));

      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      server_port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // --- Connect a client ---
    let connected = Rc::new(Cell::new(false));
    let connected_ptr = Rc::into_raw(connected.clone());

    unsafe extern "C" fn on_connect(req: *mut uv_connect_t, status: i32) {
      assert_eq!(status, 0);
      let connected = unsafe { Rc::from_raw((*req).data as *const Cell<bool>) };
      connected.set(true);
      let _ = Rc::into_raw(connected);
    }

    let mut client = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let client_ptr = client.as_mut_ptr();
    let mut connect_req = std::mem::MaybeUninit::<uv_connect_t>::uninit();
    let connect_req_ptr = connect_req.as_mut_ptr();

    unsafe {
      uv_tcp_init(uv_loop, client_ptr);
      (*connect_req_ptr).data = connected_ptr as *mut c_void;

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), server_port as i32, addr.as_mut_ptr());

      assert_ok(uv_tcp_connect(
        connect_req_ptr,
        client_ptr,
        addr.as_ptr() as *const c_void,
        Some(on_connect),
      ));
    }

    // Poll until connected.
    for _ in 0..100 {
      tick(runtime).await;
      if connected.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(connected.get(), "Client should have connected");

    // Accept the connection on the server side.
    let mut accepted = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let accepted_ptr = accepted.as_mut_ptr();
    unsafe {
      uv_tcp_init(uv_loop, accepted_ptr);
      assert_ok(uv_accept(
        server_ptr as *mut uv_stream_t,
        accepted_ptr as *mut uv_stream_t,
      ));
    }

    // Now write a small buffer — should succeed via try_write but the
    // callback must NOT fire synchronously.
    let write_data = b"hello";
    let mut write_req = std::mem::MaybeUninit::<uv_write_t>::uninit();
    let write_req_ptr = write_req.as_mut_ptr();

    unsafe {
      (*write_req_ptr).data = fired_ptr as *mut c_void;
      let buf = uv_buf_t {
        base: write_data.as_ptr() as *mut _,
        len: write_data.len(),
      };
      assert_ok(uv_write(
        write_req_ptr,
        client_ptr as *mut uv_stream_t,
        &buf,
        1,
        Some(write_cb),
      ));
    }

    // The callback must NOT have fired yet (it should be deferred).
    assert!(
      !fired.get(),
      "uv_write callback must not fire synchronously"
    );

    // Tick the event loop — now the callback should fire.
    for _ in 0..100 {
      tick(runtime).await;
      if fired.get() {
        break;
      }
      tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }
    assert!(
      fired.get(),
      "write callback should fire after event loop tick"
    );

    // Cleanup.
    unsafe {
      uv_close(accepted_ptr as *mut uv_handle_t, None);
      uv_close(client_ptr as *mut uv_handle_t, None);
      uv_close(server_ptr as *mut uv_handle_t, None);
      Rc::from_raw(connected_ptr);
      Rc::from_raw(fired_ptr);
    }
    tick(runtime).await;
  })
  .await;
}

// ========== TCP batch accept ==========

/// Verify that multiple connections queued before a tick are all accepted
/// in a single event loop iteration. This prevents starvation when the
/// connection handler does async work (e.g., Deno.listenTls) that delays
/// returning to the I/O phase.
#[tokio::test(flavor = "current_thread")]
async fn tcp_batch_accept() {
  run_test(async |runtime, uv_loop| {
    // Shared state passed through server.data: a counter and a Vec of
    // heap-allocated accepted client handles (so uv_close's deferred
    // processing doesn't hit a dangling stack pointer).
    struct AcceptState {
      count: Cell<u32>,
      clients: RefCell<Vec<*mut uv_tcp_t>>,
    }
    let state = Rc::new(AcceptState {
      count: Cell::new(0),
      clients: RefCell::new(Vec::new()),
    });
    let state_ptr = Rc::into_raw(state.clone());

    let mut server = std::mem::MaybeUninit::<uv_tcp_t>::uninit();
    let server_ptr = server.as_mut_ptr();

    unsafe extern "C" fn on_connection(
      server: *mut uv_stream_t,
      status: i32,
    ) {
      unsafe {
        assert_eq!(status, 0);
        let state_ptr = (*server).data as *const AcceptState;
        let state = &*state_ptr;

        // Heap-allocate the client handle so it stays valid until
        // uv_close processes it in the close phase.
        let client_ptr = Box::into_raw(Box::new(
          std::mem::MaybeUninit::<uv_tcp_t>::uninit(),
        )) as *mut uv_tcp_t;
        let loop_ = (*(server as *const uv_tcp_t)).loop_;
        uv_tcp_init(loop_, client_ptr);
        let rc = uv_accept(server, client_ptr as *mut uv_stream_t);
        assert_eq!(rc, 0);
        state.count.set(state.count.get() + 1);

        // Track the heap pointer so the outer scope can close + free them.
        state.clients.borrow_mut().push(client_ptr);
      }
    }

    let server_port: u16;
    unsafe {
      uv_tcp_init(uv_loop, server_ptr);
      (*server_ptr).data = state_ptr as *mut c_void;

      let mut addr = std::mem::MaybeUninit::<sockaddr_in>::uninit();
      let ip = std::ffi::CString::new("127.0.0.1").unwrap();
      uv_ip4_addr(ip.as_ptr(), 0, addr.as_mut_ptr());
      assert_ok(uv_tcp_bind(
        server_ptr,
        addr.as_ptr() as *const c_void,
        0,
        0,
      ));
      assert_ok(uv_listen(
        server_ptr as *mut uv_stream_t,
        128,
        Some(on_connection),
      ));

      let mut name = std::mem::MaybeUninit::<sockaddr_in>::zeroed();
      let mut namelen = std::mem::size_of::<sockaddr_in>() as i32;
      uv_tcp_getsockname(
        server_ptr,
        name.as_mut_ptr() as *mut c_void,
        &mut namelen,
      );
      server_port = u16::from_be(name.assume_init_ref().sin_port);
    }

    // Open multiple connections BEFORE ticking the event loop so they all
    // land in the same poll_accept batch.
    const NUM_CONNECTIONS: u32 = 8;
    let mut client_streams = Vec::new();
    for _ in 0..NUM_CONNECTIONS {
      let stream =
        tokio::net::TcpStream::connect(format!("127.0.0.1:{}", server_port))
          .await
          .unwrap();
      client_streams.push(stream);
    }

    // A single tick should accept all connections thanks to batch-accept.
    tick(runtime).await;

    let count = state.count.get();
    assert_eq!(
      count, NUM_CONNECTIONS,
      "Expected all {NUM_CONNECTIONS} connections to be accepted in one tick, got {count}"
    );

    // Cleanup: close all accepted client handles, then the server.
    drop(client_streams);
    unsafe {
      for client_ptr in state.clients.borrow().iter() {
        uv_close(*client_ptr as *mut uv_handle_t, None);
      }
      uv_close(server_ptr as *mut uv_handle_t, None);
    }
    // Tick to process deferred closes.
    tick(runtime).await;

    // Free heap-allocated client handles now that close phase is done.
    unsafe {
      for client_ptr in state.clients.borrow().iter() {
        drop(Box::from_raw(
          *client_ptr as *mut std::mem::MaybeUninit<uv_tcp_t>,
        ));
      }
      Rc::from_raw(state_ptr);
    }
  })
  .await;
}

// ========== Pipe handle lifecycle ==========

// UV_HANDLE_ACTIVE flag value (matches uv_compat.rs private const)
#[cfg(unix)]
const UV_HANDLE_ACTIVE: u32 = 1 << 0;

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn pipe_open_not_active_until_read_start() {
  run_test(async |runtime, uv_loop| {
    // Create an OS pipe pair.
    let mut pipe_fds = [0i32; 2];
    assert_eq!(unsafe { libc::pipe(pipe_fds.as_mut_ptr()) }, 0);
    let write_fd = pipe_fds[1];
    let _write_guard = FdGuard(write_fd);

    // Init and open a uv_pipe_t on the read end.
    let mut pipe = new_pipe(false);
    unsafe {
      assert_ok(pipe::uv_pipe_init(uv_loop, &mut pipe, 0));
      assert_ok(pipe::uv_pipe_open(&mut pipe, pipe_fds[0]));
    }

    // After uv_pipe_open, the handle should NOT be active.
    // This allows the event loop to exit when the pipe is idle.
    assert_eq!(
      pipe.flags & UV_HANDLE_ACTIVE,
      0,
      "pipe should not be active after uv_pipe_open"
    );

    // Start reading -- now the handle should become active.
    unsafe extern "C" fn alloc_cb(
      _handle: *mut uv_handle_t,
      suggested_size: usize,
      buf: *mut uv_buf_t,
    ) {
      // SAFETY: malloc + writing to out-param buf.
      unsafe {
        let ptr = libc::malloc(suggested_size) as *mut c_char;
        (*buf).base = ptr;
        (*buf).len = suggested_size;
      }
    }
    unsafe extern "C" fn read_cb(
      _stream: *mut uv_stream_t,
      _nread: isize,
      buf: *const uv_buf_t,
    ) {
      // SAFETY: freeing the buffer allocated by alloc_cb.
      unsafe {
        if !(*buf).base.is_null() {
          libc::free((*buf).base as *mut c_void);
        }
      }
    }
    unsafe {
      assert_ok(pipe::read_start_pipe(
        &mut pipe,
        Some(alloc_cb),
        Some(read_cb),
      ));
    }
    assert_ne!(
      pipe.flags & UV_HANDLE_ACTIVE,
      0,
      "pipe should be active after read_start"
    );

    // Stop reading and tick the loop so poll_pipe_handle deactivates it.
    unsafe {
      pipe::read_stop_pipe(&mut pipe);
    }
    tick(runtime).await;

    assert_eq!(
      pipe.flags & UV_HANDLE_ACTIVE,
      0,
      "pipe should not be active after read_stop + tick"
    );

    // Cleanup: close the pipe handle.
    unsafe {
      uv_close(&mut pipe as *mut uv_pipe_t as *mut uv_handle_t, None);
    }
    tick(runtime).await;
  })
  .await;
}