v8 147.1.0

Rust bindings to V8
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
// Copyright 2019-2021 the Deno authors. All rights reserved. MIT license.
use crate::Array;
use crate::CallbackScope;
use crate::Context;
use crate::Data;
use crate::FixedArray;
use crate::Function;
use crate::FunctionCodeHandling;
use crate::Local;
use crate::Message;
use crate::Module;
use crate::Object;
use crate::PinScope;
use crate::Platform;
use crate::Promise;
use crate::PromiseResolver;
use crate::StartupData;
use crate::String;
use crate::V8::get_current_platform;
use crate::Value;
use crate::binding::v8__HeapCodeStatistics;
use crate::binding::v8__HeapSpaceStatistics;
use crate::binding::v8__HeapStatistics;
use crate::binding::v8__Isolate__UseCounterFeature;
pub use crate::binding::v8__ModuleImportPhase as ModuleImportPhase;
use crate::cppgc::Heap;
use crate::external_references::ExternalReference;
use crate::function::FunctionCallbackInfo;
use crate::gc::GCCallbackFlags;
use crate::gc::GCType;
use crate::handle::FinalizerCallback;
use crate::handle::FinalizerMap;
use crate::isolate_create_params::CreateParams;
use crate::isolate_create_params::raw;
use crate::promise::PromiseRejectMessage;
use crate::snapshot::SnapshotCreator;
use crate::support::MapFnFrom;
use crate::support::MapFnTo;
use crate::support::Opaque;
use crate::support::ToCFn;
use crate::support::UnitType;
use crate::support::char;
use crate::support::int;
use crate::support::size_t;
use crate::wasm::WasmStreaming;
use crate::wasm::trampoline;
use std::ffi::CStr;

use std::any::Any;
use std::any::TypeId;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::c_void;
use std::fmt::{self, Debug, Formatter};
use std::hash::BuildHasher;
use std::hash::Hasher;
use std::mem::MaybeUninit;
use std::mem::align_of;
use std::mem::forget;
use std::mem::needs_drop;
use std::mem::size_of;
use std::ops::Deref;
use std::ops::DerefMut;
use std::pin::pin;
use std::ptr;
use std::ptr::NonNull;
use std::ptr::addr_of_mut;
use std::ptr::drop_in_place;
use std::ptr::null_mut;
use std::sync::Arc;
use std::sync::Mutex;

/// Policy for running microtasks:
///   - explicit: microtasks are invoked with the
///     Isolate::PerformMicrotaskCheckpoint() method;
///   - auto: microtasks are invoked when the script call depth decrements
///     to zero.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum MicrotasksPolicy {
  Explicit = 0,
  // Scoped = 1 (RAII) is omitted for now, doesn't quite map to idiomatic Rust.
  Auto = 2,
}

/// Memory pressure level for the MemoryPressureNotification.
/// None hints V8 that there is no memory pressure.
/// Moderate hints V8 to speed up incremental garbage collection at the cost
/// of higher latency due to garbage collection pauses.
/// Critical hints V8 to free memory as soon as possible. Garbage collection
/// pauses at this level will be large.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum MemoryPressureLevel {
  None = 0,
  Moderate = 1,
  Critical = 2,
}

/// Time zone redetection indicator for
/// DateTimeConfigurationChangeNotification.
///
/// kSkip indicates V8 that the notification should not trigger redetecting
/// host time zone. kRedetect indicates V8 that host time zone should be
/// redetected, and used to set the default time zone.
///
/// The host time zone detection may require file system access or similar
/// operations unlikely to be available inside a sandbox. If v8 is run inside a
/// sandbox, the host time zone has to be detected outside the sandbox before
/// calling DateTimeConfigurationChangeNotification function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum TimeZoneDetection {
  Skip = 0,
  Redetect = 1,
}

/// PromiseHook with type Init is called when a new promise is
/// created. When a new promise is created as part of the chain in the
/// case of Promise.then or in the intermediate promises created by
/// Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
/// otherwise we pass undefined.
///
/// PromiseHook with type Resolve is called at the beginning of
/// resolve or reject function defined by CreateResolvingFunctions.
///
/// PromiseHook with type Before is called at the beginning of the
/// PromiseReactionJob.
///
/// PromiseHook with type After is called right at the end of the
/// PromiseReactionJob.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum PromiseHookType {
  Init,
  Resolve,
  Before,
  After,
}

/// Types of garbage collections that can be requested via
/// [`Isolate::request_garbage_collection_for_testing`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum GarbageCollectionType {
  Full,
  Minor,
}

pub type MessageCallback = unsafe extern "C" fn(Local<Message>, Local<Value>);

bitflags! {
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  #[repr(transparent)]
  pub struct MessageErrorLevel: int {
    const LOG = 1 << 0;
    const DEBUG = 1 << 1;
    const INFO = 1 << 2;
    const ERROR = 1 << 3;
    const WARNING = 1 << 4;
    const ALL = (1 << 5) - 1;
  }
}

pub type PromiseHook =
  unsafe extern "C" fn(PromiseHookType, Local<Promise>, Local<Value>);

pub type PromiseRejectCallback = unsafe extern "C" fn(PromiseRejectMessage);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum WasmAsyncSuccess {
  Success,
  Fail,
}
pub type WasmAsyncResolvePromiseCallback = unsafe extern "C" fn(
  UnsafeRawIsolatePtr,
  Local<Context>,
  Local<PromiseResolver>,
  Local<Value>,
  WasmAsyncSuccess,
);

pub type AllowWasmCodeGenerationCallback =
  unsafe extern "C" fn(Local<Context>, Local<String>) -> bool;

/// HostInitializeImportMetaObjectCallback is called the first time import.meta
/// is accessed for a module. Subsequent access will reuse the same value.
///
/// The method combines two implementation-defined abstract operations into one:
/// HostGetImportMetaProperties and HostFinalizeImportMeta.
///
/// The embedder should use v8::Object::CreateDataProperty to add properties on
/// the meta object.
pub type HostInitializeImportMetaObjectCallback =
  unsafe extern "C" fn(Local<Context>, Local<Module>, Local<Object>);

/// HostImportModuleDynamicallyCallback is called when we require the embedder
/// to load a module. This is used as part of the dynamic import syntax.
///
/// The host_defined_options are metadata provided by the host environment, which may be used
/// to customize or further specify how the module should be imported.
///
/// The resource_name is the identifier or path for the module or script making the import request.
///
/// The specifier is the name of the module that should be imported.
///
/// The import_attributes are import assertions for this request in the form:
/// [key1, value1, key2, value2, ...] where the keys and values are of type
/// v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
/// returned from ModuleRequest::GetImportAssertions(), this array does not
/// contain the source Locations of the assertions.
///
/// The embedder must compile, instantiate, evaluate the Module, and obtain its
/// namespace object.
///
/// The Promise returned from this function is forwarded to userland JavaScript.
/// The embedder must resolve this promise with the module namespace object. In
/// case of an exception, the embedder must reject this promise with the
/// exception. If the promise creation itself fails (e.g. due to stack
/// overflow), the embedder must propagate that exception by returning an empty
/// MaybeLocal.
///
/// # Example
///
/// ```
/// fn host_import_module_dynamically_callback_example<'s>(
///   scope: &mut v8::HandleScope<'s>,
///   host_defined_options: v8::Local<'s, v8::Data>,
///   resource_name: v8::Local<'s, v8::Value>,
///   specifier: v8::Local<'s, v8::String>,
///   import_attributes: v8::Local<'s, v8::FixedArray>,
/// ) -> Option<v8::Local<'s, v8::Promise>> {
///   todo!()
/// }
/// ```
pub trait HostImportModuleDynamicallyCallback:
  UnitType
  + for<'s, 'i> FnOnce(
    &mut PinScope<'s, 'i>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    Local<'s, FixedArray>,
  ) -> Option<Local<'s, Promise>>
{
  fn to_c_fn(self) -> RawHostImportModuleDynamicallyCallback;
}

#[cfg(target_family = "unix")]
pub(crate) type RawHostImportModuleDynamicallyCallback =
  for<'s> unsafe extern "C" fn(
    Local<'s, Context>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    Local<'s, FixedArray>,
  ) -> *mut Promise;

#[cfg(all(
  target_family = "windows",
  any(target_arch = "x86_64", target_arch = "aarch64")
))]
pub type RawHostImportModuleDynamicallyCallback =
  for<'s> unsafe extern "C" fn(
    *mut *mut Promise,
    Local<'s, Context>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    Local<'s, FixedArray>,
  ) -> *mut *mut Promise;

impl<F> HostImportModuleDynamicallyCallback for F
where
  F: UnitType
    + for<'s, 'i> FnOnce(
      &mut PinScope<'s, 'i>,
      Local<'s, Data>,
      Local<'s, Value>,
      Local<'s, String>,
      Local<'s, FixedArray>,
    ) -> Option<Local<'s, Promise>>,
{
  #[inline(always)]
  fn to_c_fn(self) -> RawHostImportModuleDynamicallyCallback {
    #[allow(unused_variables)]
    #[inline(always)]
    fn scope_adapter<'s, 'i: 's, F: HostImportModuleDynamicallyCallback>(
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_attributes: Local<'s, FixedArray>,
    ) -> Option<Local<'s, Promise>> {
      let scope = pin!(unsafe { CallbackScope::new(context) });
      let mut scope = scope.init();
      (F::get())(
        &mut scope,
        host_defined_options,
        resource_name,
        specifier,
        import_attributes,
      )
    }

    #[cfg(target_family = "unix")]
    #[inline(always)]
    unsafe extern "C" fn abi_adapter<
      's,
      F: HostImportModuleDynamicallyCallback,
    >(
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_attributes: Local<'s, FixedArray>,
    ) -> *mut Promise {
      scope_adapter::<F>(
        context,
        host_defined_options,
        resource_name,
        specifier,
        import_attributes,
      )
      .map_or_else(null_mut, |return_value| return_value.as_non_null().as_ptr())
    }

    #[cfg(all(
      target_family = "windows",
      any(target_arch = "x86_64", target_arch = "aarch64")
    ))]
    #[inline(always)]
    unsafe extern "C" fn abi_adapter<
      's,
      F: HostImportModuleDynamicallyCallback,
    >(
      return_value: *mut *mut Promise,
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_attributes: Local<'s, FixedArray>,
    ) -> *mut *mut Promise {
      unsafe {
        std::ptr::write(
          return_value,
          scope_adapter::<F>(
            context,
            host_defined_options,
            resource_name,
            specifier,
            import_attributes,
          )
          .map(|return_value| return_value.as_non_null().as_ptr())
          .unwrap_or_else(null_mut),
        );
        return_value
      }
    }

    abi_adapter::<F>
  }
}

/// HostImportModuleWithPhaseDynamicallyCallback is called when we
/// require the embedder to load a module with a specific phase. This is used
/// as part of the dynamic import syntax.
///
/// The referrer contains metadata about the script/module that calls
/// import.
///
/// The specifier is the name of the module that should be imported.
///
/// The phase is the phase of the import requested.
///
/// The import_attributes are import attributes for this request in the form:
/// [key1, value1, key2, value2, ...] where the keys and values are of type
/// v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
/// returned from ModuleRequest::GetImportAttributes(), this array does not
/// contain the source Locations of the attributes.
///
/// The Promise returned from this function is forwarded to userland
/// JavaScript. The embedder must resolve this promise according to the phase
/// requested:
/// - For ModuleImportPhase::kSource, the promise must be resolved with a
///   compiled ModuleSource object, or rejected with a SyntaxError if the
///   module does not support source representation.
/// - For ModuleImportPhase::kEvaluation, the promise must be resolved with a
///   ModuleNamespace object of a module that has been compiled, instantiated,
///   and evaluated.
///
/// In case of an exception, the embedder must reject this promise with the
/// exception. If the promise creation itself fails (e.g. due to stack
/// overflow), the embedder must propagate that exception by returning an empty
/// MaybeLocal.
///
/// This callback is still experimental and is only invoked for source phase
/// imports.
pub trait HostImportModuleWithPhaseDynamicallyCallback:
  UnitType
  + for<'s, 'i> FnOnce(
    &mut PinScope<'s, 'i>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    ModuleImportPhase,
    Local<'s, FixedArray>,
  ) -> Option<Local<'s, Promise>>
{
  fn to_c_fn(self) -> RawHostImportModuleWithPhaseDynamicallyCallback;
}

#[cfg(target_family = "unix")]
pub(crate) type RawHostImportModuleWithPhaseDynamicallyCallback =
  for<'s> unsafe extern "C" fn(
    Local<'s, Context>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    ModuleImportPhase,
    Local<'s, FixedArray>,
  ) -> *mut Promise;

#[cfg(all(
  target_family = "windows",
  any(target_arch = "x86_64", target_arch = "aarch64")
))]
pub type RawHostImportModuleWithPhaseDynamicallyCallback =
  for<'s> unsafe extern "C" fn(
    *mut *mut Promise,
    Local<'s, Context>,
    Local<'s, Data>,
    Local<'s, Value>,
    Local<'s, String>,
    ModuleImportPhase,
    Local<'s, FixedArray>,
  ) -> *mut *mut Promise;

impl<F> HostImportModuleWithPhaseDynamicallyCallback for F
where
  F: UnitType
    + for<'s, 'i> FnOnce(
      &mut PinScope<'s, 'i>,
      Local<'s, Data>,
      Local<'s, Value>,
      Local<'s, String>,
      ModuleImportPhase,
      Local<'s, FixedArray>,
    ) -> Option<Local<'s, Promise>>,
{
  #[inline(always)]
  fn to_c_fn(self) -> RawHostImportModuleWithPhaseDynamicallyCallback {
    #[allow(unused_variables)]
    #[inline(always)]
    fn scope_adapter<'s, F: HostImportModuleWithPhaseDynamicallyCallback>(
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_phase: ModuleImportPhase,
      import_attributes: Local<'s, FixedArray>,
    ) -> Option<Local<'s, Promise>> {
      let scope = pin!(unsafe { CallbackScope::new(context) });
      let mut scope = scope.init();
      (F::get())(
        &mut scope,
        host_defined_options,
        resource_name,
        specifier,
        import_phase,
        import_attributes,
      )
    }

    #[cfg(target_family = "unix")]
    #[inline(always)]
    unsafe extern "C" fn abi_adapter<
      's,
      F: HostImportModuleWithPhaseDynamicallyCallback,
    >(
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_phase: ModuleImportPhase,
      import_attributes: Local<'s, FixedArray>,
    ) -> *mut Promise {
      scope_adapter::<F>(
        context,
        host_defined_options,
        resource_name,
        specifier,
        import_phase,
        import_attributes,
      )
      .map_or_else(null_mut, |return_value| return_value.as_non_null().as_ptr())
    }

    #[cfg(all(
      target_family = "windows",
      any(target_arch = "x86_64", target_arch = "aarch64")
    ))]
    #[inline(always)]
    unsafe extern "C" fn abi_adapter<
      's,
      F: HostImportModuleWithPhaseDynamicallyCallback,
    >(
      return_value: *mut *mut Promise,
      context: Local<'s, Context>,
      host_defined_options: Local<'s, Data>,
      resource_name: Local<'s, Value>,
      specifier: Local<'s, String>,
      import_phase: ModuleImportPhase,
      import_attributes: Local<'s, FixedArray>,
    ) -> *mut *mut Promise {
      unsafe {
        std::ptr::write(
          return_value,
          scope_adapter::<F>(
            context,
            host_defined_options,
            resource_name,
            specifier,
            import_phase,
            import_attributes,
          )
          .map(|return_value| return_value.as_non_null().as_ptr())
          .unwrap_or_else(null_mut),
        );
        return_value
      }
    }

    abi_adapter::<F>
  }
}

/// `HostCreateShadowRealmContextCallback` is called each time a `ShadowRealm`
/// is being constructed. You can use [`HandleScope::get_current_context`] to
/// get the [`Context`] in which the constructor is being run.
///
/// The method combines [`Context`] creation and the implementation-defined
/// abstract operation `HostInitializeShadowRealm` into one.
///
/// The embedder should use [`Context::new`] to create a new context. If the
/// creation fails, the embedder must propagate that exception by returning
/// [`None`].
pub type HostCreateShadowRealmContextCallback =
  for<'s, 'i> fn(scope: &mut PinScope<'s, 'i>) -> Option<Local<'s, Context>>;

pub type GcCallbackWithData = unsafe extern "C" fn(
  isolate: UnsafeRawIsolatePtr,
  r#type: GCType,
  flags: GCCallbackFlags,
  data: *mut c_void,
);

pub type InterruptCallback =
  unsafe extern "C" fn(isolate: UnsafeRawIsolatePtr, data: *mut c_void);

pub type NearHeapLimitCallback = unsafe extern "C" fn(
  data: *mut c_void,
  current_heap_limit: usize,
  initial_heap_limit: usize,
) -> usize;

#[repr(C)]
pub struct OomDetails {
  pub is_heap_oom: bool,
  pub detail: *const char,
}

pub type OomErrorCallback =
  unsafe extern "C" fn(location: *const char, details: &OomDetails);

// Windows x64 ABI: MaybeLocal<Value> returned on the stack.
#[cfg(target_os = "windows")]
pub type PrepareStackTraceCallback<'s> =
  unsafe extern "C" fn(
    *mut *const Value,
    Local<'s, Context>,
    Local<'s, Value>,
    Local<'s, Array>,
  ) -> *mut *const Value;

// System V ABI: MaybeLocal<Value> returned in a register.
// System V i386 ABI: Local<Value> returned in hidden pointer (struct).
#[cfg(not(target_os = "windows"))]
#[repr(C)]
pub struct PrepareStackTraceCallbackRet(*const Value);

#[cfg(not(target_os = "windows"))]
pub type PrepareStackTraceCallback<'s> =
  unsafe extern "C" fn(
    Local<'s, Context>,
    Local<'s, Value>,
    Local<'s, Array>,
  ) -> PrepareStackTraceCallbackRet;

pub type UseCounterFeature = v8__Isolate__UseCounterFeature;
pub type UseCounterCallback =
  unsafe extern "C" fn(&mut Isolate, UseCounterFeature);

unsafe extern "C" {
  fn v8__Isolate__New(params: *const raw::CreateParams) -> *mut RealIsolate;
  fn v8__Isolate__Dispose(this: *mut RealIsolate);
  fn v8__Isolate__GetNumberOfDataSlots(this: *const RealIsolate) -> u32;
  fn v8__Isolate__GetData(
    isolate: *const RealIsolate,
    slot: u32,
  ) -> *mut c_void;
  fn v8__Isolate__SetData(
    isolate: *const RealIsolate,
    slot: u32,
    data: *mut c_void,
  );
  fn v8__Isolate__Enter(this: *mut RealIsolate);
  fn v8__Isolate__Exit(this: *mut RealIsolate);
  fn v8__Isolate__GetCurrent() -> *mut RealIsolate;
  fn v8__Isolate__MemoryPressureNotification(this: *mut RealIsolate, level: u8);
  fn v8__Isolate__ClearKeptObjects(isolate: *mut RealIsolate);
  fn v8__Isolate__LowMemoryNotification(isolate: *mut RealIsolate);
  fn v8__Isolate__GetHeapStatistics(
    this: *mut RealIsolate,
    s: *mut v8__HeapStatistics,
  );
  fn v8__Isolate__SetCaptureStackTraceForUncaughtExceptions(
    this: *mut RealIsolate,
    capture: bool,
    frame_limit: i32,
  );
  fn v8__Isolate__AddMessageListener(
    isolate: *mut RealIsolate,
    callback: MessageCallback,
  ) -> bool;
  fn v8__Isolate__AddMessageListenerWithErrorLevel(
    isolate: *mut RealIsolate,
    callback: MessageCallback,
    message_levels: MessageErrorLevel,
  ) -> bool;
  fn v8__Isolate__AddGCPrologueCallback(
    isolate: *mut RealIsolate,
    callback: GcCallbackWithData,
    data: *mut c_void,
    gc_type_filter: GCType,
  );
  fn v8__Isolate__RemoveGCPrologueCallback(
    isolate: *mut RealIsolate,
    callback: GcCallbackWithData,
    data: *mut c_void,
  );
  fn v8__Isolate__AddGCEpilogueCallback(
    isolate: *mut RealIsolate,
    callback: GcCallbackWithData,
    data: *mut c_void,
    gc_type_filter: GCType,
  );
  fn v8__Isolate__RemoveGCEpilogueCallback(
    isolate: *mut RealIsolate,
    callback: GcCallbackWithData,
    data: *mut c_void,
  );
  fn v8__Isolate__NumberOfHeapSpaces(isolate: *mut RealIsolate) -> size_t;
  fn v8__Isolate__GetHeapSpaceStatistics(
    isolate: *mut RealIsolate,
    space_statistics: *mut v8__HeapSpaceStatistics,
    index: size_t,
  ) -> bool;
  fn v8__Isolate__GetHeapCodeAndMetadataStatistics(
    isolate: *mut RealIsolate,
    code_statistics: *mut v8__HeapCodeStatistics,
  ) -> bool;
  fn v8__Isolate__AddNearHeapLimitCallback(
    isolate: *mut RealIsolate,
    callback: NearHeapLimitCallback,
    data: *mut c_void,
  );
  fn v8__Isolate__RemoveNearHeapLimitCallback(
    isolate: *mut RealIsolate,
    callback: NearHeapLimitCallback,
    heap_limit: usize,
  );
  fn v8__Isolate__SetOOMErrorHandler(
    isolate: *mut RealIsolate,
    callback: OomErrorCallback,
  );
  fn v8__Isolate__AdjustAmountOfExternalAllocatedMemory(
    isolate: *mut RealIsolate,
    change_in_bytes: i64,
  ) -> i64;
  fn v8__Isolate__GetCppHeap(isolate: *mut RealIsolate) -> *mut Heap;
  fn v8__Isolate__SetPrepareStackTraceCallback(
    isolate: *mut RealIsolate,
    callback: PrepareStackTraceCallback,
  );
  fn v8__Isolate__SetPromiseHook(isolate: *mut RealIsolate, hook: PromiseHook);
  fn v8__Isolate__SetPromiseRejectCallback(
    isolate: *mut RealIsolate,
    callback: PromiseRejectCallback,
  );
  fn v8__Isolate__SetWasmAsyncResolvePromiseCallback(
    isolate: *mut RealIsolate,
    callback: WasmAsyncResolvePromiseCallback,
  );
  fn v8__Isolate__SetAllowWasmCodeGenerationCallback(
    isolate: *mut RealIsolate,
    callback: AllowWasmCodeGenerationCallback,
  );
  fn v8__Isolate__SetHostInitializeImportMetaObjectCallback(
    isolate: *mut RealIsolate,
    callback: HostInitializeImportMetaObjectCallback,
  );
  fn v8__Isolate__SetHostImportModuleDynamicallyCallback(
    isolate: *mut RealIsolate,
    callback: RawHostImportModuleDynamicallyCallback,
  );
  fn v8__Isolate__SetHostImportModuleWithPhaseDynamicallyCallback(
    isolate: *mut RealIsolate,
    callback: RawHostImportModuleWithPhaseDynamicallyCallback,
  );
  #[cfg(not(target_os = "windows"))]
  fn v8__Isolate__SetHostCreateShadowRealmContextCallback(
    isolate: *mut RealIsolate,
    callback: unsafe extern "C" fn(
      initiator_context: Local<Context>,
    ) -> *mut Context,
  );
  #[cfg(target_os = "windows")]
  fn v8__Isolate__SetHostCreateShadowRealmContextCallback(
    isolate: *mut RealIsolate,
    callback: unsafe extern "C" fn(
      rv: *mut *mut Context,
      initiator_context: Local<Context>,
    ) -> *mut *mut Context,
  );
  fn v8__Isolate__SetUseCounterCallback(
    isolate: *mut RealIsolate,
    callback: UseCounterCallback,
  );
  fn v8__Isolate__RequestInterrupt(
    isolate: *const RealIsolate,
    callback: InterruptCallback,
    data: *mut c_void,
  );
  fn v8__Isolate__TerminateExecution(isolate: *const RealIsolate);
  fn v8__Isolate__IsExecutionTerminating(isolate: *const RealIsolate) -> bool;
  fn v8__Isolate__CancelTerminateExecution(isolate: *const RealIsolate);
  fn v8__Isolate__GetMicrotasksPolicy(
    isolate: *const RealIsolate,
  ) -> MicrotasksPolicy;
  fn v8__Isolate__SetMicrotasksPolicy(
    isolate: *mut RealIsolate,
    policy: MicrotasksPolicy,
  );
  fn v8__Isolate__PerformMicrotaskCheckpoint(isolate: *mut RealIsolate);
  fn v8__Isolate__EnqueueMicrotask(
    isolate: *mut RealIsolate,
    function: *const Function,
  );
  fn v8__Isolate__SetAllowAtomicsWait(isolate: *mut RealIsolate, allow: bool);
  fn v8__Isolate__SetWasmStreamingCallback(
    isolate: *mut RealIsolate,
    callback: unsafe extern "C" fn(*const FunctionCallbackInfo),
  );
  fn v8__Isolate__DateTimeConfigurationChangeNotification(
    isolate: *mut RealIsolate,
    time_zone_detection: TimeZoneDetection,
  );
  fn v8__Isolate__HasPendingBackgroundTasks(
    isolate: *const RealIsolate,
  ) -> bool;
  fn v8__Isolate__RequestGarbageCollectionForTesting(
    isolate: *mut RealIsolate,
    r#type: usize,
  );

  fn v8__HeapProfiler__TakeHeapSnapshot(
    isolate: *mut RealIsolate,
    callback: unsafe extern "C" fn(*mut c_void, *const u8, usize) -> bool,
    arg: *mut c_void,
  );
}

/// Isolate represents an isolated instance of the V8 engine.  V8 isolates have
/// completely separate states.  Objects from one isolate must not be used in
/// other isolates.  The embedder can create multiple isolates and use them in
/// parallel in multiple threads.  An isolate can be entered by at most one
/// thread at any given time.  The Locker/Unlocker API must be used to
/// synchronize.
///
/// rusty_v8 note: Unlike in the C++ API, the Isolate is entered when it is
/// constructed and exited when dropped. Because of that v8::OwnedIsolate
/// instances must be dropped in the reverse order of creation
#[repr(transparent)]
#[derive(Debug)]
pub struct Isolate(NonNull<RealIsolate>);

#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct UnsafeRawIsolatePtr(*mut RealIsolate);

impl UnsafeRawIsolatePtr {
  pub fn null() -> Self {
    Self(std::ptr::null_mut())
  }

  pub fn is_null(&self) -> bool {
    self.0.is_null()
  }
}

#[repr(C)]
pub struct RealIsolate(Opaque);

impl Isolate {
  pub(crate) fn as_real_ptr(&self) -> *mut RealIsolate {
    self.0.as_ptr()
  }

  pub unsafe fn as_raw_isolate_ptr(&self) -> UnsafeRawIsolatePtr {
    UnsafeRawIsolatePtr(self.0.as_ptr())
  }

  #[inline]
  pub unsafe fn from_raw_isolate_ptr(ptr: UnsafeRawIsolatePtr) -> Self {
    Self(NonNull::new(ptr.0).unwrap())
  }

  #[inline]
  pub unsafe fn from_raw_isolate_ptr_unchecked(
    ptr: UnsafeRawIsolatePtr,
  ) -> Self {
    Self(unsafe { NonNull::new_unchecked(ptr.0) })
  }

  pub unsafe fn from_raw_ptr_unchecked(ptr: *mut RealIsolate) -> Self {
    Self(unsafe { NonNull::new_unchecked(ptr) })
  }

  pub unsafe fn from_raw_ptr(ptr: *mut RealIsolate) -> Self {
    Self(NonNull::new(ptr).unwrap())
  }

  #[inline]
  pub unsafe fn ref_from_raw_isolate_ptr(ptr: &UnsafeRawIsolatePtr) -> &Self {
    if ptr.is_null() {
      panic!("UnsafeRawIsolatePtr is null");
    }
    unsafe { &*(ptr as *const UnsafeRawIsolatePtr as *const Isolate) }
  }

  #[inline]
  pub unsafe fn ref_from_raw_isolate_ptr_unchecked(
    ptr: &UnsafeRawIsolatePtr,
  ) -> &Self {
    unsafe { &*(ptr as *const UnsafeRawIsolatePtr as *const Isolate) }
  }

  #[inline]
  pub unsafe fn ref_from_raw_isolate_ptr_mut(
    ptr: &mut UnsafeRawIsolatePtr,
  ) -> &mut Self {
    if ptr.is_null() {
      panic!("UnsafeRawIsolatePtr is null");
    }
    unsafe { &mut *(ptr as *mut UnsafeRawIsolatePtr as *mut Isolate) }
  }

  #[inline]
  pub unsafe fn ref_from_raw_isolate_ptr_mut_unchecked(
    ptr: &mut UnsafeRawIsolatePtr,
  ) -> &mut Self {
    unsafe { &mut *(ptr as *mut UnsafeRawIsolatePtr as *mut Isolate) }
  }

  #[inline]
  pub(crate) unsafe fn from_non_null(ptr: NonNull<RealIsolate>) -> Self {
    Self(ptr)
  }

  #[inline]
  pub(crate) unsafe fn from_raw_ref(ptr: &NonNull<RealIsolate>) -> &Self {
    // SAFETY: Isolate is a repr(transparent) wrapper around NonNull<RealIsolate>
    unsafe { &*(ptr as *const NonNull<RealIsolate> as *const Isolate) }
  }

  #[inline]
  pub(crate) unsafe fn from_raw_ref_mut(
    ptr: &mut NonNull<RealIsolate>,
  ) -> &mut Self {
    // SAFETY: Isolate is a repr(transparent) wrapper around NonNull<RealIsolate>
    unsafe { &mut *(ptr as *mut NonNull<RealIsolate> as *mut Isolate) }
  }

  // Isolate data slots used internally by rusty_v8.
  const ANNEX_SLOT: u32 = 0;
  const INTERNAL_DATA_SLOT_COUNT: u32 = 2;

  #[inline(always)]
  fn assert_embedder_data_slot_count_and_offset_correct(&self) {
    assert!(
      unsafe { v8__Isolate__GetNumberOfDataSlots(self.as_real_ptr()) }
        >= Self::INTERNAL_DATA_SLOT_COUNT
    )
  }

  fn new_impl(params: CreateParams) -> *mut RealIsolate {
    crate::V8::assert_initialized();
    let (raw_create_params, create_param_allocations) = params.finalize();
    let cxx_isolate = unsafe { v8__Isolate__New(&raw_create_params) };
    let mut isolate = unsafe { Isolate::from_raw_ptr(cxx_isolate) };
    isolate.initialize(create_param_allocations);
    cxx_isolate
  }

  pub(crate) fn initialize(&mut self, create_param_allocations: Box<dyn Any>) {
    self.assert_embedder_data_slot_count_and_offset_correct();
    self.create_annex(create_param_allocations);
  }

  /// Creates a new isolate.  Does not change the currently entered
  /// isolate.
  ///
  /// When an isolate is no longer used its resources should be freed
  /// by calling V8::dispose().  Using the delete operator is not allowed.
  ///
  /// V8::initialize() must have run prior to this.
  #[allow(clippy::new_ret_no_self)]
  pub fn new(params: CreateParams) -> OwnedIsolate {
    OwnedIsolate::new(Self::new_impl(params))
  }

  #[allow(clippy::new_ret_no_self)]
  pub fn snapshot_creator(
    external_references: Option<Cow<'static, [ExternalReference]>>,
    params: Option<CreateParams>,
  ) -> OwnedIsolate {
    SnapshotCreator::new(external_references, params)
  }

  #[allow(clippy::new_ret_no_self)]
  pub fn snapshot_creator_from_existing_snapshot(
    existing_snapshot_blob: StartupData,
    external_references: Option<Cow<'static, [ExternalReference]>>,
    params: Option<CreateParams>,
  ) -> OwnedIsolate {
    SnapshotCreator::from_existing_snapshot(
      existing_snapshot_blob,
      external_references,
      params,
    )
  }

  /// Initial configuration parameters for a new Isolate.
  #[inline(always)]
  pub fn create_params() -> CreateParams {
    CreateParams::default()
  }

  #[inline(always)]
  pub fn thread_safe_handle(&self) -> IsolateHandle {
    IsolateHandle::new(self)
  }

  /// See [`IsolateHandle::terminate_execution`]
  #[inline(always)]
  pub fn terminate_execution(&self) -> bool {
    self.thread_safe_handle().terminate_execution()
  }

  /// See [`IsolateHandle::cancel_terminate_execution`]
  #[inline(always)]
  pub fn cancel_terminate_execution(&self) -> bool {
    self.thread_safe_handle().cancel_terminate_execution()
  }

  /// See [`IsolateHandle::is_execution_terminating`]
  #[inline(always)]
  pub fn is_execution_terminating(&self) -> bool {
    self.thread_safe_handle().is_execution_terminating()
  }

  pub(crate) fn create_annex(
    &mut self,
    create_param_allocations: Box<dyn Any>,
  ) {
    let annex_arc = Arc::new(IsolateAnnex::new(self, create_param_allocations));
    let annex_ptr = Arc::into_raw(annex_arc);
    assert!(self.get_data_internal(Self::ANNEX_SLOT).is_null());
    self.set_data_internal(Self::ANNEX_SLOT, annex_ptr as *mut _);
  }

  unsafe fn dispose_annex(&mut self) -> Box<dyn Any> {
    // Set the `isolate` pointer inside the annex struct to null, so any
    // IsolateHandle that outlives the isolate will know that it can't call
    // methods on the isolate.
    let annex = self.get_annex_mut();
    {
      let _lock = annex.isolate_mutex.lock().unwrap();
      annex.isolate = null_mut();
    }

    // Clear slots and drop owned objects that were taken out of `CreateParams`.
    let create_param_allocations =
      std::mem::replace(&mut annex.create_param_allocations, Box::new(()));
    annex.slots.clear();

    // Run through any remaining guaranteed finalizers.
    for finalizer in annex.finalizer_map.drain() {
      if let FinalizerCallback::Guaranteed(callback) = finalizer {
        callback();
      }
    }

    // Subtract one from the Arc<IsolateAnnex> reference count.
    unsafe { Arc::from_raw(annex) };
    self.set_data(0, null_mut());

    create_param_allocations
  }

  #[inline(always)]
  fn get_annex(&self) -> &IsolateAnnex {
    let annex_ptr =
      self.get_data_internal(Self::ANNEX_SLOT) as *const IsolateAnnex;
    assert!(!annex_ptr.is_null());
    unsafe { &*annex_ptr }
  }

  #[inline(always)]
  fn get_annex_mut(&mut self) -> &mut IsolateAnnex {
    let annex_ptr =
      self.get_data_internal(Self::ANNEX_SLOT) as *mut IsolateAnnex;
    assert!(!annex_ptr.is_null());
    unsafe { &mut *annex_ptr }
  }

  pub(crate) fn set_snapshot_creator(
    &mut self,
    snapshot_creator: SnapshotCreator,
  ) {
    let prev = self
      .get_annex_mut()
      .maybe_snapshot_creator
      .replace(snapshot_creator);
    assert!(prev.is_none());
  }

  pub(crate) fn get_finalizer_map(&self) -> &FinalizerMap {
    &self.get_annex().finalizer_map
  }

  pub(crate) fn get_finalizer_map_mut(&mut self) -> &mut FinalizerMap {
    &mut self.get_annex_mut().finalizer_map
  }

  fn get_annex_arc(&self) -> Arc<IsolateAnnex> {
    let annex_ptr = self.get_annex();
    let annex_arc = unsafe { Arc::from_raw(annex_ptr) };
    let _ = Arc::into_raw(annex_arc.clone());
    annex_arc
  }

  /// Retrieve embedder-specific data from the isolate.
  /// Returns NULL if SetData has never been called for the given `slot`.
  pub fn get_data(&self, slot: u32) -> *mut c_void {
    self.get_data_internal(Self::INTERNAL_DATA_SLOT_COUNT + slot)
  }

  /// Associate embedder-specific data with the isolate. `slot` has to be
  /// between 0 and `Isolate::get_number_of_data_slots()`.
  #[inline(always)]
  pub fn set_data(&mut self, slot: u32, data: *mut c_void) {
    self.set_data_internal(Self::INTERNAL_DATA_SLOT_COUNT + slot, data);
  }

  /// Returns the maximum number of available embedder data slots. Valid slots
  /// are in the range of `0 <= n < Isolate::get_number_of_data_slots()`.
  pub fn get_number_of_data_slots(&self) -> u32 {
    let n = unsafe { v8__Isolate__GetNumberOfDataSlots(self.as_real_ptr()) };
    n - Self::INTERNAL_DATA_SLOT_COUNT
  }

  #[inline(always)]
  pub(crate) fn get_data_internal(&self, slot: u32) -> *mut c_void {
    unsafe { v8__Isolate__GetData(self.as_real_ptr(), slot) }
  }

  #[inline(always)]
  pub(crate) fn set_data_internal(&mut self, slot: u32, data: *mut c_void) {
    unsafe { v8__Isolate__SetData(self.as_real_ptr(), slot, data) }
  }

  // pub(crate) fn init_scope_root(&mut self) {
  //   ScopeData::new_root(self);
  // }

  // pub(crate) fn dispose_scope_root(&mut self) {
  //   ScopeData::drop_root(self);
  // }

  // /// Returns a pointer to the `ScopeData` struct for the current scope.
  // #[inline(always)]
  // pub(crate) fn get_current_scope_data(&self) -> Option<NonNull<ScopeData>> {
  //   let scope_data_ptr = self.get_data_internal(Self::CURRENT_SCOPE_DATA_SLOT);
  //   NonNull::new(scope_data_ptr).map(NonNull::cast)
  // }

  // /// Updates the slot that stores a `ScopeData` pointer for the current scope.
  // #[inline(always)]
  // pub(crate) fn set_current_scope_data(
  //   &mut self,
  //   scope_data: Option<NonNull<ScopeData>>,
  // ) {
  //   let scope_data_ptr = scope_data
  //     .map(NonNull::cast)
  //     .map_or_else(null_mut, NonNull::as_ptr);
  //   self.set_data_internal(Self::CURRENT_SCOPE_DATA_SLOT, scope_data_ptr);
  // }

  /// Get a reference to embedder data added with `set_slot()`.
  #[inline(always)]
  pub fn get_slot<T: 'static>(&self) -> Option<&T> {
    self
      .get_annex()
      .slots
      .get(&TypeId::of::<T>())
      .map(|slot| unsafe { slot.borrow::<T>() })
  }

  /// Get a mutable reference to embedder data added with `set_slot()`.
  #[inline(always)]
  pub fn get_slot_mut<T: 'static>(&mut self) -> Option<&mut T> {
    self
      .get_annex_mut()
      .slots
      .get_mut(&TypeId::of::<T>())
      .map(|slot| unsafe { slot.borrow_mut::<T>() })
  }

  /// Use with Isolate::get_slot and Isolate::get_slot_mut to associate state
  /// with an Isolate.
  ///
  /// This method gives ownership of value to the Isolate. Exactly one object of
  /// each type can be associated with an Isolate. If called more than once with
  /// an object of the same type, the earlier version will be dropped and
  /// replaced.
  ///
  /// Returns true if value was set without replacing an existing value.
  ///
  /// The value will be dropped when the isolate is dropped.
  #[inline(always)]
  pub fn set_slot<T: 'static>(&mut self, value: T) -> bool {
    self
      .get_annex_mut()
      .slots
      .insert(TypeId::of::<T>(), RawSlot::new(value))
      .is_none()
  }

  /// Removes the embedder data added with `set_slot()` and returns it if it exists.
  #[inline(always)]
  pub fn remove_slot<T: 'static>(&mut self) -> Option<T> {
    self
      .get_annex_mut()
      .slots
      .remove(&TypeId::of::<T>())
      .map(|slot| unsafe { slot.into_inner::<T>() })
  }

  /// Sets this isolate as the entered one for the current thread.
  /// Saves the previously entered one (if any), so that it can be
  /// restored when exiting.  Re-entering an isolate is allowed.
  ///
  /// rusty_v8 note: Unlike in the C++ API, the isolate is entered when it is
  /// constructed and exited when dropped.
  #[inline(always)]
  pub unsafe fn enter(&self) {
    unsafe {
      v8__Isolate__Enter(self.as_real_ptr());
    }
  }

  /// Exits this isolate by restoring the previously entered one in the
  /// current thread.  The isolate may still stay the same, if it was
  /// entered more than once.
  ///
  /// Requires: self == Isolate::GetCurrent().
  ///
  /// rusty_v8 note: Unlike in the C++ API, the isolate is entered when it is
  /// constructed and exited when dropped.
  #[inline(always)]
  pub unsafe fn exit(&self) {
    unsafe {
      v8__Isolate__Exit(self.as_real_ptr());
    }
  }

  /// Optional notification that the system is running low on memory.
  /// V8 uses these notifications to guide heuristics.
  /// It is allowed to call this function from another thread while
  /// the isolate is executing long running JavaScript code.
  #[inline(always)]
  pub fn memory_pressure_notification(&mut self, level: MemoryPressureLevel) {
    unsafe {
      v8__Isolate__MemoryPressureNotification(self.as_real_ptr(), level as u8)
    }
  }

  /// Clears the set of objects held strongly by the heap. This set of
  /// objects are originally built when a WeakRef is created or
  /// successfully dereferenced.
  ///
  /// This is invoked automatically after microtasks are run. See
  /// MicrotasksPolicy for when microtasks are run.
  ///
  /// This needs to be manually invoked only if the embedder is manually
  /// running microtasks via a custom MicrotaskQueue class's PerformCheckpoint.
  /// In that case, it is the embedder's responsibility to make this call at a
  /// time which does not interrupt synchronous ECMAScript code execution.
  #[inline(always)]
  pub fn clear_kept_objects(&mut self) {
    unsafe { v8__Isolate__ClearKeptObjects(self.as_real_ptr()) }
  }

  /// Optional notification that the system is running low on memory.
  /// V8 uses these notifications to attempt to free memory.
  #[inline(always)]
  pub fn low_memory_notification(&mut self) {
    unsafe { v8__Isolate__LowMemoryNotification(self.as_real_ptr()) }
  }

  /// Get statistics about the heap memory usage.
  #[inline(always)]
  pub fn get_heap_statistics(&mut self) -> HeapStatistics {
    let inner = unsafe {
      let mut s = MaybeUninit::zeroed();
      v8__Isolate__GetHeapStatistics(self.as_real_ptr(), s.as_mut_ptr());
      s.assume_init()
    };
    HeapStatistics(inner)
  }

  /// Returns the number of spaces in the heap.
  #[inline(always)]
  pub fn number_of_heap_spaces(&mut self) -> usize {
    unsafe { v8__Isolate__NumberOfHeapSpaces(self.as_real_ptr()) }
  }

  /// Get the memory usage of a space in the heap.
  ///
  /// \param space_statistics The HeapSpaceStatistics object to fill in
  ///   statistics.
  /// \param index The index of the space to get statistics from, which ranges
  ///   from 0 to NumberOfHeapSpaces() - 1.
  /// \returns true on success.
  #[inline(always)]
  pub fn get_heap_space_statistics(
    &mut self,
    index: usize,
  ) -> Option<HeapSpaceStatistics> {
    let inner = unsafe {
      let mut s = MaybeUninit::zeroed();
      if !v8__Isolate__GetHeapSpaceStatistics(
        self.as_real_ptr(),
        s.as_mut_ptr(),
        index,
      ) {
        return None;
      }
      s.assume_init()
    };
    Some(HeapSpaceStatistics(inner))
  }

  /// Get code and metadata statistics for the heap.
  ///
  /// \returns true on success.
  #[inline(always)]
  pub fn get_heap_code_and_metadata_statistics(
    &mut self,
  ) -> Option<HeapCodeStatistics> {
    let inner = unsafe {
      let mut s = MaybeUninit::zeroed();
      if !v8__Isolate__GetHeapCodeAndMetadataStatistics(
        self.as_real_ptr(),
        s.as_mut_ptr(),
      ) {
        return None;
      }
      s.assume_init()
    };
    Some(HeapCodeStatistics(inner))
  }

  /// Tells V8 to capture current stack trace when uncaught exception occurs
  /// and report it to the message listeners. The option is off by default.
  #[inline(always)]
  pub fn set_capture_stack_trace_for_uncaught_exceptions(
    &mut self,
    capture: bool,
    frame_limit: i32,
  ) {
    unsafe {
      v8__Isolate__SetCaptureStackTraceForUncaughtExceptions(
        self.as_real_ptr(),
        capture,
        frame_limit,
      );
    }
  }

  /// Adds a message listener (errors only).
  ///
  /// The same message listener can be added more than once and in that
  /// case it will be called more than once for each message.
  ///
  /// The exception object will be passed to the callback.
  #[inline(always)]
  pub fn add_message_listener(&mut self, callback: MessageCallback) -> bool {
    unsafe { v8__Isolate__AddMessageListener(self.as_real_ptr(), callback) }
  }

  /// Adds a message listener for the specified message levels.
  #[inline(always)]
  pub fn add_message_listener_with_error_level(
    &mut self,
    callback: MessageCallback,
    message_levels: MessageErrorLevel,
  ) -> bool {
    unsafe {
      v8__Isolate__AddMessageListenerWithErrorLevel(
        self.as_real_ptr(),
        callback,
        message_levels,
      )
    }
  }

  /// This specifies the callback called when the stack property of Error
  /// is accessed.
  ///
  /// PrepareStackTraceCallback is called when the stack property of an error is
  /// first accessed. The return value will be used as the stack value. If this
  /// callback is registed, the |Error.prepareStackTrace| API will be disabled.
  /// |sites| is an array of call sites, specified in
  /// https://v8.dev/docs/stack-trace-api
  #[inline(always)]
  pub fn set_prepare_stack_trace_callback<'s>(
    &mut self,
    callback: impl MapFnTo<PrepareStackTraceCallback<'s>>,
  ) {
    // Note: the C++ API returns a MaybeLocal but V8 asserts at runtime when
    // it's empty. That is, you can't return None and that's why the Rust API
    // expects Local<Value> instead of Option<Local<Value>>.
    unsafe {
      v8__Isolate__SetPrepareStackTraceCallback(
        self.as_real_ptr(),
        callback.map_fn_to(),
      );
    };
  }

  /// Set the PromiseHook callback for various promise lifecycle
  /// events.
  #[inline(always)]
  pub fn set_promise_hook(&mut self, hook: PromiseHook) {
    unsafe { v8__Isolate__SetPromiseHook(self.as_real_ptr(), hook) }
  }

  /// Set callback to notify about promise reject with no handler, or
  /// revocation of such a previous notification once the handler is added.
  #[inline(always)]
  pub fn set_promise_reject_callback(
    &mut self,
    callback: PromiseRejectCallback,
  ) {
    unsafe {
      v8__Isolate__SetPromiseRejectCallback(self.as_real_ptr(), callback)
    }
  }

  #[inline(always)]
  pub fn set_wasm_async_resolve_promise_callback(
    &mut self,
    callback: WasmAsyncResolvePromiseCallback,
  ) {
    unsafe {
      v8__Isolate__SetWasmAsyncResolvePromiseCallback(
        self.as_real_ptr(),
        callback,
      )
    }
  }

  #[inline(always)]
  pub fn set_allow_wasm_code_generation_callback(
    &mut self,
    callback: AllowWasmCodeGenerationCallback,
  ) {
    unsafe {
      v8__Isolate__SetAllowWasmCodeGenerationCallback(
        self.as_real_ptr(),
        callback,
      );
    }
  }

  #[inline(always)]
  /// This specifies the callback called by the upcoming importa.meta
  /// language feature to retrieve host-defined meta data for a module.
  pub fn set_host_initialize_import_meta_object_callback(
    &mut self,
    callback: HostInitializeImportMetaObjectCallback,
  ) {
    unsafe {
      v8__Isolate__SetHostInitializeImportMetaObjectCallback(
        self.as_real_ptr(),
        callback,
      );
    }
  }

  /// This specifies the callback called by the upcoming dynamic
  /// import() language feature to load modules.
  #[inline(always)]
  pub fn set_host_import_module_dynamically_callback(
    &mut self,
    callback: impl HostImportModuleDynamicallyCallback,
  ) {
    unsafe {
      v8__Isolate__SetHostImportModuleDynamicallyCallback(
        self.as_real_ptr(),
        callback.to_c_fn(),
      );
    }
  }

  /// This specifies the callback called by the upcoming dynamic
  /// import() and import.source() language feature to load modules.
  ///
  /// This API is experimental and is expected to be changed or removed in the
  /// future. The callback is currently only called when for source-phase
  /// imports. Evaluation-phase imports use the existing
  /// HostImportModuleDynamicallyCallback callback.
  #[inline(always)]
  pub fn set_host_import_module_with_phase_dynamically_callback(
    &mut self,
    callback: impl HostImportModuleWithPhaseDynamicallyCallback,
  ) {
    unsafe {
      v8__Isolate__SetHostImportModuleWithPhaseDynamicallyCallback(
        self.as_real_ptr(),
        callback.to_c_fn(),
      );
    }
  }

  /// This specifies the callback called by the upcoming `ShadowRealm`
  /// construction language feature to retrieve host created globals.
  pub fn set_host_create_shadow_realm_context_callback(
    &mut self,
    callback: HostCreateShadowRealmContextCallback,
  ) {
    #[inline]
    unsafe extern "C" fn rust_shadow_realm_callback(
      initiator_context: Local<Context>,
    ) -> *mut Context {
      let scope = pin!(unsafe { CallbackScope::new(initiator_context) });
      let mut scope = scope.init();
      let isolate = scope.as_ref();
      let callback = isolate
        .get_slot::<HostCreateShadowRealmContextCallback>()
        .unwrap();
      let context = callback(&mut scope);
      context.map_or_else(null_mut, |l| l.as_non_null().as_ptr())
    }

    // Windows x64 ABI: MaybeLocal<Context> must be returned on the stack.
    #[cfg(target_os = "windows")]
    unsafe extern "C" fn rust_shadow_realm_callback_windows(
      rv: *mut *mut Context,
      initiator_context: Local<Context>,
    ) -> *mut *mut Context {
      unsafe {
        let ret = rust_shadow_realm_callback(initiator_context);
        rv.write(ret);
      }
      rv
    }

    let slot_didnt_exist_before = self.set_slot(callback);
    if slot_didnt_exist_before {
      unsafe {
        #[cfg(target_os = "windows")]
        v8__Isolate__SetHostCreateShadowRealmContextCallback(
          self.as_real_ptr(),
          rust_shadow_realm_callback_windows,
        );
        #[cfg(not(target_os = "windows"))]
        v8__Isolate__SetHostCreateShadowRealmContextCallback(
          self.as_real_ptr(),
          rust_shadow_realm_callback,
        );
      }
    }
  }

  /// Sets a callback for counting the number of times a feature of V8 is used.
  #[inline(always)]
  pub fn set_use_counter_callback(&mut self, callback: UseCounterCallback) {
    unsafe {
      v8__Isolate__SetUseCounterCallback(self.as_real_ptr(), callback);
    }
  }

  /// Enables the host application to receive a notification before a
  /// garbage collection. Allocations are allowed in the callback function,
  /// but the callback is not re-entrant: if the allocation inside it will
  /// trigger the garbage collection, the callback won't be called again.
  /// It is possible to specify the GCType filter for your callback. But it is
  /// not possible to register the same callback function two times with
  /// different GCType filters.
  #[allow(clippy::not_unsafe_ptr_arg_deref)] // False positive.
  #[inline(always)]
  pub fn add_gc_prologue_callback(
    &mut self,
    callback: GcCallbackWithData,
    data: *mut c_void,
    gc_type_filter: GCType,
  ) {
    unsafe {
      v8__Isolate__AddGCPrologueCallback(
        self.as_real_ptr(),
        callback,
        data,
        gc_type_filter,
      );
    }
  }

  /// This function removes callback which was installed by
  /// AddGCPrologueCallback function.
  #[allow(clippy::not_unsafe_ptr_arg_deref)] // False positive.
  #[inline(always)]
  pub fn remove_gc_prologue_callback(
    &mut self,
    callback: GcCallbackWithData,
    data: *mut c_void,
  ) {
    unsafe {
      v8__Isolate__RemoveGCPrologueCallback(self.as_real_ptr(), callback, data)
    }
  }

  /// Enables the host application to receive a notification after a
  /// garbage collection.
  #[allow(clippy::not_unsafe_ptr_arg_deref)] // False positive.
  #[inline(always)]
  pub fn add_gc_epilogue_callback(
    &mut self,
    callback: GcCallbackWithData,
    data: *mut c_void,
    gc_type_filter: GCType,
  ) {
    unsafe {
      v8__Isolate__AddGCEpilogueCallback(
        self.as_real_ptr(),
        callback,
        data,
        gc_type_filter,
      );
    }
  }

  /// This function removes a callback which was added by
  /// `AddGCEpilogueCallback`.
  #[allow(clippy::not_unsafe_ptr_arg_deref)] // False positive.
  #[inline(always)]
  pub fn remove_gc_epilogue_callback(
    &mut self,
    callback: GcCallbackWithData,
    data: *mut c_void,
  ) {
    unsafe {
      v8__Isolate__RemoveGCEpilogueCallback(self.as_real_ptr(), callback, data)
    }
  }

  /// Add a callback to invoke in case the heap size is close to the heap limit.
  /// If multiple callbacks are added, only the most recently added callback is
  /// invoked.
  #[allow(clippy::not_unsafe_ptr_arg_deref)] // False positive.
  #[inline(always)]
  pub fn add_near_heap_limit_callback(
    &mut self,
    callback: NearHeapLimitCallback,
    data: *mut c_void,
  ) {
    unsafe {
      v8__Isolate__AddNearHeapLimitCallback(self.as_real_ptr(), callback, data)
    };
  }

  /// Remove the given callback and restore the heap limit to the given limit.
  /// If the given limit is zero, then it is ignored. If the current heap size
  /// is greater than the given limit, then the heap limit is restored to the
  /// minimal limit that is possible for the current heap size.
  #[inline(always)]
  pub fn remove_near_heap_limit_callback(
    &mut self,
    callback: NearHeapLimitCallback,
    heap_limit: usize,
  ) {
    unsafe {
      v8__Isolate__RemoveNearHeapLimitCallback(
        self.as_real_ptr(),
        callback,
        heap_limit,
      );
    };
  }

  /// Adjusts the amount of registered external memory. Used to give V8 an
  /// indication of the amount of externally allocated memory that is kept
  /// alive by JavaScript objects. V8 uses this to decide when to perform
  /// global garbage collections. Registering externally allocated memory
  /// will trigger global garbage collections more often than it would
  /// otherwise in an attempt to garbage collect the JavaScript objects
  /// that keep the externally allocated memory alive.
  #[inline(always)]
  pub fn adjust_amount_of_external_allocated_memory(
    &mut self,
    change_in_bytes: i64,
  ) -> i64 {
    unsafe {
      v8__Isolate__AdjustAmountOfExternalAllocatedMemory(
        self.as_real_ptr(),
        change_in_bytes,
      )
    }
  }

  #[inline(always)]
  pub fn get_cpp_heap(&mut self) -> Option<&Heap> {
    unsafe { v8__Isolate__GetCppHeap(self.as_real_ptr()).as_ref() }
  }

  #[inline(always)]
  pub fn set_oom_error_handler(&mut self, callback: OomErrorCallback) {
    unsafe { v8__Isolate__SetOOMErrorHandler(self.as_real_ptr(), callback) };
  }

  /// Returns the policy controlling how Microtasks are invoked.
  #[inline(always)]
  pub fn get_microtasks_policy(&self) -> MicrotasksPolicy {
    unsafe { v8__Isolate__GetMicrotasksPolicy(self.as_real_ptr()) }
  }

  /// Returns the policy controlling how Microtasks are invoked.
  #[inline(always)]
  pub fn set_microtasks_policy(&mut self, policy: MicrotasksPolicy) {
    unsafe { v8__Isolate__SetMicrotasksPolicy(self.as_real_ptr(), policy) }
  }

  /// Runs the default MicrotaskQueue until it gets empty and perform other
  /// microtask checkpoint steps, such as calling ClearKeptObjects. Asserts that
  /// the MicrotasksPolicy is not kScoped. Any exceptions thrown by microtask
  /// callbacks are swallowed.
  #[inline(always)]
  pub fn perform_microtask_checkpoint(&mut self) {
    unsafe { v8__Isolate__PerformMicrotaskCheckpoint(self.as_real_ptr()) }
  }

  /// Enqueues the callback to the default MicrotaskQueue
  #[inline(always)]
  pub fn enqueue_microtask(&mut self, microtask: Local<Function>) {
    unsafe { v8__Isolate__EnqueueMicrotask(self.as_real_ptr(), &*microtask) }
  }

  /// Set whether calling Atomics.wait (a function that may block) is allowed in
  /// this isolate. This can also be configured via
  /// CreateParams::allow_atomics_wait.
  #[inline(always)]
  pub fn set_allow_atomics_wait(&mut self, allow: bool) {
    unsafe { v8__Isolate__SetAllowAtomicsWait(self.as_real_ptr(), allow) }
  }

  /// Embedder injection point for `WebAssembly.compileStreaming(source)`.
  /// The expectation is that the embedder sets it at most once.
  ///
  /// The callback receives the source argument (string, Promise, etc.)
  /// and an instance of [WasmStreaming]. The [WasmStreaming] instance
  /// can outlive the callback and is used to feed data chunks to V8
  /// asynchronously.
  #[inline(always)]
  pub fn set_wasm_streaming_callback<F>(&mut self, _: F)
  where
    F: UnitType
      + for<'a, 'b, 'c> Fn(
        &'c mut PinScope<'a, 'b>,
        Local<'a, Value>,
        WasmStreaming<false>,
      ),
  {
    unsafe {
      v8__Isolate__SetWasmStreamingCallback(
        self.as_real_ptr(),
        trampoline::<F>(),
      )
    }
  }

  /// Notification that the embedder has changed the time zone, daylight savings
  /// time or other date / time configuration parameters. V8 keeps a cache of
  /// various values used for date / time computation. This notification will
  /// reset those cached values for the current context so that date / time
  /// configuration changes would be reflected.
  ///
  /// This API should not be called more than needed as it will negatively impact
  /// the performance of date operations.
  #[inline(always)]
  pub fn date_time_configuration_change_notification(
    &mut self,
    time_zone_detection: TimeZoneDetection,
  ) {
    unsafe {
      v8__Isolate__DateTimeConfigurationChangeNotification(
        self.as_real_ptr(),
        time_zone_detection,
      );
    }
  }

  /// Returns true if there is ongoing background work within V8 that will
  /// eventually post a foreground task, like asynchronous WebAssembly
  /// compilation.
  #[inline(always)]
  pub fn has_pending_background_tasks(&self) -> bool {
    unsafe { v8__Isolate__HasPendingBackgroundTasks(self.as_real_ptr()) }
  }

  /// Request garbage collection with a specific embedderstack state in this
  /// Isolate. It is only valid to call this function if --expose_gc was
  /// specified.
  ///
  /// This should only be used for testing purposes and not to enforce a garbage
  /// collection schedule. It has strong negative impact on the garbage
  /// collection performance. Use IdleNotificationDeadline() or
  /// LowMemoryNotification() instead to influence the garbage collection
  /// schedule.
  #[inline(always)]
  pub fn request_garbage_collection_for_testing(
    &mut self,
    r#type: GarbageCollectionType,
  ) {
    unsafe {
      v8__Isolate__RequestGarbageCollectionForTesting(
        self.as_real_ptr(),
        match r#type {
          GarbageCollectionType::Full => 0,
          GarbageCollectionType::Minor => 1,
        },
      );
    }
  }

  /// Disposes the isolate.  The isolate must not be entered by any
  /// thread to be disposable.
  unsafe fn dispose(&mut self) {
    // No test case in rusty_v8 show this, but there have been situations in
    // deno where dropping Annex before the states causes a segfault.
    unsafe {
      v8__Isolate__Dispose(self.as_real_ptr());
    }
  }

  /// Take a heap snapshot. The callback is invoked one or more times
  /// with byte slices containing the snapshot serialized as JSON.
  /// It's the callback's responsibility to reassemble them into
  /// a single document, e.g., by writing them to a file.
  /// Note that Chrome DevTools refuses to load snapshots without
  /// a .heapsnapshot suffix.
  pub fn take_heap_snapshot<F>(&mut self, mut callback: F)
  where
    F: FnMut(&[u8]) -> bool,
  {
    unsafe extern "C" fn trampoline<F>(
      arg: *mut c_void,
      data: *const u8,
      size: usize,
    ) -> bool
    where
      F: FnMut(&[u8]) -> bool,
    {
      unsafe {
        let mut callback = NonNull::<F>::new_unchecked(arg as _);
        if size > 0 {
          (callback.as_mut())(std::slice::from_raw_parts(data, size))
        } else {
          (callback.as_mut())(&[])
        }
      }
    }

    let arg = addr_of_mut!(callback);
    unsafe {
      v8__HeapProfiler__TakeHeapSnapshot(
        self.as_real_ptr(),
        trampoline::<F>,
        arg as _,
      );
    }
  }

  /// Set the default context to be included in the snapshot blob.
  /// The snapshot will not contain the global proxy, and we expect one or a
  /// global object template to create one, to be provided upon deserialization.
  ///
  /// # Panics
  ///
  /// Panics if the isolate was not created using [`Isolate::snapshot_creator`]
  #[inline(always)]
  pub fn set_default_context(&mut self, context: Local<Context>) {
    let snapshot_creator = self
      .get_annex_mut()
      .maybe_snapshot_creator
      .as_mut()
      .unwrap();
    snapshot_creator.set_default_context(context);
  }

  /// Add additional context to be included in the snapshot blob.
  /// The snapshot will include the global proxy.
  ///
  /// Returns the index of the context in the snapshot blob.
  ///
  /// # Panics
  ///
  /// Panics if the isolate was not created using [`Isolate::snapshot_creator`]
  #[inline(always)]
  pub fn add_context(&mut self, context: Local<Context>) -> usize {
    let snapshot_creator = self
      .get_annex_mut()
      .maybe_snapshot_creator
      .as_mut()
      .unwrap();
    snapshot_creator.add_context(context)
  }

  /// Attach arbitrary `v8::Data` to the isolate snapshot, which can be
  /// retrieved via `HandleScope::get_context_data_from_snapshot_once()` after
  /// deserialization. This data does not survive when a new snapshot is created
  /// from an existing snapshot.
  ///
  /// # Panics
  ///
  /// Panics if the isolate was not created using [`Isolate::snapshot_creator`]
  #[inline(always)]
  pub fn add_isolate_data<T>(&mut self, data: Local<T>) -> usize
  where
    for<'l> Local<'l, T>: Into<Local<'l, Data>>,
  {
    let snapshot_creator = self
      .get_annex_mut()
      .maybe_snapshot_creator
      .as_mut()
      .unwrap();
    snapshot_creator.add_isolate_data(data)
  }

  /// Attach arbitrary `v8::Data` to the context snapshot, which can be
  /// retrieved via `HandleScope::get_context_data_from_snapshot_once()` after
  /// deserialization. This data does not survive when a new snapshot is
  /// created from an existing snapshot.
  ///
  /// # Panics
  ///
  /// Panics if the isolate was not created using [`Isolate::snapshot_creator`]
  #[inline(always)]
  pub fn add_context_data<T>(
    &mut self,
    context: Local<Context>,
    data: Local<T>,
  ) -> usize
  where
    for<'l> Local<'l, T>: Into<Local<'l, Data>>,
  {
    let snapshot_creator = self
      .get_annex_mut()
      .maybe_snapshot_creator
      .as_mut()
      .unwrap();
    snapshot_creator.add_context_data(context, data)
  }
}

pub(crate) struct IsolateAnnex {
  create_param_allocations: Box<dyn Any>,
  slots: HashMap<TypeId, RawSlot, BuildTypeIdHasher>,
  finalizer_map: FinalizerMap,
  maybe_snapshot_creator: Option<SnapshotCreator>,
  // The `isolate` and `isolate_mutex` fields are there so an `IsolateHandle`
  // (which may outlive the isolate itself) can determine whether the isolate
  // is still alive, and if so, get a reference to it. Safety rules:
  // - The 'main thread' must lock the mutex and reset `isolate` to null just
  //   before the isolate is disposed.
  // - Any other thread must lock the mutex while it's reading/using the
  //   `isolate` pointer.
  isolate: *mut RealIsolate,
  isolate_mutex: Mutex<()>,
}

unsafe impl Send for IsolateAnnex {}
unsafe impl Sync for IsolateAnnex {}

impl IsolateAnnex {
  fn new(
    isolate: &mut Isolate,
    create_param_allocations: Box<dyn Any>,
  ) -> Self {
    Self {
      create_param_allocations,
      slots: HashMap::default(),
      finalizer_map: FinalizerMap::default(),
      maybe_snapshot_creator: None,
      isolate: isolate.as_real_ptr(),
      isolate_mutex: Mutex::new(()),
    }
  }
}

impl Debug for IsolateAnnex {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    f.debug_struct("IsolateAnnex")
      .field("isolate", &self.isolate)
      .field("isolate_mutex", &self.isolate_mutex)
      .finish()
  }
}

/// IsolateHandle is a thread-safe reference to an Isolate. It's main use is to
/// terminate execution of a running isolate from another thread.
///
/// It is created with Isolate::thread_safe_handle().
///
/// IsolateHandle is Cloneable, Send, and Sync.
#[derive(Clone, Debug)]
pub struct IsolateHandle(Arc<IsolateAnnex>);

impl IsolateHandle {
  // This function is marked unsafe because it must be called only with either
  // IsolateAnnex::mutex locked, or from the main thread associated with the V8
  // isolate.
  pub(crate) unsafe fn get_isolate_ptr(&self) -> *mut RealIsolate {
    self.0.isolate
  }

  #[inline(always)]
  fn new(isolate: &Isolate) -> Self {
    Self(isolate.get_annex_arc())
  }

  /// Forcefully terminate the current thread of JavaScript execution
  /// in the given isolate.
  ///
  /// This method can be used by any thread even if that thread has not
  /// acquired the V8 lock with a Locker object.
  ///
  /// Returns false if Isolate was already destroyed.
  #[inline(always)]
  pub fn terminate_execution(&self) -> bool {
    let _lock = self.0.isolate_mutex.lock().unwrap();
    if self.0.isolate.is_null() {
      false
    } else {
      unsafe { v8__Isolate__TerminateExecution(self.0.isolate) };
      true
    }
  }

  /// Resume execution capability in the given isolate, whose execution
  /// was previously forcefully terminated using TerminateExecution().
  ///
  /// When execution is forcefully terminated using TerminateExecution(),
  /// the isolate can not resume execution until all JavaScript frames
  /// have propagated the uncatchable exception which is generated.  This
  /// method allows the program embedding the engine to handle the
  /// termination event and resume execution capability, even if
  /// JavaScript frames remain on the stack.
  ///
  /// This method can be used by any thread even if that thread has not
  /// acquired the V8 lock with a Locker object.
  ///
  /// Returns false if Isolate was already destroyed.
  #[inline(always)]
  pub fn cancel_terminate_execution(&self) -> bool {
    let _lock = self.0.isolate_mutex.lock().unwrap();
    if self.0.isolate.is_null() {
      false
    } else {
      unsafe { v8__Isolate__CancelTerminateExecution(self.0.isolate) };
      true
    }
  }

  /// Is V8 terminating JavaScript execution.
  ///
  /// Returns true if JavaScript execution is currently terminating
  /// because of a call to TerminateExecution.  In that case there are
  /// still JavaScript frames on the stack and the termination
  /// exception is still active.
  ///
  /// Returns false if Isolate was already destroyed.
  #[inline(always)]
  pub fn is_execution_terminating(&self) -> bool {
    let _lock = self.0.isolate_mutex.lock().unwrap();
    if self.0.isolate.is_null() {
      false
    } else {
      unsafe { v8__Isolate__IsExecutionTerminating(self.0.isolate) }
    }
  }

  /// Request V8 to interrupt long running JavaScript code and invoke
  /// the given |callback| passing the given |data| to it. After |callback|
  /// returns control will be returned to the JavaScript code.
  /// There may be a number of interrupt requests in flight.
  /// Can be called from another thread without acquiring a |Locker|.
  /// Registered |callback| must not reenter interrupted Isolate.
  ///
  /// Returns false if Isolate was already destroyed.
  // Clippy warns that this method is dereferencing a raw pointer, but it is
  // not: https://github.com/rust-lang/rust-clippy/issues/3045
  #[allow(clippy::not_unsafe_ptr_arg_deref)]
  #[inline(always)]
  pub fn request_interrupt(
    &self,
    callback: InterruptCallback,
    data: *mut c_void,
  ) -> bool {
    let _lock = self.0.isolate_mutex.lock().unwrap();
    if self.0.isolate.is_null() {
      false
    } else {
      unsafe { v8__Isolate__RequestInterrupt(self.0.isolate, callback, data) };
      true
    }
  }
}

/// Same as Isolate but gets disposed when it goes out of scope.
#[derive(Debug)]
pub struct OwnedIsolate {
  cxx_isolate: NonNull<RealIsolate>,
}

impl OwnedIsolate {
  pub(crate) fn new(cxx_isolate: *mut RealIsolate) -> Self {
    let isolate = Self::new_already_entered(cxx_isolate);
    unsafe {
      isolate.enter();
    }
    isolate
  }

  pub(crate) fn new_already_entered(cxx_isolate: *mut RealIsolate) -> Self {
    let cxx_isolate = NonNull::new(cxx_isolate).unwrap();
    let owned_isolate: OwnedIsolate = Self { cxx_isolate };
    // owned_isolate.init_scope_root();
    owned_isolate
  }
}

impl Drop for OwnedIsolate {
  fn drop(&mut self) {
    unsafe {
      let snapshot_creator = self.get_annex_mut().maybe_snapshot_creator.take();
      assert!(
        snapshot_creator.is_none(),
        "If isolate was created using v8::Isolate::snapshot_creator, you should use v8::OwnedIsolate::create_blob before dropping an isolate."
      );
      // Safety: We need to check `this == Isolate::GetCurrent()` before calling exit()
      assert!(
        std::ptr::eq(self.cxx_isolate.as_mut(), v8__Isolate__GetCurrent()),
        "v8::OwnedIsolate instances must be dropped in the reverse order of creation. They are entered upon creation and exited upon being dropped."
      );
      // self.dispose_scope_root();
      self.exit();
      self.dispose_annex();
      Platform::notify_isolate_shutdown(&get_current_platform(), self);
      self.dispose();
    }
  }
}

impl OwnedIsolate {
  /// Creates a snapshot data blob.
  /// This must not be called from within a handle scope.
  ///
  /// # Panics
  ///
  /// Panics if the isolate was not created using [`Isolate::snapshot_creator`]
  #[inline(always)]
  pub fn create_blob(
    mut self,
    function_code_handling: FunctionCodeHandling,
  ) -> Option<StartupData> {
    let mut snapshot_creator =
      self.get_annex_mut().maybe_snapshot_creator.take().unwrap();

    // create_param_allocations is needed during CreateBlob
    // so v8 can read external references
    let _create_param_allocations = unsafe {
      // self.dispose_scope_root();
      self.dispose_annex()
    };

    // The isolate is owned by the snapshot creator; we need to forget it
    // here as the snapshot creator will drop it when running the destructor.
    std::mem::forget(self);
    snapshot_creator.create_blob(function_code_handling)
  }
}

impl Deref for OwnedIsolate {
  type Target = Isolate;
  fn deref(&self) -> &Self::Target {
    unsafe {
      std::mem::transmute::<&NonNull<RealIsolate>, &Isolate>(&self.cxx_isolate)
    }
  }
}

impl DerefMut for OwnedIsolate {
  fn deref_mut(&mut self) -> &mut Self::Target {
    unsafe {
      std::mem::transmute::<&mut NonNull<RealIsolate>, &mut Isolate>(
        &mut self.cxx_isolate,
      )
    }
  }
}

impl AsMut<Isolate> for OwnedIsolate {
  fn as_mut(&mut self) -> &mut Isolate {
    self
  }
}

impl AsMut<Isolate> for Isolate {
  fn as_mut(&mut self) -> &mut Isolate {
    self
  }
}

/// Collection of V8 heap information.
///
/// Instances of this class can be passed to v8::Isolate::GetHeapStatistics to
/// get heap statistics from V8.
pub struct HeapStatistics(v8__HeapStatistics);

impl HeapStatistics {
  #[inline(always)]
  pub fn total_heap_size(&self) -> usize {
    self.0.total_heap_size_
  }

  #[inline(always)]
  pub fn total_heap_size_executable(&self) -> usize {
    self.0.total_heap_size_executable_
  }

  #[inline(always)]
  pub fn total_physical_size(&self) -> usize {
    self.0.total_physical_size_
  }

  #[inline(always)]
  pub fn total_available_size(&self) -> usize {
    self.0.total_available_size_
  }

  #[inline(always)]
  pub fn total_global_handles_size(&self) -> usize {
    self.0.total_global_handles_size_
  }

  #[inline(always)]
  pub fn used_global_handles_size(&self) -> usize {
    self.0.used_global_handles_size_
  }

  #[inline(always)]
  pub fn used_heap_size(&self) -> usize {
    self.0.used_heap_size_
  }

  #[inline(always)]
  pub fn heap_size_limit(&self) -> usize {
    self.0.heap_size_limit_
  }

  #[inline(always)]
  pub fn malloced_memory(&self) -> usize {
    self.0.malloced_memory_
  }

  #[inline(always)]
  pub fn external_memory(&self) -> usize {
    self.0.external_memory_
  }

  #[inline(always)]
  pub fn peak_malloced_memory(&self) -> usize {
    self.0.peak_malloced_memory_
  }

  #[inline(always)]
  pub fn number_of_native_contexts(&self) -> usize {
    self.0.number_of_native_contexts_
  }

  #[inline(always)]
  pub fn number_of_detached_contexts(&self) -> usize {
    self.0.number_of_detached_contexts_
  }

  /// Returns the total number of bytes allocated since the Isolate was created.
  /// This includes all heap objects allocated in any space (new, old, code,
  /// etc.).
  #[inline(always)]
  pub fn total_allocated_bytes(&self) -> u64 {
    self.0.total_allocated_bytes_
  }

  /// Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
  /// garbage with a bit pattern.
  #[inline(always)]
  pub fn does_zap_garbage(&self) -> bool {
    self.0.does_zap_garbage_
  }
}

pub struct HeapSpaceStatistics(v8__HeapSpaceStatistics);

impl HeapSpaceStatistics {
  pub fn space_name(&self) -> &'static CStr {
    unsafe { CStr::from_ptr(self.0.space_name_) }
  }

  pub fn space_size(&self) -> usize {
    self.0.space_size_
  }

  pub fn space_used_size(&self) -> usize {
    self.0.space_used_size_
  }

  pub fn space_available_size(&self) -> usize {
    self.0.space_available_size_
  }

  pub fn physical_space_size(&self) -> usize {
    self.0.physical_space_size_
  }
}

pub struct HeapCodeStatistics(v8__HeapCodeStatistics);

impl HeapCodeStatistics {
  pub fn code_and_metadata_size(&self) -> usize {
    self.0.code_and_metadata_size_
  }

  pub fn bytecode_and_metadata_size(&self) -> usize {
    self.0.bytecode_and_metadata_size_
  }

  pub fn external_script_source_size(&self) -> usize {
    self.0.external_script_source_size_
  }

  pub fn cpu_profiler_metadata_size(&self) -> usize {
    self.0.cpu_profiler_metadata_size_
  }
}

impl<'s, F> MapFnFrom<F> for PrepareStackTraceCallback<'s>
where
  F: UnitType
    + for<'a> Fn(
      &mut PinScope<'s, 'a>,
      Local<'s, Value>,
      Local<'s, Array>,
    ) -> Local<'s, Value>,
{
  // Windows x64 ABI: MaybeLocal<Value> returned on the stack.
  #[cfg(target_os = "windows")]
  fn mapping() -> Self {
    let f = |ret_ptr, context, error, sites| {
      let scope = pin!(unsafe { CallbackScope::new(context) });
      let mut scope: crate::PinnedRef<CallbackScope> = scope.init();
      let r = (F::get())(&mut scope, error, sites);
      unsafe { std::ptr::write(ret_ptr, &*r as *const _) };
      ret_ptr
    };
    f.to_c_fn()
  }

  // System V ABI
  #[cfg(not(target_os = "windows"))]
  fn mapping() -> Self {
    let f = |context, error, sites| {
      let scope = pin!(unsafe { CallbackScope::new(context) });
      let mut scope: crate::PinnedRef<CallbackScope> = scope.init();

      let r = (F::get())(&mut scope, error, sites);
      PrepareStackTraceCallbackRet(&*r as *const _)
    };
    f.to_c_fn()
  }
}

/// A special hasher that is optimized for hashing `std::any::TypeId` values.
/// `TypeId` values are actually 64-bit values which themselves come out of some
/// hash function, so it's unnecessary to shuffle their bits any further.
#[derive(Clone, Default)]
pub(crate) struct TypeIdHasher {
  state: Option<u64>,
}

impl Hasher for TypeIdHasher {
  fn write(&mut self, _bytes: &[u8]) {
    panic!("TypeIdHasher::write() called unexpectedly");
  }

  #[inline]
  fn write_u64(&mut self, value: u64) {
    // The internal hash function of TypeId only takes the bottom 64-bits, even on versions
    // of Rust that use a 128-bit TypeId.
    let prev_state = self.state.replace(value);
    debug_assert_eq!(prev_state, None);
  }

  #[inline]
  fn finish(&self) -> u64 {
    self.state.unwrap()
  }
}

/// Factory for instances of `TypeIdHasher`. This is the type that one would
/// pass to the constructor of some map/set type in order to make it use
/// `TypeIdHasher` instead of the default hasher implementation.
#[derive(Copy, Clone, Default)]
pub(crate) struct BuildTypeIdHasher;

impl BuildHasher for BuildTypeIdHasher {
  type Hasher = TypeIdHasher;

  #[inline]
  fn build_hasher(&self) -> Self::Hasher {
    Default::default()
  }
}

const _: () = {
  assert!(
    size_of::<TypeId>() == size_of::<u64>()
      || size_of::<TypeId>() == size_of::<u128>()
  );
  assert!(
    align_of::<TypeId>() == align_of::<u64>()
      || align_of::<TypeId>() == align_of::<u128>()
  );
};

pub(crate) struct RawSlot {
  data: RawSlotData,
  dtor: Option<RawSlotDtor>,
}

type RawSlotData = MaybeUninit<usize>;
type RawSlotDtor = unsafe fn(&mut RawSlotData) -> ();

impl RawSlot {
  #[inline]
  pub fn new<T: 'static>(value: T) -> Self {
    if Self::needs_box::<T>() {
      Self::new_internal(Box::new(value))
    } else {
      Self::new_internal(value)
    }
  }

  // SAFETY: a valid value of type `T` must haven been stored in the slot
  // earlier. There is no verification that the type param provided by the
  // caller is correct.
  #[inline]
  pub unsafe fn borrow<T: 'static>(&self) -> &T {
    unsafe {
      if Self::needs_box::<T>() {
        &*(self.data.as_ptr() as *const Box<T>)
      } else {
        &*(self.data.as_ptr() as *const T)
      }
    }
  }

  // Safety: see [`RawSlot::borrow`].
  #[inline]
  pub unsafe fn borrow_mut<T: 'static>(&mut self) -> &mut T {
    unsafe {
      if Self::needs_box::<T>() {
        &mut *(self.data.as_mut_ptr() as *mut Box<T>)
      } else {
        &mut *(self.data.as_mut_ptr() as *mut T)
      }
    }
  }

  // Safety: see [`RawSlot::borrow`].
  #[inline]
  pub unsafe fn into_inner<T: 'static>(self) -> T {
    unsafe {
      let value = if Self::needs_box::<T>() {
        *std::ptr::read(self.data.as_ptr() as *mut Box<T>)
      } else {
        std::ptr::read(self.data.as_ptr() as *mut T)
      };
      forget(self);
      value
    }
  }

  const fn needs_box<T: 'static>() -> bool {
    size_of::<T>() > size_of::<RawSlotData>()
      || align_of::<T>() > align_of::<RawSlotData>()
  }

  #[inline]
  fn new_internal<B: 'static>(value: B) -> Self {
    assert!(!Self::needs_box::<B>());
    let mut self_ = Self {
      data: RawSlotData::zeroed(),
      dtor: None,
    };
    unsafe {
      ptr::write(self_.data.as_mut_ptr() as *mut B, value);
    }
    if needs_drop::<B>() {
      self_.dtor.replace(Self::drop_internal::<B>);
    };
    self_
  }

  // SAFETY: a valid value of type `T` or `Box<T>` must be stored in the slot.
  unsafe fn drop_internal<B: 'static>(data: &mut RawSlotData) {
    assert!(!Self::needs_box::<B>());
    unsafe {
      drop_in_place(data.as_mut_ptr() as *mut B);
    }
  }
}

impl Drop for RawSlot {
  fn drop(&mut self) {
    if let Some(dtor) = self.dtor {
      unsafe { dtor(&mut self.data) };
    }
  }
}

impl AsRef<Isolate> for OwnedIsolate {
  fn as_ref(&self) -> &Isolate {
    unsafe { Isolate::from_raw_ref(&self.cxx_isolate) }
  }
}
impl AsRef<Isolate> for Isolate {
  fn as_ref(&self) -> &Isolate {
    self
  }
}