rart 0.8.0

High-performance Adaptive Radix Tree implementation with SIMD optimizations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
//! Versioned Adaptive Radix Tree implementation with copy-on-write semantics.
//!
//! This module provides a persistent/versioned ART where snapshots can be taken
//! and mutated independently using copy-on-write node sharing for memory efficiency.

use std::cmp::min;
use std::collections::Bound;
use std::ops::RangeBounds;

use crate::iter::LendingKeyView;
use crate::keys::KeyTrait;
use crate::mapping::{
    NodeMapping,
    direct_mapping::{DirectMapping, DirectMappingIter},
    indexed_mapping::{IndexedMapping, IndexedMappingIter},
    sorted_keyed_mapping::{SortedKeyedMapping, SortedKeyedMappingIter},
};
use crate::partials::Partial;
use crate::utils::bitset::Bitset64;

#[cfg(not(feature = "triomphe-arc"))]
use std::sync::Arc;
#[cfg(feature = "triomphe-arc")]
use triomphe::Arc;

/// Type alias for remove operation result to reduce type complexity
type RemoveResult<P, V> = (Option<Arc<VersionedNode<P, V>>>, V);
type VersionedPrefixSubtreeView<'a, P, V> = (&'a VersionedNode<P, V>, Vec<&'a [u8]>, usize);

type VersionedIterEntry<'a, P, V> = (u8, &'a VersionedNode<P, V>);

enum VersionedIterFrameIter<'a, P: Partial, V> {
    Plain(VersionedNodeIter<'a, P, V>),
    Leading {
        first: Option<VersionedIterEntry<'a, P, V>>,
        rest: VersionedNodeIter<'a, P, V>,
    },
}

impl<'a, P: Partial, V> Iterator for VersionedIterFrameIter<'a, P, V> {
    type Item = VersionedIterEntry<'a, P, V>;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            VersionedIterFrameIter::Plain(iter) => iter.next(),
            VersionedIterFrameIter::Leading { first, rest } => first.take().or_else(|| rest.next()),
        }
    }
}

pub(crate) enum VersionedNodeIter<'a, P: Partial, V> {
    Node4(SortedKeyedMappingIter<'a, Arc<VersionedNode<P, V>>, 4>),
    Node16(SortedKeyedMappingIter<'a, Arc<VersionedNode<P, V>>, 16>),
    Node48(IndexedMappingIter<'a, Arc<VersionedNode<P, V>>, 48, Bitset64<1>>),
    Node256(DirectMappingIter<'a, Arc<VersionedNode<P, V>>>),
    Empty,
}

impl<'a, P: Partial, V> Iterator for VersionedNodeIter<'a, P, V> {
    type Item = (u8, &'a VersionedNode<P, V>);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            VersionedNodeIter::Node4(iter) => iter.next().map(|(key, child)| (key, child.as_ref())),
            VersionedNodeIter::Node16(iter) => {
                iter.next().map(|(key, child)| (key, child.as_ref()))
            }
            VersionedNodeIter::Node48(iter) => {
                iter.next().map(|(key, child)| (key, child.as_ref()))
            }
            VersionedNodeIter::Node256(iter) => {
                iter.next().map(|(key, child)| (key, child.as_ref()))
            }
            VersionedNodeIter::Empty => None,
        }
    }
}

/// Iterator over all key-value pairs in a [`VersionedAdaptiveRadixTree`].
pub struct VersionedIter<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> {
    inner: Box<dyn Iterator<Item = (K, &'a V)> + 'a>,
    _marker: std::marker::PhantomData<(K, P)>,
}

/// Iterator over stored keys that are prefixes of a probe key in a
/// [`VersionedAdaptiveRadixTree`].
///
/// This iterator follows only the path described by the probe key and yields
/// matching stored keys from shortest to longest.
pub struct VersionedPrefixMatchIter<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> {
    cur_node: Option<&'a VersionedNode<P, V>>,
    probe: K,
    cur_key: Vec<u8>,
    depth: usize,
}

struct VersionedIterInner<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> {
    node_iter_stack: Vec<(usize, VersionedIterFrameIter<'a, P, V>)>,
    cur_key: Vec<u8>,
    start_bound: Option<Bound<K>>,
}

pub(crate) struct VersionedLendingIterInner<'a, P: Partial + 'a, V> {
    node_iter_stack: Vec<(usize, usize, VersionedIterFrameIter<'a, P, V>)>,
    cur_segments: Vec<&'a [u8]>,
    cur_len: usize,
    end_bound: Option<(Vec<u8>, bool)>,
}

/// Iterator over only values in a [`VersionedAdaptiveRadixTree`].
pub struct VersionedValuesIter<'a, P: Partial + 'a, V> {
    root_value: Option<&'a V>,
    node_iter_stack: Vec<VersionedNodeIter<'a, P, V>>,
}

/// Iterator over versioned key-value pairs within a specified range.
pub struct VersionedRange<'a, K: KeyTrait + 'a, V> {
    iter: VersionedIter<'a, K, K::PartialType, V>,
    end: Bound<K>,
}

/// A versioned Adaptive Radix Tree that supports snapshot-based copy-on-write mutations.
///
/// Unlike the standard [`AdaptiveRadixTree`], this version allows taking O(1) snapshots
/// that can be independently mutated. Mutations use copy-on-write semantics to minimize
/// memory usage while maintaining structural sharing between versions.
///
/// ## Features
///
/// - **O(1) snapshots**: Create new versions instantly without copying data
/// - **Copy-on-write mutations**: Only copy nodes along the path being modified
/// - **Structural sharing**: Unmodified subtrees are shared between versions
/// - **MVCC support**: Ideal for implementing multi-version concurrency control
///
/// ## Examples
///
/// Basic insertion and snapshots:
///
/// ```rust
/// use rart::{VersionedAdaptiveRadixTree, ArrayKey};
///
/// let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, String>::new();
///
/// // insert() returns bool - optimized for performance
/// assert_eq!(tree.insert("key1", "value1".to_string()), false); // new key
/// assert_eq!(tree.insert("key1", "updated".to_string()), true);  // replacement
///
/// // Take a snapshot - O(1) operation
/// let mut snapshot = tree.snapshot();
///
/// // Mutations to snapshot don't affect original
/// snapshot.insert("key2", "value2".to_string());
///
/// assert_eq!(tree.get("key2"), None);
/// assert_eq!(snapshot.get("key2"), Some(&"value2".to_string()));
/// ```
///
/// Getting old values on replacement:
///
/// ```rust
/// use rart::{VersionedAdaptiveRadixTree, ArrayKey};
///
/// let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
///
/// // insert_and_replace() returns Option<old_value> - may clone when needed
/// assert_eq!(tree.insert_and_replace("key", 100), None);      // new key
/// assert_eq!(tree.insert_and_replace("key", 200), Some(100)); // got old value
/// ```
pub struct VersionedAdaptiveRadixTree<KeyType, ValueType>
where
    KeyType: KeyTrait,
    ValueType: Clone,
{
    root: Option<Arc<VersionedNode<KeyType::PartialType, ValueType>>>,
    version: u64,
    _phantom: std::marker::PhantomData<KeyType>,
}

/// A versioned node that can be shared between multiple tree versions.
pub struct VersionedNode<P: Partial, V> {
    pub(crate) prefix: P,
    pub(crate) value: Option<V>,
    pub(crate) content: VersionedContent<P, V>,
    pub(crate) version: u64,
}

/// Content of a versioned node, using Arc for child sharing.
pub(crate) enum VersionedContent<P: Partial, V> {
    Empty,
    Node4(Box<SortedKeyedMapping<Arc<VersionedNode<P, V>>, 4>>),
    Node16(Box<SortedKeyedMapping<Arc<VersionedNode<P, V>>, 16>>),
    Node48(Box<IndexedMapping<Arc<VersionedNode<P, V>>, 48, Bitset64<1>>>),
    Node256(Box<DirectMapping<Arc<VersionedNode<P, V>>>>),
}

impl<KeyType: KeyTrait, ValueType: Clone> Default
    for VersionedAdaptiveRadixTree<KeyType, ValueType>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<KeyType, ValueType> Clone for VersionedAdaptiveRadixTree<KeyType, ValueType>
where
    KeyType: KeyTrait,
    ValueType: Clone,
{
    /// Clone creates a new snapshot at the current version.
    /// This is equivalent to calling `snapshot()`.
    fn clone(&self) -> Self {
        Self {
            root: self.root.clone(),
            version: self.version,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<KeyType, ValueType> VersionedAdaptiveRadixTree<KeyType, ValueType>
where
    KeyType: KeyTrait,
    ValueType: Clone,
{
    /// Create a new empty versioned tree.
    pub fn new() -> Self {
        Self {
            root: None,
            version: 0,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a snapshot of the current tree state.
    ///
    /// This is an O(1) operation that creates a new tree sharing the same
    /// underlying nodes. Subsequent mutations to either tree will use
    /// copy-on-write to maintain independence.
    pub fn snapshot(&self) -> Self {
        Self {
            root: self.root.clone(),
            version: self.version + 1,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Get a value by key (generic version).
    #[inline]
    pub fn get<Key>(&self, key: Key) -> Option<&ValueType>
    where
        Key: Into<KeyType>,
    {
        self.get_k(&key.into())
    }

    /// Get a value by key reference (direct version).
    #[inline]
    pub fn get_k(&self, key: &KeyType) -> Option<&ValueType> {
        let root = self.root.as_ref()?;
        Self::get_iterate(root, key)
    }

    /// Iterate over all key-value pairs in lexicographic order.
    pub fn iter(&self) -> VersionedIter<'_, KeyType, KeyType::PartialType, ValueType> {
        VersionedIter::new(self.root.as_deref())
    }

    /// Visit all key-value pairs using a lending borrowed key view.
    pub fn for_each_view<F>(&self, on_each: F)
    where
        F: for<'view> FnMut(LendingKeyView<'_, 'view>, &ValueType),
    {
        VersionedLendingIterInner::for_each(self.root.as_deref(), on_each);
    }

    /// Create an iterator over only the values in the tree.
    pub fn values_iter(&self) -> VersionedValuesIter<'_, KeyType::PartialType, ValueType> {
        VersionedValuesIter::new(self.root.as_deref())
    }

    /// Intersect two trees using ART-native node traversal.
    ///
    /// This avoids full key-stream materialization and instead walks both tries in lockstep,
    /// pruning mismatched prefixes early.
    pub fn intersect_with<'a, F>(&'a self, other: &'a Self, mut on_match: F)
    where
        F: FnMut(KeyType, &'a ValueType, &'a ValueType),
    {
        let (Some(left_root), Some(right_root)) = (self.root.as_deref(), other.root.as_deref())
        else {
            return;
        };

        let mut key_buf = Vec::with_capacity(KeyType::MAXIMUM_SIZE.unwrap_or(64));
        Self::intersect_nodes(left_root, 0, right_root, 0, &mut key_buf, &mut on_match);
    }

    /// Intersect two trees using ART-native traversal and yield lending key views.
    pub fn intersect_lending_with<'a, F>(&'a self, other: &'a Self, mut on_match: F)
    where
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a ValueType, &'a ValueType),
    {
        let (Some(left_root), Some(right_root)) = (self.root.as_deref(), other.root.as_deref())
        else {
            return;
        };

        let mut segments = Vec::new();
        let mut key_len = 0usize;
        Self::intersect_nodes_lending(
            left_root,
            0,
            right_root,
            0,
            &mut segments,
            &mut key_len,
            &mut on_match,
        );
    }

    /// Intersect two trees and invoke a callback with value pairs only.
    ///
    /// This avoids key materialization and is useful when only the joined values are needed.
    pub fn intersect_values_with<'a, F>(&'a self, other: &'a Self, mut on_match: F)
    where
        F: FnMut(&'a ValueType, &'a ValueType),
    {
        let (Some(left_root), Some(right_root)) = (self.root.as_deref(), other.root.as_deref())
        else {
            return;
        };

        Self::intersect_nodes_values(left_root, 0, right_root, 0, &mut on_match);
    }

    /// Count the number of keys that exist in both trees.
    pub fn intersect_count(&self, other: &Self) -> usize {
        let mut count = 0usize;
        self.intersect_values_with(other, |_left_value, _right_value| {
            count += 1;
        });
        count
    }

    /// Iterate over stored key/value pairs whose keys are prefixes of `key`.
    ///
    /// Matches are yielded from shortest to longest. This differs from
    /// [`Self::prefix_iter`], which yields entries below a supplied prefix.
    #[inline]
    pub fn prefix_match_iter<Key>(
        &self,
        key: Key,
    ) -> VersionedPrefixMatchIter<'_, KeyType, KeyType::PartialType, ValueType>
    where
        Key: Into<KeyType>,
    {
        VersionedPrefixMatchIter::new(self.root.as_deref(), key.into())
    }

    /// Iterate over stored key/value pairs whose keys are prefixes of `key`.
    ///
    /// Matches are yielded from shortest to longest. This differs from
    /// [`Self::prefix_iter_k`], which yields entries below a supplied prefix.
    #[inline]
    pub fn prefix_match_iter_k(
        &self,
        key: &KeyType,
    ) -> VersionedPrefixMatchIter<'_, KeyType, KeyType::PartialType, ValueType> {
        VersionedPrefixMatchIter::new(self.root.as_deref(), key.clone())
    }

    /// Visit stored key/value pairs whose keys are prefixes of `key`.
    ///
    /// Matches are visited from shortest to longest. The key slice passed to
    /// the callback borrows from the supplied probe key, so the tree does not
    /// rebuild owned keys or maintain per-match key scratch state.
    #[inline]
    pub fn prefix_match_for_each<Key, F>(&self, key: Key, on_match: F)
    where
        Key: Into<KeyType>,
        F: FnMut(&[u8], &ValueType),
    {
        self.prefix_match_for_each_k(&key.into(), on_match)
    }

    /// Visit stored key/value pairs whose keys are prefixes of `key`.
    ///
    /// Matches are visited from shortest to longest. The key slice passed to
    /// the callback borrows from the supplied probe key, so the tree does not
    /// rebuild owned keys or maintain per-match key scratch state.
    #[inline]
    pub fn prefix_match_for_each_k<F>(&self, key: &KeyType, on_match: F)
    where
        F: FnMut(&[u8], &ValueType),
    {
        let Some(root) = self.root.as_deref() else {
            return;
        };
        Self::prefix_match_for_each_impl(root, key, on_match);
    }

    /// Iterate over all entries whose keys start with `prefix`.
    #[inline]
    pub fn prefix_iter<Key>(
        &self,
        prefix: Key,
    ) -> VersionedIter<'_, KeyType, KeyType::PartialType, ValueType>
    where
        Key: Into<KeyType>,
    {
        self.prefix_iter_k(&prefix.into())
    }

    /// Iterate over all entries whose keys start with `prefix`.
    pub fn prefix_iter_k(
        &self,
        prefix: &KeyType,
    ) -> VersionedIter<'_, KeyType, KeyType::PartialType, ValueType> {
        let Some(root) = self.root.as_deref() else {
            return VersionedIter::empty();
        };
        let Some((subtree_root, subtree_root_key)) = Self::find_prefix_subtree(root, prefix) else {
            return VersionedIter::empty();
        };
        VersionedIter::new_with_prefix(Some(subtree_root), subtree_root_key)
    }

    /// Visit all entries whose keys start with `prefix` using a lending borrowed key view.
    pub fn prefix_for_each_view<Key, F>(&self, prefix: Key, on_each: F)
    where
        Key: Into<KeyType>,
        F: for<'view> FnMut(LendingKeyView<'_, 'view>, &ValueType),
    {
        self.prefix_for_each_view_k(&prefix.into(), on_each)
    }

    /// Visit all entries whose keys start with `prefix` using a lending borrowed key view.
    pub fn prefix_for_each_view_k<F>(&self, prefix: &KeyType, on_each: F)
    where
        F: for<'view> FnMut(LendingKeyView<'_, 'view>, &ValueType),
    {
        let Some(root) = self.root.as_deref() else {
            return;
        };
        let Some((subtree_root, subtree_root_segments, subtree_root_len)) =
            Self::find_prefix_subtree_view(root, prefix)
        else {
            return;
        };
        VersionedLendingIterInner::for_each_with_prefix(
            Some(subtree_root),
            subtree_root_segments,
            subtree_root_len,
            on_each,
        );
    }

    /// Create an iterator over key-value pairs within a specified range.
    pub fn range<'a, R>(&'a self, range: R) -> VersionedRange<'a, KeyType, ValueType>
    where
        R: RangeBounds<KeyType> + 'a,
    {
        let start_bound = range.start_bound().cloned();
        let end_bound = range.end_bound().cloned();

        let iter = match start_bound {
            Bound::Unbounded => self.iter(),
            _ => VersionedIter::new_with_start_bound(self.root.as_deref(), start_bound),
        };

        VersionedRange {
            iter,
            end: end_bound,
        }
    }

    /// Visit key-value pairs within a specified range using a lending borrowed key view.
    pub fn for_each_range_view<R, F>(&self, range: R, on_each: F)
    where
        R: RangeBounds<KeyType>,
        F: for<'view> FnMut(LendingKeyView<'_, 'view>, &ValueType),
    {
        let start_bound = range.start_bound().cloned();
        let end_bound = range.end_bound().cloned();
        VersionedLendingIterInner::for_each_with_bounds(
            self.root.as_deref(),
            start_bound,
            end_bound,
            on_each,
        );
    }

    /// Insert a key-value pair (generic version).
    ///
    /// This is a performance-optimized insertion method that uses copy-on-write
    /// to ensure this operation doesn't affect other snapshots, but doesn't
    /// return the old value to avoid unnecessary cloning.
    ///
    /// # Returns
    ///
    /// - `true` if a previous value was replaced
    /// - `false` if this was a new key
    ///
    /// # Performance
    ///
    /// This method is optimized for cases where you don't need the old value.
    /// If you need the old value, use [`insert_and_replace`] instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rart::{VersionedAdaptiveRadixTree, ArrayKey};
    ///
    /// let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
    ///
    /// // Insert new key returns false
    /// assert_eq!(tree.insert("key1", 100), false);
    ///
    /// // Insert same key returns true (replacement)
    /// assert_eq!(tree.insert("key1", 200), true);
    /// ```
    ///
    /// [`insert_and_replace`]: Self::insert_and_replace
    #[inline]
    pub fn insert<KV>(&mut self, key: KV, value: ValueType) -> bool
    where
        KV: Into<KeyType>,
    {
        self.insert_k(&key.into(), value)
    }

    /// Insert a key-value pair using key reference (direct version).
    ///
    /// This is a performance-optimized insertion method that uses copy-on-write
    /// to ensure this operation doesn't affect other snapshots, but doesn't
    /// return the old value to avoid unnecessary cloning.
    ///
    /// # Returns
    ///
    /// - `true` if a previous value was replaced
    /// - `false` if this was a new key
    ///
    /// # Performance
    ///
    /// This method is optimized for cases where you don't need the old value.
    /// If you need the old value, use [`insert_and_replace_k`] instead.
    ///
    /// [`insert_and_replace_k`]: Self::insert_and_replace_k
    pub fn insert_k(&mut self, key: &KeyType, value: ValueType) -> bool {
        self.version += 1;

        let Some(root) = self.root.take() else {
            self.root = Some(Arc::new(VersionedNode::new_leaf(
                key.to_partial(0),
                value,
                self.version,
            )));
            return false;
        };

        let (new_root, was_replaced) =
            Self::insert_recurse(root, key, value, 0, self.version, None);
        self.root = Some(new_root);
        was_replaced
    }

    /// Insert a key-value pair and return the previous value if it existed (generic version).
    ///
    /// This method uses copy-on-write to ensure this operation doesn't affect other
    /// snapshots, and returns the old value when a replacement occurs. This method
    /// may need to clone the old value when nodes are shared between snapshots.
    ///
    /// # Returns
    ///
    /// - `Some(old_value)` if a previous value was replaced
    /// - `None` if this was a new key
    ///
    /// # Performance
    ///
    /// This method has higher overhead than [`insert`] because it may need to clone
    /// the old value when nodes are shared. Use [`insert`] if you don't need the old value.
    ///
    /// # Copy-on-Write Behavior
    ///
    /// - When the tree has exclusive ownership of nodes (fast path), extracts old value without cloning
    /// - When nodes are shared with snapshots (slow path), clones the old value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rart::{VersionedAdaptiveRadixTree, ArrayKey};
    ///
    /// let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
    ///
    /// // Insert new key returns None
    /// assert_eq!(tree.insert_and_replace("key1", 100), None);
    ///
    /// // Insert same key returns old value
    /// assert_eq!(tree.insert_and_replace("key1", 200), Some(100));
    ///
    /// // With snapshots, old value is cloned when necessary
    /// let snapshot = tree.snapshot();
    /// assert_eq!(tree.insert_and_replace("key1", 300), Some(200));
    /// assert_eq!(snapshot.get("key1"), Some(&200)); // Snapshot unchanged
    /// ```
    ///
    /// [`insert`]: Self::insert
    #[inline]
    pub fn insert_and_replace<KV>(&mut self, key: KV, value: ValueType) -> Option<ValueType>
    where
        KV: Into<KeyType>,
    {
        self.insert_and_replace_k(&key.into(), value)
    }

    /// Insert a key-value pair and return the previous value if it existed (direct version).
    ///
    /// This method uses copy-on-write to ensure this operation doesn't affect other
    /// snapshots, and returns the old value when a replacement occurs. This method
    /// may need to clone the old value when nodes are shared between snapshots.
    ///
    /// # Returns
    ///
    /// - `Some(old_value)` if a previous value was replaced
    /// - `None` if this was a new key
    ///
    /// # Performance
    ///
    /// This method has higher overhead than [`insert_k`] because it may need to clone
    /// the old value when nodes are shared. Use [`insert_k`] if you don't need the old value.
    ///
    /// # Copy-on-Write Behavior
    ///
    /// - When the tree has exclusive ownership of nodes (fast path), extracts old value without cloning
    /// - When nodes are shared with snapshots (slow path), clones the old value
    ///
    /// [`insert_k`]: Self::insert_k
    pub fn insert_and_replace_k(&mut self, key: &KeyType, value: ValueType) -> Option<ValueType> {
        self.version += 1;

        let Some(root) = self.root.take() else {
            self.root = Some(Arc::new(VersionedNode::new_leaf(
                key.to_partial(0),
                value,
                self.version,
            )));
            return None;
        };

        let mut old_value = None;
        let (new_root, _was_replaced) =
            Self::insert_recurse(root, key, value, 0, self.version, Some(&mut old_value));
        self.root = Some(new_root);
        old_value
    }

    /// Remove a key-value pair (generic version).
    ///
    /// Uses copy-on-write to ensure this operation doesn't affect other snapshots.
    /// Returns the removed value if the key existed.
    pub fn remove<KV>(&mut self, key: KV) -> Option<ValueType>
    where
        KV: Into<KeyType>,
    {
        self.remove_k(&key.into())
    }

    /// Remove a key-value pair using key reference (direct version).
    ///
    /// Uses copy-on-write to ensure this operation doesn't affect other snapshots.
    /// Returns the removed value if the key existed.
    pub fn remove_k(&mut self, key: &KeyType) -> Option<ValueType> {
        self.get_k(key)?;

        self.version += 1;
        let root = self
            .root
            .take()
            .expect("non-empty tree checked before remove mutation");

        // Special case: root is a leaf
        if root.is_leaf() {
            if root.prefix.len() != key.length_at(0) {
                self.root = Some(root);
                return None;
            }

            match Arc::try_unwrap(root) {
                Ok(mut owned_root) => {
                    return owned_root.value.take();
                }
                Err(shared_root) => {
                    // Root is shared, clone the value
                    let cloned_value = shared_root.value().cloned();
                    self.root = None;
                    return cloned_value;
                }
            }
        }

        if root.prefix.len() == key.length_at(0) {
            let new_root = Self::ensure_cow_node(root, self.version);
            let mut new_root = match Arc::try_unwrap(new_root) {
                Ok(owned) => owned,
                Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
            };
            let removed = new_root.value.take();
            if new_root.num_children() == 0 && new_root.value.is_none() {
                self.root = None;
            } else {
                self.root = Some(Arc::new(new_root));
            }
            return removed;
        }

        let (new_root, removed_value) = Self::remove_recurse(root, key, 0, self.version)
            .expect("prechecked key should be removable");

        // Update root, handling the case where it might become empty
        if let Some(root_node) = new_root {
            if root_node.is_inner() && root_node.num_children() == 0 && root_node.value().is_none()
            {
                self.root = None;
            } else {
                self.root = Some(root_node);
            }
        } else {
            self.root = None;
        }

        Some(removed_value)
    }

    /// Check if the tree is empty.
    pub fn is_empty(&self) -> bool {
        self.root.is_none()
    }

    /// Get the current version number of this tree.
    pub fn version(&self) -> u64 {
        self.version
    }

    /// Convert this versioned tree into a regular AdaptiveRadixTree.
    ///
    /// This method attempts to avoid cloning when possible:
    /// - If the tree has unique ownership of all nodes, it converts in-place (fast path)
    /// - If nodes are shared with other snapshots, it clones the data (slow path)
    ///
    /// # Returns
    ///
    /// A regular `AdaptiveRadixTree` containing the same key-value pairs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rart::{VersionedAdaptiveRadixTree, ArrayKey};
    ///
    /// let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
    /// vtree.insert("key1", 42);
    /// vtree.insert("key2", 84);
    ///
    /// // Convert to regular tree
    /// let tree = vtree.into_unversioned();
    /// assert_eq!(tree.get("key1"), Some(&42));
    /// assert_eq!(tree.get("key2"), Some(&84));
    /// ```
    pub fn into_unversioned(self) -> crate::tree::AdaptiveRadixTree<KeyType, ValueType> {
        use crate::tree::AdaptiveRadixTree;

        let Some(root) = self.root else {
            return AdaptiveRadixTree::new();
        };

        // Try fast path: convert Arc<VersionedNode> to owned DefaultNode
        let converted_root = Self::convert_to_unversioned_node(root);

        AdaptiveRadixTree::from_root(converted_root)
    }

    /// Convert a versioned node to an unversioned node.
    /// Uses fast path when possible (unique ownership), slow path when shared.
    fn convert_to_unversioned_node(
        node: Arc<VersionedNode<KeyType::PartialType, ValueType>>,
    ) -> crate::node::DefaultNode<KeyType::PartialType, ValueType> {
        use crate::mapping::{
            direct_mapping::DirectMapping, indexed_mapping::IndexedMapping,
            sorted_keyed_mapping::SortedKeyedMapping,
        };
        use crate::node::{Content, DefaultNode};

        match Arc::try_unwrap(node) {
            Ok(owned_node) => {
                // Fast path: we have unique ownership, convert in-place
                let VersionedNode {
                    prefix,
                    value,
                    content,
                    version: _,
                } = owned_node;
                let unversioned_content = match content {
                    VersionedContent::Empty => Content::Empty,
                    VersionedContent::Node4(km) => {
                        let mut new_km = SortedKeyedMapping::new();
                        for (key, child) in km.into_iter() {
                            let converted_child = Self::convert_to_unversioned_node(child);
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node4(Box::new(new_km))
                    }
                    VersionedContent::Node16(km) => {
                        let mut new_km = SortedKeyedMapping::new();
                        for (key, child) in km.into_iter() {
                            let converted_child = Self::convert_to_unversioned_node(child);
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node16(Box::new(new_km))
                    }
                    VersionedContent::Node48(km) => {
                        let mut new_km = IndexedMapping::new();
                        for (key, child) in km.into_iter() {
                            let converted_child = Self::convert_to_unversioned_node(child);
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node48(Box::new(new_km))
                    }
                    VersionedContent::Node256(km) => {
                        let mut new_km = DirectMapping::new();
                        for (key, child) in km.into_iter() {
                            let converted_child = Self::convert_to_unversioned_node(child);
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node256(Box::new(new_km))
                    }
                };

                DefaultNode {
                    prefix,
                    value,
                    content: unversioned_content,
                }
            }
            Err(shared_node) => {
                // Slow path: node is shared, must clone
                let unversioned_content = match &shared_node.content {
                    VersionedContent::Empty => Content::Empty,
                    VersionedContent::Node4(km) => {
                        let mut new_km = SortedKeyedMapping::new();
                        for (key, child) in km.iter() {
                            let converted_child =
                                Self::convert_to_unversioned_node(Arc::clone(child));
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node4(Box::new(new_km))
                    }
                    VersionedContent::Node16(km) => {
                        let mut new_km = SortedKeyedMapping::new();
                        for (key, child) in km.iter() {
                            let converted_child =
                                Self::convert_to_unversioned_node(Arc::clone(child));
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node16(Box::new(new_km))
                    }
                    VersionedContent::Node48(km) => {
                        let mut new_km = IndexedMapping::new();
                        for (key, child) in km.iter() {
                            let converted_child =
                                Self::convert_to_unversioned_node(Arc::clone(child));
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node48(Box::new(new_km))
                    }
                    VersionedContent::Node256(km) => {
                        let mut new_km = DirectMapping::new();
                        for (key, child) in km.iter() {
                            let converted_child =
                                Self::convert_to_unversioned_node(Arc::clone(child));
                            new_km.add_child(key, converted_child);
                        }
                        Content::Node256(Box::new(new_km))
                    }
                };

                DefaultNode {
                    prefix: shared_node.prefix.clone(),
                    value: shared_node.value.clone(),
                    content: unversioned_content,
                }
            }
        }
    }
}

impl<P: Partial, V> VersionedNode<P, V> {
    /// Create a new leaf node.
    pub fn new_leaf(prefix: P, value: V, version: u64) -> Self {
        Self {
            prefix,
            value: Some(value),
            content: VersionedContent::Empty,
            version,
        }
    }

    /// Create a new inner node.
    pub fn new_inner(prefix: P, version: u64) -> Self {
        Self {
            prefix,
            value: None,
            content: VersionedContent::Node4(Box::default()),
            version,
        }
    }

    /// Check if this is a leaf node.
    pub fn is_leaf(&self) -> bool {
        matches!(&self.content, VersionedContent::Empty)
    }

    /// Check if this is an inner node.
    pub fn is_inner(&self) -> bool {
        !self.is_leaf()
    }

    /// Get the value if this is a leaf node.
    pub fn value(&self) -> Option<&V> {
        self.value.as_ref()
    }

    /// Seek a child by key.
    pub fn seek_child(&self, key: u8) -> Option<&Arc<VersionedNode<P, V>>> {
        match &self.content {
            VersionedContent::Node4(km) => km.seek_child(key),
            VersionedContent::Node16(km) => km.seek_child(key),
            VersionedContent::Node48(km) => km.seek_child(key),
            VersionedContent::Node256(km) => km.seek_child(key),
            VersionedContent::Empty => None,
        }
    }

    /// Get the number of children.
    pub fn num_children(&self) -> usize {
        match &self.content {
            VersionedContent::Node4(km) => km.num_children(),
            VersionedContent::Node16(km) => km.num_children(),
            VersionedContent::Node48(km) => km.num_children(),
            VersionedContent::Node256(km) => km.num_children(),
            VersionedContent::Empty => 0,
        }
    }

    /// Check if this node is full and needs to grow.
    pub fn is_full(&self) -> bool {
        match &self.content {
            VersionedContent::Node4(km) => km.num_children() >= 4,
            VersionedContent::Node16(km) => km.num_children() >= 16,
            VersionedContent::Node48(km) => km.num_children() >= 48,
            VersionedContent::Node256(_) => false, // Node256 never grows
            VersionedContent::Empty => false,
        }
    }

    /// Create a grown version of this node (Node4 → Node16 → Node48 → Node256).
    pub fn grow(&self, new_version: u64) -> Self
    where
        P: Clone,
        V: Clone,
    {
        Self {
            prefix: self.prefix.clone(),
            value: self.value.clone(),
            content: match &self.content {
                VersionedContent::Node4(km) => {
                    // Grow Node4 to Node16
                    let mut new_km = SortedKeyedMapping::new();
                    for (key, child) in km.iter() {
                        new_km.add_child(key, Arc::clone(child));
                    }
                    VersionedContent::Node16(Box::new(new_km))
                }
                VersionedContent::Node16(km) => {
                    // Grow Node16 to Node48
                    let mut new_km = IndexedMapping::new();
                    for (key, child) in km.iter() {
                        new_km.add_child(key, Arc::clone(child));
                    }
                    VersionedContent::Node48(Box::new(new_km))
                }
                VersionedContent::Node48(km) => {
                    // Grow Node48 to Node256
                    let mut new_km = DirectMapping::new();
                    for (key, child) in km.iter() {
                        new_km.add_child(key, Arc::clone(child));
                    }
                    VersionedContent::Node256(Box::new(new_km))
                }
                VersionedContent::Node256(_) => {
                    panic!("Node256 cannot grow further")
                }
                VersionedContent::Empty => {
                    panic!("Leaf nodes cannot grow")
                }
            },
            version: new_version,
        }
    }

    /// Create a copy-on-write clone of this node with a new version.
    pub fn cow_clone_inner(&self, new_version: u64) -> Self
    where
        P: Clone,
        V: Clone,
    {
        Self {
            prefix: self.prefix.clone(),
            value: self.value.clone(),
            content: match &self.content {
                VersionedContent::Empty => VersionedContent::Empty,
                VersionedContent::Node4(km) => {
                    // Manually clone Node4 mapping
                    let mut new_km = SortedKeyedMapping::new();
                    for (key, child) in km.iter() {
                        new_km.add_child(key, Arc::clone(child));
                    }
                    VersionedContent::Node4(Box::new(new_km))
                }
                VersionedContent::Node16(km) => {
                    // Manually clone Node16 mapping
                    let mut new_km = SortedKeyedMapping::new();
                    for (key, child) in km.iter() {
                        new_km.add_child(key, Arc::clone(child));
                    }
                    VersionedContent::Node16(Box::new(new_km))
                }
                VersionedContent::Node48(km) => {
                    VersionedContent::Node48(Box::new(km.clone_mapping()))
                }
                VersionedContent::Node256(km) => {
                    VersionedContent::Node256(Box::new(km.clone_mapping()))
                }
            },
            version: new_version,
        }
    }

    fn add_child(&mut self, key: u8, child: Arc<VersionedNode<P, V>>)
    where
        P: Clone,
        V: Clone,
    {
        if matches!(self.content, VersionedContent::Empty) {
            self.content = VersionedContent::Node4(Box::default());
        }

        if self.is_full() {
            *self = self.grow(self.version);
        }

        match &mut self.content {
            VersionedContent::Node4(km) => km.add_child(key, child),
            VersionedContent::Node16(km) => km.add_child(key, child),
            VersionedContent::Node48(km) => km.add_child(key, child),
            VersionedContent::Node256(km) => km.add_child(key, child),
            VersionedContent::Empty => {
                unreachable!("empty nodes are promoted before adding children")
            }
        }
    }

    fn delete_child(&mut self, key: u8) -> Option<Arc<VersionedNode<P, V>>> {
        match &mut self.content {
            VersionedContent::Node4(km) => km.delete_child(key),
            VersionedContent::Node16(km) => km.delete_child(key),
            VersionedContent::Node48(km) => km.delete_child(key),
            VersionedContent::Node256(km) => km.delete_child(key),
            VersionedContent::Empty => None,
        }
    }

    pub(crate) fn iter(&self) -> VersionedNodeIter<'_, P, V> {
        match &self.content {
            VersionedContent::Node4(n) => VersionedNodeIter::Node4(n.iter()),
            VersionedContent::Node16(n) => VersionedNodeIter::Node16(n.iter()),
            VersionedContent::Node48(n) => VersionedNodeIter::Node48(n.iter()),
            VersionedContent::Node256(n) => VersionedNodeIter::Node256(n.iter()),
            VersionedContent::Empty => VersionedNodeIter::Empty,
        }
    }
}

impl<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> VersionedIterInner<'a, K, P, V> {
    #[inline]
    fn key_order(lhs: &K, rhs: &K) -> std::cmp::Ordering {
        let lhs_len = lhs.length_at(0);
        let rhs_len = rhs.length_at(0);
        let common = lhs_len.min(rhs_len);
        for i in 0..common {
            match lhs.at(i).cmp(&rhs.at(i)) {
                std::cmp::Ordering::Equal => {}
                ord => return ord,
            }
        }
        lhs_len.cmp(&rhs_len)
    }

    fn from_node_and_key(node: &'a VersionedNode<P, V>, cur_key: K) -> Self {
        Self {
            node_iter_stack: vec![(
                cur_key.length_at(0),
                VersionedIterFrameIter::Plain(node.iter()),
            )],
            cur_key: cur_key.as_ref().to_vec(),
            start_bound: None,
        }
    }

    fn new(node: &'a VersionedNode<P, V>) -> Self {
        Self::from_node_and_key(node, K::new_from_partial(&node.prefix))
    }

    fn new_with_start_bound(node: &'a VersionedNode<P, V>, start_bound: Bound<K>) -> Self {
        let seek_key = match &start_bound {
            Bound::Included(key) | Bound::Excluded(key) => Some(key),
            Bound::Unbounded => None,
        };

        if let Some(seek_key) = seek_key {
            return Self {
                node_iter_stack: Self::build_positioned_stack(node, seek_key, 0),
                cur_key: node.prefix.as_ref().to_vec(),
                start_bound: Some(start_bound),
            };
        }

        Self {
            node_iter_stack: vec![(
                node.prefix.len(),
                VersionedIterFrameIter::Plain(node.iter()),
            )],
            cur_key: node.prefix.as_ref().to_vec(),
            start_bound: None,
        }
    }

    fn build_positioned_stack(
        node: &'a VersionedNode<P, V>,
        seek_key: &K,
        depth: usize,
    ) -> Vec<(usize, VersionedIterFrameIter<'a, P, V>)> {
        let prefix_common = node.prefix.prefix_length_key(seek_key, depth);
        if prefix_common != node.prefix.len() {
            let seek_remaining = seek_key.length_at(depth);
            if prefix_common >= seek_remaining {
                return vec![(
                    node.prefix.len(),
                    VersionedIterFrameIter::Plain(node.iter()),
                )];
            }

            let node_byte = node.prefix.at(prefix_common);
            let seek_byte = seek_key.at(depth + prefix_common);

            if node_byte < seek_byte {
                return vec![];
            }

            return vec![(
                node.prefix.len(),
                VersionedIterFrameIter::Plain(node.iter()),
            )];
        }

        if seek_key.length_at(depth) == node.prefix.len() {
            return vec![(
                node.prefix.len(),
                VersionedIterFrameIter::Plain(node.iter()),
            )];
        }

        let target_depth = depth + node.prefix.len();
        let target_byte = seek_key.at(target_depth);
        let mut iter = node.iter();
        while let Some((key, child)) = iter.next() {
            if key < target_byte {
                continue;
            }

            return vec![(
                node.prefix.len(),
                VersionedIterFrameIter::Leading {
                    first: Some((key, child)),
                    rest: iter,
                },
            )];
        }

        vec![]
    }
}

impl<'a, K: KeyTrait<PartialType = P> + 'a, P: Partial + 'a, V> VersionedIter<'a, K, P, V> {
    fn empty() -> Self {
        Self {
            inner: Box::new(std::iter::empty()),
            _marker: Default::default(),
        }
    }

    fn from_root_and_children(
        root_key: K,
        root_value: Option<&'a V>,
        children: VersionedIterInner<'a, K, P, V>,
    ) -> Self {
        let inner: Box<dyn Iterator<Item = (K, &'a V)> + 'a> = match root_value {
            Some(value) => Box::new(std::iter::once((root_key, value)).chain(children)),
            None => Box::new(children),
        };

        Self {
            inner,
            _marker: Default::default(),
        }
    }

    fn new(node: Option<&'a VersionedNode<P, V>>) -> Self {
        let Some(root_node) = node else {
            return Self::empty();
        };

        let root_key = K::new_from_partial(&root_node.prefix);
        let root_value = root_node.value();

        if root_node.is_leaf() {
            return Self {
                inner: Box::new(std::iter::once((
                    root_key,
                    root_value.expect("corruption: missing data at leaf node during iteration"),
                ))),
                _marker: Default::default(),
            };
        }

        Self::from_root_and_children(root_key, root_value, VersionedIterInner::new(root_node))
    }

    fn new_with_prefix(node: Option<&'a VersionedNode<P, V>>, root_key: K) -> Self {
        let Some(root_node) = node else {
            return Self::empty();
        };

        let root_value = root_node.value();

        if root_node.is_leaf() {
            return Self {
                inner: Box::new(std::iter::once((
                    root_key,
                    root_value.expect("corruption: missing data at leaf node during iteration"),
                ))),
                _marker: Default::default(),
            };
        }

        Self::from_root_and_children(
            root_key.clone(),
            root_value,
            VersionedIterInner::from_node_and_key(root_node, root_key),
        )
    }

    fn new_with_start_bound(node: Option<&'a VersionedNode<P, V>>, start_bound: Bound<K>) -> Self {
        let Some(root_node) = node else {
            return Self::empty();
        };

        let root_key = K::new_from_partial(&root_node.prefix);
        let root_value = root_node.value();
        let satisfies_start = match &start_bound {
            Bound::Included(start_key) => {
                VersionedIterInner::<K, P, V>::key_order(&root_key, start_key)
                    >= std::cmp::Ordering::Equal
            }
            Bound::Excluded(start_key) => {
                VersionedIterInner::<K, P, V>::key_order(&root_key, start_key)
                    > std::cmp::Ordering::Equal
            }
            Bound::Unbounded => true,
        };

        if root_node.is_leaf() {
            if satisfies_start {
                return Self {
                    inner: Box::new(std::iter::once((
                        root_key,
                        root_value.expect("corruption: missing data at leaf node during iteration"),
                    ))),
                    _marker: Default::default(),
                };
            }

            return Self::empty();
        }

        let children = VersionedIterInner::new_with_start_bound(root_node, start_bound);
        if satisfies_start {
            return Self::from_root_and_children(root_key, root_value, children);
        }

        Self {
            inner: Box::new(children),
            _marker: Default::default(),
        }
    }
}

impl<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> Iterator for VersionedIter<'a, K, P, V> {
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> VersionedPrefixMatchIter<'a, K, P, V> {
    fn new(node: Option<&'a VersionedNode<P, V>>, probe: K) -> Self {
        Self {
            cur_node: node,
            probe,
            cur_key: Vec::new(),
            depth: 0,
        }
    }
}

impl<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> Iterator
    for VersionedPrefixMatchIter<'a, K, P, V>
{
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let cur_node = self.cur_node.take()?;
            let remaining_len = self.probe.length_at(self.depth);
            let prefix_len = cur_node.prefix.len();
            let prefix_common_match = cur_node.prefix.prefix_length_key(&self.probe, self.depth);

            if prefix_common_match != prefix_len {
                return None;
            }

            self.cur_key.extend_from_slice(cur_node.prefix.as_ref());
            self.depth += prefix_len;

            self.cur_node = if prefix_len == remaining_len {
                None
            } else {
                cur_node
                    .seek_child(self.probe.at(self.depth))
                    .map(std::convert::AsRef::as_ref)
            };

            if let Some(value) = cur_node.value() {
                return Some((K::new_from_slice(&self.cur_key), value));
            }
        }
    }
}

impl<'a, K: KeyTrait<PartialType = P>, P: Partial + 'a, V> Iterator
    for VersionedIterInner<'a, K, P, V>
{
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let (tree_depth, last_iter) = self.node_iter_stack.last_mut()?;
            let tree_depth = *tree_depth;
            self.cur_key.truncate(tree_depth);

            let Some((_key, node)) = last_iter.next() else {
                self.node_iter_stack.pop();
                if let Some((parent_depth, _)) = self.node_iter_stack.last() {
                    self.cur_key.truncate(*parent_depth);
                }
                continue;
            };

            self.cur_key.extend_from_slice(node.prefix.as_ref());

            let is_inner = node.is_inner();
            if is_inner {
                self.node_iter_stack.push((
                    tree_depth + node.prefix.len(),
                    VersionedIterFrameIter::Plain(node.iter()),
                ));
            }

            if let Some(value) = node.value() {
                let key = K::new_from_slice(&self.cur_key);
                if let Some(start_bound) = self.start_bound.as_ref() {
                    let satisfies_start = match start_bound {
                        Bound::Included(start_key) => {
                            VersionedIterInner::<K, P, V>::key_order(&key, start_key)
                                >= std::cmp::Ordering::Equal
                        }
                        Bound::Excluded(start_key) => {
                            VersionedIterInner::<K, P, V>::key_order(&key, start_key)
                                > std::cmp::Ordering::Equal
                        }
                        Bound::Unbounded => true,
                    };
                    if !satisfies_start {
                        continue;
                    }
                    self.start_bound = None;
                }
                return Some((key, value));
            }

            if !is_inner {
                self.cur_key.truncate(tree_depth);
            }
        }
    }
}

impl<'a, P: Partial + 'a, V> VersionedLendingIterInner<'a, P, V> {
    fn cmp_segments_to_slice(segments: &[&[u8]], len: usize, slice: &[u8]) -> std::cmp::Ordering {
        let mut offset = 0usize;
        for segment in segments {
            let remaining = &slice[offset..];
            let common = segment.len().min(remaining.len());
            match segment[..common].cmp(&remaining[..common]) {
                std::cmp::Ordering::Equal => {}
                ord => return ord,
            }

            if segment.len() != common {
                return std::cmp::Ordering::Greater;
            }
            if remaining.len() != common {
                return std::cmp::Ordering::Less;
            }
            offset += common;
        }

        len.cmp(&slice.len())
    }

    fn within_end_bound(&self) -> bool {
        let Some((end_key, inclusive)) = self.end_bound.as_ref() else {
            return true;
        };

        match Self::cmp_segments_to_slice(&self.cur_segments, self.cur_len, end_key) {
            std::cmp::Ordering::Less => true,
            std::cmp::Ordering::Equal => *inclusive,
            std::cmp::Ordering::Greater => false,
        }
    }

    fn lending_view<'view>(&'view self) -> LendingKeyView<'a, 'view> {
        LendingKeyView::new(&self.cur_segments, self.cur_len)
    }

    fn visit_each<F>(&mut self, on_each: &mut F)
    where
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a V),
    {
        loop {
            let next = {
                let (segment_depth, key_len, last_iter) = match self.node_iter_stack.last_mut() {
                    Some(v) => v,
                    None => return,
                };
                let segment_depth = *segment_depth;
                let key_len = *key_len;
                self.cur_segments.truncate(segment_depth);
                self.cur_len = key_len;

                let Some((_key, node)) = last_iter.next() else {
                    self.node_iter_stack.pop();
                    if let Some((parent_segment_depth, parent_key_len, _)) =
                        self.node_iter_stack.last()
                    {
                        self.cur_segments.truncate(*parent_segment_depth);
                        self.cur_len = *parent_key_len;
                    }
                    continue;
                };

                let segment = node.prefix.as_ref();
                if !segment.is_empty() {
                    self.cur_segments.push(segment);
                    self.cur_len += segment.len();
                }

                let is_inner = node.is_inner();
                if is_inner {
                    self.node_iter_stack.push((
                        self.cur_segments.len(),
                        self.cur_len,
                        VersionedIterFrameIter::Plain(node.iter()),
                    ));
                }

                Some((segment, is_inner, node.value()))
            };

            let Some((segment, is_inner, value)) = next else {
                continue;
            };

            if let Some(value) = value {
                if !self.within_end_bound() {
                    self.node_iter_stack.clear();
                    self.cur_segments.clear();
                    self.cur_len = 0;
                    return;
                }
                on_each(self.lending_view(), value);
            }

            if !is_inner && !segment.is_empty() {
                self.cur_segments.pop();
                self.cur_len -= segment.len();
            }
        }
    }

    fn build_positioned_stack<K: KeyTrait<PartialType = P>>(
        node: &'a VersionedNode<P, V>,
        seek_key: &K,
        depth: usize,
    ) -> Vec<(usize, usize, VersionedIterFrameIter<'a, P, V>)> {
        let root_segment_depth = usize::from(!node.prefix.as_ref().is_empty());

        let prefix_common = node.prefix.prefix_length_key(seek_key, depth);
        if prefix_common != node.prefix.len() {
            let seek_remaining = seek_key.length_at(depth);
            if prefix_common >= seek_remaining {
                return vec![(
                    root_segment_depth,
                    node.prefix.len(),
                    VersionedIterFrameIter::Plain(node.iter()),
                )];
            }

            let node_byte = node.prefix.at(prefix_common);
            let seek_byte = seek_key.at(depth + prefix_common);

            if node_byte < seek_byte {
                return vec![];
            }

            return vec![(
                root_segment_depth,
                node.prefix.len(),
                VersionedIterFrameIter::Plain(node.iter()),
            )];
        }

        if seek_key.length_at(depth) == node.prefix.len() {
            return vec![(
                root_segment_depth,
                node.prefix.len(),
                VersionedIterFrameIter::Plain(node.iter()),
            )];
        }

        let target_depth = depth + node.prefix.len();
        let target_byte = seek_key.at(target_depth);
        let mut iter = node.iter();
        while let Some((key, child)) = iter.next() {
            if key < target_byte {
                continue;
            }

            return vec![(
                root_segment_depth,
                node.prefix.len(),
                VersionedIterFrameIter::Leading {
                    first: Some((key, child)),
                    rest: iter,
                },
            )];
        }

        vec![]
    }

    fn for_each<F>(node: Option<&'a VersionedNode<P, V>>, mut on_each: F)
    where
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a V),
    {
        let Some(root_node) = node else {
            return;
        };

        let root_segments = if root_node.prefix.is_empty() {
            Vec::new()
        } else {
            vec![root_node.prefix.as_ref()]
        };
        let root_len = root_node.prefix.len();

        if let Some(value) = root_node.value() {
            on_each(LendingKeyView::new(&root_segments, root_len), value);
        }

        if root_node.is_inner() {
            let mut inner = Self {
                node_iter_stack: vec![(
                    root_segments.len(),
                    root_len,
                    VersionedIterFrameIter::Plain(root_node.iter()),
                )],
                cur_segments: root_segments,
                cur_len: root_len,
                end_bound: None,
            };
            inner.visit_each(&mut on_each);
        }
    }

    fn for_each_with_prefix<F>(
        node: Option<&'a VersionedNode<P, V>>,
        root_segments: Vec<&'a [u8]>,
        root_len: usize,
        mut on_each: F,
    ) where
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a V),
    {
        let Some(root_node) = node else {
            return;
        };

        if let Some(value) = root_node.value() {
            on_each(LendingKeyView::new(&root_segments, root_len), value);
        }

        if root_node.is_inner() {
            let mut inner = Self {
                node_iter_stack: vec![(
                    root_segments.len(),
                    root_len,
                    VersionedIterFrameIter::Plain(root_node.iter()),
                )],
                cur_segments: root_segments,
                cur_len: root_len,
                end_bound: None,
            };
            inner.visit_each(&mut on_each);
        }
    }

    fn for_each_with_bounds<K, F>(
        node: Option<&'a VersionedNode<P, V>>,
        start_bound: Bound<K>,
        end_bound: Bound<K>,
        mut on_each: F,
    ) where
        K: KeyTrait<PartialType = P>,
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a V),
    {
        let Some(root_node) = node else {
            return;
        };

        let end_bound_vec = match end_bound {
            Bound::Included(key) => Some((key.as_ref().to_vec(), true)),
            Bound::Excluded(key) => Some((key.as_ref().to_vec(), false)),
            Bound::Unbounded => None,
        };

        let root_segments = if root_node.prefix.is_empty() {
            Vec::new()
        } else {
            vec![root_node.prefix.as_ref()]
        };
        let root_len = root_node.prefix.len();
        let root_view = LendingKeyView::new(&root_segments, root_len);
        let satisfies_start = match &start_bound {
            Bound::Included(start_key) => {
                root_view.cmp_slice(start_key.as_ref()) >= std::cmp::Ordering::Equal
            }
            Bound::Excluded(start_key) => {
                root_view.cmp_slice(start_key.as_ref()) > std::cmp::Ordering::Equal
            }
            Bound::Unbounded => true,
        };
        let satisfies_end = match end_bound_vec.as_ref() {
            Some((end_key, inclusive)) => match root_view.cmp_slice(end_key) {
                std::cmp::Ordering::Less => true,
                std::cmp::Ordering::Equal => *inclusive,
                std::cmp::Ordering::Greater => false,
            },
            None => true,
        };

        if !satisfies_end {
            return;
        }

        if let Some(value) = root_node.value()
            && satisfies_start
        {
            on_each(root_view, value);
        }

        if !root_node.is_inner() {
            return;
        }

        let seek_key = match &start_bound {
            Bound::Included(key) | Bound::Excluded(key) => Some(key),
            Bound::Unbounded => None,
        };

        let mut inner = if let Some(seek_key) = seek_key {
            Self {
                node_iter_stack: Self::build_positioned_stack(root_node, seek_key, 0),
                cur_segments: root_segments,
                cur_len: root_len,
                end_bound: end_bound_vec,
            }
        } else {
            Self {
                node_iter_stack: vec![(
                    root_segments.len(),
                    root_len,
                    VersionedIterFrameIter::Plain(root_node.iter()),
                )],
                cur_segments: root_segments,
                cur_len: root_len,
                end_bound: end_bound_vec,
            }
        };

        inner.visit_each(&mut on_each);
    }
}

impl<'a, P: Partial + 'a, V> VersionedValuesIter<'a, P, V> {
    fn new(node: Option<&'a VersionedNode<P, V>>) -> Self {
        let Some(root_node) = node else {
            return Self {
                root_value: None,
                node_iter_stack: Vec::new(),
            };
        };

        Self {
            root_value: root_node.value(),
            node_iter_stack: vec![root_node.iter()],
        }
    }
}

impl<'a, P: Partial + 'a, V> Iterator for VersionedValuesIter<'a, P, V> {
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(value) = self.root_value.take() {
            return Some(value);
        }

        loop {
            let last_iter = self.node_iter_stack.last_mut()?;

            let Some((_key, node)) = last_iter.next() else {
                self.node_iter_stack.pop();
                continue;
            };

            if node.is_inner() {
                self.node_iter_stack.push(node.iter());
            }

            if let Some(value) = node.value() {
                return Some(value);
            }
        }
    }
}

impl<'a, K: KeyTrait + 'a, V> Iterator for VersionedRange<'a, K, V> {
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.iter.next()?;
        match &self.end {
            Bound::Included(end_key) => match next.0.cmp(end_key) {
                std::cmp::Ordering::Less | std::cmp::Ordering::Equal => Some(next),
                std::cmp::Ordering::Greater => None,
            },
            Bound::Excluded(end_key) => match next.0.cmp(end_key) {
                std::cmp::Ordering::Less => Some(next),
                std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => None,
            },
            Bound::Unbounded => Some(next),
        }
    }
}

// Internal implementation
impl<KeyType, ValueType> VersionedAdaptiveRadixTree<KeyType, ValueType>
where
    KeyType: KeyTrait,
    ValueType: Clone,
{
    /// Get operation that traverses the tree without modification.
    fn get_iterate<'a>(
        cur_node: &'a VersionedNode<KeyType::PartialType, ValueType>,
        key: &KeyType,
    ) -> Option<&'a ValueType> {
        let mut cur_node = cur_node;
        let mut depth = 0;

        loop {
            let prefix_common_match = cur_node.prefix.prefix_length_key(key, depth);
            if prefix_common_match != cur_node.prefix.len() {
                return None;
            }

            if cur_node.prefix.len() == key.length_at(depth) {
                return cur_node.value();
            }

            let k = key.at(depth + cur_node.prefix.len());
            depth += cur_node.prefix.len();
            cur_node = cur_node.seek_child(k)?.as_ref();
        }
    }

    fn prefix_match_for_each_impl<'a, F>(
        cur_node: &'a VersionedNode<KeyType::PartialType, ValueType>,
        key: &KeyType,
        mut on_match: F,
    ) where
        F: FnMut(&[u8], &'a ValueType),
    {
        let mut cur_node = cur_node;
        let mut depth = 0;
        let key_bytes = key.as_ref();

        loop {
            let prefix_common_match = cur_node.prefix.prefix_length_key(key, depth);
            if prefix_common_match != cur_node.prefix.len() {
                return;
            }

            let matched_len = depth + cur_node.prefix.len();
            if let Some(value) = cur_node.value() {
                on_match(&key_bytes[..matched_len], value);
            }

            if cur_node.prefix.len() == key.length_at(depth) {
                return;
            }

            let k = key.at(depth + cur_node.prefix.len());
            depth += cur_node.prefix.len();

            let Some(child) = cur_node.seek_child(k) else {
                return;
            };
            cur_node = child.as_ref();
        }
    }

    /// Recursively intersect two nodes, supporting different prefix-compression boundaries
    /// through in-prefix offsets.
    fn intersect_nodes<'a, F>(
        left: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut left_offset: usize,
        right: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut right_offset: usize,
        key_buf: &mut Vec<u8>,
        on_match: &mut F,
    ) where
        F: FnMut(KeyType, &'a ValueType, &'a ValueType),
    {
        let restore_len = key_buf.len();
        let left_prefix = left.prefix.as_ref();
        let right_prefix = right.prefix.as_ref();

        while left_offset < left_prefix.len() && right_offset < right_prefix.len() {
            let left_byte = left_prefix[left_offset];
            let right_byte = right_prefix[right_offset];
            if left_byte != right_byte {
                key_buf.truncate(restore_len);
                return;
            }
            key_buf.push(left_byte);
            left_offset += 1;
            right_offset += 1;
        }

        if left_offset < left_prefix.len() {
            if !right.is_inner() {
                key_buf.truncate(restore_len);
                return;
            }

            let edge = left_prefix[left_offset];
            let Some(right_child) = right.seek_child(edge) else {
                key_buf.truncate(restore_len);
                return;
            };

            key_buf.push(edge);
            Self::intersect_nodes(
                left,
                left_offset + 1,
                right_child.as_ref(),
                1,
                key_buf,
                on_match,
            );
            key_buf.truncate(restore_len);
            return;
        }

        if right_offset < right_prefix.len() {
            if !left.is_inner() {
                key_buf.truncate(restore_len);
                return;
            }

            let edge = right_prefix[right_offset];
            let Some(left_child) = left.seek_child(edge) else {
                key_buf.truncate(restore_len);
                return;
            };

            key_buf.push(edge);
            Self::intersect_nodes(
                left_child.as_ref(),
                1,
                right,
                right_offset + 1,
                key_buf,
                on_match,
            );
            key_buf.truncate(restore_len);
            return;
        }

        if let (Some(left_value), Some(right_value)) = (left.value(), right.value()) {
            on_match(
                KeyType::new_from_slice(key_buf.as_slice()),
                left_value,
                right_value,
            );
        }

        if left.is_inner() && right.is_inner() {
            if left.num_children() <= right.num_children() {
                for (edge, left_child) in left.iter() {
                    if let Some(right_child) = right.seek_child(edge) {
                        Self::intersect_nodes(
                            left_child,
                            0,
                            right_child.as_ref(),
                            0,
                            key_buf,
                            on_match,
                        );
                    }
                }
            } else {
                for (edge, right_child) in right.iter() {
                    if let Some(left_child) = left.seek_child(edge) {
                        Self::intersect_nodes(
                            left_child.as_ref(),
                            0,
                            right_child,
                            0,
                            key_buf,
                            on_match,
                        );
                    }
                }
            }
        }

        key_buf.truncate(restore_len);
    }

    fn intersect_nodes_lending<'a, F>(
        left: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut left_offset: usize,
        right: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut right_offset: usize,
        key_segments: &mut Vec<&'a [u8]>,
        key_len: &mut usize,
        on_match: &mut F,
    ) where
        F: for<'view> FnMut(LendingKeyView<'a, 'view>, &'a ValueType, &'a ValueType),
    {
        let restore_segments = key_segments.len();
        let restore_len = *key_len;
        let left_prefix = left.prefix.as_ref();
        let right_prefix = right.prefix.as_ref();
        let matched_left_start = left_offset;

        while left_offset < left_prefix.len() && right_offset < right_prefix.len() {
            if left_prefix[left_offset] != right_prefix[right_offset] {
                key_segments.truncate(restore_segments);
                *key_len = restore_len;
                return;
            }
            left_offset += 1;
            right_offset += 1;
        }

        if left_offset > matched_left_start {
            let matched = &left_prefix[matched_left_start..left_offset];
            key_segments.push(matched);
            *key_len += matched.len();
        }

        if left_offset < left_prefix.len() {
            if !right.is_inner() {
                key_segments.truncate(restore_segments);
                *key_len = restore_len;
                return;
            }

            let edge = left_prefix[left_offset];
            let Some(right_child) = right.seek_child(edge) else {
                key_segments.truncate(restore_segments);
                *key_len = restore_len;
                return;
            };

            let edge_segment = &left_prefix[left_offset..left_offset + 1];
            key_segments.push(edge_segment);
            *key_len += 1;
            Self::intersect_nodes_lending(
                left,
                left_offset + 1,
                right_child.as_ref(),
                1,
                key_segments,
                key_len,
                on_match,
            );
            key_segments.truncate(restore_segments);
            *key_len = restore_len;
            return;
        }

        if right_offset < right_prefix.len() {
            if !left.is_inner() {
                key_segments.truncate(restore_segments);
                *key_len = restore_len;
                return;
            }

            let edge = right_prefix[right_offset];
            let Some(left_child) = left.seek_child(edge) else {
                key_segments.truncate(restore_segments);
                *key_len = restore_len;
                return;
            };

            let edge_segment = &right_prefix[right_offset..right_offset + 1];
            key_segments.push(edge_segment);
            *key_len += 1;
            Self::intersect_nodes_lending(
                left_child.as_ref(),
                1,
                right,
                right_offset + 1,
                key_segments,
                key_len,
                on_match,
            );
            key_segments.truncate(restore_segments);
            *key_len = restore_len;
            return;
        }

        if let (Some(left_value), Some(right_value)) = (left.value(), right.value()) {
            on_match(
                LendingKeyView::new(key_segments, *key_len),
                left_value,
                right_value,
            );
        }

        if left.is_inner() && right.is_inner() {
            if left.num_children() <= right.num_children() {
                for (edge, left_child) in left.iter() {
                    if let Some(right_child) = right.seek_child(edge) {
                        Self::intersect_nodes_lending(
                            left_child,
                            0,
                            right_child.as_ref(),
                            0,
                            key_segments,
                            key_len,
                            on_match,
                        );
                    }
                }
            } else {
                for (edge, right_child) in right.iter() {
                    if let Some(left_child) = left.seek_child(edge) {
                        Self::intersect_nodes_lending(
                            left_child.as_ref(),
                            0,
                            right_child,
                            0,
                            key_segments,
                            key_len,
                            on_match,
                        );
                    }
                }
            }
        }

        key_segments.truncate(restore_segments);
        *key_len = restore_len;
    }

    /// Recursively intersect two nodes and emit only value pairs (no key reconstruction).
    fn intersect_nodes_values<'a, F>(
        left: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut left_offset: usize,
        right: &'a VersionedNode<KeyType::PartialType, ValueType>,
        mut right_offset: usize,
        on_match: &mut F,
    ) where
        F: FnMut(&'a ValueType, &'a ValueType),
    {
        let left_prefix = left.prefix.as_ref();
        let right_prefix = right.prefix.as_ref();

        while left_offset < left_prefix.len() && right_offset < right_prefix.len() {
            if left_prefix[left_offset] != right_prefix[right_offset] {
                return;
            }
            left_offset += 1;
            right_offset += 1;
        }

        if left_offset < left_prefix.len() {
            if !right.is_inner() {
                return;
            }
            let edge = left_prefix[left_offset];
            let Some(right_child) = right.seek_child(edge) else {
                return;
            };
            Self::intersect_nodes_values(left, left_offset + 1, right_child.as_ref(), 1, on_match);
            return;
        }

        if right_offset < right_prefix.len() {
            if !left.is_inner() {
                return;
            }
            let edge = right_prefix[right_offset];
            let Some(left_child) = left.seek_child(edge) else {
                return;
            };
            Self::intersect_nodes_values(left_child.as_ref(), 1, right, right_offset + 1, on_match);
            return;
        }

        if let (Some(left_value), Some(right_value)) = (left.value(), right.value()) {
            on_match(left_value, right_value);
        }

        if left.is_inner() && right.is_inner() {
            if left.num_children() <= right.num_children() {
                for (edge, left_child) in left.iter() {
                    if let Some(right_child) = right.seek_child(edge) {
                        Self::intersect_nodes_values(
                            left_child,
                            0,
                            right_child.as_ref(),
                            0,
                            on_match,
                        );
                    }
                }
            } else {
                for (edge, right_child) in right.iter() {
                    if let Some(left_child) = left.seek_child(edge) {
                        Self::intersect_nodes_values(
                            left_child.as_ref(),
                            0,
                            right_child,
                            0,
                            on_match,
                        );
                    }
                }
            }
        }
    }

    fn find_prefix_subtree<'a>(
        cur_node: &'a VersionedNode<KeyType::PartialType, ValueType>,
        prefix: &KeyType,
    ) -> Option<(&'a VersionedNode<KeyType::PartialType, ValueType>, KeyType)> {
        let mut cur_node = cur_node;
        let mut cur_key = cur_node.prefix.as_ref().to_vec();
        let mut depth = 0;

        loop {
            let prefix_common_match = cur_node.prefix.prefix_length_key(prefix, depth);
            if prefix_common_match != cur_node.prefix.len() {
                if prefix_common_match == prefix.length_at(depth) {
                    return Some((cur_node, KeyType::new_from_slice(&cur_key)));
                }
                return None;
            }

            if cur_node.prefix.len() == prefix.length_at(depth) {
                return Some((cur_node, KeyType::new_from_slice(&cur_key)));
            }

            let key = prefix.at(depth + cur_node.prefix.len());
            depth += cur_node.prefix.len();

            cur_node = cur_node.seek_child(key)?.as_ref();
            cur_key.extend_from_slice(cur_node.prefix.as_ref());
        }
    }

    fn find_prefix_subtree_view<'a>(
        cur_node: &'a VersionedNode<KeyType::PartialType, ValueType>,
        prefix: &KeyType,
    ) -> Option<VersionedPrefixSubtreeView<'a, KeyType::PartialType, ValueType>> {
        let mut cur_node = cur_node;
        let mut cur_segments = if cur_node.prefix.is_empty() {
            Vec::new()
        } else {
            vec![cur_node.prefix.as_ref()]
        };
        let mut cur_len = cur_node.prefix.len();
        let mut depth = 0;

        loop {
            let prefix_common_match = cur_node.prefix.prefix_length_key(prefix, depth);
            if prefix_common_match != cur_node.prefix.len() {
                if prefix_common_match == prefix.length_at(depth) {
                    return Some((cur_node, cur_segments, cur_len));
                }
                return None;
            }

            if cur_node.prefix.len() == prefix.length_at(depth) {
                return Some((cur_node, cur_segments, cur_len));
            }

            let key = prefix.at(depth + cur_node.prefix.len());
            depth += cur_node.prefix.len();

            cur_node = cur_node.seek_child(key)?.as_ref();
            let segment = cur_node.prefix.as_ref();
            if !segment.is_empty() {
                cur_segments.push(segment);
                cur_len += segment.len();
            }
        }
    }

    /// Copy-on-write helper: returns the node if it's already the right version,
    /// or creates a new copy if it needs to be modified.
    fn ensure_cow_node(
        node: Arc<VersionedNode<KeyType::PartialType, ValueType>>,
        target_version: u64,
    ) -> Arc<VersionedNode<KeyType::PartialType, ValueType>> {
        if node.version == target_version {
            // Already at target version, no work needed
            node
        } else {
            // Check if we have exclusive ownership
            match Arc::try_unwrap(node) {
                Ok(mut owned_node) => {
                    // We have exclusive ownership - just update version in place
                    owned_node.version = target_version;
                    Arc::new(owned_node)
                }
                Err(shared_node) => {
                    // Node is shared - need actual CoW
                    Arc::new(shared_node.cow_clone_inner(target_version))
                }
            }
        }
    }

    /// Insert with copy-on-write semantics.
    /// Returns (new_root, was_replaced).
    /// If old_value_out is Some, captures the replaced value (cloning if necessary).
    fn insert_recurse(
        cur_node: Arc<VersionedNode<KeyType::PartialType, ValueType>>,
        key: &KeyType,
        value: ValueType,
        depth: usize,
        version: u64,
        old_value_out: Option<&mut Option<ValueType>>,
    ) -> (Arc<VersionedNode<KeyType::PartialType, ValueType>>, bool) {
        let longest_common_prefix = cur_node.prefix.prefix_length_key(key, depth);
        let is_prefix_match =
            min(cur_node.prefix.len(), key.length_at(depth)) == longest_common_prefix;

        if is_prefix_match && cur_node.prefix.len() == key.length_at(depth) {
            let new_node = Self::ensure_cow_node(cur_node, version);
            let mut new_node = match Arc::try_unwrap(new_node) {
                Ok(owned) => owned,
                Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
            };
            let old_value = new_node.value.replace(value);
            let was_replaced = old_value.is_some();
            if let (Some(old_value_out), Some(old_value)) = (old_value_out, old_value) {
                *old_value_out = Some(old_value);
            }
            return (Arc::new(new_node), was_replaced);
        }

        if is_prefix_match && cur_node.prefix.len() > key.length_at(depth) {
            let mut existing_node = cur_node.cow_clone_inner(version);
            let old_prefix = existing_node.prefix.clone();
            existing_node.prefix = old_prefix.partial_after(longest_common_prefix);

            let mut new_parent =
                VersionedNode::new_inner(old_prefix.partial_before(longest_common_prefix), version);
            new_parent.value = Some(value);
            let edge = old_prefix.at(longest_common_prefix);
            new_parent.add_child(edge, Arc::new(existing_node));
            return (Arc::new(new_parent), false);
        }

        if !is_prefix_match {
            let mut new_inner = VersionedNode::new_inner(
                cur_node.prefix.partial_before(longest_common_prefix),
                version,
            );

            let k1 = cur_node.prefix.at(longest_common_prefix);
            let k2 = key.at(depth + longest_common_prefix);

            // Create the existing node with truncated prefix
            let mut existing_node_clone = cur_node.cow_clone_inner(version);
            existing_node_clone.prefix = cur_node.prefix.partial_after(longest_common_prefix);
            let existing_arc = Arc::new(existing_node_clone);

            // Create new leaf
            let new_leaf = Arc::new(VersionedNode::new_leaf(
                key.to_partial(depth + longest_common_prefix),
                value,
                version,
            ));

            // Add children to the new inner node
            match &mut new_inner.content {
                VersionedContent::Node4(km) => {
                    km.add_child(k1, existing_arc);
                    km.add_child(k2, new_leaf);
                }
                _ => unreachable!(),
            }

            return (Arc::new(new_inner), false);
        }

        if cur_node.is_leaf() {
            let edge = key.at(depth + longest_common_prefix);
            let new_leaf = Arc::new(VersionedNode::new_leaf(
                key.to_partial(depth + longest_common_prefix),
                value,
                version,
            ));
            let new_node = Self::ensure_cow_node(cur_node, version);
            let mut new_node = match Arc::try_unwrap(new_node) {
                Ok(owned) => owned,
                Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
            };
            new_node.add_child(edge, new_leaf);
            return (Arc::new(new_node), false);
        }

        // Case 3: Need to recurse deeper
        let k = key.at(depth + cur_node.prefix.len());
        let prefix_len = cur_node.prefix.len();
        let new_node = Self::ensure_cow_node(cur_node, version);

        let mut new_node_mut = match Arc::try_unwrap(new_node) {
            Ok(owned) => owned,
            Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
        };

        if let Some(child) = new_node_mut.delete_child(k) {
            // Recurse into existing child
            let (new_child, was_replaced) = Self::insert_recurse(
                child,
                key,
                value,
                depth + prefix_len,
                version,
                old_value_out,
            );

            new_node_mut.add_child(k, new_child);

            (Arc::new(new_node_mut), was_replaced)
        } else {
            // Add new child - check if node needs to grow first
            let new_leaf = Arc::new(VersionedNode::new_leaf(
                key.to_partial(depth + prefix_len),
                value,
                version,
            ));

            new_node_mut.add_child(k, new_leaf);

            (Arc::new(new_node_mut), false)
        }
    }

    /// Remove with copy-on-write semantics.
    /// Returns (new_root_option, removed_value).
    fn remove_recurse(
        cur_node: Arc<VersionedNode<KeyType::PartialType, ValueType>>,
        key: &KeyType,
        depth: usize,
        version: u64,
    ) -> Option<RemoveResult<KeyType::PartialType, ValueType>> {
        // Check prefix match
        let prefix_common_match = cur_node.prefix.prefix_length_key(key, depth);
        if prefix_common_match != cur_node.prefix.len() {
            return None;
        }

        if cur_node.prefix.len() == key.length_at(depth) {
            if cur_node.is_leaf() {
                let removed_value = cur_node.value()?.clone();
                return Some((None, removed_value));
            }

            let new_node = Self::ensure_cow_node(cur_node, version);
            let mut new_node = match Arc::try_unwrap(new_node) {
                Ok(owned) => owned,
                Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
            };
            let removed_value = new_node.value.take()?;
            if new_node.num_children() == 0 && new_node.value.is_none() {
                return Some((None, removed_value));
            }
            return Some((Some(Arc::new(new_node)), removed_value));
        }

        if cur_node.is_leaf() {
            return None;
        }

        // This is an inner node, recurse to find child
        let k = key.at(depth + cur_node.prefix.len());
        let prefix_len = cur_node.prefix.len();

        let new_node = Self::ensure_cow_node(cur_node, version);

        let mut new_node_mut = match Arc::try_unwrap(new_node) {
            Ok(owned) => owned,
            Err(_) => panic!("ensure_cow_node should have given us exclusive ownership"),
        };

        let child = new_node_mut.delete_child(k)?;
        let (new_child_opt, removed_value) =
            Self::remove_recurse(child, key, depth + prefix_len, version)
                .expect("prechecked key should be removable");

        if let Some(new_child) = new_child_opt {
            new_node_mut.add_child(k, new_child);
        }

        if new_node_mut.num_children() == 0 && new_node_mut.value.is_none() {
            return Some((None, removed_value));
        }

        Some((Some(Arc::new(new_node_mut)), removed_value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::{array_key::ArrayKey, overflow_key::OverflowKey};
    use proptest::prelude::*;
    use std::mem::size_of;

    type DenseSequentialKey = OverflowKey<8, 4>;

    fn dense_sequential_key(i: u32) -> DenseSequentialKey {
        let mut bytes = [0; 5];
        bytes[0] = 8;
        bytes[1..].copy_from_slice(&i.to_be_bytes());
        <DenseSequentialKey as crate::keys::KeyTrait>::new_from_slice(&bytes)
    }

    #[test]
    fn boxed_versioned_content_keeps_node_header_small() {
        type P = <ArrayKey<16> as crate::keys::KeyTrait>::PartialType;
        let content_size = size_of::<VersionedContent<P, u64>>();
        let node_size = size_of::<VersionedNode<P, u64>>();

        println!("VersionedContent<P, u64> = {content_size} bytes");
        println!("VersionedNode<P, u64> = {node_size} bytes");
        assert!(content_size <= 2 * size_of::<usize>());
        assert!(node_size <= 80);
    }

    #[derive(Clone, Debug)]
    enum VersionedOp {
        Get {
            key: u8,
        },
        Insert {
            key: u8,
            value: u16,
        },
        Remove {
            key: u8,
        },
        Snapshot,
        SnapshotInsert {
            snapshot_idx: u8,
            key: u8,
            value: u16,
        },
        SnapshotRemove {
            snapshot_idx: u8,
            key: u8,
        },
    }

    #[derive(Clone, Debug)]
    enum DenseVersionedOp {
        Insert {
            key_idx: u16,
            value: u16,
        },
        Remove {
            key_idx: u16,
        },
        Snapshot,
        SnapshotInsert {
            snapshot_idx: u8,
            key_idx: u16,
            value: u16,
        },
        SnapshotRemove {
            snapshot_idx: u8,
            key_idx: u16,
        },
    }

    fn versioned_op_strategy() -> impl Strategy<Value = VersionedOp> {
        prop_oneof![
            any::<u8>().prop_map(|key| VersionedOp::Get { key }),
            (any::<u8>(), any::<u16>()).prop_map(|(key, value)| VersionedOp::Insert { key, value }),
            any::<u8>().prop_map(|key| VersionedOp::Remove { key }),
            Just(VersionedOp::Snapshot),
            (any::<u8>(), any::<u8>(), any::<u16>()).prop_map(|(snapshot_idx, key, value)| {
                VersionedOp::SnapshotInsert {
                    snapshot_idx,
                    key,
                    value,
                }
            }),
            (any::<u8>(), any::<u8>())
                .prop_map(|(snapshot_idx, key)| VersionedOp::SnapshotRemove { snapshot_idx, key }),
        ]
    }

    fn dense_versioned_op_strategy() -> impl Strategy<Value = DenseVersionedOp> {
        prop_oneof![
            (0u16..512, any::<u16>())
                .prop_map(|(key_idx, value)| { DenseVersionedOp::Insert { key_idx, value } }),
            (0u16..512).prop_map(|key_idx| DenseVersionedOp::Remove { key_idx }),
            Just(DenseVersionedOp::Snapshot),
            (any::<u8>(), 0u16..512, any::<u16>()).prop_map(|(snapshot_idx, key_idx, value)| {
                DenseVersionedOp::SnapshotInsert {
                    snapshot_idx,
                    key_idx,
                    value,
                }
            },),
            (any::<u8>(), 0u16..512).prop_map(|(snapshot_idx, key_idx)| {
                DenseVersionedOp::SnapshotRemove {
                    snapshot_idx,
                    key_idx,
                }
            }),
        ]
    }

    fn assert_versioned_tree_matches_map(
        tree: &VersionedAdaptiveRadixTree<ArrayKey<16>, u16>,
        map: &std::collections::BTreeMap<u8, u16>,
    ) {
        for key in 0u8..=u8::MAX {
            assert_eq!(
                tree.get(key).copied(),
                map.get(&key).copied(),
                "mismatch at key {key}"
            );
        }
    }

    fn assert_dense_tree_matches_map(
        tree: &VersionedAdaptiveRadixTree<DenseSequentialKey, u16>,
        map: &std::collections::BTreeMap<u16, u16>,
        key_limit: u16,
    ) {
        for key_idx in 0..key_limit {
            let key = dense_sequential_key(key_idx as u32);
            assert_eq!(
                tree.get_k(&key).copied(),
                map.get(&key_idx).copied(),
                "mismatch at dense sequential key index {key_idx}"
            );
        }
    }

    proptest! {
        #[test]
        fn prop_snapshot_operations_match_reference_model(
            ops in proptest::collection::vec(versioned_op_strategy(), 0..96)
        ) {
            let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, u16>::new();
            let mut map = std::collections::BTreeMap::<u8, u16>::new();
            let mut snapshots = Vec::new();
            let mut snapshot_maps = Vec::new();

            for op in ops {
                match op {
                    VersionedOp::Get { key } => {
                        prop_assert_eq!(tree.get(key).copied(), map.get(&key).copied());
                    }
                    VersionedOp::Insert { key, value } => {
                        let expected_replaced = map.insert(key, value).is_some();
                        let actual_replaced = tree.insert(key, value);
                        prop_assert_eq!(actual_replaced, expected_replaced);
                        prop_assert_eq!(tree.get(key).copied(), map.get(&key).copied());
                    }
                    VersionedOp::Remove { key } => {
                        let expected_removed = map.remove(&key);
                        let actual_removed = tree.remove(key);
                        prop_assert_eq!(actual_removed, expected_removed);
                        prop_assert_eq!(tree.get(key).copied(), map.get(&key).copied());
                    }
                    VersionedOp::Snapshot => {
                        snapshots.push(tree.snapshot());
                        snapshot_maps.push(map.clone());
                    }
                    VersionedOp::SnapshotInsert {
                        snapshot_idx,
                        key,
                        value,
                    } => {
                        if !snapshots.is_empty() {
                            let idx = snapshot_idx as usize % snapshots.len();
                            let expected_replaced = snapshot_maps[idx].insert(key, value).is_some();
                            let actual_replaced = snapshots[idx].insert(key, value);
                            prop_assert_eq!(actual_replaced, expected_replaced);
                            prop_assert_eq!(
                                snapshots[idx].get(key).copied(),
                                snapshot_maps[idx].get(&key).copied()
                            );
                            prop_assert_eq!(tree.get(key).copied(), map.get(&key).copied());
                        }
                    }
                    VersionedOp::SnapshotRemove { snapshot_idx, key } => {
                        if !snapshots.is_empty() {
                            let idx = snapshot_idx as usize % snapshots.len();
                            let expected_removed = snapshot_maps[idx].remove(&key);
                            let actual_removed = snapshots[idx].remove(key);
                            prop_assert_eq!(actual_removed, expected_removed);
                            prop_assert_eq!(
                                snapshots[idx].get(key).copied(),
                                snapshot_maps[idx].get(&key).copied()
                            );
                            prop_assert_eq!(tree.get(key).copied(), map.get(&key).copied());
                        }
                    }
                }
            }

            assert_versioned_tree_matches_map(&tree, &map);
            for (snapshot, snapshot_map) in snapshots.iter().zip(snapshot_maps.iter()) {
                assert_versioned_tree_matches_map(snapshot, snapshot_map);
            }
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(64))]
        #[test]
        fn prop_dense_sequential_snapshots_remain_isolated(
            ops in proptest::collection::vec(dense_versioned_op_strategy(), 0..96)
        ) {
            let mut tree = VersionedAdaptiveRadixTree::<DenseSequentialKey, u16>::new();
            let mut map = std::collections::BTreeMap::<u16, u16>::new();
            let mut snapshots = Vec::new();
            let mut snapshot_maps = Vec::new();

            for key_idx in 0u16..256 {
                let key = dense_sequential_key(key_idx as u32);
                prop_assert!(!tree.insert_k(&key, key_idx));
                map.insert(key_idx, key_idx);
            }

            for op in ops {
                match op {
                    DenseVersionedOp::Insert { key_idx, value } => {
                        let key = dense_sequential_key(key_idx as u32);
                        let expected_replaced = map.insert(key_idx, value).is_some();
                        let actual_replaced = tree.insert_k(&key, value);
                        prop_assert_eq!(actual_replaced, expected_replaced);
                        prop_assert_eq!(tree.get_k(&key).copied(), map.get(&key_idx).copied());
                    }
                    DenseVersionedOp::Remove { key_idx } => {
                        let key = dense_sequential_key(key_idx as u32);
                        let expected_removed = map.remove(&key_idx);
                        let actual_removed = tree.remove_k(&key);
                        prop_assert_eq!(actual_removed, expected_removed);
                        prop_assert_eq!(tree.get_k(&key).copied(), map.get(&key_idx).copied());
                    }
                    DenseVersionedOp::Snapshot => {
                        snapshots.push(tree.snapshot());
                        snapshot_maps.push(map.clone());
                    }
                    DenseVersionedOp::SnapshotInsert {
                        snapshot_idx,
                        key_idx,
                        value,
                    } => {
                        if !snapshots.is_empty() {
                            let idx = snapshot_idx as usize % snapshots.len();
                            let key = dense_sequential_key(key_idx as u32);
                            let expected_replaced =
                                snapshot_maps[idx].insert(key_idx, value).is_some();
                            let actual_replaced = snapshots[idx].insert_k(&key, value);
                            prop_assert_eq!(actual_replaced, expected_replaced);
                            prop_assert_eq!(
                                snapshots[idx].get_k(&key).copied(),
                                snapshot_maps[idx].get(&key_idx).copied()
                            );
                            prop_assert_eq!(tree.get_k(&key).copied(), map.get(&key_idx).copied());
                        }
                    }
                    DenseVersionedOp::SnapshotRemove {
                        snapshot_idx,
                        key_idx,
                    } => {
                        if !snapshots.is_empty() {
                            let idx = snapshot_idx as usize % snapshots.len();
                            let key = dense_sequential_key(key_idx as u32);
                            let expected_removed = snapshot_maps[idx].remove(&key_idx);
                            let actual_removed = snapshots[idx].remove_k(&key);
                            prop_assert_eq!(actual_removed, expected_removed);
                            prop_assert_eq!(
                                snapshots[idx].get_k(&key).copied(),
                                snapshot_maps[idx].get(&key_idx).copied()
                            );
                            prop_assert_eq!(tree.get_k(&key).copied(), map.get(&key_idx).copied());
                        }
                    }
                }
            }

            assert_dense_tree_matches_map(&tree, &map, 512);
            for (snapshot, snapshot_map) in snapshots.iter().zip(snapshot_maps.iter()) {
                assert_dense_tree_matches_map(snapshot, snapshot_map, 512);
            }
        }
    }

    #[test]
    fn test_basic_snapshot() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert into original
        tree.insert("key1", 1);
        assert_eq!(tree.get("key1"), Some(&1));

        // Take snapshot
        let snapshot = tree.snapshot();
        assert_eq!(snapshot.get("key1"), Some(&1));
        assert_eq!(snapshot.version(), tree.version() + 1);
    }

    #[test]
    fn test_independent_mutations() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        tree.insert("key1", 1);

        let mut snapshot = tree.snapshot();

        // Mutations should be independent
        tree.insert("key2", 2);
        snapshot.insert("key3", 3);

        // Original tree should have key2 but not key3
        assert_eq!(tree.get("key2"), Some(&2));
        assert_eq!(tree.get("key3"), None);

        // Snapshot should have key3 but not key2
        assert_eq!(snapshot.get("key2"), None);
        assert_eq!(snapshot.get("key3"), Some(&3));

        // Both should still have key1
        assert_eq!(tree.get("key1"), Some(&1));
        assert_eq!(snapshot.get("key1"), Some(&1));
    }

    #[test]
    fn test_node_growth() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert enough keys to trigger Node4 → Node16 growth
        for i in 0..10 {
            let key = format!("key{i:02}");
            tree.insert(key, i);
        }

        // Verify all keys are still accessible after growth
        for i in 0..10 {
            let key = format!("key{i:02}");
            assert_eq!(tree.get(&key), Some(&i));
        }

        // Take a snapshot after growth
        let snapshot = tree.snapshot();

        // Add more keys to original tree to trigger further growth
        for i in 10..20 {
            let key = format!("key{i:02}");
            tree.insert(key, i);
        }

        // Snapshot should not have new keys
        for i in 10..20 {
            let key = format!("key{i:02}");
            assert_eq!(snapshot.get(&key), None);
            assert_eq!(tree.get(&key), Some(&i));
        }

        // But snapshot should still have original keys
        for i in 0..10 {
            let key = format!("key{i:02}");
            assert_eq!(snapshot.get(&key), Some(&i));
        }
    }

    #[test]
    fn test_structural_sharing() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Build a substantial tree structure
        for i in 0..20 {
            let key = format!("shared_key_{i:02}");
            tree.insert(key, i);
        }

        // Take multiple snapshots - they should share the same root
        let snapshot1 = tree.snapshot();
        let snapshot2 = tree.snapshot();
        let snapshot3 = tree.snapshot();

        // Verify that shared nodes have high reference counts
        // The root should be referenced by: tree + snapshot1 + snapshot2 + snapshot3 = 4 references
        if let Some(root) = &tree.root {
            let strong_count = Arc::strong_count(root);
            assert_eq!(
                strong_count, 4,
                "Root should be shared between original and 3 snapshots"
            );
        }

        // Now modify only the original tree - this should trigger CoW
        tree.insert("new_key", 999);

        // After modification, snapshots should still share the old root
        if let (Some(s1_root), Some(s2_root), Some(s3_root)) =
            (&snapshot1.root, &snapshot2.root, &snapshot3.root)
        {
            // All three snapshots should point to the same root node
            assert!(
                Arc::ptr_eq(s1_root, s2_root),
                "Snapshot1 and Snapshot2 should share root"
            );
            assert!(
                Arc::ptr_eq(s2_root, s3_root),
                "Snapshot2 and Snapshot3 should share root"
            );

            // The shared root should have exactly 3 references (from the 3 snapshots)
            let shared_count = Arc::strong_count(s1_root);
            assert_eq!(
                shared_count, 3,
                "Shared root should have 3 references after original tree CoW"
            );
        }

        // Verify that the original tree has its own root now
        if let Some(orig_root) = &tree.root {
            let orig_count = Arc::strong_count(orig_root);
            assert_eq!(
                orig_count, 1,
                "Original tree should have exclusive ownership of new root"
            );
        }

        // All snapshots should NOT see the new key
        assert_eq!(snapshot1.get("new_key"), None);
        assert_eq!(snapshot2.get("new_key"), None);
        assert_eq!(snapshot3.get("new_key"), None);

        // But original tree should see it
        assert_eq!(tree.get("new_key"), Some(&999));

        // All trees should still see the shared data
        for i in 0..20 {
            let key = format!("shared_key_{i:02}");
            assert_eq!(tree.get(&key), Some(&i));
            assert_eq!(snapshot1.get(&key), Some(&i));
            assert_eq!(snapshot2.get(&key), Some(&i));
            assert_eq!(snapshot3.get(&key), Some(&i));
        }
    }

    #[test]
    fn test_snapshot_cleanup() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Create a tree with some data
        for i in 0..10i32 {
            tree.insert(i, i * 10);
        }

        let initial_root_refs = if let Some(root) = &tree.root {
            Arc::strong_count(root)
        } else {
            panic!("Tree should have a root");
        };

        // Take several snapshots
        let snapshot1 = tree.snapshot();
        let snapshot2 = tree.snapshot();
        {
            let _snapshot3 = tree.snapshot(); // This one will be dropped immediately
        } // _snapshot3 is dropped here

        // Root should now have more references
        let with_snapshots_refs = if let Some(root) = &tree.root {
            Arc::strong_count(root)
        } else {
            panic!("Tree should have a root");
        };

        assert!(
            with_snapshots_refs > initial_root_refs,
            "Root should have more references with snapshots"
        );

        // Drop snapshot2 explicitly
        drop(snapshot2);

        // Root should have fewer references now
        let after_drops_refs = if let Some(root) = &tree.root {
            Arc::strong_count(root)
        } else {
            panic!("Tree should have a root");
        };

        assert!(
            after_drops_refs < with_snapshots_refs,
            "Root should have fewer references after dropping snapshots"
        );

        // Should be exactly: original tree + snapshot1 = 2 references
        assert_eq!(
            after_drops_refs, 2,
            "Should have exactly 2 references: tree + snapshot1"
        );

        // Verify remaining snapshot still works - check that some keys exist
        assert!(snapshot1.get(0).is_some());
        assert!(snapshot1.get(5).is_some());
        assert!(snapshot1.get(9).is_some());

        // Drop the last snapshot
        drop(snapshot1);

        // Now tree should have exclusive ownership
        let final_refs = if let Some(root) = &tree.root {
            Arc::strong_count(root)
        } else {
            panic!("Tree should have a root");
        };

        assert_eq!(
            final_refs, 1,
            "Tree should have exclusive ownership after all snapshots dropped"
        );

        // Tree should still work normally
        for i in 0..10i32 {
            assert_eq!(tree.get(i), Some(&(i * 10)));
        }
    }

    #[test]
    fn test_signed_integer_keys() {
        // Test that signed integer keys work correctly (regression test)
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert some positive and negative integers
        tree.insert(-5i32, -50);
        tree.insert(0i32, 0);
        tree.insert(1i32, 10);
        tree.insert(8i32, 80);
        tree.insert(-1i32, -10);

        // Take a snapshot
        let snapshot = tree.snapshot();

        // Verify all keys work correctly in both tree and snapshot
        assert_eq!(tree.get(-5i32), Some(&-50));
        assert_eq!(tree.get(-1i32), Some(&-10));
        assert_eq!(tree.get(0i32), Some(&0));
        assert_eq!(tree.get(1i32), Some(&10));
        assert_eq!(tree.get(8i32), Some(&80));

        assert_eq!(snapshot.get(-5i32), Some(&-50));
        assert_eq!(snapshot.get(-1i32), Some(&-10));
        assert_eq!(snapshot.get(0i32), Some(&0));
        assert_eq!(snapshot.get(1i32), Some(&10));
        assert_eq!(snapshot.get(8i32), Some(&80));

        // Test that non-existent keys return None
        assert_eq!(tree.get(99i32), None);
        assert_eq!(snapshot.get(99i32), None);
    }

    #[test]
    fn test_deep_structural_sharing() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<32>, i32>::new();

        // Create a deeper tree structure with common prefixes
        let prefixes = [
            "user",
            "user_profile",
            "user_settings",
            "system",
            "system_config",
        ];
        for (i, prefix) in prefixes.iter().enumerate() {
            for j in 0..5 {
                let key = format!("{prefix}_{j:02}");
                tree.insert(key, (i * 100 + j) as i32);
            }
        }

        // Take a snapshot
        let snapshot = tree.snapshot();

        // Modify only one branch - should trigger minimal CoW
        tree.insert("user_00", 999); // This should replace existing value

        // The modification should only affect nodes along the path to "user_00"
        // Most of the tree structure should still be shared

        // Verify the change
        assert_eq!(tree.get("user_00"), Some(&999));
        assert_eq!(snapshot.get("user_00"), Some(&0)); // Original value

        // All other keys should be the same in both
        for (i, prefix) in prefixes.iter().enumerate() {
            for j in 0..5 {
                let key = format!("{prefix}_{j:02}");
                if key != "user_00" {
                    let expected_value = (i * 100 + j) as i32;
                    assert_eq!(tree.get(&key), Some(&expected_value));
                    assert_eq!(snapshot.get(&key), Some(&expected_value));
                }
            }
        }

        // Add a completely new branch - should create new nodes but still share unchanged parts
        tree.insert("new_branch_00", 777);

        assert_eq!(tree.get("new_branch_00"), Some(&777));
        assert_eq!(snapshot.get("new_branch_00"), None);

        // All original keys should still work in both trees
        for (i, prefix) in prefixes.iter().enumerate() {
            for j in 0..5 {
                let key = format!("{prefix}_{j:02}");
                let expected_in_tree = if key == "user_00" {
                    999
                } else {
                    (i * 100 + j) as i32
                };
                let expected_in_snapshot = (i * 100 + j) as i32;

                assert_eq!(tree.get(&key), Some(&expected_in_tree));
                assert_eq!(snapshot.get(&key), Some(&expected_in_snapshot));
            }
        }
    }

    #[test]
    fn test_into_unversioned_fast_path() {
        // Test fast path: no snapshots, should have unique ownership
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert test data
        vtree.insert("key1", 10);
        vtree.insert("key2", 20);
        vtree.insert("key3", 30);
        vtree.insert("apple", 100);
        vtree.insert("application", 200);

        // Convert to unversioned tree (fast path - unique ownership)
        let tree = vtree.into_unversioned();

        // Verify all data is preserved
        assert_eq!(tree.get("key1"), Some(&10));
        assert_eq!(tree.get("key2"), Some(&20));
        assert_eq!(tree.get("key3"), Some(&30));
        assert_eq!(tree.get("apple"), Some(&100));
        assert_eq!(tree.get("application"), Some(&200));
        assert_eq!(tree.get("nonexistent"), None);
    }

    #[test]
    fn test_into_unversioned_slow_path() {
        // Test slow path: with snapshots, nodes are shared
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert test data
        vtree.insert("key1", 10);
        vtree.insert("key2", 20);
        vtree.insert("key3", 30);

        // Take a snapshot to create shared ownership
        let snapshot = vtree.snapshot();

        // Insert more data after snapshot
        vtree.insert("key4", 40);
        vtree.insert("key5", 50);

        // Convert to unversioned tree (slow path - shared ownership)
        let tree = vtree.into_unversioned();

        // Verify all data is preserved in converted tree
        assert_eq!(tree.get("key1"), Some(&10));
        assert_eq!(tree.get("key2"), Some(&20));
        assert_eq!(tree.get("key3"), Some(&30));
        assert_eq!(tree.get("key4"), Some(&40));
        assert_eq!(tree.get("key5"), Some(&50));

        // Verify snapshot still works independently
        assert_eq!(snapshot.get("key1"), Some(&10));
        assert_eq!(snapshot.get("key2"), Some(&20));
        assert_eq!(snapshot.get("key3"), Some(&30));
        assert_eq!(snapshot.get("key4"), None); // Not in snapshot
        assert_eq!(snapshot.get("key5"), None); // Not in snapshot
    }

    #[test]
    fn test_into_unversioned_empty_tree() {
        // Test empty tree conversion
        let vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let tree = vtree.into_unversioned();

        assert!(tree.is_empty());
        assert_eq!(tree.get("anything"), None);
    }

    #[test]
    fn test_into_unversioned_single_element() {
        // Test single element tree
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, String>::new();
        vtree.insert("only_key", "only_value".to_string());

        let tree = vtree.into_unversioned();
        assert_eq!(tree.get("only_key"), Some(&"only_value".to_string()));
        assert_eq!(tree.get("other"), None);
    }

    #[test]
    fn test_into_unversioned_with_node_growth() {
        // Test conversion with various node types (should trigger Node4 -> Node16 -> Node48 growth)
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, usize>::new();

        // Insert enough keys to trigger multiple node type growths
        for i in 0..60 {
            let key = format!("key_{i:03}");
            vtree.insert(key, i);
        }

        // Take a snapshot to create sharing
        let snapshot = vtree.snapshot();

        // Add more keys
        for i in 60..80 {
            let key = format!("key_{i:03}");
            vtree.insert(key, i);
        }

        // Convert to unversioned (slow path due to snapshot)
        let tree = vtree.into_unversioned();

        // Verify all keys are present
        for i in 0..80 {
            let key = format!("key_{i:03}");
            assert_eq!(tree.get(&key), Some(&i), "Missing key {key}");
        }

        // Verify snapshot has only the first 60 keys
        for i in 0..60 {
            let key = format!("key_{i:03}");
            assert_eq!(snapshot.get(&key), Some(&i));
        }
        for i in 60..80 {
            let key = format!("key_{i:03}");
            assert_eq!(snapshot.get(&key), None);
        }
    }

    #[test]
    fn test_insert_returns_bool() {
        // Test insert() return values behavior in versioned tree
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert new key should return false (not a replacement)
        assert!(!tree.insert("key1", 100));
        assert_eq!(tree.get("key1"), Some(&100));

        // Insert same key should return true (was a replacement)
        assert!(tree.insert("key1", 200));
        assert_eq!(tree.get("key1"), Some(&200));

        // Insert same key again should return true
        assert!(tree.insert("key1", 300));
        assert_eq!(tree.get("key1"), Some(&300));

        // Insert different key should return false (new key)
        assert!(!tree.insert("key2", 400));
        assert_eq!(tree.get("key2"), Some(&400));

        // Original key should still have latest value
        assert_eq!(tree.get("key1"), Some(&300));

        // Replace existing key should return true
        assert!(tree.insert("key2", 500));
        assert_eq!(tree.get("key2"), Some(&500));
    }

    #[test]
    fn test_insert_and_replace_returns_old_value() {
        // Test insert_and_replace() method that captures old values
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert new key should return None
        assert_eq!(tree.insert_and_replace("key1", 100), None);
        assert_eq!(tree.get("key1"), Some(&100));

        // Insert same key should return old value (cloned if necessary)
        assert_eq!(tree.insert_and_replace("key1", 200), Some(100));
        assert_eq!(tree.get("key1"), Some(&200));

        // Insert same key again should return current value
        assert_eq!(tree.insert_and_replace("key1", 300), Some(200));
        assert_eq!(tree.get("key1"), Some(&300));

        // Insert different key should return None
        assert_eq!(tree.insert_and_replace("key2", 400), None);
        assert_eq!(tree.get("key2"), Some(&400));

        // Replace existing key should return old value
        assert_eq!(tree.insert_and_replace("key2", 500), Some(400));
        assert_eq!(tree.get("key2"), Some(&500));
    }

    #[test]
    fn test_raw_prefix_keys_are_supported() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();

        tree.insert_k(&ArrayKey::new_from_slice(b"d"), 1);
        tree.insert_k(&ArrayKey::new_from_slice(b"da"), 2);

        assert_eq!(tree.get_k(&ArrayKey::new_from_slice(b"d")), Some(&1));
        assert_eq!(tree.get_k(&ArrayKey::new_from_slice(b"da")), Some(&2));
    }

    #[test]
    fn test_remove_longer_key_does_not_delete_leaf_root_prefix() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();
        tree.insert_k(&ArrayKey::new_from_slice(b"d"), 1);

        assert_eq!(tree.remove_k(&ArrayKey::new_from_slice(b"da")), None);
        assert_eq!(tree.get_k(&ArrayKey::new_from_slice(b"d")), Some(&1));
    }

    #[test]
    fn test_insert_with_snapshots() {
        // Test insert() behavior when nodes are shared (with snapshots)
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        // Insert initial data
        assert!(!tree.insert("key1", 100));
        assert!(!tree.insert("key2", 200));

        // Take a snapshot to create shared ownership
        let snapshot = tree.snapshot();

        // Insert same key should return true (replacement) even with shared nodes
        assert!(tree.insert("key1", 300));
        assert_eq!(tree.get("key1"), Some(&300));

        // Verify snapshot still has original value
        assert_eq!(snapshot.get("key1"), Some(&100));

        // Insert new key should return false (new key)
        assert!(!tree.insert("key3", 400));
        assert_eq!(tree.get("key3"), Some(&400));

        // Snapshot should not see new key
        assert_eq!(snapshot.get("key3"), None);

        // Test insert_and_replace with snapshots - should still capture old values
        assert_eq!(tree.insert_and_replace("key1", 500), Some(300));
        assert_eq!(tree.get("key1"), Some(&500));

        // Snapshot should still have its original value
        assert_eq!(snapshot.get("key1"), Some(&100));
    }

    #[test]
    fn test_prefix_keys_with_snapshots_preserve_isolation() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();
        tree.insert_k(&ArrayKey::new_from_slice(b"d"), 1);

        let snapshot = tree.snapshot();
        tree.insert_k(&ArrayKey::new_from_slice(b"da"), 2);

        assert_eq!(tree.get_k(&ArrayKey::new_from_slice(b"d")), Some(&1));
        assert_eq!(tree.get_k(&ArrayKey::new_from_slice(b"da")), Some(&2));
        assert_eq!(snapshot.get_k(&ArrayKey::new_from_slice(b"d")), Some(&1));
        assert_eq!(snapshot.get_k(&ArrayKey::new_from_slice(b"da")), None);
    }

    #[test]
    fn traversal_empty_tree_visits_nothing() {
        let tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();
        let mut count = 0;
        tree.for_each_view(|_, _| count += 1);
        assert_eq!(count, 0);
        assert_eq!(tree.iter().count(), 0);
        assert_eq!(tree.values_iter().count(), 0);
    }

    #[test]
    fn traversal_single_root_leaf() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();
        let key = ArrayKey::new_from_slice(b"only");
        tree.insert_k(&key, 7);

        let iter_items: Vec<_> = tree.iter().map(|(key, value)| (key, *value)).collect();
        assert_eq!(iter_items, vec![(key, 7)]);

        let mut views = Vec::new();
        tree.for_each_view(|key_view, value| {
            views.push((key_view.to_vec(), *value));
        });
        assert_eq!(views, vec![(b"only".to_vec(), 7)]);
        assert_eq!(tree.values_iter().copied().collect::<Vec<_>>(), vec![7]);
    }

    #[test]
    fn traversal_handles_key_that_is_prefix_of_another() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<8>, i32>::new();
        tree.insert_k(&ArrayKey::new_from_slice(b"d"), 1);
        tree.insert_k(&ArrayKey::new_from_slice(b"da"), 2);

        let prefix = ArrayKey::new_from_slice(b"d");
        let values: Vec<_> = tree
            .prefix_iter_k(&prefix)
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(values, vec![(b"d".to_vec(), 1), (b"da".to_vec(), 2)]);

        let mut views = Vec::new();
        tree.prefix_for_each_view_k(&prefix, |key_view, value| {
            views.push((key_view.to_vec(), *value));
        });
        assert_eq!(views, vec![(b"d".to_vec(), 1), (b"da".to_vec(), 2)]);
    }

    #[test]
    fn prefix_match_iter_returns_saved_prefixes() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        for (idx, key) in [
            b"".as_slice(),
            b"a".as_slice(),
            b"alpha".as_slice(),
            b"alphabet".as_slice(),
            b"alphabetical".as_slice(),
            b"apple".as_slice(),
        ]
        .iter()
        .enumerate()
        {
            tree.insert_k(&ArrayKey::new_from_slice(key), idx as i32);
        }

        let got: Vec<Vec<u8>> = tree
            .prefix_match_iter(ArrayKey::new_from_slice(b"alphabet"))
            .map(|(key, _)| key.as_ref().to_vec())
            .collect();

        assert_eq!(
            got,
            vec![
                b"".to_vec(),
                b"a".to_vec(),
                b"alpha".to_vec(),
                b"alphabet".to_vec(),
            ]
        );
    }

    #[test]
    fn prefix_match_for_each_returns_saved_prefixes() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        for (idx, key) in [
            b"".as_slice(),
            b"a".as_slice(),
            b"alpha".as_slice(),
            b"alphabet".as_slice(),
            b"alphabetical".as_slice(),
            b"apple".as_slice(),
        ]
        .iter()
        .enumerate()
        {
            tree.insert_k(&ArrayKey::new_from_slice(key), idx as i32);
        }

        let probe = ArrayKey::new_from_slice(b"alphabet");
        let mut got = Vec::new();
        tree.prefix_match_for_each_k(&probe, |key, value| {
            got.push((key.to_vec(), *value));
        });

        assert_eq!(
            got,
            vec![
                (b"".to_vec(), 0),
                (b"a".to_vec(), 1),
                (b"alpha".to_vec(), 2),
                (b"alphabet".to_vec(), 3),
            ]
        );
    }

    #[test]
    fn prefix_traversal_matches_inside_compressed_prefix() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        tree.insert_k(&ArrayKey::new_from_slice(b"abcdef"), 1);
        tree.insert_k(&ArrayKey::new_from_slice(b"abcxyz"), 2);

        let prefix = ArrayKey::new_from_slice(b"abc");
        let values: Vec<_> = tree
            .prefix_iter_k(&prefix)
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(
            values,
            vec![(b"abcdef".to_vec(), 1), (b"abcxyz".to_vec(), 2)]
        );
    }

    #[test]
    fn prefix_traversal_no_match_visits_nothing() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        tree.insert_k(&ArrayKey::new_from_slice(b"abcdef"), 1);

        let prefix = ArrayKey::new_from_slice(b"abz");
        let mut count = 0;
        tree.prefix_for_each_view_k(&prefix, |_, _| count += 1);
        assert_eq!(count, 0);
        assert_eq!(tree.prefix_iter_k(&prefix).count(), 0);
    }

    #[test]
    fn versioned_traversal_order_matches_unversioned_tree() {
        let mut versioned = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let mut unversioned = crate::tree::AdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let keys = [
            b"banana".as_slice(),
            b"app".as_slice(),
            b"apple".as_slice(),
            b"band".as_slice(),
            b"can".as_slice(),
            b"bandana".as_slice(),
        ];

        for (idx, key) in keys.iter().enumerate() {
            let key = ArrayKey::new_from_slice(key);
            versioned.insert_k(&key, idx as i32);
            unversioned.insert_k(&key, idx as i32);
        }

        let versioned_items: Vec<_> = versioned
            .iter()
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        let unversioned_items: Vec<_> = unversioned
            .iter()
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(versioned_items, unversioned_items);

        let start = ArrayKey::new_from_slice(b"banana");
        let end = ArrayKey::new_from_slice(b"can");
        let versioned_range: Vec<_> = versioned
            .range(start..end)
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(
            versioned_range,
            vec![
                (b"banana".to_vec(), 0),
                (b"band".to_vec(), 3),
                (b"bandana".to_vec(), 5)
            ]
        );
    }

    #[test]
    fn versioned_traversal_preserves_snapshot_isolation() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        for (key, value) in [
            (b"a".as_slice(), 1),
            (b"b".as_slice(), 2),
            (b"c".as_slice(), 3),
        ] {
            tree.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        let snapshot = tree.snapshot();
        tree.insert_k(&ArrayKey::new_from_slice(b"b"), 20);
        tree.insert_k(&ArrayKey::new_from_slice(b"d"), 4);
        assert_eq!(tree.remove_k(&ArrayKey::new_from_slice(b"a")), Some(1));

        let snapshot_items: Vec<_> = snapshot
            .iter()
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(
            snapshot_items,
            vec![(b"a".to_vec(), 1), (b"b".to_vec(), 2), (b"c".to_vec(), 3)]
        );

        let tree_items: Vec<_> = tree
            .iter()
            .map(|(key, value)| (key.as_ref().to_vec(), *value))
            .collect();
        assert_eq!(
            tree_items,
            vec![(b"b".to_vec(), 20), (b"c".to_vec(), 3), (b"d".to_vec(), 4)]
        );
    }

    #[test]
    fn traversal_covers_wide_node_shapes() {
        for size in [4usize, 16, 48, 256] {
            let mut tree = VersionedAdaptiveRadixTree::<DenseSequentialKey, usize>::new();
            for idx in 0..size {
                tree.insert_k(&dense_sequential_key(idx as u32), idx);
            }

            let values: Vec<_> = tree.values_iter().copied().collect();
            assert_eq!(values, (0..size).collect::<Vec<_>>());

            let mut viewed = Vec::new();
            tree.for_each_view(|key_view, value| {
                viewed.push((key_view.to_vec(), *value));
            });
            assert_eq!(viewed.len(), size);
            assert_eq!(viewed[0].1, 0);
            assert_eq!(viewed[size - 1].1, size - 1);
        }
    }

    fn cache_key(obj: u64, symbol: u32) -> ArrayKey<16> {
        let mut bytes = [0; 16];
        bytes[..8].copy_from_slice(&obj.to_be_bytes());
        bytes[8..12].copy_from_slice(&symbol.to_be_bytes());
        ArrayKey::new_from_slice(&bytes[..12])
    }

    fn obj_prefix(obj: u64) -> ArrayKey<16> {
        let mut bytes = [0; 16];
        bytes[..8].copy_from_slice(&obj.to_be_bytes());
        ArrayKey::new_from_slice(&bytes[..8])
    }

    #[test]
    fn prefix_for_each_view_supports_moor_shaped_cache_keys() {
        let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, usize>::new();
        for symbol in 0..5 {
            tree.insert_k(&cache_key(10, symbol), symbol as usize);
        }
        for symbol in 0..3 {
            tree.insert_k(&cache_key(11, symbol), 100 + symbol as usize);
        }

        let prefix = obj_prefix(10);
        let mut values = Vec::new();
        tree.prefix_for_each_view_k(&prefix, |key_view, value| {
            assert!(key_view.to_vec().starts_with(prefix.as_ref()));
            values.push(*value);
        });

        assert_eq!(values, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn intersect_with_returns_common_keys_and_values() {
        let mut left = VersionedAdaptiveRadixTree::<ArrayKey<32>, i32>::new();
        let mut right = VersionedAdaptiveRadixTree::<ArrayKey<32>, i32>::new();

        for (key, value) in [
            (b"a".as_slice(), 1),
            (b"ab".as_slice(), 2),
            (b"abc".as_slice(), 3),
            (b"abd".as_slice(), 4),
            (b"bzz".as_slice(), 5),
            (b"cat".as_slice(), 6),
        ] {
            left.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        for (key, value) in [
            (b"ab".as_slice(), 20),
            (b"abc".as_slice(), 30),
            (b"bzz".as_slice(), 50),
            (b"dog".as_slice(), 70),
        ] {
            right.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        let mut seen = Vec::new();
        left.intersect_with(&right, |key, left_value, right_value| {
            seen.push((key.as_ref().to_vec(), *left_value, *right_value));
        });
        seen.sort();

        assert_eq!(
            seen,
            vec![
                (b"ab".to_vec(), 2, 20),
                (b"abc".to_vec(), 3, 30),
                (b"bzz".to_vec(), 5, 50),
            ]
        );
    }

    #[test]
    fn intersect_lending_with_returns_common_keys_and_values() {
        let mut left = VersionedAdaptiveRadixTree::<ArrayKey<32>, i32>::new();
        let mut right = VersionedAdaptiveRadixTree::<ArrayKey<32>, i32>::new();

        for (key, value) in [
            (b"a".as_slice(), 1),
            (b"ab".as_slice(), 2),
            (b"abc".as_slice(), 3),
            (b"abd".as_slice(), 4),
            (b"bzz".as_slice(), 5),
        ] {
            left.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        for (key, value) in [
            (b"ab".as_slice(), 20),
            (b"abc".as_slice(), 30),
            (b"bzz".as_slice(), 50),
            (b"dog".as_slice(), 70),
        ] {
            right.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        let mut seen = Vec::new();
        left.intersect_lending_with(&right, |key, left_value, right_value| {
            seen.push((key.to_vec(), *left_value, *right_value));
        });
        seen.sort();

        assert_eq!(
            seen,
            vec![
                (b"ab".to_vec(), 2, 20),
                (b"abc".to_vec(), 3, 30),
                (b"bzz".to_vec(), 5, 50),
            ]
        );
    }

    #[test]
    fn intersect_values_with_and_count() {
        let mut left = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let mut right = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        for (key, value) in [
            (b"aa".as_slice(), 1),
            (b"ab".as_slice(), 2),
            (b"ac".as_slice(), 3),
        ] {
            left.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        for (key, value) in [
            (b"ab".as_slice(), 20),
            (b"ac".as_slice(), 30),
            (b"zz".as_slice(), 40),
        ] {
            right.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        let mut pairs = Vec::new();
        left.intersect_values_with(&right, |left_value, right_value| {
            pairs.push((*left_value, *right_value));
        });
        pairs.sort_unstable();

        assert_eq!(pairs, vec![(2, 20), (3, 30)]);
        assert_eq!(left.intersect_count(&right), 2);
    }

    #[test]
    fn intersect_with_empty_tree_visits_nothing() {
        let mut left = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let right = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        left.insert_k(&ArrayKey::new_from_slice(b"a"), 1);
        left.insert_k(&ArrayKey::new_from_slice(b"b"), 2);

        let mut count = 0usize;
        left.intersect_with(&right, |_key, _left_value, _right_value| {
            count += 1;
        });
        assert_eq!(count, 0);
        assert_eq!(left.intersect_count(&right), 0);
    }

    #[test]
    fn intersect_uses_snapshot_state_after_cow_mutations() {
        let mut left = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let mut right = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        for (key, value) in [
            (b"aa".as_slice(), 1),
            (b"ab".as_slice(), 2),
            (b"ac".as_slice(), 3),
        ] {
            left.insert_k(&ArrayKey::new_from_slice(key), value);
        }
        for (key, value) in [
            (b"ab".as_slice(), 20),
            (b"ac".as_slice(), 30),
            (b"ad".as_slice(), 40),
        ] {
            right.insert_k(&ArrayKey::new_from_slice(key), value);
        }

        let left_snapshot = left.snapshot();
        let right_snapshot = right.snapshot();

        left.insert_k(&ArrayKey::new_from_slice(b"ab"), 200);
        left.remove_k(&ArrayKey::new_from_slice(b"ac"));
        left.insert_k(&ArrayKey::new_from_slice(b"ad"), 4);
        right.insert_k(&ArrayKey::new_from_slice(b"ad"), 400);
        right.remove_k(&ArrayKey::new_from_slice(b"ab"));

        let mut snapshot_pairs = Vec::new();
        left_snapshot.intersect_with(&right_snapshot, |key, left_value, right_value| {
            snapshot_pairs.push((key.as_ref().to_vec(), *left_value, *right_value));
        });
        snapshot_pairs.sort();
        assert_eq!(
            snapshot_pairs,
            vec![(b"ab".to_vec(), 2, 20), (b"ac".to_vec(), 3, 30)]
        );

        let mut live_pairs = Vec::new();
        left.intersect_with(&right, |key, left_value, right_value| {
            live_pairs.push((key.as_ref().to_vec(), *left_value, *right_value));
        });
        live_pairs.sort();
        assert_eq!(live_pairs, vec![(b"ad".to_vec(), 4, 400)]);
    }

    #[test]
    fn dense_sequential_snapshot_isolation_survives_wide_node_cow() {
        for size in [48usize, 256] {
            let keys: Vec<_> = (0..size).map(|i| dense_sequential_key(i as u32)).collect();
            let mut tree = VersionedAdaptiveRadixTree::<DenseSequentialKey, usize>::new();
            for (i, key) in keys.iter().enumerate() {
                assert!(!tree.insert_k(key, i));
            }

            let snapshot = tree.snapshot();

            for (i, key) in keys.iter().enumerate() {
                assert!(tree.insert_k(key, i + 10_000));
            }

            for (i, key) in keys.iter().enumerate() {
                assert_eq!(snapshot.get_k(key), Some(&i));
                assert_eq!(tree.get_k(key), Some(&(i + 10_000)));
            }

            let scratch_key = dense_sequential_key((size + 1024) as u32);
            assert!(!tree.insert_k(&scratch_key, 77));
            assert_eq!(tree.remove_k(&scratch_key), Some(77));
            assert_eq!(snapshot.get_k(&scratch_key), None);
            assert_eq!(tree.get_k(&scratch_key), None);

            for (i, key) in keys.iter().enumerate() {
                assert_eq!(tree.remove_k(key), Some(i + 10_000));
                assert!(!tree.insert_k(key, i + 20_000));
            }

            for (i, key) in keys.iter().enumerate() {
                assert_eq!(snapshot.get_k(key), Some(&i));
                assert_eq!(tree.get_k(key), Some(&(i + 20_000)));
            }
        }
    }

    #[test]
    fn dense_sequential_multiple_snapshots_mutate_independently() {
        let size = 4096usize;
        let keys: Vec<_> = (0..size).map(|i| dense_sequential_key(i as u32)).collect();
        let mut tree = VersionedAdaptiveRadixTree::<DenseSequentialKey, usize>::new();

        for (i, key) in keys.iter().enumerate() {
            assert!(!tree.insert_k(key, i));
        }

        let mut snapshot_a = tree.snapshot();
        let snapshot_b = tree.snapshot();

        for (i, key) in keys.iter().enumerate() {
            assert!(tree.insert_k(key, i + 10_000));
        }

        for (i, key) in keys.iter().enumerate().step_by(3) {
            assert_eq!(snapshot_a.remove_k(key), Some(i));
            assert!(!snapshot_a.insert_k(key, i + 20_000));
        }

        for i in size..(size + 128) {
            let key = dense_sequential_key(i as u32);
            assert!(!snapshot_a.insert_k(&key, i + 30_000));
            assert_eq!(tree.get_k(&key), None);
            assert_eq!(snapshot_b.get_k(&key), None);
        }

        for (i, key) in keys.iter().enumerate() {
            assert_eq!(tree.get_k(key), Some(&(i + 10_000)));
            assert_eq!(snapshot_b.get_k(key), Some(&i));

            let expected_a = if i % 3 == 0 { i + 20_000 } else { i };
            assert_eq!(snapshot_a.get_k(key), Some(&expected_a));
        }
    }

    #[test]
    fn test_into_unversioned_preserves_tree_structure() {
        // Test that the converted tree behaves identically to a regular tree built the same way
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();
        let mut regular_tree = crate::tree::AdaptiveRadixTree::<ArrayKey<16>, i32>::new();

        let test_data = vec![
            ("apple", 1),
            ("application", 2),
            ("app", 3),
            ("banana", 4),
            ("band", 5),
            ("bandana", 6),
            ("can", 7),
            ("cannot", 8),
        ];

        // Insert same data into both trees
        for (key, value) in &test_data {
            vtree.insert(*key, *value);
            regular_tree.insert(*key, *value);
        }

        // Convert versioned tree
        let converted_tree = vtree.into_unversioned();

        // Both trees should have identical behavior
        for (key, expected_value) in &test_data {
            assert_eq!(converted_tree.get(*key), Some(expected_value));
            assert_eq!(regular_tree.get(*key), Some(expected_value));
            assert_eq!(converted_tree.get(*key), regular_tree.get(*key));
        }

        // Test non-existent keys
        let non_existent = ["xyz", "apple_pie", "ban", "candidate"];
        for key in &non_existent {
            assert_eq!(converted_tree.get(*key), None);
            assert_eq!(regular_tree.get(*key), None);
            assert_eq!(converted_tree.get(*key), regular_tree.get(*key));
        }
    }

    #[test]
    fn test_into_unversioned_memory_efficiency() {
        // Test that conversion doesn't create extra copies when not needed
        let mut vtree = VersionedAdaptiveRadixTree::<ArrayKey<16>, Box<i32>>::new();

        // Use Box<i32> to make ownership clear
        vtree.insert("key1", Box::new(42));
        vtree.insert("key2", Box::new(84));

        // Convert (fast path - no snapshots)
        let tree = vtree.into_unversioned();

        // Verify the boxed values are preserved
        assert_eq!(**tree.get("key1").unwrap(), 42);
        assert_eq!(**tree.get("key2").unwrap(), 84);
    }
}

#[cfg(test)]
mod shuttle_tests {
    use super::*;
    use crate::keys::array_key::ArrayKey;
    use shuttle::{Config, Runner, sync::Arc as ShuttleArc, thread};

    #[test]
    fn shuttle_concurrent_snapshots() {
        let runner = Runner::new(
            shuttle::scheduler::DfsScheduler::new(Some(1000), false),
            Config::new(),
        );
        runner.run(|| {
            let tree = ShuttleArc::new(std::sync::Mutex::new(VersionedAdaptiveRadixTree::<
                ArrayKey<16>,
                i32,
            >::new()));

            // Pre-populate the tree
            {
                let mut t = tree.lock().unwrap();
                for i in 0..10 {
                    t.insert(i, i * 10);
                }
            }

            // Take snapshots BEFORE starting any writer threads
            let snapshot1 = {
                let t = tree.lock().unwrap();
                t.snapshot()
            };
            let snapshot2 = {
                let t = tree.lock().unwrap();
                t.snapshot()
            };

            let tree1 = ShuttleArc::clone(&tree);

            let handle1 = thread::spawn(move || {
                // Verify snapshot contents
                for i in 0..10 {
                    assert_eq!(snapshot1.get(i), Some(&(i * 10)));
                }
                snapshot1
            });

            let handle2 = thread::spawn(move || {
                // Verify snapshot contents
                for i in 0..10 {
                    assert_eq!(snapshot2.get(i), Some(&(i * 10)));
                }
                snapshot2
            });

            let handle3 = thread::spawn(move || {
                // Modify the original tree
                let mut t = tree1.lock().unwrap();
                t.insert(100, 1000);
                assert_eq!(t.get(100), Some(&1000));
            });

            let snapshot1 = handle1.join().unwrap();
            let snapshot2 = handle2.join().unwrap();
            handle3.join().unwrap();

            // Snapshots should not see the new key
            assert_eq!(snapshot1.get(100), None);
            assert_eq!(snapshot2.get(100), None);

            // But original tree should
            let t = tree.lock().unwrap();
            assert_eq!(t.get(100), Some(&1000));
        });
    }

    #[test]
    fn shuttle_snapshot_sharing_across_threads() {
        let runner = Runner::new(
            shuttle::scheduler::DfsScheduler::new(Some(1000), false),
            Config::new(),
        );
        runner.run(|| {
            let mut tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

            // Pre-populate
            for i in 0..5 {
                tree.insert(i, i * 2);
            }

            let snapshot = ShuttleArc::new(tree.snapshot());
            let snapshot1 = ShuttleArc::clone(&snapshot);
            let snapshot2 = ShuttleArc::clone(&snapshot);
            let snapshot3 = ShuttleArc::clone(&snapshot);

            let handle1 = thread::spawn(move || {
                // Read from snapshot in thread 1
                let mut results = Vec::new();
                for i in 0..5 {
                    if let Some(val) = snapshot1.get(i) {
                        results.push(*val);
                    }
                }
                results
            });

            let handle2 = thread::spawn(move || {
                // Read from snapshot in thread 2
                let mut results = Vec::new();
                for i in 0..5 {
                    if let Some(val) = snapshot2.get(i) {
                        results.push(*val);
                    }
                }
                results
            });

            let handle3 = thread::spawn(move || {
                // Read from snapshot in thread 3
                let mut results = Vec::new();
                for i in 0..5 {
                    if let Some(val) = snapshot3.get(i) {
                        results.push(*val);
                    }
                }
                results
            });

            let results1 = handle1.join().unwrap();
            let results2 = handle2.join().unwrap();
            let results3 = handle3.join().unwrap();

            // All threads should see the same data
            let expected: Vec<i32> = (0..5).map(|i| i * 2).collect();
            assert_eq!(results1, expected);
            assert_eq!(results2, expected);
            assert_eq!(results3, expected);
        });
    }

    #[test]
    fn shuttle_concurrent_snapshot_mutations() {
        let runner = Runner::new(
            shuttle::scheduler::DfsScheduler::new(Some(1000), false),
            Config::new(),
        );
        runner.run(|| {
            let mut base_tree = VersionedAdaptiveRadixTree::<ArrayKey<16>, i32>::new();

            // Pre-populate
            for i in 0..3 {
                base_tree.insert(i, i);
            }

            // Create snapshots that will be mutated concurrently
            let snapshot1 = ShuttleArc::new(std::sync::Mutex::new(base_tree.snapshot()));
            let snapshot2 = ShuttleArc::new(std::sync::Mutex::new(base_tree.snapshot()));

            let s1 = ShuttleArc::clone(&snapshot1);
            let s2 = ShuttleArc::clone(&snapshot2);

            let handle1 = thread::spawn(move || {
                let mut snap = s1.lock().unwrap();
                snap.insert(10, 100);
                snap.insert(11, 110);

                // Verify our mutations
                assert_eq!(snap.get(10), Some(&100));
                assert_eq!(snap.get(11), Some(&110));

                // Should still see original data
                for i in 0..3 {
                    assert_eq!(snap.get(i), Some(&i));
                }
            });

            let handle2 = thread::spawn(move || {
                let mut snap = s2.lock().unwrap();
                snap.insert(20, 200);
                snap.insert(21, 210);

                // Verify our mutations
                assert_eq!(snap.get(20), Some(&200));
                assert_eq!(snap.get(21), Some(&210));

                // Should still see original data
                for i in 0..3 {
                    assert_eq!(snap.get(i), Some(&i));
                }
            });

            handle1.join().unwrap();
            handle2.join().unwrap();

            // Verify independence - snapshot1 shouldn't see snapshot2's changes
            {
                let snap1 = snapshot1.lock().unwrap();
                assert_eq!(snap1.get(10), Some(&100));
                assert_eq!(snap1.get(11), Some(&110));
                assert_eq!(snap1.get(20), None); // Shouldn't see snapshot2's data
                assert_eq!(snap1.get(21), None);
            }

            {
                let snap2 = snapshot2.lock().unwrap();
                assert_eq!(snap2.get(20), Some(&200));
                assert_eq!(snap2.get(21), Some(&210));
                assert_eq!(snap2.get(10), None); // Shouldn't see snapshot1's data
                assert_eq!(snap2.get(11), None);
            }
        });
    }

    #[test]
    fn shuttle_many_readers_one_writer() {
        let runner = Runner::new(
            shuttle::scheduler::DfsScheduler::new(Some(1000), false),
            Config::new(),
        );
        runner.run(|| {
            let tree = ShuttleArc::new(std::sync::Mutex::new(VersionedAdaptiveRadixTree::<
                ArrayKey<16>,
                i32,
            >::new()));

            // Pre-populate
            {
                let mut t = tree.lock().unwrap();
                for i in 0..10 {
                    t.insert(i, i * 3);
                }
            }

            // Take a snapshot before spawning threads
            let snapshot = {
                let t = tree.lock().unwrap();
                ShuttleArc::new(t.snapshot())
            };

            let tree_for_writer = ShuttleArc::clone(&tree);

            // Spawn multiple readers
            let mut reader_handles = Vec::new();
            for reader_id in 0..3 {
                let snap = ShuttleArc::clone(&snapshot);
                let handle = thread::spawn(move || {
                    let mut sum = 0;
                    for i in 0..10 {
                        if let Some(val) = snap.get(i) {
                            sum += val;
                        }
                    }
                    (reader_id, sum)
                });
                reader_handles.push(handle);
            }

            // Spawn one writer
            let writer_handle = thread::spawn(move || {
                let mut tree = tree_for_writer.lock().unwrap();
                // Add new data
                for i in 100..105 {
                    tree.insert(i, i * 5);
                }

                // Verify writer can see its own changes
                let mut writer_sum = 0;
                for i in 100..105 {
                    if let Some(val) = tree.get(i) {
                        writer_sum += val;
                    }
                }
                writer_sum
            });

            // Collect results
            let expected_reader_sum = (0..10).map(|i| i * 3).sum::<i32>();
            for handle in reader_handles {
                let (reader_id, sum) = handle.join().unwrap();
                assert_eq!(sum, expected_reader_sum, "Reader {reader_id} got wrong sum");
            }

            let writer_sum = writer_handle.join().unwrap();
            let expected_writer_sum = (100..105).map(|i| i * 5).sum::<i32>();
            assert_eq!(writer_sum, expected_writer_sum);

            // Verify readers didn't see writer's changes (they used snapshot)
            for i in 100..105 {
                assert_eq!(snapshot.get(i), None);
            }
        });
    }

    #[test]
    fn shuttle_snapshot_drop_safety() {
        let runner = Runner::new(
            shuttle::scheduler::DfsScheduler::new(Some(1000), false),
            Config::new(),
        );
        runner.run(|| {
            let tree = ShuttleArc::new(std::sync::Mutex::new(VersionedAdaptiveRadixTree::<
                ArrayKey<16>,
                i32,
            >::new()));

            // Pre-populate
            {
                let mut t = tree.lock().unwrap();
                for i in 0..5 {
                    t.insert(i, i * 7);
                }
            }

            let tree1 = ShuttleArc::clone(&tree);
            let tree2 = ShuttleArc::clone(&tree);

            let handle1 = thread::spawn(move || {
                let snapshot = {
                    let t = tree1.lock().unwrap();
                    t.snapshot()
                };

                // Use snapshot briefly
                let mut sum = 0;
                for i in 0..5 {
                    if let Some(val) = snapshot.get(i) {
                        sum += val;
                    }
                }
                sum
                // Snapshot drops here
            });

            let handle2 = thread::spawn(move || {
                let snapshot = {
                    let t = tree2.lock().unwrap();
                    t.snapshot()
                };

                // Use snapshot briefly
                let mut count = 0;
                for i in 0..5 {
                    if snapshot.get(i).is_some() {
                        count += 1;
                    }
                }
                count
                // Snapshot drops here
            });

            let sum = handle1.join().unwrap();
            let count = handle2.join().unwrap();

            assert_eq!(sum, (0..5).map(|i| i * 7).sum::<i32>());
            assert_eq!(count, 5);

            // Original tree should still work after snapshots are dropped
            let t = tree.lock().unwrap();
            for i in 0..5 {
                assert_eq!(t.get(i), Some(&(i * 7)));
            }
        });
    }
}