euv-core 0.46.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Inline small-list operations for reactive subscriber and dependency collections.
impl<T> SmallSubList<T>
where
    T: Copy + PartialEq,
{
    /// Returns `true` when zero entries are stored.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the list contains no items.
    #[must_use]
    #[inline(always)]
    pub(crate) fn is_empty(&self) -> bool {
        match self {
            Self::Empty => true,
            Self::One(_) | Self::Two(_, _) => false,
            Self::Many(vec) => vec.is_empty(),
        }
    }

    /// Returns the number of stored entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of items currently stored.
    #[must_use]
    #[inline(always)]
    pub(crate) fn len(&self) -> usize {
        match self {
            Self::Empty => 0,
            Self::One(_) => 1,
            Self::Two(_, _) => 2,
            Self::Many(vec) => vec.len(),
        }
    }

    /// Returns the entry at `index` if in bounds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    /// - `usize` - Zero-based item index.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Copied item at `index`, or `None` when out of bounds.
    #[must_use]
    #[inline(always)]
    pub(crate) fn get(&self, index: usize) -> Option<T> {
        match self {
            Self::Empty => None,
            Self::One(first) => {
                if index == 0 {
                    Some(*first)
                } else {
                    None
                }
            }
            Self::Two(first, second) => match index {
                0 => Some(*first),
                1 => Some(*second),
                _ => None,
            },
            Self::Many(vec) => vec.get(index).copied(),
        }
    }

    /// Checks whether `target` already exists within the prefix `0..end`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    /// - `usize` - Exclusive upper index bound of the prefix.
    /// - `T` - Entry to search for.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `target` appears before index `end`.
    #[must_use]
    #[inline(always)]
    pub(crate) fn contains_prefix(&self, end: usize, target: T) -> bool {
        if end == 0 {
            return false;
        }
        match self {
            Self::Empty => false,
            Self::One(first) => *first == target,
            Self::Two(first, second) => {
                if *first == target {
                    true
                } else {
                    end > 1 && *second == target
                }
            }
            Self::Many(vec) => {
                let bound: usize = end.min(vec.len());
                vec[..bound].contains(&target)
            }
        }
    }

    /// Finds the first index `>= start` whose entry equals `target`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    /// - `usize` - Inclusive start index.
    /// - `T` - Entry to locate.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Matching index if found at or after `start`.
    #[must_use]
    #[inline(always)]
    pub(crate) fn find_from(&self, start: usize, target: T) -> Option<usize> {
        match self {
            Self::Empty => None,
            Self::One(first) => {
                if start == 0 && *first == target {
                    Some(0)
                } else {
                    None
                }
            }
            Self::Two(first, second) => {
                if start == 0 && *first == target {
                    Some(0)
                } else if start <= 1 && *second == target {
                    Some(1)
                } else {
                    None
                }
            }
            Self::Many(vec) => {
                let mut idx: usize = start;
                while idx < vec.len() {
                    if vec[idx] == target {
                        return Some(idx);
                    }
                    idx += 1;
                }
                None
            }
        }
    }

    /// Swaps two in-bounds entries at `a` and `b`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `usize` - First element index.
    /// - `usize` - Second element index.
    #[inline(always)]
    pub(crate) fn swap(&mut self, a: usize, b: usize) {
        if a == b {
            return;
        }
        match self {
            Self::Empty | Self::One(_) => {}
            Self::Two(first, second) => {
                if (a == 0 && b == 1) || (a == 1 && b == 0) {
                    swap(first, second);
                }
            }
            Self::Many(vec) => {
                if a < vec.len() && b < vec.len() {
                    vec.swap(a, b);
                }
            }
        }
    }

    /// Appends `value` assuming uniqueness has already been established by the caller.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `T` - Unique entry to append.
    #[inline(always)]
    pub(crate) fn push_unchecked(&mut self, value: T) {
        match self {
            Self::Empty => {
                *self = Self::One(value);
            }
            Self::One(first) => {
                *self = Self::Two(*first, value);
            }
            Self::Two(first, second) => {
                let mut list: Vec<T> = Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY);
                list.push(*first);
                list.push(*second);
                list.push(value);
                *self = Self::Many(list);
            }
            Self::Many(vec) => {
                vec.push(value);
            }
        }
    }

    /// Splits off and returns all entries at indices `>= keep_len`, keeping `0..keep_len` in place.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `usize` - Number of leading entries to retain.
    ///
    /// # Returns
    ///
    /// - `Self` - Removed tail entries.
    #[inline(always)]
    pub(crate) fn take_tail(&mut self, keep_len: usize) -> Self {
        match self {
            Self::Empty => Self::Empty,
            Self::One(first) => {
                if keep_len == 0 {
                    let item: T = *first;
                    *self = Self::Empty;
                    Self::One(item)
                } else {
                    Self::Empty
                }
            }
            Self::Two(first, second) => match keep_len {
                0 => {
                    let a: T = *first;
                    let b: T = *second;
                    *self = Self::Empty;
                    Self::Two(a, b)
                }
                1 => {
                    let a: T = *first;
                    let b: T = *second;
                    *self = Self::One(a);
                    Self::One(b)
                }
                _ => Self::Empty,
            },
            Self::Many(vec) => {
                if keep_len >= vec.len() {
                    return Self::Empty;
                }
                let removed: usize = vec.len() - keep_len;
                if removed == 1
                    && let Some(item) = vec.pop()
                {
                    return Self::One(item);
                }
                if removed == 2
                    && let Some(second) = vec.pop()
                    && let Some(first) = vec.pop()
                {
                    return Self::Two(first, second);
                }
                Self::Many(vec.split_off(keep_len))
            }
        }
    }

    /// Appends `value` if it is not already present, promoting inline storage to `Many` only on the third unique item.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `T` - Entry to insert uniquely.
    #[inline(always)]
    pub(crate) fn push_unique(&mut self, value: T) {
        match self {
            Self::Empty => {
                *self = Self::One(value);
            }
            Self::One(first) => {
                if *first != value {
                    *self = Self::Two(*first, value);
                }
            }
            Self::Two(first, second) => {
                if *first != value && *second != value {
                    let mut list: Vec<T> = Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY);
                    list.push(*first);
                    list.push(*second);
                    list.push(value);
                    *self = Self::Many(list);
                }
            }
            Self::Many(vec) => {
                if !vec.contains(&value) {
                    vec.push(value);
                }
            }
        }
    }

    /// Removes every occurrence of `target` while preserving insertion order of remaining entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `T` - Entry value to remove.
    #[inline(always)]
    pub(crate) fn remove_item(&mut self, target: T) {
        match self {
            Self::Empty => {}
            Self::One(first) => {
                if *first == target {
                    *self = Self::Empty;
                }
            }
            Self::Two(first, second) => {
                if *first == target {
                    *self = Self::One(*second);
                } else if *second == target {
                    *self = Self::One(*first);
                }
            }
            Self::Many(vec) => {
                vec.retain(|item: &T| *item != target);
            }
        }
    }

    /// Empties all stored items while retaining heap capacity if already promoted to `Many`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    #[inline(always)]
    pub(crate) fn clear(&mut self) {
        match self {
            Self::Empty => {}
            Self::One(_) | Self::Two(_, _) => {
                *self = Self::Empty;
            }
            Self::Many(vec) => {
                vec.clear();
            }
        }
    }

    /// Visits every stored item in insertion order without allocating.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Small list reference.
    /// - `F` - Visitor closure receiving each copied item.
    #[inline(always)]
    pub(crate) fn for_each<F>(&self, mut visit: F)
    where
        F: FnMut(T),
    {
        match self {
            Self::Empty => {}
            Self::One(first) => {
                visit(*first);
            }
            Self::Two(first, second) => {
                visit(*first);
                visit(*second);
            }
            Self::Many(vec) => {
                for item in vec.iter().copied() {
                    visit(item);
                }
            }
        }
    }

    /// Drains and visits every stored item in insertion order while retaining `Many` heap capacity.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable small list reference.
    /// - `F` - Visitor closure receiving each drained item.
    #[inline(always)]
    pub(crate) fn drain_each<F>(&mut self, mut visit: F)
    where
        F: FnMut(T),
    {
        match self {
            Self::Empty => {}
            Self::One(first) => {
                let item: T = *first;
                *self = Self::Empty;
                visit(item);
            }
            Self::Two(first, second) => {
                let a: T = *first;
                let b: T = *second;
                *self = Self::Empty;
                visit(a);
                visit(b);
            }
            Self::Many(vec) => {
                for item in vec.drain(..) {
                    visit(item);
                }
            }
        }
    }
}

/// Panic-safe tracking guard helpers.
impl TrackingGuard {
    /// Creates an armed `TrackingGuard` protecting the newly pushed observer frame.
    ///
    /// # Returns
    ///
    /// - `Self` - Armed unwind guard.
    #[must_use]
    #[inline(always)]
    pub(crate) fn new() -> Self {
        Self { active: true }
    }

    /// Disarms the guard before normal completion pops the tracking frame explicitly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable guard reference.
    #[inline(always)]
    pub(crate) fn disarm(&mut self) {
        let Self { active } = self;
        *active = false;
    }
}

/// Dirty-propagation target extraction for subscriber small-lists.
impl SmallSubList<SubscriberId> {
    /// Extracts a zero-allocation copyable dispatch target for dirty propagation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Subscriber list reference.
    ///
    /// # Returns
    ///
    /// - `DirtyTarget` - Inline target for 0..=2 subscribers or `Many` heap fallback.
    #[must_use]
    #[inline(always)]
    pub(crate) fn dirty_target(&self) -> DirtyTarget {
        match self {
            Self::Empty => DirtyTarget::Empty,
            Self::One(sub) => DirtyTarget::One(*sub),
            Self::Two(first, second) => DirtyTarget::Two(*first, *second),
            Self::Many(vec) => {
                if vec.is_empty() {
                    DirtyTarget::Empty
                } else {
                    DirtyTarget::Many
                }
            }
        }
    }
}

/// Unwind cleanup popping any leaked observer frame if a reactive computation panics.
impl Drop for TrackingGuard {
    /// Pops the leaked frame from `observer_stack` when unwinding while still armed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable guard being dropped.
    fn drop(&mut self) {
        let Self { active } = self;
        if *active {
            with_runtime(
                |rt: &mut ReactiveRuntime| {
                    let _: Option<Option<(SubscriberId, usize)>> =
                        rt.get_mut_observer_stack().pop();
                },
                (),
            );
        }
    }
}

/// Default initialization for `ReactiveRuntime`.
impl Default for ReactiveRuntime {
    /// Creates an empty reactive runtime with preallocated arena buffers.
    ///
    /// # Returns
    ///
    /// - `Self` - The initialized runtime instance.
    fn default() -> Self {
        Self {
            signals: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_signals: Vec::new(),
            memos: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_memos: Vec::new(),
            effects: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_effects: Vec::new(),
            scopes: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_scopes: Vec::new(),
            observer_stack: Vec::new(),
            scope_stack: Vec::new(),
            pending_effects: Vec::new(),
            dirty_queue: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
            check_scratch: Vec::new(),
            flush_batch_scratch: Vec::new(),
            scope_stack_scratch: Vec::new(),
            dispose_effects_scratch: Vec::new(),
            dispose_memos_scratch: Vec::new(),
            dispose_signals_scratch: Vec::new(),
            batch_depth: 0,
            flushing: false,
            clock: 0,
            global_states: HashMap::new(),
            named_global_states: HashMap::new(),
            event_channels: HashMap::new(),
        }
    }
}

/// Core arena operations for `ReactiveRuntime`.
impl ReactiveRuntime {
    /// Allocates a new signal slot storing `initial_value`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `T` - Initial signal value.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Handle for the newly created signal.
    pub(crate) fn create_signal<T>(&mut self, initial_value: T) -> SignalId
    where
        T: 'static,
    {
        let boxed: Box<dyn Any> = Box::new(initial_value);
        let id: SignalId = if let Some(index) = self.get_mut_free_signals().pop() {
            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_value(Some(boxed));
            entry.get_mut_subscribers().clear();
            SignalId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_signals().len() as u32;
            self.get_mut_signals().push(SignalEntry {
                generation: 1,
                version: 0,
                value: Some(boxed),
                subscribers: SmallSubList::Empty,
            });
            SignalId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_signal_to_scope(scope_id, id);
        }
        id
    }

    /// Allocates a new root-lifetime signal in the arena without binding it to the active transient `Scope`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `T` - Initial signal value.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Newly allocated detached signal identifier.
    pub(crate) fn create_detached_signal<T>(&mut self, initial_value: T) -> SignalId
    where
        T: 'static,
    {
        let boxed: Box<dyn Any> = Box::new(initial_value);
        if let Some(index) = self.get_mut_free_signals().pop() {
            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_value(Some(boxed));
            entry.get_mut_subscribers().clear();
            SignalId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_signals().len() as u32;
            self.get_mut_signals().push(SignalEntry {
                generation: 1,
                version: 0,
                value: Some(boxed),
                subscribers: SmallSubList::Empty,
            });
            SignalId::from_slot(SlotId::new(index, 1))
        }
    }

    /// Registers or replaces a root-lifetime global state signal keyed by `TypeId::of::<T>()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `T` - Initial or replacement global state value.
    ///
    /// # Returns
    ///
    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)` when updating an existing slot.
    pub(crate) fn provide_global_state<T>(&mut self, initial: T) -> (SignalId, bool)
    where
        T: 'static,
    {
        let key: TypeId = TypeId::of::<T>();
        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
            let slot: SlotId = existing_id.slot();
            let alive: bool = self
                .get_signals()
                .get(slot.as_usize())
                .map(|e: &SignalEntry| {
                    e.get_generation() == slot.get_generation() && e.value.is_some()
                })
                .unwrap_or(false);
            if alive {
                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
                return (existing_id, flush);
            }
        }
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
        (id, false)
    }

    /// Looks up a registered root-lifetime global state signal keyed by `TypeId::of::<T>()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    ///
    /// # Returns
    ///
    /// - `Option<SignalId>` - Registered signal handle if present.
    pub(crate) fn lookup_global_state<T>(&self) -> Option<SignalId>
    where
        T: 'static,
    {
        self.get_global_states().get(&TypeId::of::<T>()).copied()
    }

    /// Looks up a registered global state signal or initializes it lazily with `init`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `F` - Lazy initializer invoked only when absent.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Existing or newly created global state signal handle.
    pub(crate) fn get_or_init_global_state<T, F>(&mut self, init: F) -> SignalId
    where
        T: 'static,
        F: FnOnce() -> T,
    {
        let key: TypeId = TypeId::of::<T>();
        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
            return existing_id;
        }
        let id: SignalId = self.create_detached_signal(init());
        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
        id
    }

    /// Registers or replaces a string-keyed root-lifetime named global state signal.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `&str` - Global state channel name.
    /// - `T` - Initial or replacement value.
    ///
    /// # Returns
    ///
    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)`.
    pub(crate) fn provide_named_global_state<T>(
        &mut self,
        name: &str,
        initial: T,
    ) -> (SignalId, bool)
    where
        T: 'static,
    {
        if let Some(existing_id) = self.get_named_global_states().get(name).copied() {
            let slot: SlotId = existing_id.slot();
            let alive: bool = self
                .get_signals()
                .get(slot.as_usize())
                .map(|e: &SignalEntry| {
                    e.get_generation() == slot.get_generation() && e.value.is_some()
                })
                .unwrap_or(false);
            if alive {
                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
                return (existing_id, flush);
            }
        }
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self
            .get_mut_named_global_states()
            .insert(name.to_string(), id);
        (id, false)
    }

    /// Looks up a string-keyed named global state signal.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `&str` - Global state channel name.
    ///
    /// # Returns
    ///
    /// - `Option<SignalId>` - Registered signal handle if present.
    pub(crate) fn lookup_named_global_state(&self, name: &str) -> Option<SignalId> {
        self.get_named_global_states().get(name).copied()
    }

    /// Looks up or allocates the detached event channel signal for custom event type `E`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Detached `Signal<(u64, Option<E>)>` channel identifier.
    pub(crate) fn ensure_event_channel<E>(&mut self) -> SignalId
    where
        E: CustomEvent,
    {
        let key: TypeId = TypeId::of::<E>();
        if let Some(existing_id) = self.get_event_channels().get(&key).copied() {
            return existing_id;
        }
        let initial: (u64, Option<E>) = (0, None);
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self.get_mut_event_channels().insert(key, id);
        id
    }

    /// Reads a signal value via cloning inside the arena and records dependency tracking.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to read.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Cloned signal value if the slot is alive and matches type `T`.
    #[inline]
    pub(crate) fn read_signal_cloned<T>(&mut self, id: SignalId) -> Option<T>
    where
        T: Clone + 'static,
    {
        if !self.get_observer_stack().is_empty() {
            self.track_dependency(DependencyId::Signal(id));
        }
        let slot: SlotId = id.slot();
        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
        if entry.get_generation() != slot.get_generation() {
            return None;
        }
        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
        boxed.downcast_ref::<T>().cloned()
    }

    /// Reads a signal value without recording any reactive dependency.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to inspect.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Cloned signal value if alive and matching type `T`.
    #[inline]
    pub(crate) fn read_signal_untracked<T>(&self, id: SignalId) -> Option<T>
    where
        T: Clone + 'static,
    {
        let slot: SlotId = id.slot();
        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
        if entry.get_generation() != slot.get_generation() {
            return None;
        }
        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
        boxed.downcast_ref::<T>().cloned()
    }

    /// Returns whether a live signal slot currently has one or more active subscribers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to inspect.
    ///
    /// # Returns
    ///
    /// - `bool` - True when the signal is alive and observed by at least one subscriber.
    #[inline]
    pub(crate) fn signal_has_subscribers(&self, id: SignalId) -> bool {
        let slot: SlotId = id.slot();
        self.get_signals()
            .get(slot.as_usize())
            .map(|entry: &SignalEntry| {
                entry.get_generation() == slot.get_generation()
                    && entry.value.is_some()
                    && !entry.get_subscribers().is_empty()
            })
            .unwrap_or(false)
    }

    /// Writes a new signal value in place and propagates dirty notifications without heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to update.
    /// - `T` - Replacement value.
    ///
    /// # Returns
    ///
    /// - `(bool, bool)` - Tuple `(updated, should_flush)` indicating whether the signal was alive and whether effects are pending.
    #[inline]
    pub(crate) fn write_signal<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
    where
        T: 'static,
    {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return (false, false);
        };
        let stale: bool = entry.get_generation() != slot.get_generation();
        if stale || entry.value.is_none() {
            return (false, false);
        }
        if let Some(existing) = entry
            .value
            .as_mut()
            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
        {
            *existing = value;
        } else {
            entry.set_value(Some(Box::new(value)));
        }
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let target: DirtyTarget = entry.get_subscribers().dirty_target();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if matches!(target, DirtyTarget::Empty) {
            return (true, false);
        }
        self.propagate_signal_dirty(idx, target);
        let should_flush: bool = self.get_batch_depth() == 0
            && !self.get_flushing()
            && !self.get_pending_effects().is_empty();
        (true, should_flush)
    }

    /// Takes a live signal's boxed payload for zero-clone in-place mutation outside the runtime borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier whose payload should be temporarily taken.
    ///
    /// # Returns
    ///
    /// - `Option<Box<dyn Any>>` - Existing boxed value when the slot is alive and matches type `T`.
    #[inline]
    pub(crate) fn take_signal_box<T>(&mut self, id: SignalId) -> Option<Box<dyn Any>>
    where
        T: 'static,
    {
        let slot: SlotId = id.slot();
        let entry: &mut SignalEntry = self.get_mut_signals().get_mut(slot.as_usize())?;
        if entry.get_generation() != slot.get_generation() {
            return None;
        }
        if !entry
            .value
            .as_ref()
            .is_some_and(|boxed: &Box<dyn Any>| boxed.is::<T>())
        {
            return None;
        }
        entry.value.take()
    }

    /// Restores a mutated signal payload box, bumps version and clock, and returns immediately when unobserved.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier receiving its mutated payload.
    /// - `Box<dyn Any>` - Mutated payload box previously taken via `take_signal_box`.
    ///
    /// # Returns
    ///
    /// - `(bool, bool)` - Tuple `(updated, should_flush)` indicating whether the signal was alive and whether effects must flush.
    #[inline]
    pub(crate) fn commit_signal_box(&mut self, id: SignalId, boxed: Box<dyn Any>) -> (bool, bool) {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return (false, false);
        };
        if entry.get_generation() != slot.get_generation() {
            return (false, false);
        }
        entry.set_value(Some(boxed));
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let target: DirtyTarget = entry.get_subscribers().dirty_target();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if matches!(target, DirtyTarget::Empty) {
            return (true, false);
        }
        self.propagate_signal_dirty(idx, target);
        let should_flush: bool = self.get_batch_depth() == 0
            && !self.get_flushing()
            && !self.get_pending_effects().is_empty();
        (true, should_flush)
    }

    /// Writes a signal value and propagates dirtiness without checking flush state, returning whether subscribers existed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to update.
    /// - `T` - Replacement value.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the signal was alive and had at least one downstream subscriber.
    #[inline]
    fn write_signal_no_flush<T>(&mut self, id: SignalId, value: T) -> bool
    where
        T: 'static,
    {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return false;
        };
        let stale: bool = entry.get_generation() != slot.get_generation();
        if stale || entry.value.is_none() {
            return false;
        }
        if let Some(existing) = entry
            .value
            .as_mut()
            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
        {
            *existing = value;
        } else {
            entry.set_value(Some(Box::new(value)));
        }
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let target: DirtyTarget = entry.get_subscribers().dirty_target();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if matches!(target, DirtyTarget::Empty) {
            return false;
        }
        self.propagate_signal_dirty(idx, target);
        true
    }

    /// Atomically updates an optional deselected and newly selected `Selector` signal pair in one runtime borrow.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `Option<SignalId>` - Previously selected key signal to set to `false`, if any.
    /// - `Option<SignalId>` - Newly selected key signal to set to `true`, if any.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one signal had subscribers and effects must be flushed now.
    pub(crate) fn write_selector_pair(
        &mut self,
        old_id: Option<SignalId>,
        new_id: Option<SignalId>,
    ) -> bool {
        let mut any_subs: bool = false;
        if let Some(id) = old_id
            && self.write_signal_no_flush(id, false)
        {
            any_subs = true;
        }
        if let Some(id) = new_id
            && self.write_signal_no_flush(id, true)
        {
            any_subs = true;
        }
        any_subs
            && self.get_batch_depth() == 0
            && !self.get_flushing()
            && !self.get_pending_effects().is_empty()
    }

    /// Writes a new signal value in place only when it differs from the stored value.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to update.
    /// - `T` - Candidate value compared using `PartialEq`.
    ///
    /// # Returns
    ///
    /// - `(bool, bool)` - Tuple `(changed, should_flush)` indicating whether the value changed and whether effects are pending.
    #[inline]
    pub(crate) fn write_signal_if_changed<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
    where
        T: PartialEq + 'static,
    {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return (false, false);
        };
        if entry.get_generation() != slot.get_generation() {
            return (false, false);
        }
        let Some(current) = entry
            .value
            .as_mut()
            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
        else {
            return (false, false);
        };
        if *current == value {
            return (false, false);
        }
        *current = value;
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let target: DirtyTarget = entry.get_subscribers().dirty_target();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if matches!(target, DirtyTarget::Empty) {
            return (true, false);
        }
        self.propagate_signal_dirty(idx, target);
        let should_flush: bool = self.get_batch_depth() == 0
            && !self.get_flushing()
            && !self.get_pending_effects().is_empty();
        (true, should_flush)
    }

    /// Allocates a new memo slot with an in-place type-erased computation closure.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Memo computation closure mutating the cached value in place and returning `changed`.
    ///
    /// # Returns
    ///
    /// - `MemoId` - Handle for the newly created memo.
    pub(crate) fn create_memo<F>(&mut self, compute: F) -> MemoId
    where
        F: FnMut(&mut Option<Box<dyn Any>>) -> bool + 'static,
    {
        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
        let compute_rc: MemoComputeFn = Rc::new(RefCell::new(compute));
        let id: MemoId = if let Some(index) = self.get_mut_free_memos().pop() {
            let entry: &mut MemoEntry = &mut self.get_mut_memos()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_state(NodeState::Dirty);
            entry.set_value(None);
            entry.set_compute(Some(compute_rc));
            entry.get_mut_dependencies().clear();
            entry.get_mut_subscribers().clear();
            entry.set_depth(depth);
            MemoId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_memos().len() as u32;
            self.get_mut_memos().push(MemoEntry {
                generation: 1,
                version: 0,
                state: NodeState::Dirty,
                value: None,
                compute: Some(compute_rc),
                dependencies: SmallSubList::Empty,
                subscribers: SmallSubList::Empty,
                depth,
            });
            MemoId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_memo_to_scope(scope_id, id);
        }
        id
    }

    /// Allocates a new effect slot and schedules it for immediate execution.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Effect callback closure.
    ///
    /// # Returns
    ///
    /// - `EffectId` - Handle for the newly created effect.
    pub(crate) fn create_effect<F>(&mut self, callback: F) -> EffectId
    where
        F: FnMut() + 'static,
    {
        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
        let callback_rc: Rc<RefCell<dyn FnMut()>> = Rc::new(RefCell::new(callback));
        let id: EffectId = if let Some(index) = self.get_mut_free_effects().pop() {
            let entry: &mut EffectEntry = &mut self.get_mut_effects()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_alive(true);
            entry.set_scheduled(false);
            entry.set_callback(Some(callback_rc));
            entry.get_mut_dependencies().clear();
            entry.set_depth(depth);
            entry.set_frozen_depth(0);
            entry.set_pending_while_frozen(false);
            EffectId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_effects().len() as u32;
            self.get_mut_effects().push(EffectEntry {
                generation: 1,
                alive: true,
                scheduled: false,
                callback: Some(callback_rc),
                dependencies: SmallSubList::Empty,
                depth,
                frozen_depth: 0,
                pending_while_frozen: false,
            });
            EffectId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_effect_to_scope(scope_id, id);
        }
        id
    }

    /// Creates a new ownership scope and optionally links it to the active parent scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    ///
    /// # Returns
    ///
    /// - `ScopeId` - Identifier for the newly created scope.
    pub(crate) fn create_scope(&mut self) -> ScopeId {
        let parent_opt: Option<ScopeId> = self.get_scope_stack().last().copied();
        let live_parent: Option<ScopeId> = parent_opt.filter(|parent_id: &ScopeId| {
            let parent_slot: SlotId = parent_id.slot();
            self.get_scopes()
                .get(parent_slot.as_usize())
                .is_some_and(|parent: &ScopeEntry| {
                    parent.get_generation() == parent_slot.get_generation() && parent.get_alive()
                })
        });
        let id: ScopeId = if let Some(index) = self.get_mut_free_scopes().pop() {
            let entry: &mut ScopeEntry = &mut self.get_mut_scopes()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_alive(true);
            entry.set_frozen(false);
            entry.set_parent(live_parent);
            entry.get_mut_signals().clear();
            entry.get_mut_memos().clear();
            entry.get_mut_effects().clear();
            entry.get_mut_children().clear();
            entry.get_mut_cleanups().clear();
            ScopeId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_scopes().len() as u32;
            self.get_mut_scopes().push(ScopeEntry {
                generation: 1,
                alive: true,
                frozen: false,
                parent: live_parent,
                signals: Vec::new(),
                memos: Vec::new(),
                effects: Vec::new(),
                children: Vec::new(),
                cleanups: Vec::new(),
            });
            ScopeId::from_slot(SlotId::new(index, 1))
        };
        if let Some(parent_id) = live_parent {
            let parent_slot: SlotId = parent_id.slot();
            if let Some(parent) = self.get_mut_scopes().get_mut(parent_slot.as_usize()) {
                parent.get_mut_children().push(id);
            }
        }
        id
    }

    /// Registers a cleanup callback on the currently active scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Cleanup closure invoked when the active scope disposes.
    pub(crate) fn register_cleanup<F>(&mut self, cleanup: F)
    where
        F: FnOnce() + 'static,
    {
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            let slot: SlotId = scope_id.slot();
            if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
                && entry.get_generation() == slot.get_generation()
                && entry.get_alive()
            {
                entry.get_mut_cleanups().push(Box::new(cleanup));
            }
        }
    }

    /// Records `dependency` on the currently executing observer using O(1) cursor reuse on stable graphs.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `DependencyId` - The dependency accessed during evaluation.
    pub(crate) fn track_dependency(&mut self, dependency: DependencyId) {
        let Some(Some((subscriber, cursor))) = self.get_observer_stack().last().copied() else {
            return;
        };
        let reuse_outcome: Option<usize> = match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize()) else {
                    return;
                };
                if entry.get_generation() != slot.get_generation() {
                    return;
                }
                let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
                if deps.get(cursor) == Some(dependency) {
                    Some(cursor + 1)
                } else if deps.contains_prefix(cursor, dependency) {
                    return;
                } else if let Some(found_idx) = deps.find_from(cursor + 1, dependency) {
                    deps.swap(cursor, found_idx);
                    Some(cursor + 1)
                } else {
                    None
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize()) else {
                    return;
                };
                if entry.get_generation() != slot.get_generation() {
                    return;
                }
                let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
                if deps.get(cursor) == Some(dependency) {
                    Some(cursor + 1)
                } else if deps.contains_prefix(cursor, dependency) {
                    return;
                } else if let Some(found_idx) = deps.find_from(cursor + 1, dependency) {
                    deps.swap(cursor, found_idx);
                    Some(cursor + 1)
                } else {
                    None
                }
            }
        };
        if let Some(next_cursor) = reuse_outcome {
            if let Some(Some((_, top_cursor))) = self.get_mut_observer_stack().last_mut() {
                *top_cursor = next_cursor;
            }
            return;
        }
        self.detach_tail_dependencies(subscriber, cursor);
        match dependency {
            DependencyId::Signal(sig_id) => {
                let slot: SlotId = sig_id.slot();
                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().push_unique(subscriber);
                }
            }
            DependencyId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().push_unique(subscriber);
                }
            }
        }
        match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_dependencies().push_unchecked(dependency);
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_dependencies().push_unchecked(dependency);
                }
            }
        }
        if let Some(Some((_, top_cursor))) = self.get_mut_observer_stack().last_mut() {
            *top_cursor = cursor + 1;
        }
    }

    /// Pops the top tracking frame and unsubscribes any stale tail dependencies beyond its final cursor.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    pub(crate) fn finish_tracking(&mut self) {
        if let Some(Some((subscriber, cursor))) = self.get_mut_observer_stack().pop() {
            self.detach_tail_dependencies(subscriber, cursor);
        }
    }

    /// Truncates `subscriber`'s dependency list to `keep_len` and unsubscribes from any removed tail dependencies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SubscriberId` - Observer whose tail dependencies should be trimmed.
    /// - `usize` - Number of active leading dependencies to retain.
    fn detach_tail_dependencies(&mut self, subscriber: SubscriberId, keep_len: usize) {
        let stale: SmallSubList<DependencyId> = match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                match self.get_mut_memos().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
                        if deps.len() <= keep_len {
                            return;
                        }
                        deps.take_tail(keep_len)
                    }
                    _ => return,
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                match self.get_mut_effects().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
                        if deps.len() <= keep_len {
                            return;
                        }
                        deps.take_tail(keep_len)
                    }
                    _ => return,
                }
            }
        };
        stale.for_each(|dep: DependencyId| match dep {
            DependencyId::Signal(sig_id) => {
                let slot: SlotId = sig_id.slot();
                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().remove_item(subscriber);
                }
            }
            DependencyId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().remove_item(subscriber);
                }
            }
        });
    }

    /// Drains pending effects into the reusable batch buffer while preserving `pending_effects` capacity and tracking depth order.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `Vec<(u32, EffectId)>` - Reusable caller-owned batch buffer returned from the prior flush step.
    ///
    /// # Returns
    ///
    /// - `FlushStep` - Next single effect, batch with sortedness flag, or `FlushStep::Done`.
    pub(crate) fn drain_pending_flush_step(
        &mut self,
        mut batch: Vec<(u32, EffectId)>,
    ) -> FlushStep {
        let pending_len: usize = self.get_pending_effects().len();
        if pending_len == 0 {
            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
                self.set_flush_batch_scratch(batch);
            }
            self.set_flushing(false);
            return FlushStep::Done;
        }
        if pending_len == 1 {
            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
                self.set_flush_batch_scratch(batch);
            }
            if let Some(eff_id) = self.get_mut_pending_effects().pop() {
                return FlushStep::Single(eff_id);
            }
            self.set_flushing(false);
            return FlushStep::Done;
        }
        if batch.capacity() < self.get_flush_batch_scratch().capacity() {
            batch = take(self.get_mut_flush_batch_scratch());
        }
        let Self {
            effects,
            pending_effects,
            ..
        } = self;
        batch.clear();
        if batch.capacity() < pending_effects.len() {
            batch.reserve(pending_effects.len() - batch.capacity());
        }
        let mut prev_depth: u32 = 0;
        let mut is_sorted: bool = true;
        for eff_id in pending_effects.drain(..) {
            let slot: SlotId = eff_id.slot();
            if let Some(entry) = effects.get(slot.as_usize())
                && entry.get_generation() == slot.get_generation()
                && entry.get_alive()
            {
                let depth: u32 = entry.get_depth();
                if depth < prev_depth {
                    is_sorted = false;
                }
                prev_depth = depth;
                batch.push((depth, eff_id));
            }
        }
        if batch.is_empty() {
            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
                self.set_flush_batch_scratch(batch);
            }
            self.set_flushing(false);
            FlushStep::Done
        } else {
            FlushStep::Batch(batch, is_sorted)
        }
    }

    /// Extracts upstream `MemoId` dependencies for `NodeState::Check` memo slot `memo_idx` without heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Memo arena slot index.
    ///
    /// # Returns
    ///
    /// - `Option<MemoCheckDeps>` - Snapshot of upstream memo dependencies, or `None` when zero upstream memos exist.
    pub(crate) fn collect_check_memos(&mut self, memo_idx: usize) -> Option<MemoCheckDeps> {
        let Self {
            memos,
            check_scratch,
            ..
        } = self;
        let entry: &MemoEntry = memos.get(memo_idx)?;
        let mut inline_buf: [MemoId; 4] = [MemoId::default(); 4];
        let mut inline_len: usize = 0;
        let mut spill_start: Option<usize> = None;
        entry.get_dependencies().for_each(|dep: DependencyId| {
            if let DependencyId::Memo(parent_memo) = dep {
                if spill_start.is_some() {
                    check_scratch.push(parent_memo);
                } else if inline_len < inline_buf.len() {
                    inline_buf[inline_len] = parent_memo;
                    inline_len += 1;
                } else {
                    let start: usize = check_scratch.len();
                    check_scratch.extend_from_slice(&inline_buf);
                    check_scratch.push(parent_memo);
                    spill_start = Some(start);
                }
            }
        });
        if let Some(start) = spill_start {
            Some(MemoCheckDeps::Spill(start, check_scratch.len()))
        } else if inline_len == 0 {
            None
        } else {
            Some(MemoCheckDeps::Inline(inline_buf, inline_len as u8))
        }
    }

    /// Propagates dirty flags downstream from a signal using inline fast paths for 1..=2 subscribers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Signal arena slot index (used only for `DirtyTarget::Many`).
    /// - `DirtyTarget` - Pre-extracted subscriber dispatch target.
    #[inline]
    pub(crate) fn propagate_signal_dirty(&mut self, signal_idx: usize, target: DirtyTarget) {
        match target {
            DirtyTarget::Empty => {}
            DirtyTarget::One(sub) => {
                self.mark_single_subscriber_dirty(sub, false);
            }
            DirtyTarget::Two(first, second) => {
                self.mark_single_subscriber_dirty(first, false);
                self.mark_single_subscriber_dirty(second, false);
            }
            DirtyTarget::Many => {
                self.mark_signal_subscribers_dirty(signal_idx);
            }
        }
    }

    /// Propagates dirty flags downstream from a recomputed memo using inline fast paths for 1..=2 subscribers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Memo arena slot index (used only for `DirtyTarget::Many`).
    /// - `DirtyTarget` - Pre-extracted subscriber dispatch target.
    #[inline]
    pub(crate) fn propagate_memo_dirty(&mut self, memo_idx: usize, target: DirtyTarget) {
        match target {
            DirtyTarget::Empty => {}
            DirtyTarget::One(sub) => {
                self.mark_single_subscriber_dirty(sub, true);
            }
            DirtyTarget::Two(first, second) => {
                self.mark_single_subscriber_dirty(first, true);
                self.mark_single_subscriber_dirty(second, true);
            }
            DirtyTarget::Many => {
                self.mark_memo_subscribers_dirty(memo_idx);
            }
        }
    }

    /// Schedules a single dirty effect without touching `dirty_queue`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `EffectId` - Effect identifier to schedule or flag while frozen.
    /// - `bool` - `true` when propagating from a pulled memo recomputation.
    #[inline(always)]
    fn schedule_dirty_effect(&mut self, effect_id: EffectId, from_memo: bool) {
        let Self {
            effects,
            observer_stack,
            pending_effects,
            ..
        } = self;
        if from_memo
            && !observer_stack.is_empty()
            && observer_stack
                .iter()
                .any(|frame: &Option<(SubscriberId, usize)>| {
                    matches!(frame, Some((SubscriberId::Effect(active), _)) if *active == effect_id)
                })
        {
            return;
        }
        let slot: SlotId = effect_id.slot();
        if let Some(entry) = effects.get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            if entry.get_frozen_depth() > 0 {
                entry.set_pending_while_frozen(true);
            } else if !entry.get_scheduled() {
                entry.set_scheduled(true);
                pending_effects.push(effect_id);
            }
        }
    }

    /// Marks a single direct subscriber dirty and walks linear 1-subscriber memo chains in registers before spilling to `dirty_queue`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SubscriberId` - Direct downstream subscriber.
    /// - `bool` - `true` when propagating from a pulled memo recomputation.
    #[inline]
    fn mark_single_subscriber_dirty(&mut self, first_sub: SubscriberId, from_memo: bool) {
        let mut cur_sub: SubscriberId = first_sub;
        let mut target_state: NodeState = NodeState::Dirty;
        loop {
            match cur_sub {
                SubscriberId::Effect(effect_id) => {
                    self.schedule_dirty_effect(effect_id, from_memo);
                    return;
                }
                SubscriberId::Memo(memo_id) => {
                    let slot: SlotId = memo_id.slot();
                    let idx: usize = slot.as_usize();
                    let next_target: DirtyTarget = {
                        let Some(entry) = self.get_mut_memos().get_mut(idx) else {
                            return;
                        };
                        let stale: bool = entry.get_generation() != slot.get_generation();
                        if stale || entry.compute.is_none() {
                            return;
                        }
                        let cur_state: NodeState = entry.get_state();
                        let check_covered: bool =
                            cur_state == NodeState::Check && target_state == NodeState::Check;
                        if cur_state == NodeState::Dirty || check_covered {
                            return;
                        }
                        entry.set_state(target_state);
                        entry.get_subscribers().dirty_target()
                    };
                    match next_target {
                        DirtyTarget::Empty => return,
                        DirtyTarget::One(next_sub) => {
                            cur_sub = next_sub;
                            target_state = NodeState::Check;
                        }
                        DirtyTarget::Two(first, second) => {
                            let dq: &mut Vec<(SubscriberId, NodeState)> =
                                self.get_mut_dirty_queue();
                            dq.clear();
                            dq.push((first, NodeState::Check));
                            dq.push((second, NodeState::Check));
                            self.drain_dirty_queue(from_memo);
                            return;
                        }
                        DirtyTarget::Many => {
                            let Self {
                                memos, dirty_queue, ..
                            } = self;
                            dirty_queue.clear();
                            if let Some(entry) = memos.get(idx)
                                && let SmallSubList::Many(vec) = entry.get_subscribers()
                            {
                                for child_sub in vec.iter().copied() {
                                    dirty_queue.push((child_sub, NodeState::Check));
                                }
                            }
                            self.drain_dirty_queue(from_memo);
                            return;
                        }
                    }
                }
            }
        }
    }

    /// Propagates dirty flags downstream from signal slot `signal_idx` using the reusable scratch queue.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Signal arena slot index.
    pub(crate) fn mark_signal_subscribers_dirty(&mut self, signal_idx: usize) {
        let Self {
            signals,
            dirty_queue,
            ..
        } = self;
        dirty_queue.clear();
        if let Some(entry) = signals.get(signal_idx) {
            entry
                .get_subscribers()
                .for_each(|subscriber: SubscriberId| {
                    dirty_queue.push((subscriber, NodeState::Dirty));
                });
        }
        self.drain_dirty_queue(false);
    }

    /// Propagates dirty flags downstream from memo slot `memo_idx` using the reusable scratch queue.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Memo arena slot index.
    pub(crate) fn mark_memo_subscribers_dirty(&mut self, memo_idx: usize) {
        let Self {
            memos, dirty_queue, ..
        } = self;
        dirty_queue.clear();
        if let Some(entry) = memos.get(memo_idx) {
            entry
                .get_subscribers()
                .for_each(|subscriber: SubscriberId| {
                    dirty_queue.push((subscriber, NodeState::Dirty));
                });
        }
        self.drain_dirty_queue(true);
    }

    /// Drains the reusable `dirty_queue`, marking downstream memos and scheduling effects with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `bool` - `true` when propagating from a pulled memo recomputation (skipping currently executing effects on `observer_stack`).
    fn drain_dirty_queue(&mut self, from_memo: bool) {
        let Self {
            memos,
            effects,
            observer_stack,
            pending_effects,
            dirty_queue,
            ..
        } = self;
        let check_running: bool = from_memo && !observer_stack.is_empty();
        while let Some((sub, target_state)) = dirty_queue.pop() {
            match sub {
                SubscriberId::Memo(memo_id) => {
                    let slot: SlotId = memo_id.slot();
                    if let Some(entry) = memos.get_mut(slot.as_usize()) {
                        let stale: bool = entry.get_generation() != slot.get_generation();
                        if stale || entry.compute.is_none() {
                            continue;
                        }
                        let cur_state: NodeState = entry.get_state();
                        let check_covered: bool =
                            cur_state == NodeState::Check && target_state == NodeState::Check;
                        if cur_state == NodeState::Dirty || check_covered {
                            continue;
                        }
                        entry.set_state(target_state);
                        match entry.get_subscribers() {
                            SmallSubList::Empty => {}
                            SmallSubList::One(child_sub) => {
                                dirty_queue.push((*child_sub, NodeState::Check));
                            }
                            SmallSubList::Two(first, second) => {
                                dirty_queue.push((*first, NodeState::Check));
                                dirty_queue.push((*second, NodeState::Check));
                            }
                            SmallSubList::Many(vec) => {
                                for child_sub in vec.iter().copied() {
                                    dirty_queue.push((child_sub, NodeState::Check));
                                }
                            }
                        }
                    }
                }
                SubscriberId::Effect(effect_id) => {
                    if check_running
                        && observer_stack.iter().any(
                            |frame: &Option<(SubscriberId, usize)>| {
                                matches!(frame, Some((SubscriberId::Effect(active), _)) if *active == effect_id)
                            },
                        )
                    {
                        continue;
                    }
                    let slot: SlotId = effect_id.slot();
                    if let Some(entry) = effects.get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                        && entry.get_alive()
                    {
                        if entry.get_frozen_depth() > 0 {
                            entry.set_pending_while_frozen(true);
                        } else if !entry.get_scheduled() {
                            entry.set_scheduled(true);
                            pending_effects.push(effect_id);
                        }
                    }
                }
            }
        }
    }

    /// Detaches a subscriber from all of its previously tracked upstream dependencies while preserving heap capacity.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SubscriberId` - Subscriber whose dependency links should be cleared.
    pub(crate) fn clear_dependencies(&mut self, subscriber: SubscriberId) {
        let mut deps: SmallSubList<DependencyId> = match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                match self.get_mut_memos().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        take(entry.get_mut_dependencies())
                    }
                    _ => SmallSubList::Empty,
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                match self.get_mut_effects().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        take(entry.get_mut_dependencies())
                    }
                    _ => SmallSubList::Empty,
                }
            }
        };
        if deps.is_empty() {
            return;
        }
        deps.drain_each(|dep: DependencyId| match dep {
            DependencyId::Signal(sig_id) => {
                let slot: SlotId = sig_id.slot();
                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().remove_item(subscriber);
                }
            }
            DependencyId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.get_mut_subscribers().remove_item(subscriber);
                }
            }
        });
        if matches!(deps, SmallSubList::Many(_)) {
            match subscriber {
                SubscriberId::Memo(memo_id) => {
                    let slot: SlotId = memo_id.slot();
                    if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                    {
                        entry.set_dependencies(deps);
                    }
                }
                SubscriberId::Effect(effect_id) => {
                    let slot: SlotId = effect_id.slot();
                    if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                    {
                        entry.set_dependencies(deps);
                    }
                }
            }
        }
    }

    /// Disposes a signal slot and returns it to the free list.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to dispose.
    pub(crate) fn dispose_signal(&mut self, id: SignalId) {
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.value.is_some()
        {
            entry.set_value(None);
            entry.get_mut_subscribers().clear();
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_signals().push(slot.get_index());
        }
    }

    /// Disposes a memo slot and detaches its dependencies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `MemoId` - Memo identifier to dispose.
    pub(crate) fn dispose_memo(&mut self, id: MemoId) {
        self.clear_dependencies(SubscriberId::Memo(id));
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.compute.is_some()
        {
            entry.set_value(None);
            entry.set_compute(None);
            entry.get_mut_subscribers().clear();
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_memos().push(slot.get_index());
        }
    }

    /// Disposes an effect slot and detaches its dependencies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `EffectId` - Effect identifier to dispose.
    pub(crate) fn dispose_effect(&mut self, id: EffectId) {
        self.clear_dependencies(SubscriberId::Effect(id));
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.set_alive(false);
            entry.set_scheduled(false);
            entry.set_frozen_depth(0);
            entry.set_pending_while_frozen(false);
            entry.set_callback(None);
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_effects().push(slot.get_index());
        }
    }

    /// Collects all resources belonging to a scope and marks them disposed, returning cleanup closures.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Scope identifier to dispose recursively.
    ///
    /// # Returns
    ///
    /// - `Vec<Box<dyn FnOnce()>>` - Cleanup callbacks to execute outside the runtime borrow.
    pub(crate) fn dispose_scope_collect(&mut self, id: ScopeId) -> Vec<Box<dyn FnOnce()>> {
        let mut all_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
        let root_slot: SlotId = id.slot();
        let has_children: bool = {
            let Self {
                scopes,
                free_scopes,
                scope_stack_scratch,
                dispose_effects_scratch,
                dispose_memos_scratch,
                dispose_signals_scratch,
                ..
            } = self;
            let Some(entry) = scopes.get_mut(root_slot.as_usize()) else {
                return all_cleanups;
            };
            let inactive: bool =
                entry.get_generation() != root_slot.get_generation() || !entry.get_alive();
            if inactive {
                return all_cleanups;
            }
            entry.set_alive(false);
            entry.set_frozen(false);
            entry.set_parent(None);
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            free_scopes.push(root_slot.get_index());
            dispose_effects_scratch.clear();
            dispose_memos_scratch.clear();
            dispose_signals_scratch.clear();
            let children_non_empty: bool = !entry.get_children().is_empty();
            if children_non_empty {
                scope_stack_scratch.clear();
                scope_stack_scratch.append(entry.get_mut_children());
            }
            if !entry.get_effects().is_empty() {
                dispose_effects_scratch.append(entry.get_mut_effects());
            }
            if !entry.get_memos().is_empty() {
                dispose_memos_scratch.append(entry.get_mut_memos());
            }
            if !entry.get_signals().is_empty() {
                dispose_signals_scratch.append(entry.get_mut_signals());
            }
            if !entry.get_mut_cleanups().is_empty() {
                all_cleanups = take(entry.get_mut_cleanups());
            }
            children_non_empty
        };
        if has_children {
            let Self {
                scopes,
                free_scopes,
                scope_stack_scratch,
                dispose_effects_scratch,
                dispose_memos_scratch,
                dispose_signals_scratch,
                ..
            } = self;
            while let Some(current_id) = scope_stack_scratch.pop() {
                let slot: SlotId = current_id.slot();
                if let Some(entry) = scopes.get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                    && entry.get_alive()
                {
                    entry.set_alive(false);
                    entry.set_frozen(false);
                    entry.set_parent(None);
                    let next_gen: u32 = entry.get_generation().wrapping_add(1);
                    entry.set_generation(next_gen);
                    free_scopes.push(slot.get_index());
                    if !entry.get_children().is_empty() {
                        scope_stack_scratch.append(entry.get_mut_children());
                    }
                    if !entry.get_effects().is_empty() {
                        dispose_effects_scratch.append(entry.get_mut_effects());
                    }
                    if !entry.get_memos().is_empty() {
                        dispose_memos_scratch.append(entry.get_mut_memos());
                    }
                    if !entry.get_signals().is_empty() {
                        dispose_signals_scratch.append(entry.get_mut_signals());
                    }
                    if !entry.get_mut_cleanups().is_empty() {
                        if all_cleanups.is_empty() {
                            all_cleanups = take(entry.get_mut_cleanups());
                        } else {
                            all_cleanups.append(entry.get_mut_cleanups());
                        }
                    }
                }
            }
        }
        while let Some(eff) = self.get_mut_dispose_effects_scratch().pop() {
            self.dispose_effect(eff);
        }
        while let Some(memo) = self.get_mut_dispose_memos_scratch().pop() {
            self.dispose_memo(memo);
        }
        while let Some(sig) = self.get_mut_dispose_signals_scratch().pop() {
            self.dispose_signal(sig);
        }
        all_cleanups
    }

    /// Computes live diagnostic statistics for the runtime arena.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reference to the reactive runtime.
    ///
    /// # Returns
    ///
    /// - `ReactiveStats` - Snapshot of live node counts and write clock.
    #[must_use]
    pub fn stats(&self) -> ReactiveStats {
        let live_signals: usize = self
            .get_signals()
            .iter()
            .filter(|entry: &&SignalEntry| entry.value.is_some())
            .count();
        let live_memos: usize = self
            .get_memos()
            .iter()
            .filter(|entry: &&MemoEntry| entry.compute.is_some())
            .count();
        let live_effects: usize = self
            .get_effects()
            .iter()
            .filter(|entry: &&EffectEntry| entry.get_alive())
            .count();
        let live_scopes: usize = self
            .get_scopes()
            .iter()
            .filter(|entry: &&ScopeEntry| entry.get_alive())
            .count();
        ReactiveStats::new(
            live_signals,
            live_memos,
            live_effects,
            live_scopes,
            self.get_clock(),
        )
    }

    /// Attaches a signal identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `SignalId` - Signal identifier to attach.
    fn attach_signal_to_scope(&mut self, scope_id: ScopeId, signal_id: SignalId) {
        let slot: SlotId = scope_id.slot();
        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_signals().push(signal_id);
        }
    }

    /// Attaches a memo identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `MemoId` - Memo identifier to attach.
    fn attach_memo_to_scope(&mut self, scope_id: ScopeId, memo_id: MemoId) {
        let slot: SlotId = scope_id.slot();
        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_memos().push(memo_id);
        }
    }

    /// Attaches an effect identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `EffectId` - Effect identifier to attach.
    fn attach_effect_to_scope(&mut self, scope_id: ScopeId, effect_id: EffectId) {
        let slot: SlotId = scope_id.slot();
        let scope_is_frozen: bool = if let Some(entry) =
            self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_effects().push(effect_id);
            entry.get_frozen()
        } else {
            false
        };
        if scope_is_frozen {
            let eff_slot: SlotId = effect_id.slot();
            if let Some(eff) = self.get_mut_effects().get_mut(eff_slot.as_usize())
                && eff.get_generation() == eff_slot.get_generation()
            {
                let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
                eff.set_frozen_depth(next_d);
            }
        }
    }

    /// Applies a freeze or resume transition to a slice of scope-owned effects without cloning.
    ///
    /// # Arguments
    ///
    /// - `&[EffectId]` - Slice of effects owned by a scope.
    /// - `bool` - `true` to increment freeze depth; `false` to decrement and schedule pending effects.
    /// - `&mut [EffectEntry]` - Mutable effect arena slice.
    /// - `&mut Vec<EffectId>` - Pending effect queue receiving any resumed dirty effects.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one resumed effect was newly scheduled.
    #[inline]
    fn apply_scope_effects_frozen(
        effect_ids: &[EffectId],
        freeze: bool,
        effects: &mut [EffectEntry],
        pending_effects: &mut Vec<EffectId>,
    ) -> bool {
        let mut any_resumed_dirty: bool = false;
        for &eff_id in effect_ids {
            let eslot: SlotId = eff_id.slot();
            if let Some(eff) = effects.get_mut(eslot.as_usize())
                && eff.get_generation() == eslot.get_generation()
                && eff.get_alive()
            {
                if freeze {
                    let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
                    eff.set_frozen_depth(next_d);
                } else {
                    let next_d: u32 = eff.get_frozen_depth().saturating_sub(1);
                    eff.set_frozen_depth(next_d);
                    if next_d == 0 && eff.get_pending_while_frozen() {
                        eff.set_pending_while_frozen(false);
                        if !eff.get_scheduled() {
                            eff.set_scheduled(true);
                            pending_effects.push(eff_id);
                            any_resumed_dirty = true;
                        }
                    }
                }
            }
        }
        any_resumed_dirty
    }

    /// Recursively freezes or resumes `id` and all nested child scopes, coalescing any pending dirty effects on resume.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Root scope identifier to freeze or resume.
    /// - `bool` - `true` to freeze; `false` to resume.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when resuming scheduled one or more deferred effects that require flushing.
    pub(crate) fn set_scope_frozen(&mut self, id: ScopeId, freeze: bool) -> bool {
        let Self {
            scopes,
            effects,
            pending_effects,
            scope_stack_scratch,
            batch_depth,
            flushing,
            ..
        } = self;
        let root_slot: SlotId = id.slot();
        let Some(root_entry) = scopes.get_mut(root_slot.as_usize()) else {
            return false;
        };
        let inactive: bool =
            root_entry.get_generation() != root_slot.get_generation() || !root_entry.get_alive();
        if inactive || root_entry.get_frozen() == freeze {
            return false;
        }
        root_entry.set_frozen(freeze);
        let root_children_empty: bool = root_entry.get_children().is_empty();
        let root_effects_empty: bool = root_entry.get_effects().is_empty();
        if root_children_empty && root_effects_empty {
            return false;
        }
        let mut any_resumed_dirty: bool = if root_effects_empty {
            false
        } else {
            Self::apply_scope_effects_frozen(
                root_entry.get_effects(),
                freeze,
                effects,
                pending_effects,
            )
        };
        if root_children_empty {
            return any_resumed_dirty && *batch_depth == 0 && !*flushing;
        }
        scope_stack_scratch.clear();
        scope_stack_scratch.extend_from_slice(root_entry.get_children());
        while let Some(cur_id) = scope_stack_scratch.pop() {
            let slot: SlotId = cur_id.slot();
            if let Some(entry) = scopes.get(slot.as_usize())
                && entry.get_generation() == slot.get_generation()
                && entry.get_alive()
            {
                if !entry.get_children().is_empty() {
                    scope_stack_scratch.extend_from_slice(entry.get_children());
                }
                if !entry.get_effects().is_empty()
                    && Self::apply_scope_effects_frozen(
                        entry.get_effects(),
                        freeze,
                        effects,
                        pending_effects,
                    )
                {
                    any_resumed_dirty = true;
                }
            }
        }
        any_resumed_dirty && *batch_depth == 0 && !*flushing
    }

    /// Returns whether scope `id` is currently alive and frozen.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `ScopeId` - Scope identifier to query.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the scope is frozen.
    #[inline]
    pub(crate) fn is_scope_frozen(&self, id: ScopeId) -> bool {
        let slot: SlotId = id.slot();
        self.get_scopes()
            .get(slot.as_usize())
            .map(|entry: &ScopeEntry| {
                entry.get_generation() == slot.get_generation()
                    && entry.get_alive()
                    && entry.get_frozen()
            })
            .unwrap_or(false)
    }

    /// Returns the currently active reactive `ScopeId` on the top of the scope stack, if any.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    ///
    /// # Returns
    ///
    /// - `Option<ScopeId>` - Active scope identifier or `None` outside `Scope::run`/`Scope::enter`.
    #[must_use]
    #[inline(always)]
    pub(crate) fn current_scope_id(&self) -> Option<ScopeId> {
        self.get_scope_stack().last().copied()
    }

    /// Returns `true` when `candidate` equals `root` or is a live descendant scope of `root`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `ScopeId` - Scope identifier to test.
    /// - `ScopeId` - Subtree root scope identifier.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether `candidate` belongs to `root`'s scope hierarchy.
    #[must_use]
    pub(crate) fn is_scope_in_subtree(&self, candidate: ScopeId, root: ScopeId) -> bool {
        if candidate == root {
            return true;
        }
        let scopes: &[ScopeEntry] = self.get_scopes();
        let max_steps: usize = scopes.len();
        let mut cur: ScopeId = candidate;
        let mut steps: usize = 0;
        while steps < max_steps {
            let slot: SlotId = cur.slot();
            let Some(entry) = scopes.get(slot.as_usize()) else {
                return false;
            };
            let inactive: bool =
                entry.get_generation() != slot.get_generation() || !entry.get_alive();
            if inactive {
                return false;
            }
            let Some(parent_id) = entry.get_parent() else {
                return false;
            };
            if parent_id == root {
                let root_slot: SlotId = root.slot();
                return scopes
                    .get(root_slot.as_usize())
                    .is_some_and(|root_entry: &ScopeEntry| {
                        root_entry.get_generation() == root_slot.get_generation()
                            && root_entry.get_alive()
                    });
            }
            cur = parent_id;
            steps += 1;
        }
        false
    }

    /// Returns `true` when `id` itself or any live ancestor scope is currently frozen.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `ScopeId` - Scope identifier to test.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether `id` is suspended by freezing.
    #[must_use]
    pub(crate) fn is_scope_effectively_frozen(&self, id: ScopeId) -> bool {
        let scopes: &[ScopeEntry] = self.get_scopes();
        let max_steps: usize = scopes.len();
        let mut cur: ScopeId = id;
        let mut steps: usize = 0;
        while steps < max_steps {
            let slot: SlotId = cur.slot();
            let Some(entry) = scopes.get(slot.as_usize()) else {
                return false;
            };
            let inactive: bool =
                entry.get_generation() != slot.get_generation() || !entry.get_alive();
            if inactive {
                return false;
            }
            if entry.get_frozen() {
                return true;
            }
            let Some(parent_id) = entry.get_parent() else {
                return false;
            };
            cur = parent_id;
            steps += 1;
        }
        false
    }
}