alist 0.1.0

Association list offering fast lookups while preserving insertion order
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
//! # alist
//!
//! `alist` is a Rust crate for working with **association lists**,
//! a simple data structure inspired by Lisp.
//!
//! This implementation is backed by a `Vec` of key-value pairs,
//! preserving the order of insertions and enabling optimized
//! retrieval of items in `O(1)` under certain conditions.
//!
//! ## What is an Association List?
//!
//! An **association list (alist)** is a collection of key-value pairs.
//! It provides a lightweight alternative to hash-based data structures
//! for simple mappings or dictionary-like functionality, especially in
//! contexts where order and immutability are crucial.
//!
//! Like `HashMap`, this implementation does not allow multiple values for the same key,
//! inserting a duplicate key overwrites the existing value.
//!
//! Association lists often outperform hashmaps when working with small datasets, but their performance tends to degrade
//! as the dataset grows larger.
//!
//! This crate mitigates the typical performance drawbacks of association lists on larger datasets by leveraging the
//! stable ordering of items in the list through the Bookmark API.
//!
//! Items in the `alist` are stored in insertion order, which only changes when an element is removed. This property allows
//! the creation of a "bookmark" for an item, significantly improving retrieval times.
//!
//! A bookmark is essentially a record of the item's position in the internal vector. If the item has not been moved,
//! access to it is `O(1)`. If the item has been moved, a linear search is performed, with a worst-case complexity of `O(n)`.
//!
//! These features make `alist` a viable alternative to `HashMap` or `BTreeMap` in scenarios where:
//! - Data removal is infrequent.  
//! - The dataset is small.  
//! - The data type does not implement `Hash` or `Ord`, as this crate only requires items to implement `Eq`.  
//!
//! ### Key Features:
//! - **Order Preservation**: Items are stored in insertion order, which can be essential for certain applications.
//! - **Optimized Retrieval**: By leveraging the sequential nature of the underlying `Vec`, the implementation supports an optimization for retrieving items in `O(1)`.
//! - **Simplicity**: A straightforward design that avoids the overhead of hash-based collections while providing robust functionality.
//!
//! ### Example in Rust:
//! ```rust
//! use alist::AList;
//!
//! let mut alist = AList::new();
//! alist.insert("key1", "value1");
//! alist.insert("key2", "value2");
//!
//! // Linear lookup
//! if let Some(value) = alist.get("key1") {
//!     println!("Found: {}", value);
//! }
//!
//! // Fast lookup
//! let mut k2 = alist.bookmark("key2").unwrap();
//! assert_eq!(alist.get(&mut k2), Some(&"value2"));
//!
//! // Overwriting a value
//! alist.insert("key1", "new_value");
//! assert_eq!(alist.get("key1"), Some(&"new_value"));
//! ```

mod bookmark;
mod entry;
mod into_iter;
mod into_keys;
mod into_values;
mod iter;
mod iter_mut;
mod keys;
mod macros;
mod occupied_entry;
mod sailed;
mod vacant_entry;
mod values;
mod values_mut;

pub use bookmark::Bookmark;
pub use entry::Entry;
pub use into_iter::IntoIter;
pub use into_keys::IntoKeys;
pub use into_values::IntoValues;
pub use iter::Iter;
pub use iter_mut::IterMut;
pub use keys::Keys;
pub use occupied_entry::OccupiedEntry;
pub use vacant_entry::VacantEntry;
pub use values::Values;
pub use values_mut::ValuesMut;

use sailed::{ContainsKey, Get, GetKeyValue, GetKeyValueMut, GetMut, Remove, RemoveEntry};

use core::borrow::Borrow;
use core::fmt;
use core::hash::{BuildHasher, Hash, Hasher};

use std::collections::hash_map::{DefaultHasher, RandomState};
use std::sync::OnceLock;

/// A association list (alist) implementation, backed by a `Vec` of key-value pairs.
///
/// `AList` preserves the insertion order of elements, making it suitable for scenarios where order matters.
/// It requires keys to implement only the `Eq` trait, providing a simple alternative to `HashMap` or `BTreeMap`.
///
/// ### Features
/// - **Order Preservation**: Items are stored in insertion order, which can be essential for certain applications.
/// - **Optimized Retrieval**: By leveraging the sequential nature of the underlying `Vec`, the implementation supports an optimization for retrieving items in `O(1)`.
/// - **Simplicity**: A straightforward design that avoids the overhead of hash-based collections while providing robust functionality.
///
/// ### Example
/// ```rust
/// use alist::AList;
///
/// let mut alist = AList::new();
/// alist.insert("key1", "value1");
/// alist.insert("key2", "value2");
///
/// assert_eq!(alist.get("key1"), Some(&"value1"));
/// ```
///
/// Use `AList` for small datasets, infrequent removals, or when the data type does not implement `Hash` or `Ord`.
pub struct AList<K, V> {
    pairs: Vec<(K, V)>,
}

impl<K: Eq, V> FromIterator<(K, V)> for AList<K, V> {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut this = Self::new();
        this.extend(iter);
        this
    }
}

impl<K, V> Default for AList<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> AList<K, V> {
    /// Creates a new, empty `AList`.
    ///
    /// This method initializes an empty association list, ready to store key-value pairs.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let alist: AList<&str, &str> = AList::new();
    /// assert!(alist.is_empty());
    /// ```
    pub const fn new() -> Self {
        Self { pairs: Vec::new() }
    }

    /// Creates a new `AList` with a specified initial capacity.
    ///
    /// This method pre-allocates space for the specified number of key-value pairs,
    /// reducing the need for reallocations as the list grows.
    ///
    /// ### Parameters
    /// - `capacity`: The number of key-value pairs to allocate space for initially.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let alist: AList<&str, &str> = AList::with_capacity(10);
    /// assert!(alist.is_empty());
    /// assert!(alist.capacity() >= 10, "Expected the capacity to be at least 10");
    /// ```
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            pairs: Vec::with_capacity(capacity),
        }
    }

    /// Creates a bookmark for the specified key.
    ///
    /// This method allows you to "bookmark" a key in the association list, which can be used for more efficient
    /// retrieval of the corresponding value later. The bookmark stores the position of the key in the internal vector,
    /// and if the item hasn't been moved, retrieving it by this bookmark will be `O(1)`. Otherwise, a linear search is performed.
    /// If the search is performed the bookmark is updated accordingly.
    ///
    /// ### Parameters
    /// - `key`: A reference to the key to bookmark. The key must implement `Borrow<Q>`, and `Q` must implement `Eq`.
    ///
    /// ### Returns
    /// - `Some(Bookmark)` if the key exists in the list, otherwise `None`.
    ///
    /// ### Example
    /// ```rust
    /// use alist::{AList, Bookmark};
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    /// alist.insert("key2", "value2");
    ///
    /// if let Some(mut bookmark) = alist.bookmark("key1") {
    ///     assert_eq!(alist.get(&mut bookmark), Some(&"value1"));
    /// }
    /// ```
    pub fn bookmark<'q, Q>(&self, key: &'q Q) -> Option<Bookmark<'q, Q, K, V>>
    where
        K: Borrow<Q>,
        Q: Eq + ?Sized,
    {
        let position = self.position(key)?;
        Some(Bookmark::new_with_position(key, position))
    }

    /// Returns an entry for the specified key in the `AList`, allowing for insertion or modification.
    ///
    /// This method provides an `Entry` API, enabling you to insert a value if the key is not already present
    /// or modify the value if the key exists. The `Entry` API is useful for operations that depend on whether
    /// the key is already in the list.
    ///
    /// ### Parameters
    /// - `key`: The key to look up or insert in the `AList`. The key must implement `Eq`.
    ///
    /// ### Returns
    /// - An `Entry` object, which can be used to insert or modify a value associated with the key.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    ///
    /// // Insert a value if the key doesn't exist
    /// alist.entry("key1").or_insert("value1");
    ///
    /// // Modify the value if the key exists
    /// alist.entry("key1").and_modify(|v| *v = "new_value");
    ///
    /// assert_eq!(alist.get("key1"), Some(&"new_value"));
    /// ```
    pub fn entry(&mut self, key: K) -> Entry<K, V>
    where
        K: Eq,
    {
        if let Some(position) = self.position(&key) {
            return Entry::Occupied(OccupiedEntry::new(self, position));
        }

        Entry::Vacant(VacantEntry::new(self, key))
    }

    /// Inserts a key-value pair into the `AList`.
    ///
    /// If the key already exists in the `AList`, its value is updated to the provided `value`, and the old value is returned.
    /// If the key does not exist, the new pair is appended to the list.
    /// Time complexity is O(n).
    ///
    /// ### Parameters
    /// - `key`: The key to insert or update. Must implement `Eq`.
    /// - `value`: The value to associate with the key.
    ///
    /// ### Returns
    /// - `Some(V)` containing the previous value associated with the key if it already existed.
    /// - `None` if the key was not present in the `AList`.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    ///
    /// // Insert a new key-value pair
    /// assert!(alist.insert("key1", "value1").is_none());
    ///
    /// // Update an existing key
    /// assert_eq!(alist.insert("key1", "new_value"), Some("value1"));
    ///
    /// // Check the updated value
    /// assert_eq!(alist.get("key1"), Some(&"new_value"));
    /// ```
    pub fn insert(&mut self, key: K, value: V) -> Option<V>
    where
        K: Eq,
    {
        match self.find_mut(&key) {
            Some((_, v)) => Some(std::mem::replace(v, value)),
            None => {
                self.pairs.push((key, value));
                None
            }
        }
    }

    /// Retrieves a reference to the value associated with the given key in the `AList`.
    ///
    /// This method takes any type implementing the `Get<K, V>` trait, enabling flexible key lookups.
    /// If the key exists in the `AList`, a reference to the associated value is returned. Otherwise, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `Get<K, V>` trait, used to locate the value.
    ///
    /// ### Returns
    /// - `Some(&V)` if the key exists in the `AList`.
    /// - `None` if the key is not found.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    ///
    /// // Retrieve a value by key
    /// assert_eq!(alist.get("key1"), Some(&"value1"));
    ///
    /// // Attempt to retrieve a non-existent key
    /// assert!(alist.get("key2").is_none());
    ///
    /// // Retrive a value by its bookmark
    /// let mut k1 = alist.bookmark("key1").unwrap();
    /// assert_eq!(alist.get(&mut k1), Some(&"value1"));
    /// ```
    pub fn get(&self, key: impl Get<K, V>) -> Option<&V> {
        key.get(self)
    }

    /// Retrieves a mutable reference to the value associated with the given key in the `AList`.
    ///
    /// This method takes any type implementing the `GetMut<K, V>` trait, enabling flexible key lookups.
    /// If the key exists in the `AList`, a mutable reference to the associated value is returned. Otherwise, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `GetMut<K, V>` trait, used to locate the value.
    ///
    /// ### Returns
    /// - `Some(&mut V)` if the key exists in the `AList`.
    /// - `None` if the key is not found.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    ///
    /// // Retrieve a value by key
    /// assert_eq!(alist.get_mut("key1"), Some(&mut "value1"));
    ///
    /// // Attempt to retrieve a non-existent key
    /// assert!(alist.get_mut("key2").is_none());
    ///
    /// // Retrive a value by its bookmark
    /// let mut k1 = alist.bookmark("key1").unwrap();
    /// assert_eq!(alist.get_mut(&mut k1), Some(&mut "value1"));
    /// ```
    pub fn get_mut(&mut self, key: impl GetMut<K, V>) -> Option<&mut V> {
        key.get_mut(self)
    }

    /// Retrieves a reference to the key and its associated value in the `AList`.
    ///
    /// This method takes any type implementing the `GetKeyValue<K, V>` trait, enabling flexible key lookups.
    /// If the key exists in the `AList`, a reference to the key and its associated value is returned as a tuple.
    /// Otherwise, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `GetKeyValue<K, V>` trait, used to locate the key-value pair.
    ///
    /// ### Returns
    /// - `Some((&K, &V))` if the key exists in the `AList`, containing references to the key and value.
    /// - `None` if the key is not found.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    ///
    /// // Retrieve a key-value pair by key
    /// if let Some((k, v)) = alist.get_key_value("key1") {
    ///     assert_eq!(k, &"key1");
    ///     assert_eq!(v, &"value1");
    /// }
    ///
    /// // Attempt to retrieve a non-existent key
    /// assert!(alist.get_key_value("key2").is_none());
    ///
    /// // Retrive a value by its bookmark
    /// let mut k1 = alist.bookmark("key1").unwrap();
    /// assert_eq!(alist.get_key_value(&mut k1), Some((&"key1", &"value1")));
    /// ```
    pub fn get_key_value(&self, key: impl GetKeyValue<K, V>) -> Option<(&K, &V)> {
        key.get_key_value(self)
    }

    /// Retrieves a mutable reference to the key and its associated value in the `AList`.
    ///
    /// This method takes any type implementing the `GetKeyValueMut<K, V>` trait, enabling flexible key lookups.
    /// If the key exists in the `AList`, a reference to the key and its associated mutable value is returned as a tuple.
    /// Otherwise, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `GetKeyValueMut<K, V>` trait, used to locate the key-value pair.
    ///
    /// ### Returns
    /// - `Some((&K, &mut V))` if the key exists in the `AList`, containing references to the key and value.
    /// - `None` if the key is not found.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    ///
    /// // Retrieve a key-value pair by key
    /// if let Some((k, v)) = alist.get_key_value_mut("key1") {
    ///     assert_eq!(k, &"key1");
    ///     assert_eq!(v, &mut "value1");
    /// }
    ///
    /// // Attempt to retrieve a non-existent key
    /// assert!(alist.get_key_value_mut("key2").is_none());
    ///
    /// // Retrive a value by its bookmark
    /// let mut k1 = alist.bookmark("key1").unwrap();
    /// assert_eq!(alist.get_key_value_mut(&mut k1), Some((&"key1", &mut "value1")));
    /// ```
    pub fn get_key_value_mut(&mut self, key: impl GetKeyValueMut<K, V>) -> Option<(&K, &mut V)> {
        key.get_key_value_mut(self)
    }

    /// Checks if the given key exists in the `AList`.
    ///
    /// This method takes any type implementing the `ContainsKey<K, V>` trait, allowing flexible key checks.
    /// It returns `true` if the key is present in the `AList`, and `false` otherwise.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `ContainsKey<K, V>` trait, used to determine if the key exists.
    ///
    /// ### Returns
    /// - `true` if the key exists in the `AList`.
    /// - `false` if the key is not found.
    ///
    /// ### Example
    /// ```rust
    /// use alist::{AList, Bookmark};
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    ///
    /// // Check for the existence of a key
    /// assert!(alist.contains_key("key1"));
    /// assert!(!alist.contains_key("key2"));
    ///
    /// // Check for the existence of a key by its bookmark
    /// let mut k1 = alist.bookmark("key1").unwrap();
    /// assert!(alist.contains_key(&mut k1));
    /// let mut k2 = Bookmark::new("key2");
    /// assert!(!alist.contains_key(&mut k2));
    /// ```
    pub fn contains_key(&self, key: impl ContainsKey<K, V>) -> bool {
        key.contains_key(self)
    }

    /// Removes a key-value pair from the `AList`.
    ///
    /// This method takes any type implementing the `Remove<K, V>` trait to identify the key to be removed.
    /// If the key exists in the `AList`, the pair is removed, and the associated value is returned.
    /// If the key does not exist, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `Remove<K, V>` trait, used to locate the key-value pair to remove.
    ///
    /// ### Returns
    /// - `Some(V)` containing the value associated with the removed key if it existed.
    /// - `None` if the key was not found in the `AList`.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    /// alist.insert("key2", "value2");
    ///
    /// // Remove an existing key
    /// assert_eq!(alist.remove("key1"), Some("value1"));
    /// assert!(!alist.contains_key("key1"));
    ///
    /// // Remove an existing key by its bookmark
    /// let k2 = alist.bookmark("key2").unwrap();
    /// assert_eq!(alist.remove(k2), Some("value2"));
    /// assert!(!alist.contains_key("key2"));
    ///
    /// // Attempt to remove a non-existent key
    /// assert!(alist.remove("key2").is_none());
    /// ```
    pub fn remove(&mut self, key: impl Remove<K, V>) -> Option<V> {
        key.remove(self)
    }

    /// Removes a key-value pair from the `AList` and returns it as a tuple.
    ///
    /// This method takes any type implementing the `RemoveEntry<K, V>` trait to locate the key-value pair to remove.
    /// If the key exists in the `AList`, the pair is removed, and the key and value are returned as a tuple.
    /// If the key does not exist, `None` is returned.
    ///
    /// ### Parameters
    /// - `key`: An input implementing the `RemoveEntry<K, V>` trait, used to locate the key-value pair to remove.
    ///
    /// ### Returns
    /// - `Some((K, V))` containing the removed key and its associated value if the key existed.
    /// - `None` if the key was not found in the `AList`.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", "value1");
    /// alist.insert("key2", "value2");
    ///
    /// // Remove an existing key-value pair
    /// assert_eq!(alist.remove_entry("key1"), Some(("key1", "value1")));
    /// assert!(!alist.contains_key("key1"));
    ///
    /// // Remove an existing key-value pair by its bookmark
    /// let k2 = alist.bookmark("key2").unwrap();
    /// assert_eq!(alist.remove_entry(k2), Some(("key2", "value2")));
    /// assert!(!alist.contains_key("key2"));
    ///
    /// // Attempt to remove a non-existent key
    /// assert!(alist.remove_entry("nonexistent").is_none());
    /// ```
    pub fn remove_entry(&mut self, key: impl RemoveEntry<K, V>) -> Option<(K, V)> {
        key.remove_entry(self)
    }

    /// Retains only the key-value pairs in the `AList` that satisfy a predicate.
    ///
    /// This method takes a closure and applies it to each key-value pair in the `AList`.
    /// Only pairs for which the closure returns `true` are kept in the list; others are removed.
    ///
    /// ### Parameters
    /// - `f`: A closure of the form `FnMut(&K, &mut V) -> bool`, applied to each key-value pair.
    ///        If the closure returns `true`, the pair is retained; otherwise, it is removed.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    /// alist.insert("key3", 3);
    ///
    /// // Retain only pairs where the value is greater than 1
    /// alist.retain(|_, v| *v > 1);
    ///
    /// assert!(!alist.contains_key("key1"));
    /// assert!(alist.contains_key("key2"));
    /// assert!(alist.contains_key("key3"));
    /// ```
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&K, &V) -> bool,
    {
        self.pairs.retain(|(k, v)| f(k, v));
    }

    /// Retains only the key-value pairs in the `AList` that satisfy a predicate, allowing mutable access to the values.
    ///
    /// This method takes a closure that provides mutable access to the values during the retention process.
    /// Key-value pairs for which the closure returns `true` are kept in the list, while others are removed.
    ///
    /// ### Parameters
    /// - `f`: A closure of the form `FnMut(&K, &mut V) -> bool`, applied to each key-value pair.
    ///        If the closure returns `true`, the pair is retained; otherwise, it is removed.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    /// alist.insert("key3", 3);
    ///
    /// // Retain pairs where the value is odd, and double the values
    /// alist.retain_mut(|_, v| {
    ///     if (*v & 1) != 0 {
    ///         *v *= 2;
    ///         true
    ///     } else {
    ///         false
    ///     }
    /// });
    ///
    /// assert_eq!(alist.get("key1"), Some(&2));
    /// assert!(!alist.contains_key("key2"));
    /// assert_eq!(alist.get("key3"), Some(&6));
    /// ```
    pub fn retain_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        self.pairs.retain_mut(|(k, v)| f(k, v));
    }

    fn position<Q>(&self, key: &Q) -> Option<usize>
    where
        K: Borrow<Q>,
        Q: Eq + ?Sized,
    {
        self.pairs.iter().position(|(k, _)| k.borrow() == key)
    }

    fn find<Q>(&self, key: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
        Q: Eq + ?Sized,
    {
        self.pairs
            .iter()
            .find(|(k, _)| k.borrow() == key)
            .map(|(k, v)| (k, v))
    }

    fn find_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
    where
        K: Borrow<Q>,
        Q: Eq + ?Sized,
    {
        self.pairs
            .iter_mut()
            .find(|(k, _)| k.borrow() == key)
            .map(|(k, v)| (&*k, v))
    }

    fn is_valid<Q>(&self, bookmark: &Bookmark<Q, K, V>) -> bool
    where
        K: Borrow<Q>,
        Q: Eq + ?Sized,
    {
        self.pairs
            .get(bookmark.position)
            .map(|(k, _)| k.borrow() == bookmark.key())
            .unwrap_or(false)
    }
}

impl<K: Eq, V> Extend<(K, V)> for AList<K, V> {
    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        let pairs = iter.into_iter();

        let (lower, upper) = pairs.size_hint();
        self.reserve(usize::min(upper.unwrap_or(lower), 8));

        for (key, value) in pairs {
            match self.find_mut(&key) {
                None => self.pairs.push((key, value)),
                Some((_, v)) => *v = value,
            }
        }
    }
}

impl<'a, K: Eq + Clone, V: Clone> Extend<(&'a K, &'a V)> for AList<K, V> {
    fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, values: T) {
        self.extend(values.into_iter().map(|(k, v)| (k.clone(), v.clone())))
    }
}

impl<K, V> AList<K, V> {
    /// Reduces the capacity of the `AList` as much as possible.
    ///
    /// This method ensures that the capacity of the underlying storage is equal to or just larger than the
    /// current length of the `AList`. It can help reduce memory usage when the list has grown beyond its needs.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::with_capacity(100);
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// assert!(alist.capacity() >= 100);
    /// alist.shrink_to_fit();
    /// assert!(alist.capacity() >= alist.len());
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.pairs.shrink_to_fit();
    }

    /// Shrinks the capacity of the `AList` to the specified minimum, if possible.
    ///
    /// If the current capacity is greater than the specified minimum and the minimum is at least as large as
    /// the current length of the `AList`, this method reduces the capacity. Otherwise, the capacity remains unchanged.
    ///
    /// ### Parameters
    /// - `min_capacity`: The minimum capacity to shrink the `AList` to. Must be at least the current length.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::with_capacity(100);
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// assert!(alist.capacity() >= 100);
    /// alist.shrink_to(10);
    /// assert!(alist.capacity() >= 10);
    /// ```
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.pairs.shrink_to(min_capacity);
    }

    /// Reserves capacity for at least the specified number of elements.
    ///
    /// This method ensures that the `AList` can hold at least the specified number of elements without reallocating.
    /// If the current capacity is already sufficient, no change is made; otherwise, the capacity is increased.
    ///
    /// ### Parameters
    /// - `additional`: The minimum number of elements to reserve space for. The `AList` will have enough capacity to
    ///   accommodate these elements without reallocating.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist: AList<&str, i32> = AList::new();
    /// alist.reserve(100);
    /// assert!(alist.capacity() >= 100);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        self.pairs.reserve(additional);
    }

    /// Reserves exactly the specified number of elements' worth of capacity.
    ///
    /// This method ensures that the `AList` has enough capacity for at least the specified number of elements.
    /// Unlike `reserve`, it may allocate exactly the amount needed to hold that many elements, without
    /// over-allocating space.
    ///
    /// ### Parameters
    /// - `additional`: The exact number of elements to reserve space for. The `AList` will have enough capacity to
    ///   accommodate these elements, with no extra space.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist: AList<&str, i32> = AList::new();
    /// alist.reserve_exact(100);
    /// assert!(alist.capacity() >= 100);
    /// ```
    pub fn reserve_exact(&mut self, additional: usize) {
        self.pairs.reserve_exact(additional);
    }

    /// Returns the number of elements the `AList` can hold without reallocating.
    ///
    /// This method returns the current capacity of the `AList`, which represents the number of elements the list can
    /// store without needing to allocate additional space. The capacity is not necessarily equal to the number of elements
    /// in the list (which is returned by the `len` method), as it may include extra reserved space.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// assert!(alist.capacity() >= 0); // The initial capacity might not be zero.
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    /// assert!(alist.capacity() >= 2); // Capacity is greater than or equal to the number of inserted elements.
    /// ```
    pub fn capacity(&self) -> usize {
        self.pairs.capacity()
    }

    /// Returns the number of elements in the `AList`.
    ///
    /// This method returns the number of key-value pairs currently stored in the `AList`. It does not include any
    /// unused capacity or space reserved, only the actual elements in the list.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    /// assert_eq!(alist.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.pairs.len()
    }

    /// Returns `true` if the `AList` contains no elements, otherwise `false`.
    ///
    /// This method checks whether the `AList` has any key-value pairs. It returns `true` if there are no elements,
    /// and `false` otherwise.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// assert!(alist.is_empty());

    /// alist.insert("key1", 1);
    /// assert!(!alist.is_empty());

    /// alist.clear();
    /// assert!(alist.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }

    /// Removes all elements from the `AList`.
    ///
    /// This method clears the list, removing all key-value pairs. The capacity of the `AList` is not affected,
    /// so the next time the list grows, it will start from the same allocated capacity.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    /// assert_eq!(alist.len(), 2);
    ///
    /// alist.clear();
    /// assert_eq!(alist.len(), 0);
    /// assert!(alist.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.pairs.clear();
    }

    /// Returns an iterator over the keys of the `AList`.
    ///
    /// This method returns an iterator that yields references to the keys of the key-value pairs stored in the `AList`.
    /// The keys are yielded in the order they were inserted, and the iterator will not modify the list.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// let keys: Vec<_> = alist.keys().collect();
    /// assert_eq!(&keys[..], &[&"key1", &"key2"]);
    /// ```
    pub fn keys(&self) -> Keys<K, V> {
        Keys::from_delegate(self.pairs.iter())
    }

    /// Consumes the `AList` and returns an iterator over the keys.
    ///
    /// This method consumes the `AList` and returns an iterator that yields the keys of the key-value pairs in the order
    /// they were inserted. After calling `into_keys`, the `AList` is no longer accessible as it has been consumed.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// let keys: Vec<_> = alist.into_keys().collect();
    /// assert_eq!(keys, vec!["key1", "key2"]);
    /// ```
    pub fn into_keys(self) -> IntoKeys<K, V> {
        IntoKeys::from_delegate(self.pairs.into_iter())
    }

    /// Returns an iterator over the values of the `AList`.
    ///
    /// This method returns an iterator that yields references to the values of the key-value pairs stored in the `AList`.
    /// The values are yielded in the order they were inserted, and the iterator will not modify the list.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// let values: Vec<_> = alist.values().collect();
    /// assert_eq!(values, vec![&1, &2]);
    /// ```
    pub fn values(&self) -> Values<K, V> {
        Values::from_delegate(self.pairs.iter())
    }

    /// Returns a mutable iterator over the values of the `AList`.
    ///
    /// This method returns a mutable iterator that allows modifying the values of the key-value pairs stored in the `AList`.
    /// The values are yielded in the order they were inserted, and the iterator will not modify the structure of the list.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// for value in alist.values_mut() {
    ///     *value *= 2;  // Doubling each value
    /// }
    ///
    /// let values: Vec<_> = alist.values().collect();
    /// assert_eq!(&values[..], &[&2, &4]);
    /// ```
    pub fn values_mut(&mut self) -> ValuesMut<K, V> {
        ValuesMut::from_delegate(self.pairs.iter_mut())
    }

    /// Consumes the `AList` and returns an iterator over the values.
    ///
    /// This method consumes the `AList` and returns an iterator that yields the values of the key-value pairs in the order
    /// they were inserted. After calling `into_values`, the `AList` is no longer accessible as it has been consumed.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// let values: Vec<_> = alist.into_values().collect();
    /// assert_eq!(values, vec![1, 2]);
    /// ```
    pub fn into_values(self) -> IntoValues<K, V> {
        IntoValues::from_delegate(self.pairs.into_iter())
    }

    /// Returns an iterator over the key-value pairs of the `AList`.
    ///
    /// This method returns an iterator that yields references to the key-value pairs stored in the `AList` in the order
    /// they were inserted. The iterator allows read-only access to both the keys and values.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// let pairs: Vec<_> = alist.iter().collect();
    /// assert_eq!(&pairs[..], &[(&"key1", &1), (&"key2", &2)]);
    /// ```
    pub fn iter(&self) -> Iter<K, V> {
        Iter::from_delegate(self.pairs.iter())
    }

    /// Returns a mutable iterator over the key-value pairs of the `AList`.
    ///
    /// This method returns a mutable iterator that allows modifying both the keys and values of the key-value pairs stored
    /// in the `AList`. The iterator yields the key-value pairs in the order they were inserted.
    ///
    /// ### Example
    /// ```rust
    /// use alist::AList;
    ///
    /// let mut alist = AList::new();
    /// alist.insert("key1", 1);
    /// alist.insert("key2", 2);
    ///
    /// for (_key, value) in alist.iter_mut() {
    ///     *value *= 2;  // Doubling each value
    /// }
    ///
    /// let values: Vec<_> = alist.values().collect();
    /// assert_eq!(&values[..], &[&2, &4]);
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<K, V> {
        IterMut::from_delegate(self.pairs.iter_mut())
    }
}

impl<K, V> IntoIterator for AList<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::from_delegate(self.pairs.into_iter())
    }
}

impl<'a, K, V> IntoIterator for &'a AList<K, V> {
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V> IntoIterator for &'a mut AList<K, V> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<K: Clone, V: Clone> Clone for AList<K, V> {
    fn clone(&self) -> Self {
        Self {
            pairs: self.pairs.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.pairs.clone_from(&source.pairs)
    }
}

impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for AList<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        let mut map = f.debug_map();
        self.pairs.iter().for_each(|(k, v)| {
            map.entry(k, v);
        });
        map.finish()
    }
}

impl<K: Eq, V: PartialEq> PartialEq for AList<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.len() == other.len()
            && self
                .iter()
                .all(|(k, v)| other.get(k).filter(|w| v == *w).is_some())
    }
}

impl<K: Eq, V: Eq> Eq for AList<K, V> {}

impl<K: Hash, V: Hash> Hash for AList<K, V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let hasher_builder = global_hasher_builder();
        let hash = self
            .values()
            .map(|p| hasher_builder.hash_one(p))
            .fold(hasher_builder.hash_one(self.len()), |l, r| l ^ r);

        state.write_usize(self.len());
        state.write_u64(hash);
    }
}

fn global_hasher_builder() -> &'static impl BuildHasher<Hasher = DefaultHasher> {
    static INSTANCE: OnceLock<RandomState> = OnceLock::new();
    INSTANCE.get_or_init(RandomState::new)
}

#[cfg(test)]
mod tests {
    use std::hash::{BuildHasher, BuildHasherDefault, DefaultHasher};

    use crate::{alist, AList, Bookmark};

    #[test]
    fn alist_macro() {
        let sut = alist! {
            "k1" => "v1",
            "k2" => "v2",
            "k1" => "w1",
        };

        assert_eq!(
            sut.into_iter().collect::<Vec<_>>(),
            [("k1", "w1"), ("k2", "v2")]
        );
    }

    #[test]
    fn hash() {
        let symbols = ["x", "y", "z"];
        let values = [1, 2, 3];

        let mut pairs = symbols
            .into_iter()
            .zip(values.into_iter())
            .collect::<Vec<_>>();

        let mut l = pairs.iter().cloned().collect::<AList<_, _>>();

        pairs.swap(0, 2);
        let mut r = pairs.into_iter().collect::<AList<_, _>>();

        assert_eq!(l, r);

        let hasher_builder = BuildHasherDefault::<DefaultHasher>::default();
        let (h1, h2) = (hasher_builder.hash_one(&l), hasher_builder.hash_one(&r));
        assert_eq!(h1, h2);

        r.remove("x");
        let (h1, h2) = (hasher_builder.hash_one(&l), hasher_builder.hash_one(&r));
        assert_ne!(h1, h2);

        l.remove("x");
        let (h1, h2) = (hasher_builder.hash_one(&l), hasher_builder.hash_one(&r));
        assert_eq!(h1, h2);
    }

    #[test]
    fn new_creates_empty_alist() {
        let sut: AList<&str, &str> = AList::new();
        assert!(sut.is_empty(), "Expected the alist to be empty");
        assert_eq!(sut.len(), 0, "Expected the length of the alist to be 0");
    }

    #[test]
    fn default_creates_empty_alist() {
        let sut: AList<&str, &str> = AList::default();
        assert!(sut.is_empty(), "Expected the alist to be empty");
        assert_eq!(sut.len(), 0, "Expected the length of the alist to be 0");
    }

    #[test]
    fn with_capacity_creates_alist_with_specified_capacity() {
        let capacity = 10;
        let sut: AList<&str, &str> = AList::with_capacity(capacity);
        assert!(sut.is_empty(), "Expected the alist to be empty");
        assert!(
            sut.capacity() >= capacity,
            "Expected the alist to have a capacity of at least {}",
            capacity
        );
    }

    #[test]
    fn bookmark_creates_valid_bookmark() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Create a bookmark for "key1"
        if let Some(mut bookmark) = sut.bookmark("key1") {
            assert_eq!(sut.get(&mut bookmark), Some(&"value1"));
        } else {
            panic!("Expected bookmark to be created for 'key1'");
        }
    }

    #[test]
    fn bookmark_returns_none_for_nonexistent_key() {
        let sut: AList<&str, &str> = AList::new();

        // Try creating a bookmark for a non-existent key
        assert!(
            sut.bookmark("nonexistent").is_none(),
            "Expected None for nonexistent key"
        );
    }

    #[test]
    fn entry_insert_new_key() {
        let mut sut = AList::new();

        // Insert a new key-value pair
        sut.entry("key1").or_insert("value1");

        assert_eq!(
            sut.get("key1"),
            Some(&"value1"),
            "Expected 'key1' to be inserted with 'value1'"
        );
    }

    #[test]
    fn entry_modify_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Modify the value of an existing key
        sut.entry("key1").and_modify(|v| *v = "new_value");

        assert_eq!(
            sut.get("key1"),
            Some(&"new_value"),
            "Expected 'key1' to have its value updated to 'new_value'"
        );
    }

    #[test]
    fn entry_insert_if_not_exists() {
        let mut sut = AList::new();

        // Insert a value if the key doesn't exist
        sut.entry("key1").or_insert("value1");

        // Ensure the value is not overwritten for an existing key
        sut.entry("key1").or_insert("other_value");

        assert_eq!(
            sut.get("key1"),
            Some(&"value1"),
            "Expected 'key1' to remain 'value1' after re-insertion attempt"
        );
    }

    #[test]
    fn insert_new_key() {
        let mut sut = AList::new();

        // Insert a new key-value pair
        let result = sut.insert("key1", "value1");
        assert!(result.is_none(), "Expected None for a new key insertion");
        assert_eq!(
            sut.get("key1"),
            Some(&"value1"),
            "Expected 'key1' to map to 'value1'"
        );
    }

    #[test]
    fn insert_update_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Update the value for an existing key
        let result = sut.insert("key1", "new_value");
        assert_eq!(
            result,
            Some("value1"),
            "Expected 'value1' as the previous value"
        );
        assert_eq!(
            sut.get("key1"),
            Some(&"new_value"),
            "Expected 'key1' to map to 'new_value'"
        );
    }

    #[test]
    fn insert_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Verify both keys are present
        assert_eq!(
            sut.get("key1"),
            Some(&"value1"),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get("key2"),
            Some(&"value2"),
            "Expected 'key2' to map to 'value2'"
        );
    }

    #[test]
    fn get_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Retrieve an existing key
        let result = sut.get("key1");
        assert_eq!(
            result,
            Some(&"value1"),
            "Expected to retrieve 'value1' for 'key1'"
        );

        // Retrieve an existing key by its bookmark
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let result = sut.get(&mut k1);
        assert_eq!(
            result,
            Some(&"value1"),
            "Expected to retrieve 'value1' for 'key1'"
        );
    }

    #[test]
    fn get_nonexistent_key() {
        let sut: AList<&str, &str> = AList::new();

        // Attempt to retrieve a non-existent key
        let result = sut.get("nonexistent");
        assert!(result.is_none(), "Expected None for a non-existent key");

        // Attempt to retrieve a non-existent key from its bookmark
        let mut bookmark = Bookmark::new("nonexistent");
        let result = sut.get(&mut bookmark);
        assert!(result.is_none(), "Expected None for a non-existent key");
    }

    #[test]
    fn get_with_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Retrieve values for multiple keys
        assert_eq!(
            sut.get("key1"),
            Some(&"value1"),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get("key2"),
            Some(&"value2"),
            "Expected 'key2' to map to 'value2'"
        );

        // Retrieve values for multiple keys by their bookmarks
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let mut k2 = Bookmark::new("key2");
        assert_eq!(
            sut.get(&mut k1),
            Some(&"value1"),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get(&mut k2),
            Some(&"value2"),
            "Expected 'key2' to map to 'value2'"
        );
    }

    #[test]
    fn get_mut_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Retrieve an existing key
        let result = sut.get_mut("key1");
        assert_eq!(
            result,
            Some(&mut "value1"),
            "Expected to retrieve 'value1' for 'key1'"
        );

        // Retrieve an existing key by its bookmark
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let result = sut.get_mut(&mut k1);
        assert_eq!(
            result,
            Some(&mut "value1"),
            "Expected to retrieve 'value1' for 'key1'"
        );
    }

    #[test]
    fn get_mut_nonexistent_key() {
        let mut sut: AList<&str, &str> = AList::new();

        // Attempt to retrieve a non-existent key
        let result = sut.get_mut("nonexistent");
        assert!(result.is_none(), "Expected None for a non-existent key");

        // Attempt to retrieve a non-existent key from its bookmark
        let mut bookmark = Bookmark::new("nonexistent");
        let result = sut.get_mut(&mut bookmark);
        assert!(result.is_none(), "Expected None for a non-existent key");
    }

    #[test]
    fn get_mut_with_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Retrieve values for multiple keys
        assert_eq!(
            sut.get_mut("key1"),
            Some(&mut "value1"),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get_mut("key2"),
            Some(&mut "value2"),
            "Expected 'key2' to map to 'value2'"
        );

        // Retrieve values for multiple keys by their bookmarks
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let mut k2 = Bookmark::new("key2");
        assert_eq!(
            sut.get_mut(&mut k1),
            Some(&mut "value1"),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get_mut(&mut k2),
            Some(&mut "value2"),
            "Expected 'key2' to map to 'value2'"
        );
    }

    #[test]
    fn get_key_value_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Retrieve an existing key-value pair
        if let Some((key, value)) = sut.get_key_value("key1") {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        } else {
            panic!("Expected to retrieve key-value pair for 'key1'");
        }

        // Retrieve an existing key-value pair by its bookmark
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        if let Some((key, value)) = sut.get_key_value(&mut k1) {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        } else {
            panic!("Expected to retrieve key-value pair for 'key1'");
        }
    }

    #[test]
    fn get_key_value_nonexistent_key() {
        let sut: AList<&str, &str> = AList::new();

        // Attempt to retrieve a non-existent key
        let result = sut.get_key_value("nonexistent");
        assert!(result.is_none(), "Expected None for a non-existent key");

        // Attempt to retrieve a non-existent key from its bookmark
        let mut bookmark = Bookmark::new("nonexistent");
        let result = sut.get_key_value(&mut bookmark);
        assert!(result.is_none(), "Expected None for a non-existent key");
    }

    #[test]
    fn get_key_value_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Retrieve key-value pairs for multiple keys
        if let Some((key, value)) = sut.get_key_value("key1") {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        }

        if let Some((key, value)) = sut.get_key_value("key2") {
            assert_eq!(key, &"key2", "Expected 'key2' as the retrieved key");
            assert_eq!(value, &"value2", "Expected 'value2' as the retrieved value");
        }

        // Retrievekey-value pairs for multiple keys by their bookmarks
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let mut k2 = Bookmark::new("key2");
        assert_eq!(
            sut.get_key_value(&mut k1),
            Some((&"key1", &"value1")),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get_key_value(&mut k2),
            Some((&"key2", &"value2")),
            "Expected 'key2' to map to 'value2'"
        );
    }

    #[test]
    fn get_key_value_mut_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Retrieve an existing key-value pair
        if let Some((key, value)) = sut.get_key_value_mut("key1") {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        } else {
            panic!("Expected to retrieve key-value pair for 'key1'");
        }

        // Retrieve an existing key-value pair by its bookmark
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        if let Some((key, value)) = sut.get_key_value_mut(&mut k1) {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        } else {
            panic!("Expected to retrieve key-value pair for 'key1'");
        }
    }

    #[test]
    fn get_key_value_mut_nonexistent_key() {
        let mut sut: AList<&str, &str> = AList::new();

        // Attempt to retrieve a non-existent key
        let result = sut.get_key_value_mut("nonexistent");
        assert!(result.is_none(), "Expected None for a non-existent key");

        // Attempt to retrieve a non-existent key from its bookmark
        let mut bookmark = Bookmark::new("nonexistent");
        let result = sut.get_key_value_mut(&mut bookmark);
        assert!(result.is_none(), "Expected None for a non-existent key");
    }

    #[test]
    fn get_key_value_mut_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Retrieve key-value pairs for multiple keys
        if let Some((key, value)) = sut.get_key_value_mut("key1") {
            assert_eq!(key, &"key1", "Expected 'key1' as the retrieved key");
            assert_eq!(value, &"value1", "Expected 'value1' as the retrieved value");
        }

        if let Some((key, value)) = sut.get_key_value_mut("key2") {
            assert_eq!(key, &"key2", "Expected 'key2' as the retrieved key");
            assert_eq!(value, &"value2", "Expected 'value2' as the retrieved value");
        }

        // Retrievekey-value pairs for multiple keys by their bookmarks
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let mut k2 = Bookmark::new("key2");
        assert_eq!(
            sut.get_key_value_mut(&mut k1),
            Some((&"key1", &mut "value1")),
            "Expected 'key1' to map to 'value1'"
        );
        assert_eq!(
            sut.get_key_value_mut(&mut k2),
            Some((&"key2", &mut "value2")),
            "Expected 'key2' to map to 'value2'"
        );
    }

    #[test]
    fn contains_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");

        // Check for an existing key
        assert!(
            sut.contains_key("key1"),
            "Expected 'key1' to exist in the list"
        );

        // Check for an existing key by its bookmark
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        assert!(sut.contains_key(&mut k1));
    }

    #[test]
    fn contains_nonexistent_key() {
        let sut: AList<&str, &str> = AList::new();

        // Check for a non-existent key
        assert!(
            !sut.contains_key("nonexistent"),
            "Expected 'nonexistent' to not exist in the list"
        );

        // Check for an non-existent key by its bookmark
        let mut bookmark = Bookmark::new("nonexistent");
        assert!(
            !sut.contains_key(&mut bookmark),
            "Expected 'nonexistent' to not exist in the list"
        );
    }

    #[test]
    fn contains_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Check for multiple keys
        assert!(
            sut.contains_key("key1"),
            "Expected 'key1' to exist in the list"
        );
        assert!(
            sut.contains_key("key2"),
            "Expected 'key2' to exist in the list"
        );
        assert!(
            !sut.contains_key("key3"),
            "Expected 'key3' to not exist in the list"
        );

        // Check for multiple keys by their bookmarks
        let mut k1 = sut
            .bookmark("key1")
            .expect("Expected a valid bookmark for 'key1'");
        let mut k2 = Bookmark::new("key2");
        let mut k3 = Bookmark::new("key3");
        assert!(
            sut.contains_key(&mut k1),
            "Expected 'key1' to exist in the list"
        );
        assert!(
            sut.contains_key(&mut k2),
            "Expected 'key2' to exist in the list"
        );
        assert!(
            !sut.contains_key(&mut k3),
            "Expected 'key3' to not exist in the list"
        );
    }

    #[test]
    fn remove_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Remove an existing key
        let result = sut.remove("key1");
        assert_eq!(
            result,
            Some("value1"),
            "Expected to remove 'key1' with value 'value1'"
        );
        assert!(
            !sut.contains_key("key1"),
            "Expected 'key1' to be removed from the list"
        );

        // Remove an existing key by its bookmark
        let k2 = sut
            .bookmark("key2")
            .expect("Expected a valid bookmark for 'key2'");
        let result = sut.remove(k2);
        assert_eq!(
            result,
            Some("value2"),
            "Expected to remove 'key2' with value 'value2'"
        );
        assert!(
            !sut.contains_key("key2"),
            "Expected 'key2' to be removed from the list"
        );
    }

    #[test]
    fn remove_nonexistent_key() {
        let mut sut: AList<&str, &str> = AList::new();

        // Attempt to remove a non-existent key
        let result = sut.remove("nonexistent");
        assert!(
            result.is_none(),
            "Expected None when attempting to remove a non-existent key"
        );

        // Attempt to remove a non-existent key by its bookmark
        let bookmark = Bookmark::new("nonexistent");
        let result = sut.remove(bookmark);
        assert!(
            result.is_none(),
            "Expected None when attempting to remove a non-existent key"
        );
    }

    #[test]
    fn remove_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");
        sut.insert("key3", "value3");
        sut.insert("key4", "value4");

        // Remove multiple keys
        assert_eq!(
            sut.remove("key1"),
            Some("value1"),
            "Expected to remove 'key1' with value 'value1'"
        );
        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");

        assert_eq!(
            sut.remove("key2"),
            Some("value2"),
            "Expected to remove 'key2' with value 'value2'"
        );
        assert!(!sut.contains_key("key2"), "Expected 'key2' to be removed");

        // Remove multiple keys by their bookmarks
        let k3 = sut
            .bookmark("key3")
            .expect("Expected a valid bookmark for 'key3'");
        let k4 = Bookmark::new("key4");

        assert_eq!(
            sut.remove(k3),
            Some("value3"),
            "Expected to remove 'key3' with value 'value3'"
        );
        assert!(!sut.contains_key("key3"), "Expected 'key3' to be removed");

        assert_eq!(
            sut.remove(k4),
            Some("value4"),
            "Expected to remove 'key4' with value 'value4'"
        );
        assert!(!sut.contains_key("key4"), "Expected 'key4' to be removed");
    }

    #[test]
    fn remove_entry_existing_key() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");

        // Remove an existing key-value pair
        let result = sut.remove_entry("key1");
        assert_eq!(
            result,
            Some(("key1", "value1")),
            "Expected to remove 'key1' with value 'value1'"
        );
        assert!(
            !sut.contains_key("key1"),
            "Expected 'key1' to be removed from the list"
        );

        // Remove an existing key-value pair by its bookmark
        let k2 = sut.bookmark("key2").unwrap();
        let result = sut.remove_entry(k2);
        assert_eq!(
            result,
            Some(("key2", "value2")),
            "Expected to remove 'key2' with value 'value2'"
        );
        assert!(
            !sut.contains_key("key2"),
            "Expected 'key2' to be removed from the list"
        );
    }

    #[test]
    fn remove_entry_nonexistent_key() {
        let mut sut: AList<&str, &str> = AList::new();

        // Attempt to remove a non-existent key
        let result = sut.remove_entry("nonexistent");
        assert!(
            result.is_none(),
            "Expected None when attempting to remove a non-existent key"
        );

        // Attempt to remove a non-existent key by its bookmark
        let bookmark = Bookmark::new("nonexistent");
        let result = sut.remove_entry(bookmark);
        assert!(
            result.is_none(),
            "Expected None when attempting to remove a non-existent key"
        );
    }

    #[test]
    fn remove_entry_multiple_keys() {
        let mut sut = AList::new();
        sut.insert("key1", "value1");
        sut.insert("key2", "value2");
        sut.insert("key3", "value3");
        sut.insert("key4", "value4");

        // Remove multiple key-value pairs
        assert_eq!(
            sut.remove_entry("key1"),
            Some(("key1", "value1")),
            "Expected to remove 'key1' with value 'value1'"
        );
        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");

        assert_eq!(
            sut.remove_entry("key2"),
            Some(("key2", "value2")),
            "Expected to remove 'key2' with value 'value2'"
        );
        assert!(!sut.contains_key("key2"), "Expected 'key2' to be removed");

        // Remove multiple key-value pairs by their bookmarks
        let k3 = sut
            .bookmark("key3")
            .expect("Expected a valid bookmark for 'key3'");
        let k4 = Bookmark::new("key4");

        assert_eq!(
            sut.remove_entry(k3),
            Some(("key3", "value3")),
            "Expected to remove 'key3' with value 'value3'"
        );
        assert!(!sut.contains_key("key3"), "Expected 'key3' to be removed");

        assert_eq!(
            sut.remove_entry(k4),
            Some(("key4", "value4")),
            "Expected to remove 'key4' with value 'value4'"
        );
        assert!(!sut.contains_key("key4"), "Expected 'key4' to be removed");
    }

    #[test]
    fn retain_some_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        sut.insert("key3", 3);

        // Retain only pairs where the value is greater than 1
        sut.retain(|_, v| *v > 1);

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert!(sut.contains_key("key2"), "Expected 'key2' to be retained");
        assert!(sut.contains_key("key3"), "Expected 'key3' to be retained");
    }

    #[test]
    fn retain_all_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Retain all pairs
        sut.retain(|_, _| true);

        assert!(sut.contains_key("key1"), "Expected 'key1' to be retained");
        assert!(sut.contains_key("key2"), "Expected 'key2' to be retained");
    }

    #[test]
    fn retain_no_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Remove all pairs
        sut.retain(|_, _| false);

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert!(!sut.contains_key("key2"), "Expected 'key2' to be removed");
    }

    #[test]
    fn retain_based_on_keys() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        sut.insert("key3", 3);

        // Retain only pairs with keys starting with 'key2'
        sut.retain(|k, _| *k == "key2");

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert!(sut.contains_key("key2"), "Expected 'key2' to be retained");
        assert!(!sut.contains_key("key3"), "Expected 'key3' to be removed");
    }

    #[test]
    fn retain_mut_some_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        sut.insert("key3", 3);

        // Retain pairs with even values and double their values
        sut.retain_mut(|_, v| {
            if *v % 2 == 0 {
                *v *= 2;
                true
            } else {
                false
            }
        });

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert_eq!(
            sut.get("key2"),
            Some(&4),
            "Expected 'key2' to be retained and doubled"
        );
        assert!(!sut.contains_key("key3"), "Expected 'key3' to be removed");
    }

    #[test]
    fn retain_mut_all_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Retain all pairs and increment their values
        sut.retain_mut(|_, v| {
            *v += 1;
            true
        });

        assert_eq!(
            sut.get("key1"),
            Some(&2),
            "Expected 'key1' to be retained and incremented"
        );
        assert_eq!(
            sut.get("key2"),
            Some(&3),
            "Expected 'key2' to be retained and incremented"
        );
    }

    #[test]
    fn retain_mut_no_pairs() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Remove all pairs
        sut.retain_mut(|_, _| false);

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert!(!sut.contains_key("key2"), "Expected 'key2' to be removed");
    }

    #[test]
    fn retain_mut_based_on_keys() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        sut.insert("key3", 3);

        // Retain only pairs with keys starting with 'key2' and increment their values
        sut.retain_mut(|k, v| {
            if *k == "key2" {
                *v += 1;
                true
            } else {
                false
            }
        });

        assert!(!sut.contains_key("key1"), "Expected 'key1' to be removed");
        assert_eq!(
            sut.get("key2"),
            Some(&3),
            "Expected 'key2' to be retained and incremented"
        );
        assert!(!sut.contains_key("key3"), "Expected 'key3' to be removed");
    }

    #[test]
    fn extend_with_new_items() {
        let mut sut = AList::new();

        let new_items = vec![("key1", 1), ("key2", 2), ("key3", 3)];
        sut.extend(new_items);

        assert_eq!(sut.get("key1"), Some(&1), "Expected 'key1' to have value 1");
        assert_eq!(sut.get("key2"), Some(&2), "Expected 'key2' to have value 2");
        assert_eq!(sut.get("key3"), Some(&3), "Expected 'key3' to have value 3");
    }

    #[test]
    fn extend_with_replacing_items() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let new_items = vec![("key2", 20), ("key3", 30)];
        sut.extend(new_items);

        assert_eq!(
            sut.get("key1"),
            Some(&1),
            "Expected 'key1' to retain value 1"
        );
        assert_eq!(
            sut.get("key2"),
            Some(&20),
            "Expected 'key2' to be replaced with value 20"
        );
        assert_eq!(
            sut.get("key3"),
            Some(&30),
            "Expected 'key3' to be inserted with value 30"
        );
    }

    #[test]
    fn extend_with_empty_iterator() {
        let mut sut = AList::new();
        sut.insert("key1", 1);

        sut.extend(Vec::<(&str, i32)>::new());

        assert_eq!(
            sut.get("key1"),
            Some(&1),
            "Expected 'key1' to remain unchanged"
        );
        assert_eq!(sut.len(), 1, "Expected the AList to contain one item");
    }

    #[test]
    fn extend_with_duplicate_keys() {
        let mut sut = AList::new();
        sut.insert("key1", 1);

        let new_items = vec![("key1", 10), ("key1", 20)];
        sut.extend(new_items);

        assert_eq!(
            sut.get("key1"),
            Some(&20),
            "Expected 'key1' to have the last inserted value 20"
        );
    }

    #[test]
    fn extend_with_ref_items() {
        let mut sut: AList<&str, i32> = AList::new();

        let new_items = [(&"key1", &1), (&"key2", &2), (&"key3", &3)];
        sut.extend(new_items);

        assert_eq!(sut.get("key1"), Some(&1), "Expected 'key1' to have value 1");
        assert_eq!(sut.get("key2"), Some(&2), "Expected 'key2' to have value 2");
        assert_eq!(sut.get("key3"), Some(&3), "Expected 'key3' to have value 3");
    }

    #[test]
    fn shrink_to_fit_reduces_capacity() {
        let mut sut = AList::with_capacity(100);
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let old_capacity = sut.capacity();
        assert!(
            old_capacity >= 100,
            "Expected initial capacity to be at least 100"
        );

        sut.shrink_to_fit();
        let new_capacity = sut.capacity();

        assert!(
            new_capacity >= sut.len(),
            "Expected capacity to be no less than length"
        );
        assert!(
            new_capacity <= old_capacity,
            "Expected capacity to be reduced"
        );
    }

    #[test]
    fn shrink_to_fit_no_effect_when_exact_capacity() {
        let mut sut = AList::with_capacity(2);
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let old_capacity = sut.capacity();
        sut.shrink_to_fit();
        let new_capacity = sut.capacity();

        assert_eq!(
            new_capacity, old_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn shrink_to_reduces_capacity() {
        let mut sut = AList::with_capacity(100);
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let old_capacity = sut.capacity();
        assert!(
            old_capacity >= 100,
            "Expected initial capacity to be at least 100"
        );

        sut.shrink_to(10);
        let new_capacity = sut.capacity();

        assert!(
            new_capacity >= 10,
            "Expected capacity to be no less than the specified minimum"
        );
        assert!(
            new_capacity <= old_capacity,
            "Expected capacity to be reduced"
        );
    }

    #[test]
    fn shrink_to_no_effect_when_below_length() {
        let mut sut = AList::with_capacity(2);
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let old_capacity = sut.capacity();
        sut.shrink_to(1);
        let new_capacity = sut.capacity();

        assert_eq!(
            new_capacity, old_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn shrink_to_exact_length() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        sut.shrink_to(sut.len());
        let new_capacity = sut.capacity();

        assert_eq!(
            new_capacity,
            sut.len(),
            "Expected capacity to match the length of the AList"
        );
    }

    #[test]
    fn reserve_increases_capacity_when_needed() {
        let mut sut: AList<&str, i32> = AList::new();
        let initial_capacity = sut.capacity();

        sut.reserve(100);
        assert!(
            sut.capacity() >= 100,
            "Expected capacity to be at least 100"
        );
        assert!(
            sut.capacity() > initial_capacity,
            "Expected capacity to increase"
        );
    }

    #[test]
    fn reserve_does_not_increase_capacity_if_sufficient() {
        let mut sut: AList<&str, i32> = AList::with_capacity(100);
        let initial_capacity = sut.capacity();

        sut.reserve(10);
        assert_eq!(
            sut.capacity(),
            initial_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn reserve_does_not_increase_capacity_for_zero() {
        let mut sut: AList<&str, i32> = AList::new();
        let initial_capacity = sut.capacity();

        sut.reserve(0);
        assert_eq!(
            sut.capacity(),
            initial_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn reserve_exact_increases_capacity_when_needed() {
        let mut sut: AList<&str, i32> = AList::new();
        let initial_capacity = sut.capacity();

        sut.reserve_exact(100);
        assert!(
            sut.capacity() >= 100,
            "Expected capacity to be at least 100"
        );
        assert!(
            sut.capacity() > initial_capacity,
            "Expected capacity to increase"
        );
    }

    #[test]
    fn reserve_exact_does_not_increase_capacity_if_sufficient() {
        let mut sut: AList<&str, i32> = AList::with_capacity(100);
        let initial_capacity = sut.capacity();

        sut.reserve_exact(10);
        assert_eq!(
            sut.capacity(),
            initial_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn reserve_exact_does_not_increase_capacity_for_zero() {
        let mut sut: AList<&str, i32> = AList::new();
        let initial_capacity = sut.capacity();

        sut.reserve_exact(0);
        assert_eq!(
            sut.capacity(),
            initial_capacity,
            "Expected capacity to remain unchanged"
        );
    }

    #[test]
    fn clear_removes_all_elements() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        assert_eq!(sut.len(), 2);

        sut.clear();
        assert_eq!(sut.len(), 0);
        assert!(sut.is_empty(), "Expected AList to be empty after clear");
    }

    #[test]
    fn clear_leaves_capacity_untouched() {
        let mut sut = AList::with_capacity(100);
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        let old_capacity = sut.capacity();

        sut.clear();
        assert_eq!(sut.len(), 0);
        assert!(
            sut.capacity() >= old_capacity,
            "Expected capacity to remain the same after clear"
        );
    }

    #[test]
    fn capacity_increases_with_insertions() {
        let mut sut = AList::new();
        let initial_capacity = sut.capacity();

        sut.insert("key1", 1);
        sut.insert("key2", 2);
        assert!(
            sut.capacity() >= initial_capacity,
            "Expected capacity to be at least 2 after insertions"
        );

        // After removing elements, the capacity shouldn't shrink unless manually changed (e.g., via shrink_to_fit)
        sut.remove("key1");
        assert!(
            sut.capacity() >= 2,
            "Expected capacity to remain the same after removal"
        );
    }

    #[test]
    fn capacity_does_not_decrease_after_clear() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);
        let current_capacity = sut.capacity();

        sut.clear();
        assert_eq!(sut.len(), 0);
        assert!(
            sut.capacity() >= current_capacity,
            "Expected capacity to remain unchanged after clear"
        );
    }

    #[test]
    fn capacity_after_reserve() {
        let mut sut: AList<&str, i32> = AList::new();
        let initial_capacity = sut.capacity();

        sut.reserve(100);
        assert!(
            sut.capacity() >= 100,
            "Expected capacity to increase after reserve"
        );
        assert!(
            sut.capacity() > initial_capacity,
            "Expected capacity to increase after reserve"
        );
    }

    #[test]
    fn capacity_does_not_increase_with_zero_insertions() {
        let mut sut = alist! {
            "key1" => 1,
        };
        let initial_capacity = sut.capacity();

        sut.remove("key1");

        assert_eq!(
            sut.capacity(),
            initial_capacity,
            "Expected capacity to remain the same after no insertions"
        );
    }

    #[test]
    fn len_returns_correct_number_of_elements() {
        let mut sut = AList::new();
        assert_eq!(sut.len(), 0);

        sut.insert("key1", 1);
        sut.insert("key2", 2);
        assert_eq!(sut.len(), 2);

        sut.remove("key1");
        assert_eq!(sut.len(), 1);

        sut.clear();
        assert_eq!(sut.len(), 0);
    }

    #[test]
    fn is_empty_returns_correct_status() {
        let mut sut = AList::new();
        assert!(sut.is_empty(), "Expected AList to be empty initially");

        sut.insert("key1", 1);
        assert!(
            !sut.is_empty(),
            "Expected AList to be non-empty after insertion"
        );

        sut.clear();
        assert!(sut.is_empty(), "Expected AList to be empty after clearing");
    }

    #[test]
    fn is_empty_after_remove() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.remove("key1");

        assert!(
            sut.is_empty(),
            "Expected AList to be empty after removal of last element"
        );
    }

    #[test]
    fn keys_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let keys: Vec<_> = sut.keys().collect();
        assert_eq!(
            &keys[..],
            &[&"key1", &"key2"],
            "Expected keys to be in the same order as they were inserted"
        );
    }

    #[test]
    fn keys_is_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let keys: Vec<_> = sut.keys().collect();
        assert!(
            keys.is_empty(),
            "Expected keys iterator to be empty when AList is empty"
        );
    }

    #[test]
    fn keys_does_not_modify_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let mut keys = sut.keys();
        assert_eq!(keys.next(), Some(&"key1"));
        assert_eq!(keys.next(), Some(&"key2"));

        // Ensure that the original list is unchanged
        assert_eq!(sut.len(), 2);
        assert_eq!(sut.get("key1"), Some(&1));
        assert_eq!(sut.get("key2"), Some(&2));
    }

    #[test]
    fn into_keys_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let keys: Vec<_> = sut.into_keys().collect();
        assert_eq!(
            keys,
            vec!["key1", "key2"],
            "Expected keys to be in the same order as they were inserted"
        );
    }

    #[test]
    fn into_keys_consumes_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let keys: Vec<_> = sut.into_keys().collect();
        assert_eq!(keys, vec!["key1", "key2"]);
    }

    #[test]
    fn into_keys_returns_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let keys: Vec<_> = sut.into_keys().collect();
        assert!(
            keys.is_empty(),
            "Expected into_keys to return an empty iterator when AList is empty"
        );
    }

    #[test]
    fn values_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let values: Vec<_> = sut.values().collect();
        assert_eq!(
            values,
            vec![&1, &2],
            "Expected values to be in the same order as they were inserted"
        );
    }

    #[test]
    fn values_is_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let values: Vec<_> = sut.values().collect();
        assert!(
            values.is_empty(),
            "Expected values iterator to be empty when AList is empty"
        );
    }

    #[test]
    fn values_does_not_modify_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let mut values = sut.values();
        assert_eq!(values.next(), Some(&1));
        assert_eq!(values.next(), Some(&2));

        // Ensure that the original list is unchanged
        assert_eq!(sut.len(), 2);
        assert_eq!(sut.get("key1"), Some(&1));
        assert_eq!(sut.get("key2"), Some(&2));
    }

    #[test]
    fn values_mut_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let values: Vec<_> = sut.values_mut().collect();
        assert_eq!(
            values,
            vec![&mut 1, &mut 2],
            "Expected values to be in the same order as they were inserted"
        );
    }

    #[test]
    fn values_mut_allows_modifying_values() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        for value in sut.values_mut() {
            *value *= 2; // Doubling each value
        }

        let values: Vec<_> = sut.values().collect();
        assert_eq!(
            &values[..],
            &[&2, &4],
            "Expected values to be doubled after modification"
        );
    }

    #[test]
    fn values_mut_is_empty_when_list_is_empty() {
        let mut sut: AList<&str, i32> = AList::new();
        let values: Vec<_> = sut.values_mut().collect();
        assert!(
            values.is_empty(),
            "Expected values_mut iterator to be empty when AList is empty"
        );
    }

    #[test]
    fn values_mut_does_not_modify_the_structure_of_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Modifying values using values_mut
        for value in sut.values_mut() {
            *value *= 2;
        }

        // Ensure that the structure (keys) is unchanged
        assert_eq!(sut.len(), 2);
        assert_eq!(sut.get("key1"), Some(&2));
        assert_eq!(sut.get("key2"), Some(&4));
    }

    #[test]
    fn into_values_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let values: Vec<_> = sut.into_values().collect();
        assert_eq!(
            values,
            vec![1, 2],
            "Expected values to be in the same order as they were inserted"
        );
    }

    #[test]
    fn into_values_consumes_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let values: Vec<_> = sut.into_values().collect();
        assert_eq!(values, vec![1, 2]);
    }

    #[test]
    fn into_values_returns_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let values: Vec<_> = sut.into_values().collect();
        assert!(
            values.is_empty(),
            "Expected into_values to return an empty iterator when AList is empty"
        );
    }

    #[test]
    fn iter_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let pairs: Vec<_> = sut.iter().collect();
        assert_eq!(
            pairs,
            vec![(&"key1", &1), (&"key2", &2)],
            "Expected key-value pairs to be in the same order as they were inserted"
        );
    }

    #[test]
    fn iter_is_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let pairs: Vec<_> = sut.iter().collect();
        assert!(
            pairs.is_empty(),
            "Expected iter to return an empty iterator when AList is empty"
        );
    }

    #[test]
    fn iter_does_not_modify_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Iterating over the list should not modify it
        for (_key, value) in sut.iter() {
            // Just checking that we can access the values without modifying them
            assert!(*value == 1 || *value == 2);
        }

        // Ensure that the structure (key-value pairs) is unchanged
        assert_eq!(sut.len(), 2);
        assert_eq!(sut.get("key1"), Some(&1));
        assert_eq!(sut.get("key2"), Some(&2));
    }

    #[test]
    fn iter_mut_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let pairs: Vec<_> = sut.iter_mut().collect();
        assert_eq!(
            pairs,
            vec![(&"key1", &mut 1), (&"key2", &mut 2)],
            "Expected key-value pairs to be in the same order as they were inserted"
        );
    }

    #[test]
    fn iter_mut_allows_modifying_values() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        for (_key, value) in sut.iter_mut() {
            *value *= 2; // Doubling each value
        }

        let values: Vec<_> = sut.values().collect();
        assert_eq!(
            &values[..],
            &[&2, &4],
            "Expected values to be doubled after modification"
        );
    }

    #[test]
    fn iter_mut_is_empty_when_list_is_empty() {
        let mut sut: AList<&str, i32> = AList::new();
        let pairs: Vec<_> = sut.iter_mut().collect();
        assert!(
            pairs.is_empty(),
            "Expected iter_mut to return an empty iterator when AList is empty"
        );
    }

    #[test]
    fn iter_mut_does_not_modify_the_structure_of_the_list() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        // Modifying values using iter_mut
        for (_key, value) in sut.iter_mut() {
            *value *= 2;
        }

        // Ensure that the structure (keys) is unchanged
        assert_eq!(sut.len(), 2);
        assert_eq!(sut.get("key1"), Some(&2));
        assert_eq!(sut.get("key2"), Some(&4));
    }

    #[test]
    fn into_iter_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let pairs: Vec<_> = sut.into_iter().collect();
        assert_eq!(
            pairs,
            vec![("key1", 1), ("key2", 2)],
            "Expected key-value pairs to be in the same order as they were inserted"
        );
    }

    #[test]
    fn into_iter_is_empty_when_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let pairs: Vec<_> = sut.into_iter().collect();
        assert!(
            pairs.is_empty(),
            "Expected into_iter to return an empty iterator when AList is empty"
        );
    }

    #[test]
    fn into_iter_for_alist_ref_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let pairs: Vec<_> = (&sut).into_iter().collect();
        assert_eq!(
            &pairs[..],
            &[(&"key1", &1), (&"key2", &2)],
            "Expected key-value pairs to be in the same order as they were inserted"
        );
    }

    #[test]
    fn into_iter_for_alist_mut_ref_returns_correct_order_of_insertions() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let pairs: Vec<_> = (&mut sut).into_iter().collect();
        assert_eq!(
            &pairs[..],
            &[(&"key1", &mut 1), (&"key2", &mut 2)],
            "Expected key-value pairs to be in the same order as they were inserted"
        );
    }

    #[test]
    fn clone_creates_an_exact_copy() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        sut.insert("key2", 2);

        let clone = sut.clone();

        // Ensure the clone contains the same elements in the same order
        assert_eq!(sut.len(), clone.len());
        assert_eq!(sut.get("key1"), clone.get("key1"));
        assert_eq!(sut.get("key2"), clone.get("key2"));

        // Ensure the original and the clone are independent
        sut.insert("key3", 3);
        assert!(
            clone.get("key3").is_none(),
            "Expected clone to not reflect changes made to the original after cloning"
        );
    }

    #[test]
    fn clone_of_empty_list_is_empty() {
        let sut: AList<&str, i32> = AList::new();
        let clone = sut.clone();

        // Ensure the clone is also empty
        assert!(
            clone.is_empty(),
            "Expected the clone of an empty AList to also be empty"
        );
    }

    #[test]
    fn equal_lists_are_detected() {
        let mut sut1 = AList::new();
        sut1.insert("key1", 1);
        sut1.insert("key2", 2);

        let mut sut2 = AList::new();
        sut2.insert("key1", 1);
        sut2.insert("key2", 2);

        assert_eq!(sut1, sut2, "Expected two identical ALists to be equal");
    }

    #[test]
    fn equal_lists_with_different_order_are_detected() {
        let mut sut1 = AList::new();
        sut1.insert("key1", 1);
        sut1.insert("key2", 2);

        let mut sut2 = AList::new();
        sut2.insert("key2", 2);
        sut2.insert("key1", 1);

        assert_eq!(
            sut1, sut2,
            "Expected two ALists with identical keys/values but different orders to be equal"
        );
    }

    #[test]
    fn unequal_lists_are_detected_due_to_different_keys() {
        let mut sut1 = AList::new();
        sut1.insert("key1", 1);
        sut1.insert("key2", 2);

        let mut sut2 = AList::new();
        sut2.insert("key3", 1);
        sut2.insert("key2", 2);

        assert_ne!(
            sut1, sut2,
            "Expected two ALists with different keys to not be equal"
        );
    }

    #[test]
    fn unequal_lists_are_detected_due_to_different_values() {
        let mut sut1 = AList::new();
        sut1.insert("key1", 1);
        sut1.insert("key2", 2);

        let mut sut2 = AList::new();
        sut2.insert("key1", 1);
        sut2.insert("key2", 3);

        assert_ne!(
            sut1, sut2,
            "Expected two ALists with the same keys but different values to not be equal"
        );
    }

    #[test]
    fn unequal_lists_are_detected_due_to_different_lengths() {
        let mut sut1 = AList::new();
        sut1.insert("key1", 1);

        let mut sut2 = AList::new();
        sut2.insert("key1", 1);
        sut2.insert("key2", 2);

        assert_ne!(
            sut1, sut2,
            "Expected two ALists with different lengths to not be equal"
        );
    }

    #[test]
    fn debug_format_displays_empty_list() {
        let sut: AList<&str, i32> = AList::new();
        let debug_output = format!("{:?}", sut);

        assert_eq!(
            debug_output, "{}",
            "Expected debug output to show an empty AList"
        );
    }

    #[test]
    fn debug_format_displays_single_item() {
        let mut sut = AList::new();
        sut.insert("key1", 1);
        let debug_output = format!("{:?}", sut);

        assert_eq!(
            debug_output, r#"{"key1": 1}"#,
            "Expected debug output to show a single key-value pair"
        );
    }

    #[test]
    fn debug_format_preserves_order_of_insertion() {
        let mut sut = AList::new();
        sut.insert("key2", 2);
        sut.insert("key1", 1);
        let debug_output = format!("{:?}", sut);

        assert_eq!(
            debug_output, r#"{"key2": 2, "key1": 1}"#,
            "Expected debug output to preserve insertion order"
        );
    }
}