rstrie 0.6.0

A generalized Trie implementation for Rust.
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
//! A trie library for Rust that allows generic implementing a generic [Trie].
//!
//! A [Trie] actually does not store keys directly but supports storing the individual
//! fragments of what composes a key. For instance, a [String] trie will use [char] and will
//! have the signature `Trie::<char, ()>` ([Trie]).
//!
//! The [Trie] supports the entire API of the standard library's HashMap along with
//! various common algorithms that a [Trie] data structure should support. This [Trie] implementation
//! is optimized for extensibility and supporting many types and may not necessarily be
//! the most memory optimized.
//!
//! # Example
//! ```
//! use rstrie::Trie;
//!
//! let mut trie = Trie::<char, usize>::new();
//! trie.insert("hello".chars(), 4);
//! trie.insert("hey".chars(), 5);
//!
//! assert_eq!(trie.get("hello".chars()), Some(&4));
//! ```

use std::{
    borrow::Borrow, cmp::Ordering, error::Error, fmt::Debug, iter::Peekable, marker::PhantomData, ops::{Deref, DerefMut, Index, IndexMut}, slice::GetDisjointMutError, vec::IntoIter
};

use list::{DisjointMutIndices, Node, NodeIndex, Slots};

use crate::list::SlotsIterMut;
mod list;

/// A [Trie] that is implemented for [String] types. As textual
/// data is the most common usecase for the [Trie], they get some
/// special attention.
///
/// # Example
/// ```
/// use rstrie::StrTrie;
///
/// let trie = StrTrie::<usize>::new();
/// ```
pub type StrTrie<V> = Trie<char, V>;

/// A [Trie] is a data structure that is commonly used to
/// store and retrieve strings in a memory-efficient manner. This crate takes a slightly different approach, allowing for the building
/// of Tries from arbitrary types as long as they can satisfy certain properties.
/// 
/// In our case, the key must implement the [Ord] type. This is because the nodes
/// store a list of keys that are sorted, and binary search is used for efficient lookup
/// of the storage index. 
/// 
/// # Example
/// ```
/// use rstrie::Trie;
/// 
/// let mut trie: Trie<char, usize> = Trie::new();
/// trie.insert("hello".chars(), 4);
/// trie.insert("hey".chars(), 5);
/// 
/// assert_eq!(trie.get("hello".chars()), Some(&4));
/// assert_eq!(trie.get("hey".chars()), Some(&5));
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Trie<K, V> {
    /// The node pool, this is where the internal nodes are actually store. This
    /// improves cache locality and ease of access while limiting weird lifetime errors.
    node: Slots<K, V>,
    /// The amount of items in the Trie.
    size: usize,
}

#[derive(Debug)]
/// Contains the details of an incomplete [Trie] walk.
/// This is usually used to insert new nodes along incomplete
/// paths. For instance,
/// ```example
///             t
///            /  
///           e   
///          / \    
///         s   a
///          \
///           t
/// ```
/// For instance when "tea" was inserted, we would have a *common* path
/// up until 'e' and then it would diverge.
struct WalkFailure<'a, I> {
    /// The root of the walk.
    root: NodeIndex,
    /// The remainder of the path as an iterator.
    remainder: &'a mut I,
}

/// The walk trajectory. This is a list of node indexes that
/// is used to construct various types/various operations within the [Trie].
#[derive(Debug)]
struct WalkTrajectory {
    /// The list of indices.
    path: Vec<NodeIndex>,
}

impl<K, V> Default for Trie<K, V> {
    /// Creates an empty [Trie] with the [Default] value for
    /// the hasher.
    ///
    /// # Example
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, ()>::default();
    /// ```
    fn default() -> Self {
        Self::new()
    }
}

/// The walk context object is a walk across the entire trie. It is
/// driven forward with the [WalkCtx::drive] method.
#[derive(Debug)]
struct WalkCtx {
    /// The pending paths to walk. Each of these is a stak.
    pending: Vec<Vec<NodeIndex>>,
}

/// Iterates automatically over the [WalkCtx] object by continually
/// driving it forward using the [Trie] provided.
struct WalkIter<'a, K, V> {
    trie: &'a Trie<K, V>,
    context: WalkCtx,
}

impl WalkCtx {
    /// Drives this forward, this is similar to the
    pub fn drive<K, V>(&mut self, trie: &Trie<K, V>) -> Option<(NodeIndex, Vec<NodeIndex>)> {
        while let Some(pending) = self.pending.pop() {
            let current = pending.last().expect("Pending list was empty.");

            for &child in trie.node[*current].subkeys().rev() {
                // Create a new path.
                let mut new_path = pending.clone();
                new_path.push(child);
                self.pending.push(new_path);
            }

            if trie.node[*current].value().is_some() {
                // We have reached a root.
                return Some((*current, pending));
            }
        }

        None
    }
}

impl<K, V> Iterator for WalkIter<'_, K, V> {
    type Item = (NodeIndex, Vec<NodeIndex>);

    /// Returns the next item in the [WalkIter].
    fn next(&mut self) -> Option<Self::Item> {
        self.context.drive(self.trie)
    }
}

impl<K, V> Trie<K, V> {
    /// Given a path, traverses the [Trie], collecting them into the
    /// return type. Very common method when the user requires the key fragments
    /// to be combined into the entire key.
    fn collect_path_keys<'a, J>(&'a self, nodes: &[NodeIndex]) -> J
    where
        J: FromIterator<&'a K>,
    {
        nodes
            .iter()
            .map(|f| self.node[*f].key())
            .filter_map(<Option<K>>::as_ref)
            .collect()
    }

    /// Performs a standard internal walk of the [Trie] without any special
    /// functor. This will return the last node in the walk. It is a convienence
    /// method to ease the call signatures when we do not explicitly need to
    /// perform any collection on the [Trie].
    fn internal_walk_with_index<'b, I, B>(
        &self,
        remainder: &'b mut Peekable<I>,
    ) -> Result<NodeIndex, WalkFailure<'b, Peekable<I>>>
    where
        I: Iterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.internal_walk_with_fn(remainder, |_| {})
    }

    /// Performs an internal walk of the [Trie] and obtains the path
    /// used to get there. Internally, this just calls the internal walk
    /// function and has it collect the nodes as we go.
    fn internal_walk_with_path<'b, I, B>(
        &self,
        remainder: &'b mut Peekable<I>,
    ) -> Result<WalkTrajectory, WalkFailure<'b, Peekable<I>>>
    where
        I: Iterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.internal_walk_with_path_fn(remainder, |_| {})
    }

    /// Performs an internal walk of the [Trie] and obtains the path
    /// used to get there. Internally, this just calls the internal walk
    /// function and has it collect the nodes as we go.
    fn internal_walk_with_path_fn<'b, I, F, B>(
        &self,
        remainder: &'b mut Peekable<I>,
        mut functor: F,
    ) -> Result<WalkTrajectory, WalkFailure<'b, Peekable<I>>>
    where
        I: Iterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
        F: FnMut(NodeIndex),
    {
        let mut trajectory_path = vec![];

        self.internal_walk_with_fn(remainder, |node| {
            trajectory_path.push(node);
            functor(node);
        })?;

        Ok(WalkTrajectory {
            path: trajectory_path,
        })
    }

    /// Given a [NodeIndex] and an array, this will fold the key into the
    /// array ONLY if the key links to a non-root node (one where the key is not null).
    fn fold_in_key_optionally<'a>(&'a self, node: NodeIndex, array: &mut Vec<&'a K>) {
        if let Some(inner) = self.node[node].key() {
            array.push(inner);
        }
    }

    /// Performs an internal walk of the [Trie] but collects the key as we go.
    fn internal_walk_collect_key<'a, I, J, B>(
        &self,
        remainder: &'a mut Peekable<I>,
    ) -> Result<(J, NodeIndex), WalkFailure<'a, Peekable<I>>>
    where
        I: Iterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
        for<'b> J: FromIterator<&'b K>,
    {
        let mut collector = vec![];
        let index = self.internal_walk_with_fn(remainder, |nk| {
            self.fold_in_key_optionally(nk, &mut collector)
        })?;
        Ok((collector.into_iter().collect::<J>(), index))
    }

    /// Starts an iterative walk of the [Trie] starting at
    /// the specified root. This allows for efficient and truly
    /// lazy iteration over parts of the [Trie] in a no-copy way.
    fn perform_walk(&self, root: NodeIndex) -> WalkCtx {
        WalkCtx {
            pending: vec![vec![root]],
        }
    }
    /// Performs an internal walk of the [Trie]. This is the most important function
    /// for the operation of the [Trie]. It takes in a visitor function that is called
    /// every time a nodes key is accessed, this allows for activities such as collecting
    /// the key.
    ///
    /// If the walk is fully succesful, as in we can propery traverse the path to the end, we
    /// return the [NodeIndex] of the last node.
    ///
    /// If the walk cannot be completed, we return a [WalkFailure] struct that contains the necessary
    /// information to perform insertion.
    fn internal_walk_with_fn<'b, I, F, B>(
        &self,
        remainder: &'b mut Peekable<I>,
        visitor_fn: F,
    ) -> Result<NodeIndex, WalkFailure<'b, Peekable<I>>>
    where
        I: Iterator<Item = B>,
        B: Borrow<K>,
        K: Ord,
        F: FnMut(NodeIndex),
    {
        self.internal_walk_with_fn_cmp(remainder, visitor_fn, |a, b| a.cmp(b.borrow()))
    }
    /// Performs an internal walk of the [Trie]. This is the most important function
    /// for the operation of the [Trie]. It takes in a visitor function that is called
    /// every time a nodes key is accessed, this allows for activities such as collecting
    /// the key.
    ///
    /// If the walk is fully succesful, as in we can propery traverse the path to the end, we
    /// return the [NodeIndex] of the last node.
    ///
    /// If the walk cannot be completed, we return a [WalkFailure] struct that contains the necessary
    /// information to perform insertion.
    fn internal_walk_with_fn_cmp<'a, F, C, A, B>(
        &self,
        remainder: &'a mut Peekable<A>,
        mut visitor_fn: F,
        mut cmp_fn: C,
    ) -> Result<NodeIndex, WalkFailure<'a, Peekable<A>>>
    where
        A: Iterator<Item = B>,
        F: FnMut(NodeIndex),
        for<'b> C: FnMut(&'b K, &'b B) -> Ordering,
    {
        // The root for the path.
        visitor_fn(NodeIndex::ROOT);

        let mut end = &NodeIndex::ROOT;
        loop {
            let Some(current) = remainder.peek() else {
                break;
            };

            // Call on the current node.
            visitor_fn(*end);

            if let Some(slot) = self.node[*end].get_with(&self.node, |k| cmp_fn(k, current)) {
                end = slot;
            } else {
                return Err(WalkFailure {
                    root: *end,
                    remainder,
                });
            }

            // Actually consume.
            remainder.next();
        }

        // Call on the very last index, if we reach this point this is indicatvie
        // of a succesful complete walk.
        visitor_fn(*end);

        Ok(*end)
    }
}

impl<K, V> Trie<K, V> {
    /// Creates a new [Trie] with no keys and records. This will
    /// create a [Trie] with a capacity of zero using the [Trie::with_capacity] method.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, &str>::new();
    /// assert_eq!(tree.len(), 0);
    /// ```
    pub fn new() -> Self {
        Self::with_capacity(0)
    }
    /// Returns the capacity of the underlying arena allocator.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, ()>::with_capacity(3);
    /// assert_eq!(trie.capacity(), 3);
    /// ```
    pub fn capacity(&self) -> usize {
        self.node.capacity()
    }
    /// Creates a new [Trie] with a certain specified capacity.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::with_capacity(20);
    /// assert!(tree.is_empty());
    /// ```
    pub fn with_capacity(slots: usize) -> Self {
        Self {
            node: Slots::with_capacity(slots),
            size: 0,
        }
    }

    /// Looks up the node pool index for a certain key,
    /// the key is an iterator over the prefixes. For instance,
    /// for strings this would be characters. This method forms the basis
    /// for [Trie::get] and [Trie::get_mut].
    fn lookup_key<I, B>(&self, key: I) -> Option<NodeIndex>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.internal_walk_with_index(&mut key.into_iter().peekable())
            .ok()
    }

    /// Checks if a key is a prefix within a [Trie]. This
    /// may or may not be an exact math.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, ()>::new();
    /// trie.insert("hello".chars(), ());
    /// trie.insert("hey".chars(), ());
    /// trie.insert("hero".chars(), ());
    ///
    /// assert!(trie.is_prefix(['h', 'e']));
    /// assert!(trie.is_prefix(['h', 'e', 'r']));
    /// assert!(!trie.is_prefix(['h', 'e', 'r', 'y']));
    /// ```
    pub fn is_prefix<I, B>(&self, key: I) -> bool
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.internal_walk_with_index(&mut key.into_iter().peekable())
            .is_ok()
    }

    /// Performs a distance search with a custom function.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    /// use std::cmp::Reverse;
    ///
    /// let mut trie = Trie::<char, ()>::new();
    /// trie.insert("123".chars(), ());
    /// trie.insert("1".chars(), ());
    /// trie.insert("12".chars(), ());
    ///
    /// let longest = trie.search_with_score_fn(|c| c.len());
    /// assert_eq!(longest, Some(vec![ &'1', &'2', &'3' ]));
    ///
    /// let shortest = trie.search_with_score_fn(|c| Reverse(c.len()));
    /// assert_eq!(shortest, Some(vec![ &'1' ]));
    /// ```
    pub fn search_with_score_fn<F, B>(&self, mut distance: F) -> Option<Vec<&K>>
    where
        K: Ord,
        F: FnMut(&[&K]) -> B,
        B: Ord,
    {
        let full_walk = WalkIter {
            context: self.perform_walk(NodeIndex::ROOT),
            trie: self,
        };

        let mut best_score = None;
        let mut best_candidate = None;

        for (_, node_index) in full_walk {
            let collected = self.collect_path_keys::<Vec<_>>(&node_index);
            let score = distance(&collected);
            if best_score.is_none() || *best_score.as_ref().expect("Best score was none despite us asserting it was not.") < score {
                best_score = Some(score);
                best_candidate = Some(collected);
            }
        }

        best_candidate
    }
    /// Gets all the completions of a key. This will
    /// traverse the tree to the point at which the key
    /// diverges. This is also called a 'common prefix search'.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, ()>::new();
    /// tree.insert("hello".chars(), ());
    /// tree.insert("hey".chars(), ());
    /// tree.insert("james".chars(), ());
    ///
    ///
    /// let mut values = tree.completions("he".chars())
    ///     .into_iter()
    ///     .collect::<Vec<(String, &())>>();
    /// assert_eq!(values.len(), 2);
    ///
    ///
    /// assert_eq!(values[0].0, "hello");
    /// assert_eq!(values[1].0, "hey");
    /// ```
    pub fn completions<'a, I, B, J>(&'a self, key: I) -> CompletionIter<'a, K, V, J>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        J: FromIterator<B>,
        B: Borrow<K>,
    {
        let mut collector = vec![];
        match self.internal_walk_with_fn(key.into_iter().peekable().by_ref(), |nk| {
            self.fold_in_key_optionally(nk, &mut collector)
        }) {
            Ok(inner) => CompletionIter {
                beginning: collector,
                inner: self.perform_walk(inner),
                trie: self,
                _transform: PhantomData,
            },
            Err(_) => {
                // Here we will create something that just will not iterate.
                CompletionIter {
                    beginning: vec![],
                    _transform: PhantomData,
                    inner: WalkCtx { pending: vec![] },
                    trie: self,
                }
            }
        }
    }
    /// Performs a postfix search of the tree, returning
    /// the postfixes.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, ()>::new();
    /// tree.insert("hello".chars(), ());
    /// tree.insert("hey".chars(), ());
    /// tree.insert("james".chars(), ());
    ///
    /// let mut values: Vec<(String, &())> = tree.postfix_search("he".chars())
    ///     .into_iter()
    ///     .collect::<Vec<_>>();
    /// assert_eq!(values.len(), 2);
    ///
    ///
    /// assert_eq!(values[0].0, "llo");
    /// assert_eq!(values[1].0, "y");
    /// ```
    pub fn postfix_search<'a, I, B, J>(&'a self, key: I) -> PostfixIter<'a, K, V, J>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        J: FromIterator<K>,
        B: Borrow<K>,
    {
        let mut collector = vec![];
        match self.internal_walk_with_fn(key.into_iter().peekable().by_ref(), |nk| {
            self.fold_in_key_optionally(nk, &mut collector)
        }) {
            Ok(inner) => PostfixIter {
                inner: self.perform_walk(inner),
                trie: self,
                _transform: PhantomData,
            },
            Err(_) => {
                // Here we will create something that just will not iterate.
                PostfixIter {
                    _transform: PhantomData,
                    inner: WalkCtx { pending: vec![] },
                    trie: self,
                }
            }
        }
    }

    /// Returns an iterator over the values of the [Trie]
    /// data structure.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.values();
    ///
    /// assert_eq!(values.next().cloned(), Some(1));
    /// assert_eq!(values.next().cloned(), Some(2));
    /// assert_eq!(values.next().cloned(), None);
    /// ```
    pub fn values(&self) -> ValueIterRef<'_, K, V> {
        ValueIterRef {
            values: self.node.slot_iter(),
        }
    }

    /// Returns an iterator over the values of the [Trie]
    /// data structure mutably.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.values_mut();
    ///
    /// assert_eq!(values.next().cloned(), Some(1));
    ///
    /// // Mutate a value to verify mutabiltiy.
    /// *values.next().unwrap() = 3;
    ///
    ///
    /// assert_eq!(values.next().cloned(), None);
    ///
    ///
    /// // Check the value was properly mutate.
    /// assert_eq!(*tree.get("bye".chars()).unwrap(), 3);
    /// ```
    pub fn values_mut(&mut self) -> ValueIterMut<'_, K, V> {
        ValueIterMut {
            values: self.node.slot_iter_mut(),
        }
    }

    /// Clears the [Trie], returning all key-value pairs as an
    /// iterator. Keeps the allocated memory for reuse.
    /// TODO: Is the root re-added after it is dropped?
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a', 'b', 'c'], 1);
    /// trie.insert(['a', 'c'], 2);
    /// trie.insert(['b'], 3);
    ///
    /// let mut iter = trie.drain::<String>();
    /// assert_eq!(iter.next(), Some(("abc".to_string(), 1)));
    /// assert_eq!(iter.next(), Some(("ac".to_string(), 2)));
    /// assert_eq!(iter.next(), Some(("b".to_string(), 3)));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub fn drain<J>(&mut self) -> Drain<'_, K, V, J>
    where
        for<'b> J: FromIterator<&'b K>,
    {
        let keys = self.keys::<J>().collect::<Vec<_>>();

        Drain {
            key_iter: keys.into_iter(),
            inner: self.node.drain_slots(),
        }
    }

    /// Returns an iterator over the values of the [Trie]
    /// data structure mutably.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.values_mut();
    ///
    /// assert_eq!(values.next().cloned(), Some(1));
    ///
    /// // Mutate a value to verify mutabiltiy.
    /// *values.next().unwrap() = 3;
    ///
    ///
    /// assert_eq!(values.next().cloned(), None);
    ///
    ///
    /// // Check the value was properly mutate.
    /// assert_eq!(*tree.get("bye".chars()).unwrap(), 3);
    /// ```
    pub fn into_values(mut self) -> ValueIter<V> {
        let values = self
            .node
            .drain_slots()
            .flatten()
            .filter_map(Node::into_value)
            .collect::<Vec<V>>();

        ValueIter {
            inner: values.into_iter(),
        }
    }
    /// Returns the longest prefix match.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert("he".chars(), 1);
    /// trie.insert("hel".chars(), 2);
    /// trie.insert("hello".chars(), 3);
    ///
    /// assert_eq!(trie.longest_prefix_entry("hello".chars()), Some(("hello".to_string(), &3)));
    /// assert_eq!(trie.longest_prefix_entry("hellothere".chars()), Some(("hello".to_string(), &3)));
    /// ```
    pub fn longest_prefix_entry<I, J, B>(&self, key: I) -> Option<(J, &V)>
    where
        I: IntoIterator<Item = B>,
        B: Borrow<K>,
        for<'b> J: FromIterator<&'b K>,
        K: Ord,
    {
        let mut last_productive = NodeIndex::ROOT;
        let mut position = 0;
        let mut last_productive_position = 0;
        let mut collector = vec![];
        self.find_longest_prefix_fn(key, |nk, k| {
            if self.node[nk].value().is_some() {
                last_productive = nk;
                last_productive_position = position;
            }
            collector.push(k);
            position += 1;
        })?;
        let value = self.node[last_productive].value().as_ref()?;
        let key: J = collector[0..last_productive_position + 1]
            .iter()
            .copied()
            .collect();
        Some((key, value))
    }
    /// Returns the longest prefix match.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert("he".chars(), 1);
    /// trie.insert("hel".chars(), 2);
    /// trie.insert("hello".chars(), 3);
    ///
    /// assert_eq!(trie.longest_prefix("hello".chars()), Some(&3));
    /// assert_eq!(trie.longest_prefix("hellothere".chars()), Some(&3));
    /// ```
    pub fn longest_prefix<I, B>(&self, key: I) -> Option<&V>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        let mut last_productive = NodeIndex::ROOT;
        self.find_longest_prefix_fn(key, |nk, _| {
            if self.node[nk].value().is_some() {
                last_productive = nk;
            }
        })?;
        self.node[last_productive].value().as_ref()
    }

    fn find_longest_prefix_fn<'a, I, F, B>(&'a self, key: I, mut functor: F) -> Option<NodeIndex>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
        F: FnMut(NodeIndex, &'a K),
    {
        match self.internal_walk_with_fn(key.into_iter().peekable().by_ref(), |nk| {
            if let Some(inner) = self.node[nk].key() {
                functor(nk, inner);
            }
        }) {
            Ok(end) => Some(end),
            Err(WalkFailure { root, .. }) => {
                // The match was not an exact match (common case)
                Some(root)
            }
        }
    }
    /// Returns an iterator over the keys of the [Trie]
    /// data structure.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.keys::<String>();
    ///
    /// assert_eq!(key_iter.next().unwrap(), "bye");
    /// assert_eq!(key_iter.next().unwrap(), "hello");
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn keys<'a, J>(&'a self) -> KeyIter<'a, K, V, J>
    where
        J: FromIterator<&'a K>,
    {
        KeyIter {
            inner: WalkIter {
                context: self.perform_walk(NodeIndex::ROOT),
                trie: self,
            },
            _type: PhantomData,
        }
    }

    /// Returns an iterator over the entries of the [Trie]
    /// data structure.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.into_entries::<String>();
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), 3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), 4));
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn into_entries<J>(self) -> IntoEntryIter<K, V, J>
    where
        for<'a> J: FromIterator<&'a K>,
    {
        IntoEntryIter {
            inner: self.perform_walk(NodeIndex::ROOT),
            trie: self,
            _type: PhantomData,
        }
    }
    /// Returns an iterator over the entries of the [Trie]
    /// data structure.
    ///
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.entries::<String>();
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), &3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), &4));
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn entries<'a, J>(&'a self) -> EntryIterRef<'a, K, V, J>
    where
        J: FromIterator<&'a K>,
    {
        EntryIterRef {
            inner: WalkIter {
                context: self.perform_walk(NodeIndex::ROOT),
                trie: self,
            },
            _type: PhantomData,
        }
    }

    /// Returns an iterator over the entries of the [Trie]
    /// data structure.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.entries_mut::<String>();
    ///
    /// assert_eq!(*key_iter.next().unwrap().1, 3);
    /// assert_eq!(*key_iter.next().unwrap().1, 4);
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn entries_mut<J>(&mut self) -> EntryIterMut<'_, K, V, J>
    where
        for<'a> J: FromIterator<&'a K>,
    {
        EntryIterMut {
            inner: self.perform_walk(NodeIndex::ROOT),
            trie: self,
            // slot: None,.
            _type: PhantomData,
        }
    }

    /// Gets a value from the [Trie] according to
    /// the key. The key is an iterable that can be used
    /// to access the record.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, &str>::new();
    /// tree.insert("hello".chars(), "world");
    /// tree.insert("hellooo".chars(), "world2");
    /// assert_eq!(*tree.get("hello".chars()).unwrap(), "world");
    /// ```
    pub fn get<I, B>(&self, key: I) -> Option<&V>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.node[self.lookup_key(key)?].value().as_ref()
    }
    /// Tries to get the key map.
    ///
    /// # Errors
    /// If the keys are not disjoint, i.e, if they map to the same value.
    fn try_get_key_map<I, B, const N: usize>(
        &mut self,
        keys: [I; N],
    ) -> Result<[NodeIndex; N], TryGetKeyMapError>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        let mut array = [NodeIndex::ROOT; N];

        for (i, k) in keys.into_iter().enumerate() {
            let candidate = self.lookup_key(k);

            if let Some(candidate) = candidate {
                if array.contains(&candidate) {
                    return Err(TryGetKeyMapError::Duplicate(candidate.position()));
                }
            }
            array[i] = candidate.ok_or(TryGetKeyMapError::KeyDoesNotExist)?;
        }

        Ok(array)
    }
    /// Attempts to get many mutable references to the array with a set of
    /// valid keys. All keys must be disjoint and valid or else the entire
    /// set will return None.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 3);
    /// tree.insert("world".chars(), 4);
    ///
    /// let mut keys = tree.get_disjoint_mut([ "hello".chars(), "world".chars() ]);
    /// *keys[0].as_mut().unwrap() = 4;
    /// *keys[1].as_mut().unwrap() = 2;
    ///
    /// assert_eq!(tree.get("hello".chars()), Some(&4));
    /// assert_eq!(tree.get("world".chars()), Some(&2));
    /// ```
    pub fn get_disjoint_mut<I, B, const N: usize>(
        &mut self,
        keys: [I; N],
    ) -> DisjointMutIndices<'_, K, V, N>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        self.try_get_disjoint_mut(keys)
            .expect("Keys were overlapping.")
    }
    /// Attempts to get many mutable references to the array with a set of
    /// valid keys. All keys must be disjoint and valid or else the entire
    /// set will return None.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 3);
    /// tree.insert("world".chars(), 4);
    ///
    /// let mut keys = tree.try_get_disjoint_mut([ "hello".chars(), "world".chars() ]).unwrap();
    /// *keys[0].as_mut().unwrap() = 4;
    /// *keys[1].as_mut().unwrap() = 2;
    ///
    /// assert_eq!(tree.get("hello".chars()), Some(&4));
    /// assert_eq!(tree.get("world".chars()), Some(&2));
    /// ```
    pub fn try_get_disjoint_mut<I, B, const N: usize>(
        &mut self,
        keys: [I; N],
    ) -> Result<DisjointMutIndices<K, V, N>, GetDisjointMutError>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        // Calculate the key map.
        let array = self
            .try_get_key_map(keys)
            .map_err(|_| GetDisjointMutError::OverlappingIndices)?;
        self.node.get_disjoint_mut(array)
    }

    /// Gets a mutable reference of a value from the [Trie] according to
    /// the key. The key is an iterable that can be used
    /// to access the record.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, &str>::new();
    /// tree.insert("hello".chars(), "world");
    /// assert_eq!(*tree.get_mut("hello".chars()).unwrap(), "world");
    ///
    /// *tree.get_mut("hello".chars()).unwrap() = "world2";
    /// assert_eq!(*tree.get_mut("hello".chars()).unwrap(), "world2");
    /// ```
    pub fn get_mut<I, B>(&mut self, key: I) -> Option<&mut V>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        let index = self.lookup_key(key)?;
        self.node[index].value_mut().as_mut()
    }
    /// Returns the amount of records within
    /// the [Trie].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, &str>::new();
    /// tree.insert("hello".chars(), "world");
    /// assert_eq!(tree.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.size
    }
    /// Returns true if the [Trie] is empty,
    /// else it will return false.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, &str>::new();
    /// assert!(tree.is_empty());
    ///
    /// tree.insert("hello".chars(), "world");
    /// assert!(!tree.is_empty());
    ///
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Will clear the [Trie] data structure.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    /// assert!(tree.is_empty());
    ///
    /// tree.insert("hello".chars(), 0);
    /// assert!(!tree.is_empty());
    ///
    /// tree.clear();
    /// assert!(tree.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.node.clear();
        self.size = 0;
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a', 'b', 'c'], 1);
    ///
    /// assert_eq!(trie.get_key_value(['a', 'b', 'c']), Some(("abc".to_string(), &1)))
    ///
    /// ```
    pub fn get_key_value<I, B, J>(&self, key: I) -> Option<(J, &V)>
    where
        I: IntoIterator<Item = B>,
        for<'a> J: FromIterator<&'a K>,
        K: Ord,
        B: Borrow<K>,
    {
        let (key, value) = self
            .internal_walk_collect_key(&mut key.into_iter().peekable())
            .ok()?;
        Some((key, self.node[value].value().as_ref()
            .expect("Walk terminated on a node that did not have a value, i.e., was not a proper key termination.")
        ))
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// # Examples
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a'], 1);
    ///
    /// assert_eq!(trie.get_key_value_mut(['a']), Some(("a".to_string(), &mut 1)));
    ///
    /// *trie.get_key_value_mut::<_, _, String>(['a']).as_mut().unwrap().1 = 2;
    /// assert_eq!(trie.get_key_value_mut::<_, _, String>(['a']), Some(("a".to_string(), &mut 2)));
    ///
    ///
    /// ```
    pub fn get_key_value_mut<I, B, J>(&mut self, key: I) -> Option<(J, &mut V)>
    where
        I: IntoIterator<Item = B>,
        for<'a> J: FromIterator<&'a K>,
        K: Ord,
        B: Borrow<K>,
    {
        let (key, value) = self
            .internal_walk_collect_key(&mut key.into_iter().peekable())
            .ok()?;
        Some((key, self.node[value].value_mut().as_mut().expect("Iteration erroneously terminated on non-leaf node.")))
    }

    /// Removes a key from the [Trie], returning the computed key and value
    /// if the key was previously in the map.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a'], 2);
    ///
    /// assert_eq!(trie.remove_entry::<_, _, String>(['a']), Some(("a".to_string(), 2)));
    ///
    /// ```
    ///
    pub fn remove_entry<I, B, J>(&mut self, key: I) -> Option<(J, V)>
    where
        I: IntoIterator<Item = B>,
        J: FromIterator<K>,
        K: Ord + Clone,
        B: Borrow<K>,
    {
        let mut path = vec![];
        let trajectory = self
            .internal_walk_with_path_fn(key.into_iter().peekable().by_ref(), |nk| {
                self.fold_in_key_optionally(nk, &mut path)
            })
            .ok()?;

        let traj_path = trajectory.path.last().copied();

        if traj_path.is_some() {
            let reconstruction = path.into_iter().cloned().collect::<J>();
            let value = self.remove_post_walk(&trajectory.path)?;
            Some((reconstruction, value))
        } else {
            self.remove_post_walk(&trajectory.path)?;
            None
        }
    }

    /// Reserves capacity for at least additional more elements to be inserted in the [Trie].
    /// The collection may reserve more space to avoid frequent reallocations.
    pub fn reserve(&mut self, space: usize) {
        self.node.reserve(space);
    }
    /// Deletes a record from the [Trie] according to the
    /// key. It will return the old value if it is present within the
    /// data structure.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    /// tree.insert("hello".chars(), 12);
    ///
    /// assert_eq!(tree.remove("hello".chars()).unwrap(), 12);
    /// ```
    pub fn remove<I, B>(&mut self, master: I) -> Option<V>
    where
        I: IntoIterator<Item = B>,
        K: Ord,
        B: Borrow<K>,
    {
        // Calculate the removal trajectory.
        let trajectory = self
            .internal_walk_with_path(master.into_iter().peekable().by_ref())
            .ok()?;

        // Remove and then correct the removal.
        self.remove_post_walk(&trajectory.path)
    }

    /// Detaches a node and its subkeys recursively. Since subkeys are
    /// always dependent on their parent, this is equivalent to just deleting
    /// a subtree.
    fn detach_node(&mut self, source: NodeIndex) {
        let keys = self.node[source].subkeys().copied().collect::<Vec<_>>();
        for i in keys {
            self.detach_node(i);
        }
        self.node.remove(source);
    }
    /// Performs the actual removal from the [Trie]. This will
    /// traverse back from the node using the calculated trajectory
    /// in order to remove the node from the [Trie].
    ///
    /// This method exists to allow us to easily implement remove entry
    /// without having to walk the tree a second time to reconstruct the [Trie].
    fn remove_post_walk(&mut self, path: &[NodeIndex]) -> Option<V>
    where
        K: Ord,
    {
        let internal_value = self.node[*path.last()?].value_mut().take();

        if internal_value.is_some() {
            self.size -= 1;
        }
        let mut sub_index: isize = (path.len() - 1) as isize;

        // Starting at the very end, this travels up the tree, removing
        // all nodes attached to the tail that are no longer valid.
        while sub_index >= 0 {
            // Selected index.
            let sh_index = path[sub_index as usize];

            // If we do not have children...
            // WHY? Because if we have children, clearly this forms
            // part of a superkey, and thus removing it would then remove
            // that as well. Consider:
            //
            // "Yes"
            // "Yesman"
            //
            // Both of these share a subtree, but deleting "Yes" should
            // not also delete "Yesman".
            if self.node[sh_index].sub_key_len() == 0 && self.node[sh_index].value().is_none() {
                // Detach the node....
                self.detach_node(sh_index);

                // Then if there is something that is above it, remove it.
                if sub_index > 0 {
                    let above = path[(sub_index - 1) as usize];
                    self.node[above].remove_subkey(sh_index);
                }
            } else {
                // If we have children, then clearly this is a valid path, so we will
                // not detach it and thus the path that preceeds this node is still valid,
                // so there is no purpose in continuation.
                break;
            }
            sub_index -= 1;
        }

        internal_value
    }
    /// Checks if the [Trie] contains a key. This operation
    /// occurs in the same time as [Trie::get].
    pub fn contains_key<I>(&self, master: I) -> bool
    where
        I: Iterator<Item = K>,
        K: Ord,
    {
        self.get(master).is_some()
    }
    /// Checks if the [Trie] contains a value. This operation will
    /// perform a linear search of the tree and thus [Trie::get] and
    /// [Trie::get_mut] should be used instead.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    /// tree.insert("hello".chars(), 12);
    ///
    /// assert!(tree.contains_value(&12));
    /// assert!(!tree.contains_value(&11));
    ///
    /// ```
    pub fn contains_value(&self, value: &V) -> bool
    where
        V: Eq,
    {
        self.node
            .iter()
            .any(|(_, v)| v.value().as_ref().is_some_and(|inner| inner == value))
    }

    /// Puts a new record in the [Trie], returning the old value
    /// if there previously was a value present.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    /// tree.insert("hello".chars(), 1);
    ///
    /// // Verify the key is in the tree.
    /// assert_eq!(*tree.get("hello".chars()).unwrap(), 1);
    ///
    /// // Verify the key replacement.
    /// assert_eq!(tree.insert("hello".chars(), 2).unwrap(), 1);
    /// ```
    pub fn insert<I>(&mut self, master: I, value: V) -> Option<V>
    where
        I: IntoIterator<Item = K>,
        K: Ord,
    {
        match self.internal_walk_with_index(master.into_iter().peekable().by_ref()) {
            Ok(v) => {
                // This node already exists, so replace it and then return
                // the previous value.
                let current = self.node[v].value_mut().take();
                if current.is_none() {
                    self.size += 1;
                }
                *self.node[v].value_mut() = Some(value);

 
                current
            }
            Err(WalkFailure {
                mut root,
                remainder,
            }) => {
                
                let mut nk = root;
                for item in remainder {
                    nk = self.node.insert(Node::keyed(item));
                    self.node.insert_subkey(root, nk);
                    root = nk;
                }
                *self.node[nk].value_mut() = Some(value);
                self.size += 1;
                None
            }
        }
    }

    /// This will remove any unused space in the underlying arena allocator and
    /// then shrink the arena to fit this data. This can help improve cache locality.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a'], 1);
    /// trie.insert(['d'], 2);
    /// trie.insert(['b'], 3);
    /// trie.insert(['b', 'c'], 4);
    ///
    /// trie.remove(['d']);
    /// trie.shrink_to_fit();
    ///
    /// assert_eq!(trie.get(['a']), Some(&1));
    /// assert_eq!(trie.get(['d']), None);
    /// assert_eq!(trie.get(['b']), Some(&3));
    /// assert_eq!(trie.get(['b', 'c']), Some(&4));
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.node.defragment();
        self.node.shrink_to_fit();
    }
}

#[derive(Debug)]
pub struct CompletionIter<'a, K, V, J> {
    trie: &'a Trie<K, V>,
    /// The root path.
    beginning: Vec<&'a K>,
    /// The list of completions, this functions as a bump
    /// allocator and is used to build out the list.
    inner: WalkCtx,
    /// The value to which the iterators will be transformed during iteration.
    _transform: PhantomData<J>,
}

#[derive(Debug)]
pub struct PostfixIter<'a, K, V, J> {
    trie: &'a Trie<K, V>,
    /// The list of completions, this functions as a bump
    /// allocator and is used to build out the list.
    inner: WalkCtx,
    /// The value to which the iterators will be transformed during iteration.
    _transform: PhantomData<J>,
}

impl<I, K, V> Index<I> for Trie<K, V>
where
    I: IntoIterator<Item = K>,
    K: Ord,
{
    type Output = V;

    /// Returns a reference to the value corresponding to the supplied key.
    ///
    /// # Panics
    /// Panics if the key is not present in the [Trie].
    ///
    /// # Example
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie = Trie::<char, usize>::new();
    ///
    /// trie.insert(['a'], 1);
    ///
    /// assert_eq!(trie[['a']], 1);
    ///
    /// ```
    fn index(&self, index: I) -> &Self::Output {
        self.get(index).as_ref()
            .expect("Could not find index in Trie!")
    }
}

impl<'a, K, V, J> Iterator for CompletionIter<'a, K, V, J>
where
    J: FromIterator<&'a K>,
{
    type Item = (J, &'a V);

    /// Gets the next completion. This is comptued lazily.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, ()>::new();
    /// tree.insert("hello".chars(), ());
    /// tree.insert("hey".chars(), ());
    ///
    ///
    /// let mut values = tree.completions("he".chars())
    ///     .into_iter()
    ///     .collect::<Vec<(String, &())>>();
    ///
    /// values.sort();
    ///
    ///
    /// assert_eq!(values[0].0, "hello");
    /// assert_eq!(values[1].0, "hey");
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (current, path) = self.inner.drive(self.trie)?;

        let key = assemble_completion(self.trie, &self.beginning, path);

        Some((key, self.trie.node[current].value().as_ref().expect("Iteration erroneously terminated on non-leaf node.")))
    }
}

impl<'a, K, V, J> Iterator for PostfixIter<'a, K, V, J>
where
    J: FromIterator<&'a K>,
{
    type Item = (J, &'a V);

    /// Gets the next completion. This is comptued lazily.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, ()>::new();
    /// tree.insert("hello".chars(), ());
    /// tree.insert("hey".chars(), ());
    ///
    ///
    /// let mut values = tree.postfix_search("he".chars())
    ///     .into_iter()
    ///     .collect::<Vec<(String, &())>>();
    /// assert_eq!(values.len(), 2);
    ///
    ///
    /// assert_eq!(values[0].0, "llo");
    /// assert_eq!(values[1].0, "y");
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (current, path) = self.inner.drive(self.trie)?;

        let key = path
            .iter()
            .map(|f| self.trie.node[*f].key())
            .filter_map(|f| f.as_ref())
            .skip(1);
        Some((
            key.collect(),
            self.trie.node[current].value().as_ref().expect("Walk terminated on a non-leaf node. This means that the internal structure of the Trie is corrupted or there is an error in the WalkCtx implementation."),
        ))
    }
}

fn assemble_completion<'a, K, V, J>(
    trie: &'a Trie<K, V>,
    beginning: &Vec<&'a K>,
    walked: Vec<NodeIndex>,
) -> J
where
    J: FromIterator<&'a K>,
{
    let tail_end = walked
        .into_iter()
        .map(|nk| trie.node[nk].key())
        .filter_map(<Option<K>>::as_ref);

    beginning
        .iter()
        // The following lines just omit the very last element.
        .rev()
        .skip(1)
        .rev()
        .copied()
        .chain(tail_end)
        .collect::<J>()
}

impl<K, V, I> IndexMut<I> for Trie<K, V>
where
    K: Ord,
    I: IntoIterator<Item = K>,
{
    /// Indexes mutably into the [Trie] using an iterator index.
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, i32>::from([
    ///     ("apple".chars(), 4)
    /// ]);
    ///
    /// tree["apple".chars()] = 5;
    ///
    /// assert_eq!(tree["apple".chars()], 5);
    /// ```
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        self.get_mut(index).expect("Invalid trie index")
    }
}

/// An iterator created by consuming the [Trie].
/// Contains all the entries of the [Trie].
pub struct EntryIterMut<'a, K, V, J> {
    /// The internal reference to the [Trie].
    trie: &'a mut Trie<K, V>,
    /// The walk context for iterating over the fields.
    inner: WalkCtx,
    /// The type that we will collect into. Although technically
    /// we could collect into a different type on each iteration, we
    /// want to avoid this type of strange behaviour and streamline
    /// the process.
    _type: PhantomData<J>,
}

/// An iterator created by consuming the [Trie].
///
/// Contains all the entries of the [Trie].
pub struct IntoEntryIter<K, V, J> {
    trie: Trie<K, V>,
    inner: WalkCtx,
    _type: PhantomData<J>,
}

/// An iterator created by consuming the [Trie].
///
/// Contains all the entries of the [Trie].
pub struct EntryIterRef<'a, K, V, J> {
    inner: WalkIter<'a, K, V>,
    _type: PhantomData<J>,
}

/// An iterator created by consuming the [Trie].
///
/// Contains all the keys of the [Trie].
pub struct KeyIter<'a, K, V, J> {
    inner: WalkIter<'a, K, V>,
    _type: PhantomData<J>,
}

/// An iterator created by consuming the [Trie].
///
/// Contains all the elements of the [Trie].
pub struct ValueIter<V> {
    inner: IntoIter<V>,
}

/// An iterator over the values of a [Trie].
pub struct ValueIterRef<'a, K, V> {
    values: std::slice::Iter<'a, Option<Node<K, V>>>,
}

/// An iterator over the values of a [Trie]
/// that provides mutable references.
pub struct ValueIterMut<'a, K, V> {
    values: SlotsIterMut<'a, K, V>,
}

impl<V> Trie<char, V> {
    /// A special implementation of [Trie::insert] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    /// ```
    pub fn insert_str(&mut self, key: &str, value: V) -> Option<V> {
        self.insert(key.chars(), value)
    }
    /// A special implementation of [Trie::remove] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// assert!(trie.remove_str("hello").is_none());
    /// ```
    pub fn remove_str(&mut self, key: &str) -> Option<V> {
        self.remove(key.chars())
    }
    /// A special implementation of [Trie::contains_key] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    ///
    /// assert!(trie.contains_key_str("hello"));
    /// assert!(!trie.contains_key_str("hey"));
    ///
    ///
    /// ```
    pub fn contains_key_str(&self, key: &str) -> bool {
        self.contains_key(key.chars())
    }
    /// A special implementation of [Trie::is_prefix] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    ///
    /// assert!(trie.is_prefix_str("hello"));
    /// assert!(trie.is_prefix_str("he"));
    /// assert!(!trie.is_prefix_str("hellop"));
    ///
    ///
    /// ```
    pub fn is_prefix_str(&self, key: &str) -> bool {
        self.is_prefix(key.chars())
    }
    /// A special implementation of [Trie::completions] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    /// trie.insert_str("hey", 1);
    /// trie.insert_str("james", 2);
    ///
    /// let mut values = trie.completions_str("he");
    /// assert_eq!(values.next().unwrap().0.as_str(), "hello");
    /// assert_eq!(values.next().unwrap().0.as_str(), "hey");
    /// ```
    pub fn completions_str(&self, key: &str) -> CompletionIter<'_, char, V, String> {
        self.completions(key.chars())
    }
    /// A special implementation of [Trie::postfix_search] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    /// trie.insert_str("hey", 1);
    /// trie.insert_str("james", 2);
    ///
    /// let mut values = trie.postfix_search_str("he");
    /// assert_eq!(values.next().unwrap().0.as_str(), "llo");
    /// assert_eq!(values.next().unwrap().0.as_str(), "y");
    /// ```
    pub fn postfix_search_str(&self, key: &str) -> PostfixIter<'_, char, V, String> {
        self.postfix_search(key.chars())
    }
    /// A special implementation of [Trie::longest_prefix_entry] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    /// trie.insert_str("hey", 1);
    /// trie.insert_str("james", 2);
    ///
    /// assert_eq!(trie.longest_prefix_entry_str("hello"), Some(("hello".to_string(), &3)));
    /// assert_eq!(trie.longest_prefix_entry_str("hellothere"), Some(("hello".to_string(), &3)));
    /// ```
    pub fn longest_prefix_entry_str(&self, key: &str) -> Option<(String, &V)> {
        self.longest_prefix_entry(key.chars())
    }
    /// A special implementation of [Trie::longest_prefix] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    /// trie.insert_str("hello", 3);
    /// trie.insert_str("hey", 1);
    /// trie.insert_str("james", 2);
    ///
    /// assert_eq!(trie.longest_prefix_str("hello"), Some(&3));
    /// assert_eq!(trie.longest_prefix_str("hellothere"), Some(&3));
    /// ```
    pub fn longest_prefix_str(&self, key: &str) -> Option<&V> {
        self.longest_prefix(key.chars())
    }
    /// A special implementation of [Trie::keys] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = trie.keys_str();
    /// assert_eq!(key_iter.next().unwrap(), "bye");
    /// assert_eq!(key_iter.next().unwrap(), "hello");
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn keys_str(&self) -> KeyIter<'_, char, V, String> {
        self.keys()
    }
    /// A special implementation of [Trie::into_entries] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = trie.into_entries_str();
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), 3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), 4));
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn into_entries_str(self) -> IntoEntryIter<char, V, String> {
        self.into_entries()
    }
    /// A special implementation of [Trie::entries] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = trie.entries_str();
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), &3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), &4));
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn entries_str(&self) -> EntryIterRef<'_, char, V, String> {
        self.entries()
    }
    /// A special implementation of [Trie::entries_mut] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = trie.entries_mut_str();
    ///
    /// assert_eq!(*key_iter.next().unwrap().1, 3);
    /// assert_eq!(*key_iter.next().unwrap().1, 4);
    /// assert!(key_iter.next().is_none());
    /// ```
    pub fn entries_mut_str(&mut self) -> EntryIterMut<'_, char, V, String> {
        self.entries_mut()
    }
    /// A special implementation of [Trie::get] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut tree = StrTrie::<&str>::new();
    /// tree.insert_str("hello", "world");
    /// tree.insert_str("hellooo", "world2");
    /// assert_eq!(*tree.get_str("hello").unwrap(), "world");
    /// ```
    pub fn get_str(&self, key: &str) -> Option<&V> {
        self.get(key.chars())
    }
    /// A special implementation of [Trie::get_mut] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut tree = StrTrie::<&str>::new();
    /// tree.insert_str("hello", "world");
    /// assert_eq!(*tree.get_mut_str("hello").unwrap(), "world");
    ///
    /// *tree.get_mut_str("hello").unwrap() = "world2";
    /// assert_eq!(*tree.get_mut_str("hello").unwrap(), "world2");
    /// ```
    pub fn get_mut_str(&mut self, key: &str) -> Option<&mut V> {
        self.get_mut(key.chars())
    }
    /// A special implementation of [Trie::get_disjoint_mut] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut tree = StrTrie::<usize>::new();
    ///
    /// tree.insert_str("hello", 3);
    /// tree.insert_str("world", 4);
    ///
    /// let mut keys = tree.get_disjoint_mut_str([
    ///     "hello",
    ///     "world"
    /// ]);
    /// *keys[0].as_mut().unwrap() = 4;
    /// *keys[1].as_mut().unwrap() = 2;
    ///
    /// assert_eq!(tree.get_str("hello"), Some(&4));
    /// assert_eq!(tree.get_str("world"), Some(&2));
    /// ```
    pub fn get_disjoint_mut_str<const N: usize>(
        &mut self,
        key: [&str; N],
    ) -> DisjointMutIndices<'_, char, V, N> {
        let modded = core::array::from_fn(|i| key[i].chars());
        self.get_disjoint_mut(modded)
    }
    /// A special implementation of [Trie::try_get_disjoint_mut] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut tree = StrTrie::<usize>::new();
    ///
    /// tree.insert_str("hello", 3);
    /// tree.insert_str("world", 4);
    ///
    /// let mut keys = tree.try_get_disjoint_mut_str([
    ///     "hello",
    ///     "world"
    /// ]).unwrap();
    /// *keys[0].as_mut().unwrap() = 4;
    /// *keys[1].as_mut().unwrap() = 2;
    ///
    /// assert_eq!(tree.get_str("hello"), Some(&4));
    /// assert_eq!(tree.get_str("world"), Some(&2));
    /// ```
    pub fn try_get_disjoint_mut_str<const N: usize>(
        &mut self,
        key: [&str; N],
    ) -> Result<DisjointMutIndices<'_, char, V, N>, GetDisjointMutError> {
        let modded = core::array::from_fn(|i| key[i].chars());
        self.try_get_disjoint_mut(modded)
    }
    /// A special implementation of [Trie::get_key_value] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    ///
    /// trie.insert_str("abc", 1);
    ///
    /// assert_eq!(trie.get_key_value_str("abc"), Some(("abc".to_string(), &1)))
    ///
    /// ```
    pub fn get_key_value_str(&self, key: &str) -> Option<(String, &V)> {
        self.get_key_value(key.chars())
    }
    /// A special implementation of [Trie::get_key_value_mut] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    ///
    /// trie.insert_str("a", 1);
    ///
    /// assert_eq!(trie.get_key_value_mut_str("a"), Some(("a".to_string(), &mut 1)));
    ///
    /// *trie.get_key_value_mut_str("a").as_mut().unwrap().1 = 2;
    /// assert_eq!(trie.get_key_value_mut_str("a"), Some(("a".to_string(), &mut 2)));
    ///
    ///
    /// ```
    pub fn get_key_value_mut_str(&mut self, key: &str) -> Option<(String, &mut V)> {
        self.get_key_value_mut(key.chars())
    }
    /// A special implementation of [Trie::remove_entry] designed specifically for
    /// strings.
    ///
    /// NOTE: This is just a helper method. There are no string-based optimizations
    /// going on here.
    ///
    /// # Example
    /// ```
    /// use rstrie::StrTrie;
    ///
    /// let mut trie = StrTrie::<usize>::new();
    ///
    /// trie.insert_str("a", 2);
    ///
    /// assert_eq!(trie.remove_entry_str("a"), Some(("a".to_string(), 2)));
    ///
    /// ```
    pub fn remove_entry_str(&mut self, key: &str) -> Option<(String, V)> {
        self.remove_entry(key.chars())
    }
}

impl<K, V, J> Iterator for IntoEntryIter<K, V, J>
where
    for<'b> J: FromIterator<&'b K>,
{
    type Item = (J, V);

    /// Iterates over the mutably borrowed entries within a [Trie].
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.into_entries::<String>();
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), 3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), 4));
    /// assert!(key_iter.next().is_none());
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (current, path) = { self.inner.drive(&self.trie)? };

        let calced = self.trie.collect_path_keys::<J>(&path);

        Some((calced, self.trie.node[current].value_mut().take().expect("Iteration terminated erroneously on a non-leaf node.")))
    }
}

impl<'a, K, V, J> Iterator for EntryIterMut<'a, K, V, J>
where
    for<'b> J: FromIterator<&'b K>,
{
    type Item = (J, ValueSlot<'a, K, V>);

    /// Iterates over the mutably borrowed entries within a [Trie].
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.entries_mut::<String>();
    ///
    /// assert_eq!(*key_iter.next().unwrap().1, 3);
    /// assert_eq!(*key_iter.next().unwrap().1, 4);
    /// assert!(key_iter.next().is_none());
    ///
    /// let mut key_iter = tree.entries_mut::<String>();
    ///
    /// *key_iter.next().unwrap().1 = 5;
    ///
    ///
    /// let mut key_iter = tree.entries_mut::<String>();
    ///
    /// assert_eq!(*key_iter.next().unwrap().1, 5);
    /// assert_eq!(*key_iter.next().unwrap().1, 4);
    /// assert!(key_iter.next().is_none());
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (current, path) = { self.inner.drive(self.trie)? };

        let calced = self.trie.collect_path_keys::<J>(&path);

        // SAFETY: The borrow checker does not know that subsequent calls return distinct
        // nodes, and thus the aliasing rules are upheld and we only have a single mutable reference at a time.
        let candidate = unsafe { &mut *(&mut self.trie.node[current] as *mut Node<K, V>) };

        Some((calced, ValueSlot { node: candidate }))
    }
}

pub struct ValueSlot<'a, K, V> {
    node: &'a mut Node<K, V>,
}

impl<K, V> Deref for ValueSlot<'_, K, V> {
    type Target = V;
    fn deref(&self) -> &Self::Target {
        self.node.value().as_ref().expect("Tried to read node value but was None.")
    }
}

impl<K, V> DerefMut for ValueSlot<'_, K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.node.value_mut_unchecked()
    }
}

impl<K, V> PartialEq for Trie<K, V>
where
    K: PartialEq,
    V: PartialEq,
{
    /// Checks if two [Trie] are equal.
    fn eq(&self, other: &Self) -> bool {
        self.node.eq(&other.node)
    }
}

impl<'a, K, V, J> Iterator for EntryIterRef<'a, K, V, J>
where
    J: FromIterator<&'a K>,
{
    type Item = (J, &'a V);

    /// Iterates over the owned entries within a [Trie].
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::from([
    ///     ("hello".chars(), 4),
    ///     ("bye".chars(), 3)
    /// ]);
    ///
    /// let mut key_iter = tree.into_entries::<String>();
    ///
    ///
    /// assert_eq!(key_iter.next().unwrap(), ("bye".to_string(), 3));
    /// assert_eq!(key_iter.next().unwrap(), ("hello".to_string(), 4));
    /// assert!(key_iter.next().is_none());
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (curr, path) = self.inner.next()?;

        Some((
            self.inner.trie.collect_path_keys(&path),
            self.inner.trie.node[curr].value().as_ref()
                .expect("Walk terminated on non-leaf node.")
        ))
    }
}

impl<'a, K, V, J> Iterator for KeyIter<'a, K, V, J>
where
    J: FromIterator<&'a K>,
{
    type Item = J;

    /// Iterates over the owned keys within a [Trie].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.keys::<String>();
    ///
    /// assert_eq!(values.next().unwrap(), "bye");
    /// assert_eq!(values.next().unwrap(), "hello");
    /// assert_eq!(values.next().as_ref(), None);
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let (_, path) = self.inner.next()?;
        Some(self.inner.trie.collect_path_keys(&path))
    }
}

impl<V> Iterator for ValueIter<V> {
    type Item = V;

    /// Iterates over the owned values within a [Trie].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.into_values();
    ///
    /// assert_eq!(values.next(), Some(1));
    /// assert_eq!(values.next(), Some(2));
    /// assert_eq!(values.next(), None);
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a, K, V> Iterator for ValueIterMut<'a, K, V> {
    type Item = &'a mut V;

    /// Iterates over the values mutably within a [Trie].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.values_mut();
    ///
    /// assert_eq!(values.next().cloned(), Some(1));
    /// assert_eq!(values.next().cloned(), Some(2));
    /// assert_eq!(values.next().cloned(), None);
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let mut current = None;
        while current.is_none() {
            // The INITIAL option can be propagated because this is the iterator one,
            // so if this is none then we are done anyways.
            let node = self.values.next()?;
            // We need to extract the value, and we continue until the value is something.
            current = node.value_mut().as_mut();
        }

        current
    }
}

fn map_node_to_value<K, V>(option: Option<&Node<K, V>>) -> Option<&V> {
    let val = option?;
    val.value().as_ref()
}

impl<'a, K, V> Iterator for ValueIterRef<'a, K, V> {
    type Item = &'a V;

    /// Iterates over the values within a [Trie].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree = Trie::<char, usize>::new();
    ///
    /// tree.insert("hello".chars(), 1);
    /// tree.insert("bye".chars(), 2);
    ///
    ///
    /// let mut values  = tree.values();
    ///
    /// assert_eq!(values.next().cloned(), Some(1));
    /// assert_eq!(values.next().cloned(), Some(2));
    /// assert_eq!(values.next().cloned(), None);
    /// ```
    fn next(&mut self) -> Option<Self::Item> {
        let mut current = None;
        while current.is_none() {
            // The INITIAL option can be propagated because this is the iterator one,
            // so if this is none then we are done anyways.
            let node = self.values.next()?;
            // We need to extract the value, and we continue until the value is something.
            current = map_node_to_value(node.as_ref());
        }

        current
    }
}

impl<KP, K, V> Extend<(KP, V)> for Trie<K, V>
where
    K: Ord,
    KP: IntoIterator<Item = K>,
{
    /// Extends a [Trie] from an iterator of tuples. The tuples must contain
    /// a valid key element, that is, it can be converted to an iterator
    /// of the sub-element. For instance, for [str] this is usually [char].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree: Trie<char, &str> = Trie::new();
    /// assert_eq!(tree.len(), 0);
    ///
    /// tree.extend([ ("hello".chars(), "world") ].into_iter());
    ///
    /// assert_eq!(*tree.get("hello".chars()).unwrap(), "world");
    ///
    /// ```
    #[inline]
    fn extend<T: IntoIterator<Item = (KP, V)>>(&mut self, iter: T) {
        for (key, value) in iter {
            self.insert(key, value);
        }
    }
}

impl<'a, KP, K, V> Extend<(KP, &'a V)> for Trie<K, V>
where
    K: Ord,
    V: Clone,
    KP: IntoIterator<Item = K>,
{
    /// Extends a [Trie] from an iterator of tuples. The tuples must contain
    /// a valid key element, that is, it can be converted to an iterator
    /// of the sub-element. For instance, for [str] this is usually [char].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree: Trie<char, &str> = Trie::new();
    /// assert_eq!(tree.len(), 0);
    ///
    /// tree.extend([ ("hello".chars(), "world") ].into_iter());
    ///
    /// assert_eq!(*tree.get("hello".chars()).unwrap(), "world");
    ///
    /// ```
    #[inline]
    fn extend<T: IntoIterator<Item = (KP, &'a V)>>(&mut self, iter: T) {
        for (key, value) in iter {
            self.insert(key, value.clone());
        }
    }
}

impl<KP, K, V> FromIterator<(KP, V)> for Trie<K, V>
where
    K: Ord,
    KP: IntoIterator<Item = K>,
{
    /// Creates a [Trie] from an iterator of tuples. The tuples must contain
    /// a valid key element, that is, it can be converted to an iterator
    /// of the sub-element. For instance, for [str] this is usually [char].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut tree: Trie<char, usize> = Trie::from_iter([
    ///     ("hello".chars(), 4)
    /// ].into_iter());
    ///
    /// assert_eq!(tree.len(), 1);
    /// assert_eq!(*tree.get("hello".chars()).unwrap(), 4);
    /// ```
    fn from_iter<T: IntoIterator<Item = (KP, V)>>(iter: T) -> Self {
        let mut map = Trie::new();
        map.extend(iter);
        map
    }
}

impl<KP, K, V, const N: usize> From<[(KP, V); N]> for Trie<K, V>
where
    K: Ord,
    KP: IntoIterator<Item = K>,
{
    /// Creates a [Trie] from an array of tuples. The tuples must contain
    /// a valid key element, that is, it can be converted to an iterator
    /// of the sub-element. For instance, for [str] this is usually [char].
    ///
    /// ```
    /// use rstrie::Trie;
    ///
    /// let mut trie: Trie<char, i32> = Trie::from([
    ///     ("hello".chars(), 4)
    /// ]);
    ///
    /// assert_eq!(trie.len(), 1);
    /// assert_eq!(*trie.get("hello".chars()).unwrap(), 4);
    /// ```
    fn from(arr: [(KP, V); N]) -> Self {
        Self::from_iter(arr)
    }
}

pub struct Drain<'a, K, V, J> {
    key_iter: std::vec::IntoIter<J>,
    inner: std::vec::Drain<'a, Option<Node<K, V>>>,
}

impl<K, V, J> Iterator for Drain<'_, K, V, J> {
    type Item = (J, V);
    fn next(&mut self) -> Option<Self::Item> {
        let mut current = None;
        while current.is_none() {
            // This is okay to propagate.
            if let Some(node) = self.inner.next()? {
                current = node.into_value();
            }
        }
        Some((self.key_iter.next()?, current.expect("The current iterating node was supposedly filled, but turned out to be None.")))
    }
}

pub enum TryGetKeyMapError {
    KeyDoesNotExist,
    Duplicate(usize)
}

impl std::fmt::Display for TryGetKeyMapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::KeyDoesNotExist => f.write_str("KeyDoesNotExist"),
            Self::Duplicate(i) => write!(f, "Duplicate({i})")
        }
    }
}

impl std::fmt::Debug for TryGetKeyMapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <Self as std::fmt::Display>::fmt(self, f)
    }
}

impl Error for TryGetKeyMapError {

    fn description(&self) -> &str {
        match self {
            Self::Duplicate(_) => "There was a duplicate key, they were not disjoint.",
            Self::KeyDoesNotExist => "Failed to get one of the keys from the slotmap"
        }
    }
}

#[cfg(feature = "arbitrary")]
mod arbitrary_trie {
    use core::f32;
    use arbitrary::{Arbitrary, Unstructured};

    use crate::Trie;

    fn random_norm_float(u: &mut Unstructured<'_>) -> arbitrary::Result<f32> {
        Ok(f32::from_bits(u32::arbitrary(u)?).abs() / f32::MAX)
    }

    impl<'a, K, V> Arbitrary<'a> for Trie<K, V>
    where
        K: Arbitrary<'a> + Ord + Clone,
        V: Arbitrary<'a>,
    {
        fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
            let mut trie = Trie::<K, V>::new();
            let trie_length = u16::arbitrary(u)? as usize;
            let mut buffer = Vec::new();
            for _ in 0..trie_length {
                let vector: Vec<K> = Vec::arbitrary(u)?;
                let value = V::arbitrary(u)?;

                buffer.push(Some(vector.clone()));

                trie.insert(vector.into_iter(), value);
            }

            let thres = random_norm_float(u)?;
            for i in 0..buffer.len() {
                if random_norm_float(u)? < thres {
                    let key = buffer.get_mut(i)
                        .ok_or(arbitrary::Error::IncorrectFormat)?
                        .take()
                        .ok_or(arbitrary::Error::IncorrectFormat)?;

                    trie.remove(key.into_iter());
                }
            }

            Ok(trie)
        }
    }
}

#[cfg(test)]
mod tests {

    use std::{cmp::Reverse, time::Duration};

    use super::Trie;

    #[test]
    #[cfg(feature = "arbitrary")]
    pub fn test_arbitrary_crate() {
        use arbitrary::{Arbitrary, Unstructured};
        use rand::Rng;

        let val: [u8; 12] = rand::rng().random();

        let trie: Trie<char, usize> = Trie::arbitrary(&mut Unstructured::new(&val)).unwrap();
        let trie2: Trie<char, usize> = Trie::arbitrary(&mut Unstructured::new(&val)).unwrap();
        assert_eq!(trie, trie2);
    }

    #[test]
    pub fn test_root_len_mod() {
        let mut trie = Trie::<char, usize>::new();

        assert_eq!(trie.len(), 0);
        trie.insert_str("", 3);
        assert_eq!(trie.len(), 1);

        trie.insert_str("", 4);
        assert_eq!(trie.len(), 1);

        trie.remove_str("");
        assert_eq!(trie.len(), 0);
    }

    #[test]
    pub fn test_size_duplicates() {
        let mut trie = Trie::<char, usize>::from([
            ("hello".chars(), 4),
            ("hey".chars(), 3),
            ("hamburger".chars(), 10),
        ]);

        assert_eq!(trie.len(), 3);
        trie.insert("hello".chars(), 4);
        assert_eq!(trie.len(), 3);

        trie.insert("heman".chars(), 10);
        assert_eq!(trie.len(), 4);

        trie.remove("heman".chars());
        assert_eq!(trie.len(), 3);

        trie.remove("heman".chars());
        assert_eq!(trie.len(), 3);

        trie.remove("albert".chars());
        assert_eq!(trie.len(), 3);
    }

    #[test]
    #[cfg(all(feature = "arbitrary", feature = "serde"))]
    pub fn arbtest_arb_impl() {
        use arbitrary::Arbitrary;

        arbtest::arbtest(|u| {
            let standard = Trie::<char, usize>::arbitrary(u)?;
            let reversed: Trie<char, usize> =
                serde_json::from_slice(&serde_json::to_vec(&standard).unwrap()).unwrap();
            assert_eq!(standard, reversed);
            Ok(())
        })
        .budget(Duration::from_secs(5));
    }

    #[test]
    pub fn test_delete_root_vector() {
        let mut root = Trie::<char, usize>::from([("hello".chars(), 4)]);
        root.insert([], 5);
        root.remove::<[char; 0], char>([]);
        root.remove::<[char; 0], char>([]);
    }

    #[test]
    #[cfg(all(feature = "rkyv", feature = "serde"))]
    pub fn arbtest_arb_impl_rkyv() {
        use arbitrary::Arbitrary;
        use rkyv::rancor::Error;

        arbtest::arbtest(|u| {
            let standard = Trie::<char, u64>::arbitrary(u)?;

            // println!("STADNAR: {:?}", standard);

            let archived = rkyv::to_bytes::<Error>(&standard).unwrap();

            let archived: Trie<char, u64> = rkyv::from_bytes::<_, Error>(&archived).unwrap();

            // let reversed: Trie<char, usize> = serde_json::from_slice(&serde_json::to_vec(&standard).unwrap()).unwrap();
            assert_eq!(standard, archived);
            Ok(())
        })
        .budget(Duration::from_secs(5));
    }

    #[test]
    #[cfg(feature = "serde")]
    pub fn test_serde_serialize_map() {
        let tree = Trie::<char, usize>::from([("hello".chars(), 4), ("hey".chars(), 5)]);

        let val = serde_json::to_vec(&tree).unwrap();
        let tree2: Trie<char, usize> = serde_json::from_slice(&val).unwrap();
        assert_eq!(tree, tree2);
    }

    #[test]
    pub fn trie_get_kv_properly() {
        let trie: Trie<char, i32> = Trie::from([(['h', 'e', 'l', 'l', 'o'], 4)]);

        assert_eq!(
            trie.get_key_value::<_, _, String>("hello".chars()),
            Some(("hello".to_string(), &4))
        );
    }

    #[test]
    pub fn test_entry_mut() {
        let mut tree = Trie::<char, usize>::from([("hello".chars(), 4), ("bye".chars(), 3)]);

        let mut key_iter = tree.entries_mut::<String>();

        assert_eq!(*key_iter.next().unwrap().1, 3);
        assert_eq!(*key_iter.next().unwrap().1, 4);

        assert!(key_iter.next().is_none());

        let mut key_iter = tree.entries_mut::<String>();

        *key_iter.next().unwrap().1 = 5;

        let mut key_iter = tree.entries_mut::<String>();

        assert_eq!(*key_iter.next().unwrap().1, 5);
        assert_eq!(*key_iter.next().unwrap().1, 4);
        assert!(key_iter.next().is_none());
    }

    #[test]
    pub fn trie_from_tuples() {
        let trie: Trie<char, i32> = Trie::from([("hello".chars(), 4)]);
        assert_eq!(trie.get("hello".chars()), Some(&4));
    }

    #[test]
    pub fn trie_disjoint_mut() {
        let mut tree = Trie::<char, usize>::new();

        tree.insert("hello".chars(), 3);
        tree.insert("world".chars(), 4);

        let mut keys = tree.get_disjoint_mut(["hello".chars(), "world".chars()]);

        *keys[0].as_mut().unwrap() = 4;
        *keys[1].as_mut().unwrap() = 2;

        assert_eq!(tree.get("hello".chars()), Some(&4));
        assert_eq!(tree.get("world".chars()), Some(&2));
    }

    #[test]
    pub fn test_trie_equality_simple() {
        let trie_1 = Trie::from([("hello".chars(), 3), ("good".chars(), 2)]);
        let trie_2 = Trie::from([("hello".chars(), 3), ("good".chars(), 2)]);
        let trie_3 = Trie::from([("hello".chars(), 3), ("good".chars(), 3)]);
        assert_eq!(trie_1, trie_2);
        assert_ne!(trie_1, trie_3);
    }

    #[test]
    pub fn test_into_values() {
        let trie: Trie<char, usize> = Trie::from([("".chars(), 1), ("tra".chars(), 2)]);

        let mut values = trie.into_values();
        assert_eq!(values.next(), Some(1));
        assert_eq!(values.next(), Some(2));
    }

    #[test]
    pub fn test_removal_subword() {
        let mut trie_1 = Trie::from([("hello".chars(), 3), ("good".chars(), 2)]);

        trie_1.insert("go".chars(), 8);
        assert_eq!(trie_1.remove("go".chars()), Some(8));
        assert!(trie_1.contains_key("good".chars()));

        // panic!("ye");
    }

    #[test]
    pub fn test_trie_equality_complex() {
        let mut trie_1 = Trie::from([("hello".chars(), 3), ("good".chars(), 2)]);
        let mut trie_2 = Trie::from([("hello".chars(), 3), ("good".chars(), 2)]);
        trie_2.remove("hello".chars());
        trie_2.insert("hey".chars(), 12);
        trie_2.insert("hello".chars(), 3);
        // trie_2.remove("hey".chars());

        trie_1.remove("good".chars());
        trie_1.insert("go".chars(), 8);
        trie_1.insert("hey".chars(), 12);

        assert!(trie_1.contains_key("hey".chars()));
        trie_1.insert("good".chars(), 2);
        trie_1.remove("go".chars());
        assert!(trie_1.contains_key("good".chars()));

        assert_eq!(trie_1, trie_2);
        // assert_ne!(trie_1, trie_3);
    }

    #[test]
    pub fn trie_test_defragment() {
        let mut trie = Trie::<char, usize>::new();

        trie.insert(['a'], 1);
        trie.insert(['d'], 2);
        trie.insert(['b'], 3);
        trie.insert(['b', 'c'], 4);

        //
        assert_eq!(trie.get(['a']), Some(&1));
        assert_eq!(trie.get(['d']), Some(&2));
        assert_eq!(trie.get(['b']), Some(&3));
        assert_eq!(trie.get(['b', 'c']), Some(&4));

        trie.remove(['d']);

        assert_eq!(trie.get(['a']), Some(&1));
        assert_eq!(trie.get(['d']), None);
        assert_eq!(trie.get(['b']), Some(&3));
        assert_eq!(trie.get(['b', 'c']), Some(&4));

        trie.shrink_to_fit();

        assert_eq!(trie.get(['a']), Some(&1));
        assert_eq!(trie.get(['d']), None);
        assert_eq!(trie.get(['b']), Some(&3));
        assert_eq!(trie.get(['b', 'c']), Some(&4));
    }

    #[test]
    pub fn trie_into_values() {
        let mut tree = Trie::<char, usize>::new();

        tree.insert("hello".chars(), 1);
        tree.insert("bye".chars(), 2);

        let mut values = tree.into_values();

        assert_eq!(values.next(), Some(1));
        assert_eq!(values.next(), Some(2));
        assert_eq!(values.next(), None);
    }

    #[test]
    pub fn path_traversal_test() {
        let mut tree = Trie::<char, &str>::new();
        tree.insert(['t', 'e', 's', 't'], "sample_1");
        tree.insert("tea".chars(), "Sample_2");
    }

    #[test]
    pub fn basic_trie_insert() {
        let mut tree: Trie<char, &str> = Trie::new();
        tree.insert("test".chars(), "sample_1");
        tree.insert("testttt".chars(), "sample_2");
        assert!(tree.contains_key("test".chars()));
        assert_eq!(*tree.get("test".chars()).unwrap(), "sample_1");
    }

    #[test]
    pub fn basic_trie_insert_multi_keys() {
        let mut tree: Trie<char, &str> = Trie::new();
        tree.insert("test".chars(), "sample_1");
        // tree.insert("george".chars(), "sample_2");

        println!("INSERTING TEA...");
        tree.insert("tea".chars(), "sample_3");

        for (key, value) in tree.node.iter() {
            println!("({key:?}) -> {value:?}");
        }

        // assert!(tree.contains_key("test".chars()));
        // assert!(tree.contains_key("george".chars()));
        println!("\n\n\nStarting Tea...");
        assert!(tree.contains_key("tea".chars()));
        assert_eq!(*tree.get("test".chars()).unwrap(), "sample_1");
        assert_eq!(*tree.get("tea".chars()).unwrap(), "sample_3");
    }

    #[test]
    pub fn basic_trie_deletion() {
        let mut tree: Trie<char, &str> = Trie::new();
        tree.insert("test".chars(), "sample_1");

        assert_eq!(tree.len(), 1);

        assert!(tree.contains_key("test".chars()));

        println!("Helo");

        tree.remove("test".chars());
        println!("Deleetign");
        assert!(!tree.contains_key("test".chars()));
        assert_eq!(tree.len(), 0);
    }

    #[test]
    pub fn trie_deletion_multikey() {
        let mut tree: Trie<char, &str> = Trie::new();
        tree.insert("test".chars(), "sample_1");
        tree.insert("tea".chars(), "sample_2");

        assert!(tree.contains_key("test".chars()));
        assert!(tree.contains_key("tea".chars()));

        tree.remove("tea".chars());
        assert!(!tree.contains_key("tea".chars()));
        assert!(tree.contains_key("test".chars()));
    }

    #[test]
    pub fn test_arbitrary_insert() {
        let mut tree: Trie<char, String> = Trie::new();
        arbtest::arbtest(|u| {
            let key: String = u.arbitrary::<[char; 32]>().unwrap().iter().collect();
            let value: String = u.arbitrary::<[char; 32]>().unwrap().iter().collect();
            tree.insert(key.chars(), value);

            assert!(tree.contains_key(key.chars()));

            Ok(())
        });
    }

    #[test]
    pub fn completions_test() {
        let mut tree = Trie::<char, ()>::new();
        tree.insert("hello".chars(), ());
        tree.insert("hey".chars(), ());
        tree.insert("james".chars(), ());

        let mut values = tree
            .completions::<_, _, String>("he".chars())
            .into_iter()
            .collect::<Vec<_>>();

        values.sort();

        assert_eq!(values.len(), 2);

        assert_eq!(values[0].0, "hello");
        assert_eq!(values[1].0, "hey");

        assert_eq!(
            tree.completions::<_, char, String>([])
                .map(|(a, _)| a)
                .collect::<Vec<_>>(),
            vec![
                String::from("hello"),
                String::from("hey"),
                String::from("james")
            ]
        );
        assert_eq!(
            tree.completions::<_, _, String>(['h', 'e', 'l', 'l', 'o'])
                .map(|(a, _)| a)
                .collect::<Vec<_>>(),
            vec![String::from("hello")]
        );
    }

    #[test]
    pub fn test_arbitrary_deletion() {
        let mut tree: Trie<char, String> = Trie::new();
        arbtest::arbtest(|u| {
            let key: String = u.arbitrary::<[char; 4]>().unwrap().iter().collect();
            let value: String = u.arbitrary::<[char; 4]>().unwrap().iter().collect();

            assert_eq!(
                tree.contains_key(key.chars()),
                tree.remove(key.chars()).is_some()
            );

            tree.insert(key.chars(), value);

            assert_eq!(
                tree.contains_key(key.chars()),
                tree.remove(key.chars()).is_some()
            );

            Ok(())
        })
        .budget(Duration::from_secs(3));
    }

    #[test]
    pub fn test_longest_prefix() {
        let mut trie = Trie::<char, usize>::new();

        trie.insert("he".chars(), 1);
        trie.insert("hel".chars(), 2);
        trie.insert("hello".chars(), 3);

        assert_eq!(
            trie.longest_prefix_entry("hello".chars()),
            Some(("hello".to_string(), &3))
        );
        assert_eq!(
            trie.longest_prefix_entry("hellothere".chars()),
            Some(("hello".to_string(), &3))
        );
    }

    #[test]
    pub fn test_entry_iter_mut_soundness() {
        let mut trie = Trie::from([("hello".chars(), 42), ("hey".chars(), 55)]);

        let wow = trie.entries_mut::<String>();
        for (_, mut val) in wow {
            *val = 23;
        }

        for (_, val) in trie.entries::<String>() {
            assert_eq!(*val, 23);
        }
    }

    #[test]
    pub fn test_longest_prefix_routing_table() {
        let mut trie = Trie::<bool, MatchRule>::new();

        fn convert_to_bits(val: u8) -> [bool; 8] {
            let mut result = [false; 8];
            for i in 0..8 {
                result[7 - i] = (val & (1 << i)) != 0;
                // println!("Value: {:08b}", );
            }
            result
        }

        #[derive(PartialEq, Eq, Debug)]
        enum MatchRule {
            Forward(u8),
            Delete,
        }

        // All addresses that start with 101 get forwarded to 3.
        trie.insert([true, false, true], MatchRule::Forward(3));

        // All addresses that start with 1010 get forwarded to 4;
        trie.insert([true, false, true, false], MatchRule::Forward(4));

        // All addresses that start with 1010001 get deleted
        trie.insert(
            [true, false, true, false, false, false, true],
            MatchRule::Delete,
        );

        assert_eq!(
            trie.longest_prefix(convert_to_bits(0b10100000u8)),
            Some(&MatchRule::Forward(4))
        );
        assert_eq!(
            trie.longest_prefix(convert_to_bits(0b10110000u8)),
            Some(&MatchRule::Forward(3))
        );
        assert_eq!(
            trie.longest_prefix(convert_to_bits(0b10100010u8)),
            Some(&MatchRule::Delete)
        );
    }

    #[test]
    pub fn test_scoring_fn() {
        let mut trie = Trie::<char, ()>::new();
        trie.insert("hello".chars(), ());
        trie.insert("he".chars(), ());
        trie.insert("hema".chars(), ());

        assert_eq!(
            trie.search_with_score_fn(|f| f.len()),
            Some(vec![&'h', &'e', &'l', &'l', &'o'])
        );
        assert_eq!(
            trie.search_with_score_fn(|f| Reverse(f.len())),
            Some(vec![&'h', &'e'])
        );
    }

    #[test]
    pub fn test_scoring_fn_levinstein() {
        let mut trie = Trie::<char, ()>::new();
        trie.insert("hello".chars(), ());
        trie.insert("he".chars(), ());
        trie.insert("hema".chars(), ());
        trie.insert("racecar".chars(), ());
        trie.insert("nissan".chars(), ());

        let lev = |target| {
            let lev_result = trie.search_with_score_fn(|f| {
                let string = f.iter().copied().collect::<String>();
                let distance = edit_distance::edit_distance(target, &string);
                Reverse(distance)
            });

            lev_result.map(|f| f.into_iter().copied().collect::<String>())
        };

        assert_eq!(lev("hello"), Some("hello".to_string()));
        assert_eq!(lev("niwan"), Some("nissan".to_string()));

        // assert_eq!(trie.search_with_score_fn(|f| f.len()), Some(vec![ &'h', &'e', &'l', &'l', &'o' ]));
        // assert_eq!(trie.search_with_score_fn(|f| Reverse(f.len())), Some(vec![ &'h', &'e' ]));
    }
}