evictor 0.7.2

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

mod lfu;
mod lru;
mod mru;
mod queue;
#[cfg(feature = "rand")]
mod random;
mod r#ref;
mod sieve;

use std::hash::Hash;
use std::num::NonZeroUsize;

pub use lfu::LfuPolicy;
pub use lru::LruPolicy;
pub use mru::MruPolicy;
pub use queue::FifoPolicy;
pub use queue::LifoPolicy;
#[cfg(feature = "rand")]
pub use random::RandomPolicy;
pub use r#ref::Entry;
pub use sieve::SievePolicy;
use tether_map::Ptr;
use tether_map::linked_hash_map::LinkedHashMap;

#[cfg(not(feature = "ahash"))]
type RandomState = std::hash::RandomState;
#[cfg(feature = "ahash")]
type RandomState = ahash::RandomState;

mod private {
    pub trait Sealed {}
}

#[doc(hidden)]
#[must_use]
pub enum InsertionResult<K, T> {
    Inserted(Ptr, Option<T>),
    Updated(Ptr),
    FoundTouchedNoUpdate(Ptr),
    NotFoundNoInsert(K, Option<T>),
}

impl<K, T> std::fmt::Debug for InsertionResult<K, T> {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            InsertionResult::Inserted(ptr, _) => f.debug_tuple("Inserted").field(ptr).finish(),
            InsertionResult::Updated(ptr) => f.debug_tuple("Updated").field(ptr).finish(),
            InsertionResult::FoundTouchedNoUpdate(ptr) => {
                f.debug_tuple("FoundTouchedNoUpdate").field(ptr).finish()
            }
            InsertionResult::NotFoundNoInsert(_, _) => f.debug_tuple("NotFoundNoInsert").finish(),
        }
    }
}

#[doc(hidden)]
pub enum InsertOrUpdateAction<T> {
    InsertOrUpdate(T),
    TouchNoUpdate,
    NoInsert(Option<T>),
}

/// Trait for wrapping values in cache entries.
///
/// This trait allows policies to associate additional metadata with cached
/// values while providing uniform access to the underlying data. Different
/// eviction policies may store additional information alongside the cached
/// value (such as access frequency for Lfu or access timestamps).
///
/// # Type Parameters
///
/// * `T` - The type of the cached value being wrapped
///
/// # Design Notes
///
/// This trait abstracts over the storage requirements of different eviction
/// policies. Some policies like Lru only need to store the value itself,
/// while others like Lfu need to track additional metadata such as access
/// frequency counts. By using this trait, the cache implementation can
/// remain generic over different storage strategies.
#[doc(hidden)]
pub trait EntryValue<T>: private::Sealed {
    /// Creates a new entry containing the given value.
    ///
    /// This method should initialize any policy-specific metadata to
    /// appropriate default values. For example, an Lfu policy might
    /// initialize access counts to zero, while an Lru policy might not need
    /// any additional initialization.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to be stored in the cache entry
    fn new(value: T) -> Self;

    /// Converts the entry into its contained value.
    ///
    /// This method consumes the entry and extracts the wrapped value,
    /// discarding any policy-specific metadata. This is typically used
    /// when an entry is being removed from the cache.
    fn into_value(self) -> T;

    /// Returns a reference to the contained value.
    ///
    /// This method provides read-only access to the cached value without
    /// affecting any policy-specific metadata or consuming the entry.
    fn value(&self) -> &T;

    /// Returns a mutable reference to the contained value.
    ///
    /// This method provides write access to the cached value. The policy
    /// may or may not update its metadata when this method is called,
    /// depending on the specific implementation requirements.
    fn value_mut(&mut self) -> &mut T;
}

/// Trait for cache metadata that tracks eviction state.
///
/// This trait provides policy-specific metadata storage and the ability
/// to identify which entry should be evicted next. Different eviction
/// policies maintain different types of metadata to efficiently determine
/// eviction order.
///
/// # Design Philosophy
///
/// The metadata abstraction allows each eviction policy to maintain its
/// own internal state without exposing implementation details to the
/// generic cache structure. This enables efficient O(1) eviction decisions
/// across all supported policies.
///
/// # Metadata Examples by Policy
///
/// - **Lru/Mru**: Typically maintains a doubly-linked list order via indices
/// - **Lfu**: May track frequency buckets and least-used indices
/// - **Fifo/Lifo**: Often just tracks head/tail pointers for queue ordering
/// - **Random**: May maintain no additional state or seed information
///
/// # Default Implementation
///
/// The `Default` trait bound ensures that metadata can be easily initialized
/// when creating a new cache. The default state should represent an empty
/// cache with no entries.
#[doc(hidden)]
pub trait Metadata<T>: Default + private::Sealed + Clone {
    /// The entry type used by this policy to wrap cached values.
    type EntryType: EntryValue<T>;

    /// Returns the index of the entry that should be evicted next.
    ///
    /// This method provides the core eviction logic by identifying which
    /// entry in the cache should be removed when space is needed. The
    /// returned index corresponds to a position in the cache's internal
    /// storage (typically an `LinkedHashMap`).
    ///
    /// # Returns
    ///
    /// The index of the entry that would be evicted next according to
    /// this policy's eviction strategy. For an empty cache, this method's
    /// behavior is unspecified.
    ///
    /// # Performance
    ///
    /// This method must have O(1) time complexity to maintain the cache's
    /// performance guarantees. Implementations should pre-compute or
    /// efficiently track the tail index rather than scanning entries.
    ///
    /// # Policy-Specific Behavior
    ///
    /// - **Lru**: Returns index of least recently used entry
    /// - **Mru**: Returns index of most recently used entry
    /// - **Lfu**: Returns index of least frequently used entry
    /// - **Fifo**: Returns index of first inserted entry
    /// - **Lifo**: Returns index of last inserted entry
    /// - **Random**: Returns index of randomly selected entry
    ///
    /// # Usage
    ///
    /// This method is typically called by the cache implementation when:
    /// - The cache is at capacity and a new entry needs to be inserted
    /// - The `pop()` method is called to explicitly remove the tail entry
    /// - The `tail()` method is called to inspect the next eviction candidate
    fn candidate_removal_index<K>(
        &self,
        queue: &LinkedHashMap<K, Self::EntryType, RandomState>,
    ) -> Option<Ptr>;

    fn clone_from<K>(
        &mut self,
        other: &Self,
        new_queue: &LinkedHashMap<K, Self::EntryType, RandomState>,
    ) {
        let _ = new_queue;
        <Self as Clone>::clone_from(self, other);
    }
}

/// Trait defining cache eviction policies.
///
/// This trait encapsulates the behavior of different cache eviction strategies
/// such as Lru, Mru, Lfu, Fifo, Lifo, and Random. Each policy defines how
/// entries are prioritized and which entry should be evicted when the cache is
/// full.
///
/// # Type Parameters
///
/// * `T` - The type of values stored in the cache
///
/// # Associated Types
///
/// This trait defines three associated types that work together:
/// - `EntryType`: Wraps cached values with policy-specific metadata
/// - `MetadataType`: Maintains global policy state for eviction decisions
/// - `IntoIter`: Provides owned iteration over cache contents in eviction order
///
/// # Policy Implementations
///
/// The crate provides several built-in policy implementations:
///
/// ## Recency-Based Policies
/// - **Lru (Least Recently Used)**: Evicts entries that haven't been accessed
///   recently
/// - **Mru (Most Recently Used)**: Evicts entries that were accessed most
///   recently
///
/// ## Frequency-Based Policies  
/// - **Lfu (Least Frequently Used)**: Evicts entries with the lowest access
///   count
///
/// ## Insertion-Order Policies
/// - **Fifo (First In, First Out)**: Evicts entries in insertion order
/// - **Lifo (Last In, First Out)**: Evicts entries in reverse insertion order
///
/// ## Randomized Policies
/// - **Random**: Evicts entries randomly
///
/// ## Sieve Policy
/// - **Sieve**: Uses a visited bit and hand pointer for efficient eviction with
///   second-chance semantics
///
/// # Error Handling
///
/// Policy implementations should handle edge cases gracefully:
/// - Empty caches (no entries to evict)
/// - Single-entry caches
/// - Invalid indices (though these should not occur in normal operation)
///
/// # Iteration Order Consistency
///
/// The `iter()` and `into_iter()` methods must return entries in eviction
/// order, meaning the first item returned should be the same as what `tail()`
/// would return (except for policies where the order is specified as
/// arbitrary e.g. [`Random`]).
#[doc(hidden)]
pub trait Policy<T>: private::Sealed {
    /// The metadata type used by this policy to track eviction state.
    type MetadataType: Metadata<T>;

    /// The iterator type returned by `into_iter()`.
    type IntoIter<K: Hash + Eq>: Iterator<Item = (K, T)>;

    #[track_caller]
    fn insert_or_update_entry<K: Hash + Eq>(
        key: K,
        make_room_on_insert: bool,
        get_value: impl FnOnce(&K, /* is_insert */ bool) -> InsertOrUpdateAction<T>,
        metadata: &mut Self::MetadataType,
        queue: &mut LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> InsertionResult<K, T>;

    /// Updates the entry's position in the eviction order.
    ///
    /// This method is called when an entry is accessed (via get, insert, etc.)
    /// and should update the policy's internal state to reflect the access.
    ///
    /// # Parameters
    /// - `index`: The index of the accessed entry
    /// - `metadata`: Mutable reference to policy metadata
    /// - `queue`: Mutable reference to the cache's storage
    ///
    /// # Returns
    /// The new index of the entry after any reordering
    #[track_caller]
    fn touch_entry<K: Hash + Eq>(
        ptr: Ptr,
        metadata: &mut Self::MetadataType,
        queue: &mut LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    );

    /// Evict the next entry from the cache. Returns the pointer to the next
    /// entry in the queue after removal, and the removed key-value pair if
    /// available.
    #[inline]
    #[track_caller]
    fn evict_entry<K: Hash + Eq>(
        metadata: &mut Self::MetadataType,
        queue: &mut LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> Option<(K, <Self::MetadataType as Metadata<T>>::EntryType)> {
        let removed = metadata.candidate_removal_index(queue)?;
        Self::remove_entry(removed, metadata, queue).1
    }

    /// Removes the entry at the specified index and returns the index of the
    /// entry which replaced it.
    ///
    /// This method handles the removal of an entry and updates the policy's
    /// internal state to maintain consistency.
    ///
    /// **Note**: After the removal of the item at `index`, the element at
    /// `index` **must be** the last element in the queue. That is, if you have
    /// a queue like `[0, 1, 2, 3]`, and you remove index 1, the queue must
    /// become `[0, 3, 2]`. This is relied on for insertion and retain
    /// operations.
    ///
    /// # Parameters
    /// - `index`: The index of the entry to remove
    /// - `metadata`: Mutable reference to policy metadata
    /// - `queue`: Mutable reference to the cache's storage
    ///
    /// # Returns
    /// - A pointer to the next entry in the queue after removal
    /// - The removed key-value pair, or None if the index was invalid
    #[allow(clippy::type_complexity)]
    #[track_caller]
    fn remove_entry<K: Hash + Eq>(
        ptr: Ptr,
        metadata: &mut Self::MetadataType,
        queue: &mut LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> (
        Option<Ptr>,
        Option<(K, <Self::MetadataType as Metadata<T>>::EntryType)>,
    );

    #[track_caller]
    fn remove_key<K: Hash + Eq>(
        key: &K,
        metadata: &mut Self::MetadataType,
        queue: &mut LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> Option<<Self::MetadataType as Metadata<T>>::EntryType>;

    /// Returns an iterator over the entries in the cache in eviction order.
    ///
    /// The iterator yields key-value pairs in the order they would be evicted,
    /// starting with the entry that would be evicted first (the "tail" of the
    /// eviction order). The specific ordering depends on the policy:
    ///
    /// - **Lru**: Iterates from least recently used to most recently used
    /// - **Mru**: Iterates from most recently used to least recently used
    /// - **Lfu**: Iterates from least frequently used to most frequently used,
    ///   with ties broken by insertion/access order
    /// - **Fifo**: Iterates from first inserted to last inserted
    /// - **Lifo**: Iterates from last inserted to first inserted
    /// - **Random**: Iterates in random order (debug) or arbitrary order
    ///   (release)
    ///
    /// This is an internal trait method used by policy implementations.
    ///
    /// # Parameters
    /// - `metadata`: Reference to policy-specific metadata for traversal
    /// - `queue`: Reference to the cache's underlying storage
    ///
    /// # Returns
    /// An iterator yielding `(&Key, &Value)` pairs in eviction order
    fn iter<'q, K>(
        metadata: &'q Self::MetadataType,
        queue: &'q LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> impl Iterator<Item = (&'q K, &'q T)>
    where
        T: 'q;

    /// Converts the cache into an iterator over key-value pairs in eviction
    /// order.
    ///
    /// This method consumes the cache and returns an iterator that yields `(K,
    /// T)` pairs. The iteration order depends on the specific eviction
    /// policy:
    ///
    /// - **Lru**: Items are yielded from least recently used to most recently
    ///   used
    /// - **Mru**: Items are yielded from most recently used to least recently
    ///   used
    /// - **Lfu**: Items are yielded from least frequently used to most
    ///   frequently used
    /// - **Fifo**: Items are yielded from first inserted to last inserted
    /// - **Lifo**: Items are yielded from last inserted to first inserted
    /// - **Random**: Items are yielded in an arbitrary order.
    ///
    /// # Parameters
    /// - `metadata`: The policy's metadata containing eviction state
    ///   information
    /// - `queue`: The cache's internal storage map containing all key-value
    ///   pairs
    ///
    /// # Returns
    /// An iterator that yields `(K, T)` pairs in the policy-specific eviction
    /// order. The iterator takes ownership of the cache contents, making
    /// this a consuming operation.
    fn into_iter<K: Hash + Eq>(
        metadata: Self::MetadataType,
        queue: LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> Self::IntoIter<K>;

    /// Converts the cache entries into an iterator of key-entry pairs in
    /// eviction order.
    ///
    /// This method is similar to `into_iter()` but returns the full entry
    /// wrappers instead of just the values. This allows access to any
    /// policy-specific metadata stored within the entries, which can be
    /// useful for debugging, analysis, or advanced cache operations.
    ///
    /// # Parameters
    ///
    /// * `metadata` - The policy's metadata containing eviction state
    ///   information
    /// * `queue` - The cache's internal storage map containing all key-entry
    ///   pairs
    ///
    /// # Returns
    ///
    /// An iterator that yields `(K, <Self::MetadataType as
    /// Metadata<T>>::EntryType)` pairs in the policy-specific eviction
    /// order. The iterator consumes the cache contents.
    ///
    /// # Use Cases
    ///
    /// This method is primarily used for internal implementation details where
    /// entry metadata is needed
    ///
    /// For typical usage, prefer `into_iter()` which extracts just the values.
    fn into_entries<K: Hash + Eq>(
        metadata: Self::MetadataType,
        queue: LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) -> impl Iterator<Item = (K, <Self::MetadataType as Metadata<T>>::EntryType)>;

    /// Validates the cache's internal state against the full set of kv pairs
    /// known. This is **expensive** and should only be used for debugging
    /// purposes.
    #[cfg(all(debug_assertions, feature = "internal-debugging"))]
    #[doc(hidden)]
    fn debug_validate<K: Hash + Eq + std::fmt::Debug>(
        metadata: &Self::MetadataType,
        queue: &LinkedHashMap<K, <Self::MetadataType as Metadata<T>>::EntryType, RandomState>,
    ) where
        T: std::fmt::Debug;
}

/// A least-recently-used (Lru) cache.
///
/// Evicts the entry that was accessed longest ago when the cache is full.
/// This policy is ideal for workloads where recently accessed items are
/// more likely to be accessed again.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Lru;
///
/// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
///
/// cache.get(&1); // Mark as recently used
/// cache.insert(4, "four".to_string()); // Evicts key 2
///
/// // `into_iter` returns the items in eviction order, which is Lru first.
/// assert_eq!(
///     cache.into_iter().collect::<Vec<_>>(),
///     [
///         (3, "three".to_string()),
///         (1, "one".to_string()),
///         (4, "four".to_string()),
///     ]
/// );
/// ```
#[doc(alias = "LRU")]
pub type Lru<Key, Value> = Cache<Key, Value, LruPolicy>;

/// See [`Lru`].
#[doc(hidden)]
pub type LRU<Key, Value> = Lru<Key, Value>;

/// A most-recently-used (Mru) cache.
///
/// Evicts the entry that was accessed most recently when the cache is full.
/// This policy can be useful for workloads with sequential access patterns
/// where the most recently accessed item is unlikely to be needed again.
///
/// # Time Complexity  
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Mru;
///
/// let mut cache = Mru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
///
/// cache.get(&1); // Mark as recently used
/// cache.insert(4, "four".to_string()); // Evicts key 1
///
/// // `into_iter` returns the items in eviction order, which is Mru first.
/// assert_eq!(
///     cache.into_iter().collect::<Vec<_>>(),
///     [
///         (4, "four".to_string()),
///         (3, "three".to_string()),
///         (2, "two".to_string()),
///     ]
/// );
/// ```
#[doc(alias = "MRU")]
pub type Mru<Key, Value> = Cache<Key, Value, MruPolicy>;

/// See [`Mru`].
#[doc(hidden)]
pub type MRU<Key, Value> = Mru<Key, Value>;

/// A least-frequently-used (Lfu) cache.
///
/// This implementation uses frequency buckets with doubly-linked lists to
/// achieve O(1) time complexity for all operations.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Lfu;
///
/// let mut cache = Lfu::<i32, String>::new(NonZeroUsize::new(4).unwrap());
///
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
/// cache.insert(4, "four".to_string());
///
/// // Access key 1 multiple times to increase its frequency
/// cache.get(&1);
/// cache.get(&1);
/// cache.get(&1);
///
/// // Access key 2, 3 once
/// cache.get(&2);
/// cache.get(&3);
///
/// // Key 4 has frequency 0 (never accessed after insertion)
/// // Insert new item - this will evict the least frequently used (key 4)
/// cache.insert(5, "five".to_string());
///
/// // `into_iter` returns the items in eviction order, which is Lfu first, with Lru tiebreaking.
/// assert_eq!(
///     cache.into_iter().collect::<Vec<_>>(),
///     [
///         (5, "five".to_string()),
///         (2, "two".to_string()),
///         (3, "three".to_string()),
///         (1, "one".to_string()),
///     ]
/// );
/// ```
#[doc(alias = "LFU")]
pub type Lfu<Key, Value> = Cache<Key, Value, LfuPolicy>;

/// See [`Lfu`].
#[doc(hidden)]
pub type LFU<Key, Value> = Lfu<Key, Value>;

/// A first-in-first-out (Fifo) cache.
///
/// Evicts the entry that was inserted earliest when the cache is full.
/// This policy treats the cache as a queue where the oldest inserted
/// item is removed first, regardless of access patterns.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Fifo;
///
/// let mut cache = Fifo::<i32, String>::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
///
/// cache.get(&1); // Access key 1 - this doesn't affect eviction order in Fifo
/// cache.insert(4, "four".to_string()); // Evicts key 1 (first inserted)
///
/// // `into_iter` returns the items in eviction order, which is Fifo.
/// assert_eq!(
///     cache.into_iter().collect::<Vec<_>>(),
///     [
///         (2, "two".to_string()),
///         (3, "three".to_string()),
///         (4, "four".to_string()),
///     ]
/// );
/// ```
#[doc(alias = "FIFO")]
pub type Fifo<Key, Value> = Cache<Key, Value, FifoPolicy>;

/// See [`Fifo`].
#[doc(hidden)]
pub type FIFO<Key, Value> = Fifo<Key, Value>;

/// A last-in-first-out (Lifo) cache.
///
/// Evicts the entry that was inserted most recently when the cache is full.
/// This policy treats the cache as a stack where the most recently inserted
/// item is removed first, regardless of access patterns.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Lifo;
///
/// let mut cache = Lifo::<i32, String>::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
///
/// cache.get(&1); // Access key 1 - this doesn't affect eviction order in Lifo
/// cache.insert(4, "four".to_string()); // Evicts key 3 (most recently inserted)
///
/// // `into_iter` returns the items in eviction order, which is Lifo.
/// assert_eq!(
///     cache.into_iter().collect::<Vec<_>>(),
///     [
///         (4, "four".to_string()),
///         (2, "two".to_string()),
///         (1, "one".to_string()),
///     ]
/// );
/// ```
#[doc(alias = "LIFO")]
pub type Lifo<Key, Value> = Cache<Key, Value, LifoPolicy>;

/// See [`Lifo`].
#[doc(hidden)]
pub type LIFO<Key, Value> = Lifo<Key, Value>;

/// A random eviction cache.
///
/// Evicts entries randomly when the cache is full. This policy can be useful
/// for workloads where no particular access pattern can be predicted, or as
/// a simple baseline for comparison with other eviction policies.
///
/// The random selection is performed using the `rand` crate. You **must
/// not** rely on the order returned by iteration. This is enforced by
/// randomizing the order of iteration during debug builds. Release builds do
/// not perform this randomization for performance reasons, but the order is
/// still arbitrary and should not be relied upon.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1)
///
/// # Examples
///
/// ```
/// use std::num::NonZeroUsize;
///
/// use evictor::Random;
///
/// let mut cache = Random::<i32, String>::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one".to_string());
/// cache.insert(2, "two".to_string());
/// cache.insert(3, "three".to_string());
///
/// // Access doesn't affect eviction order in Random policy
/// cache.get(&1);
/// cache.insert(4, "four".to_string()); // Evicts a random entry
///
/// // The order returned by `into_iter` is not predictable
/// let pairs: Vec<_> = cache.into_iter().collect();
/// assert_eq!(pairs.len(), 3);
/// ```
#[cfg(feature = "rand")]
pub type Random<Key, Value> = Cache<Key, Value, RandomPolicy>;

/// A Sieve cache implementing the algorithm outlined in the paper
/// [Sieve is Simpler than Lru](https://junchengyang.com/publication/nsdi24-SIEVE.pdf).
///
/// Sieve uses a "visited" bit per entry and a hand pointer that scans
/// for eviction candidates, giving recently accessed items a "second chance"
/// before eviction.
///
/// # Algorithm Overview
///
/// Sieve maintains:
/// - A **visited bit** for each cache entry (initially false)
/// - A **hand pointer** that moves through entries looking for eviction
///   candidates
/// - A **doubly-linked list** structure for efficient traversal
///
/// ## Key Operations
///
/// ### Access (get/get_mut)
/// When an entry is accessed:
/// 1. The visited bit is set to `true`
/// 2. The entry position in eviction order may be updated
///
/// ### Eviction
/// When space is needed:
/// 1. The hand pointer scans entries starting from its current position
/// 2. For each entry with `visited = true`: reset to `false` and continue
///    scanning
/// 3. The first entry with `visited = false` is evicted
/// 4. The hand pointer advances to the next position
///
/// This gives recently accessed entries a "second chance" - they're skipped
/// once during eviction scanning, but evicted if accessed again without being
/// used.
///
/// # Time Complexity
/// - Insert/Get/Remove: O(1) average, O(n) worst case
/// - Peek/Contains: O(1) average, O(n) worst case
/// - Pop/Clear: O(1) average, O(n) worst case
///
/// # Examples
///
/// ## Basic Usage
/// ```rust
/// use std::num::NonZeroUsize;
///
/// use evictor::Sieve;
///
/// let mut cache = Sieve::new(NonZeroUsize::new(3).unwrap());
/// cache.insert(1, "one");
/// cache.insert(2, "two");
/// cache.insert(3, "three");
///
/// // Access entry 1 to set its visited bit
/// cache.get(&1);
///
/// // This will evict entry 2 (unvisited), not entry 1
/// cache.insert(4, "four");
/// assert!(cache.contains_key(&1)); // Still present (second chance)
/// assert!(!cache.contains_key(&2)); // Evicted
/// ```
///
/// ## Second Chance Behavior
/// ```rust
/// use std::num::NonZeroUsize;
///
/// use evictor::Sieve;
///
/// let mut cache = Sieve::new(NonZeroUsize::new(2).unwrap());
/// cache.insert("A", 1);
/// cache.insert("B", 2);
///
/// // Access A to mark it as visited
/// cache.get(&"A");
///
/// // Insert C - will scan and find A visited, reset its bit, continue to B
/// cache.insert("C", 3);
/// assert!(cache.contains_key(&"A")); // A got second chance
/// assert!(!cache.contains_key(&"B")); // B was evicted
///
/// // Now A's visited bit is false, so next eviction will remove A
/// cache.insert("D", 4);
/// assert!(!cache.contains_key(&"A")); // A evicted (used its second chance)
/// assert!(cache.contains_key(&"C"));
/// assert!(cache.contains_key(&"D"));
/// ```
///
/// ## Comparison with peek() vs get()
/// ```rust
/// use std::num::NonZeroUsize;
///
/// use evictor::Sieve;
///
/// let mut cache = Sieve::new(NonZeroUsize::new(2).unwrap());
/// cache.insert(1, "one");
/// cache.insert(2, "two");
///
/// // peek() does NOT set visited bit
/// cache.peek(&1);
/// cache.insert(3, "three"); // Evicts 1 (not visited)
/// assert!(!cache.contains_key(&1));
///
/// // get() DOES set visited bit
/// cache.get(&2);
/// cache.insert(4, "four"); // Evicts 3 (2 gets second chance)
/// assert!(cache.contains_key(&2));
/// assert!(!cache.contains_key(&3));
/// ```
///
/// ## Iteration Order
/// ```rust
/// use std::num::NonZeroUsize;
///
/// use evictor::Sieve;
///
/// let mut cache = Sieve::new(NonZeroUsize::new(3).unwrap());
/// cache.insert("A", 1);
/// cache.insert("B", 2);
/// cache.insert("C", 3);
///
/// // Iteration follows eviction order (starting from hand position)
/// let items: Vec<_> = cache.iter().collect();
/// // Order depends on hand position and visited bits
/// assert_eq!(items.len(), 3);
///
/// // First item should match tail() (next eviction candidate)
/// assert_eq!(cache.tail().unwrap(), cache.iter().next().unwrap());
/// ```
#[doc(alias = "SIEVE")]
pub type Sieve<Key, Value> = Cache<Key, Value, SievePolicy>;

/// See [`Sieve`].
#[doc(hidden)]
pub type SIEVE<Key, Value> = Sieve<Key, Value>;

/// Cache performance and usage statistics.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "statistics")] {
/// use evictor::Lru;
///
/// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
/// cache.insert("a".to_string(), 1);
/// cache.insert("b".to_string(), 2);
///
/// let stats = cache.statistics();
/// assert_eq!(stats.len(), 2);
/// assert_eq!(stats.insertions(), 2);
/// assert_eq!(stats.evictions(), 0);
/// # }
/// ```
#[derive(Clone, Debug)]
#[cfg(feature = "statistics")]
pub struct Statistics {
    len: usize,
    capacity: NonZeroUsize,
    evictions: u64,
    insertions: u64,
    misses: u64,
    hits: u64,
}

#[cfg(feature = "statistics")]
impl Statistics {
    fn with_capacity(capacity: NonZeroUsize) -> Self {
        Self {
            len: 0,
            capacity,
            evictions: 0,
            insertions: 0,
            misses: 0,
            hits: 0,
        }
    }

    /// Returns `true` if the cache contains no entries.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// assert!(cache.statistics().is_empty());
    ///
    /// cache.insert("key".to_string(), "value".to_string());
    /// assert!(!cache.statistics().is_empty());
    /// # }
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the current number of entries stored in the cache.
    ///
    /// This count represents the actual number of key-value pairs currently
    /// residing in the cache, which may be less than the cache's capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(3).unwrap());
    /// assert_eq!(cache.statistics().len(), 0);
    ///
    /// cache.insert("a".to_string(), 1);
    /// cache.insert("b".to_string(), 2);
    /// assert_eq!(cache.statistics().len(), 2);
    /// # }
    /// ```
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the current cache residency as a percentage (0.0 to 100.0).
    ///
    /// Residency represents how full the cache is, calculated as the current
    /// number of entries divided by the maximum capacity, expressed as a
    /// percentage. A residency of 100.0% indicates the cache is at full
    /// capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(4).unwrap());
    /// assert_eq!(cache.statistics().residency(), 0.0);
    ///
    /// cache.insert("a".to_string(), 1);
    /// cache.insert("b".to_string(), 2);
    /// assert_eq!(cache.statistics().residency(), 50.0);
    ///
    /// cache.insert("c".to_string(), 3);
    /// cache.insert("d".to_string(), 4);
    /// assert_eq!(cache.statistics().residency(), 100.0);
    /// # }
    /// ```
    pub fn residency(&self) -> f64 {
        self.len as f64 / self.capacity.get() as f64 * 100.0
    }

    /// Returns the maximum capacity of the cache.
    ///
    /// This is the maximum number of key-value pairs that the cache can store
    /// before eviction policies take effect to make room for new entries.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let cache: Lru<String, i32> = Lru::new(std::num::NonZeroUsize::new(100).unwrap());
    /// assert_eq!(cache.statistics().capacity(), 100);
    /// # }
    /// ```
    pub fn capacity(&self) -> usize {
        self.capacity.get()
    }

    /// Returns the total number of evictions that have occurred.
    ///
    /// An eviction happens when an entry is removed from the cache to make room
    /// for a new entry, according to the cache's eviction policy (LRU, LFU,
    /// etc.). This counter tracks the lifetime total of such removals.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// assert_eq!(cache.statistics().evictions(), 0);
    ///
    /// cache.insert("a".to_string(), 1);
    /// cache.insert("b".to_string(), 2);
    /// assert_eq!(cache.statistics().evictions(), 0);
    ///
    /// // This insertion will evict the least recently used entry
    /// cache.insert("c".to_string(), 3);
    /// assert_eq!(cache.statistics().evictions(), 1);
    /// # }
    /// ```
    pub fn evictions(&self) -> u64 {
        self.evictions
    }

    /// Returns the total number of insertion operations that have occurred.
    ///
    /// This counter increments every time a new key-value pair is inserted into
    /// the cache, regardless of whether it causes an eviction. Updates to
    /// existing keys do not count as insertions.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// assert_eq!(cache.statistics().insertions(), 0);
    ///
    /// cache.insert("a".to_string(), 1);
    /// assert_eq!(cache.statistics().insertions(), 1);
    ///
    /// cache.insert("a".to_string(), 2); // Update existing key
    /// assert_eq!(cache.statistics().insertions(), 1);
    /// # }
    /// ```
    pub fn insertions(&self) -> u64 {
        self.insertions
    }

    /// Returns the total number of cache hits.
    ///
    /// A cache hit occurs when a requested key is found in the cache.
    /// This metric is useful for measuring cache effectiveness.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// cache.insert("a".to_string(), 1);
    ///
    /// assert_eq!(cache.statistics().hits(), 0);
    ///
    /// cache.get(&"a".to_string()); // Hit
    /// assert_eq!(cache.statistics().hits(), 1);
    ///
    /// cache.get(&"b".to_string()); // Miss
    /// assert_eq!(cache.statistics().hits(), 1);
    /// # }
    /// ```
    pub fn hits(&self) -> u64 {
        self.hits
    }

    /// Returns the total number of cache misses.
    ///
    /// A cache miss occurs when a requested key is not found in the cache.
    /// High miss rates may indicate the cache size is too small or the access
    /// pattern is not well-suited for caching.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// cache.insert("a".to_string(), 1);
    ///
    /// assert_eq!(cache.statistics().misses(), 0);
    ///
    /// cache.get(&"a".to_string()); // Hit
    /// assert_eq!(cache.statistics().misses(), 0);
    ///
    /// cache.get(&"b".to_string()); // Miss
    /// assert_eq!(cache.statistics().misses(), 1);
    /// # }
    /// ```
    pub fn misses(&self) -> u64 {
        self.misses
    }

    /// Returns the cache hit rate as a percentage (0.0 to 100.0).
    ///
    /// The hit rate is calculated as `hits / (hits + misses) * 100`.
    /// A higher hit rate indicates better cache performance. Returns 0.0
    /// if no cache access operations have been performed yet.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// cache.insert("a".to_string(), 1);
    /// cache.insert("b".to_string(), 2);
    ///
    /// // Initially no accesses, so hit rate is 0
    /// assert_eq!(cache.statistics().hit_rate(), 0.0);
    ///
    /// cache.get(&"a".to_string()); // Hit
    /// cache.get(&"b".to_string()); // Hit
    /// cache.get(&"c".to_string()); // Miss
    ///
    /// // 2 hits out of 3 total accesses = 66.67%
    /// assert!((cache.statistics().hit_rate() - 66.66666666666666).abs() < f64::EPSILON);
    /// # }
    /// ```
    pub fn hit_rate(&self) -> f64 {
        if self.hits + self.misses == 0 {
            0.0
        } else {
            self.hits as f64 / (self.hits + self.misses) as f64 * 100.0
        }
    }

    /// Returns the cache miss rate as a percentage (0.0 to 100.0).
    ///
    /// The miss rate is calculated as `misses / (hits + misses) * 100`.
    /// A lower miss rate indicates better cache performance. Returns 0.0
    /// if no cache access operations have been performed yet.
    ///
    /// Note: `hit_rate() + miss_rate()` always equals 100.0 (when there have
    /// been accesses).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "statistics")] {
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(std::num::NonZeroUsize::new(2).unwrap());
    /// cache.insert("a".to_string(), 1);
    ///
    /// // Initially no accesses, so miss rate is 0
    /// assert_eq!(cache.statistics().miss_rate(), 0.0);
    ///
    /// cache.get(&"a".to_string()); // Hit
    /// cache.get(&"b".to_string()); // Miss
    /// cache.get(&"c".to_string()); // Miss
    ///
    /// // 2 misses out of 3 total accesses = 66.67%
    /// assert!((cache.statistics().miss_rate() - 66.66666666666666).abs() < f64::EPSILON);
    /// # }
    /// ```
    pub fn miss_rate(&self) -> f64 {
        if self.hits + self.misses == 0 {
            0.0
        } else {
            self.misses as f64 / (self.hits + self.misses) as f64 * 100.0
        }
    }
}

/// A generic cache implementation with configurable eviction policies.
///
/// `Cache` is the underlying generic structure that powers Lru, Mru, Lfu,
/// Fifo, Lifo, Random, and Sieve caches. The eviction behavior is determined by
/// the `PolicyType` parameter, which must implement the `Policy` trait.
///
/// For most use cases, you should use the type aliases [`Lru`], [`Mru`],
/// [`Lfu`], [`Fifo`], [`Lifo`], [`Random`], or [`Sieve`] instead of using
/// `Cache` directly.
///
/// # Type Parameters
///
/// * `Key` - The type of keys stored in the cache. Must implement [`Hash`] +
///   [`Eq`].
/// * `Value` - The type of values stored in the cache.
/// * `PolicyType` - The eviction policy implementation. Must implement
///   `Policy`.
///
/// # Memory Management
///
/// - Pre-allocates space for `capacity` entries to minimize reallocations
/// - Automatically evicts entries when capacity is exceeded
pub struct Cache<Key, Value, PolicyType: Policy<Value>> {
    queue:
        LinkedHashMap<Key, <PolicyType::MetadataType as Metadata<Value>>::EntryType, RandomState>,
    capacity: NonZeroUsize,
    metadata: PolicyType::MetadataType,

    #[cfg(feature = "statistics")]
    statistics: Statistics,
}

impl<Key, Value, PolicyType: Policy<Value>> std::fmt::Debug for Cache<Key, Value, PolicyType>
where
    Key: std::fmt::Debug,
    Value: std::fmt::Debug,
    PolicyType::MetadataType: std::fmt::Debug,
    <PolicyType::MetadataType as Metadata<Value>>::EntryType: std::fmt::Debug,
{
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        f.debug_struct("Cache")
            .field("queue", &self.queue)
            .field("capacity", &self.capacity)
            .field("metadata", &self.metadata)
            .finish()
    }
}

impl<Key, Value, PolicyType: Policy<Value>> Clone for Cache<Key, Value, PolicyType>
where
    Key: Clone + Hash + Eq,
    Value: Clone,
    <PolicyType::MetadataType as Metadata<Value>>::EntryType: Clone,
{
    fn clone(&self) -> Self {
        let mut metadata = <PolicyType::MetadataType as Default>::default();
        <PolicyType::MetadataType as Metadata<Value>>::clone_from(
            &mut metadata,
            &self.metadata,
            &self.queue,
        );
        Self {
            queue: self.queue.clone(),
            metadata,
            capacity: self.capacity,
            #[cfg(feature = "statistics")]
            statistics: self.statistics.clone(),
        }
    }
}

impl<Key: Hash + Eq, Value, PolicyType: Policy<Value>> Cache<Key, Value, PolicyType> {
    /// Creates a new, empty cache with the specified capacity.
    ///
    /// The cache will be able to hold at most `capacity` entries. When the
    /// cache is full and a new entry is inserted, the policy determines
    /// which existing entry will be evicted.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The maximum number of entries the cache can hold. Must be
    ///   greater than zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let cache: Lru<i32, String> = Lru::new(NonZeroUsize::new(100).unwrap());
    /// assert_eq!(cache.capacity(), 100);
    /// assert!(cache.is_empty());
    /// ```
    pub fn new(capacity: NonZeroUsize) -> Self {
        Self {
            queue: LinkedHashMap::with_capacity_and_hasher(capacity.get(), RandomState::default()),
            capacity,
            metadata: PolicyType::MetadataType::default(),
            #[cfg(feature = "statistics")]
            statistics: Statistics::with_capacity(capacity),
        }
    }

    /// Returns the current statistics for the cache.
    #[cfg(feature = "statistics")]
    pub fn statistics(&self) -> Statistics {
        Statistics {
            len: self.queue.len(),
            capacity: self.capacity,
            ..self.statistics
        }
    }

    /// Resets the cache statistics to their initial state.
    #[cfg(feature = "statistics")]
    pub fn reset_statistics(&mut self) {
        self.statistics = Statistics::with_capacity(self.capacity);
    }

    /// Removes all entries from the cache.
    ///
    /// After calling this method, the cache will be empty and
    /// [`len()`](Self::len) will return 0. The capacity remains unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// assert_eq!(cache.len(), 2);
    /// cache.clear();
    /// assert_eq!(cache.len(), 0);
    /// assert!(cache.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.queue.clear();
        self.metadata = PolicyType::MetadataType::default();
    }

    /// Returns a reference to the value without updating its position in the
    /// cache.
    ///
    /// This method provides read-only access to a value without affecting the
    /// eviction order. Unlike [`get()`](Self::get), this will not mark the
    /// entry as touched.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up in the cache
    ///
    /// # Returns
    ///
    /// * `Some(&Value)` if the key exists in the cache
    /// * `None` if the key is not found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// let previous_order = cache
    ///     .iter()
    ///     .map(|(k, v)| (*k, v.clone()))
    ///     .collect::<Vec<_>>();
    ///
    /// // Peek doesn't affect eviction order
    /// assert_eq!(cache.peek(&1), Some(&"one".to_string()));
    /// assert_eq!(cache.peek(&3), None);
    ///
    /// assert_eq!(cache.into_iter().collect::<Vec<_>>(), previous_order);
    /// ```
    pub fn peek(
        &self,
        key: &Key,
    ) -> Option<&Value> {
        self.queue.get(key).map(|entry| entry.value())
    }

    /// Returns a mutable reference to the value, updating the cache if the
    /// value is modified while borrowed.
    ///
    /// This method provides mutable access to a cached value through a smart
    /// `Entry` wrapper that automatically updates the cache's eviction
    /// order **only if** the value is actually modified during the borrow.
    /// Unlike [`get_mut()`](Self::get_mut), which always marks an entry as
    /// touched, `peek_mut` preserves the current eviction order unless changes
    /// are made to the value.
    ///
    /// The returned `Entry` acts as a smart pointer that:
    /// - Provides transparent access to the underlying value via
    ///   `Deref`/`DerefMut`
    /// - Tracks whether the value was modified during the borrow
    /// - Automatically updates the cache's eviction order on drop if
    ///   modifications occurred
    /// - Leaves the eviction order unchanged if no modifications were made
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up in the cache
    ///
    /// # Returns
    ///
    /// * `Some(`[`Entry<'_, Key, Value, PolicyType>`](crate::Entry)`)` - If the
    ///   key exists
    /// * `None` - If the key is not found in the cache
    ///
    /// # Behavior
    ///
    /// ## No Modification
    /// If you obtain an `Entry` but don't modify the value, the cache's
    /// eviction order remains unchanged:
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", vec![1, 2, 3]);
    /// cache.insert("B", vec![4, 5, 6]);
    ///
    /// let original_order: Vec<_> = cache.iter().map(|(k, _)| *k).collect();
    ///
    /// // Peek at the value without modifying it
    /// if let Some(entry) = cache.peek_mut(&"A") {
    ///     let _len = entry.len(); // Read-only access
    ///     // No modifications made
    /// }
    ///
    /// // Eviction order is preserved
    /// let new_order: Vec<_> = cache.iter().map(|(k, _)| *k).collect();
    /// assert_eq!(original_order, new_order);
    /// ```
    ///
    /// ## With Modification
    /// If you modify the value through the `Entry`, the cache automatically
    /// updates the eviction order when the `Entry` is dropped:
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", vec![1, 2, 3]);
    /// cache.insert("B", vec![4, 5, 6]);
    /// cache.insert("C", vec![7, 8, 9]);
    ///
    /// // Before: eviction order is A -> B -> C (A would be evicted first)
    /// assert_eq!(cache.tail().unwrap().0, &"A");
    ///
    /// // Modify "A" through peek_mut
    /// if let Some(mut entry) = cache.peek_mut(&"A") {
    ///     entry.push(4); // This modifies the value
    /// } // Entry is dropped here, triggering cache update
    ///
    /// // After: "A" is now most recently used, "B" would be evicted first
    /// assert_eq!(cache.tail().unwrap().0, &"B");
    /// ```
    ///
    /// # Performance
    ///
    /// - **Lookup**: O(1) average, O(n) worst case (same as hash map lookup)
    /// - **No modification**: No additional overhead beyond the lookup
    /// - **With modification**: O(1) cache reordering when the `Entry` is
    ///   dropped
    pub fn peek_mut<'q>(
        &'q mut self,
        key: &'q Key,
    ) -> Option<Entry<'q, Key, Value, PolicyType>> {
        self.queue
            .get_ptr(key)
            .map(|ptr| Entry::new(ptr, key, self))
    }

    /// Returns a reference to the entry that would be evicted next.
    ///
    /// This method provides access to the entry at the "tail" of the eviction
    /// order without affecting the cache state. The specific entry returned
    /// depends on the policy:
    /// - Lru: Returns the least recently used entry
    /// - Mru: Returns the most recently used entry
    /// - Lfu: Returns the least frequently used entry
    /// - Fifo: Returns the first inserted entry
    /// - Lifo: Returns the last inserted entry
    /// - Random: Returns a randomly selected entry
    /// - Sieve: Returns the next entry that would be evicted after any second
    ///   chances. This may involve an O(n) scan across the cache to find the
    ///   next unvisited entry. **This does not update the visited bit, so an
    ///   eviction will need to rescan even if this method is called**.
    ///
    /// # Returns
    ///
    /// * `Some((&Key, &Value))` if the cache is not empty
    /// * `None` if the cache is empty
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// assert_eq!(cache.tail(), None);
    ///
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// // In Lru, tail returns the least recently used
    /// let (key, value) = cache.tail().unwrap();
    /// assert_eq!(key, &1);
    /// assert_eq!(value, &"one".to_string());
    /// ```
    pub fn tail(&self) -> Option<(&Key, &Value)> {
        let ptr = self.metadata.candidate_removal_index(&self.queue)?;
        self.queue
            .ptr_get_entry(ptr)
            .map(|(key, value)| (key, value.value()))
    }

    /// Returns true if the cache contains the given key.
    ///
    /// This method provides a quick way to check for key existence without
    /// affecting the eviction order or retrieving the value.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to check for existence
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    ///
    /// assert!(cache.contains_key(&1));
    /// assert!(!cache.contains_key(&2));
    /// ```
    pub fn contains_key(
        &self,
        key: &Key,
    ) -> bool {
        self.queue.contains_key(key)
    }

    /// Gets the value for a key, or inserts it using the provided function.
    ///
    /// If the key exists, returns a reference to the existing value and marks
    /// it as touched. If the key doesn't exist, calls the provided function to
    /// create a new value, inserts it, and returns a reference to it.
    ///
    /// When inserting into a full cache, the policy determines which entry is
    /// evicted. The evicted entry's value is returned as the second tuple
    /// element when an eviction occurs, otherwise `None`.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up or insert
    /// * `or_insert` - Function called to create the value if the key doesn't
    ///   exist
    ///
    /// # Returns
    ///
    /// A tuple `(&Value, Option<Value>)` where the first element is a reference
    /// to the value (existing or newly inserted), and the second element is the
    /// evicted value if an eviction occurred.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    ///
    /// // Insert new value
    /// let (value, evicted) = cache.get_or_insert_with(1, |&key| format!("value_{}", key));
    /// assert_eq!(value, "value_1");
    /// assert!(evicted.is_none());
    ///
    /// // Get existing value (function not called)
    /// let (value, evicted) = cache.get_or_insert_with(1, |&key| format!("different_{}", key));
    /// assert_eq!(value, "value_1");
    /// assert!(evicted.is_none());
    /// ```
    pub fn get_or_insert_with(
        &mut self,
        key: Key,
        or_insert: impl FnOnce(&Key) -> Value,
    ) -> (&Value, Option<Value>) {
        let (value, evicted) = self.get_or_insert_with_mut(key, or_insert);
        (&*value, evicted)
    }

    /// Gets the value for a key, or inserts it using the provided function.
    ///
    /// This is the mutable version of
    /// [`get_or_insert_with()`](Self::get_or_insert_with). If the key
    /// exists, returns a mutable reference to the existing value and marks
    /// it as touched. If the key doesn't exist, calls the provided function to
    /// create a new value, inserts it, and returns a mutable reference to
    /// it.
    ///
    /// When inserting into a full cache, the policy determines which entry is
    /// evicted. The evicted entry's value is returned as the second tuple
    /// element when an eviction occurs, otherwise `None`.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up or insert
    /// * `or_insert` - Function called to create the value if the key doesn't
    ///   exist
    ///
    /// # Returns
    ///
    /// A tuple `(&mut Value, Option<Value>)` where the first element is a
    /// mutable reference to the value (existing or newly inserted), and the
    /// second element is the evicted value if an eviction occurred.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    ///
    /// // Insert new value and modify it
    /// let (value, _) = cache.get_or_insert_with_mut(1, |&key| format!("value_{}", key));
    /// value.push_str("_modified");
    /// assert_eq!(cache.peek(&1), Some(&"value_1_modified".to_string()));
    ///
    /// // Get existing value and modify it further (function not called)
    /// let (value, _) = cache.get_or_insert_with_mut(1, |&key| format!("different_{}", key));
    /// value.push_str("_again");
    /// assert_eq!(cache.peek(&1), Some(&"value_1_modified_again".to_string()));
    /// ```
    pub fn get_or_insert_with_mut(
        &mut self,
        key: Key,
        or_insert: impl FnOnce(&Key) -> Value,
    ) -> (&mut Value, Option<Value>) {
        let will_evict = self.queue.len() == self.capacity.get();
        let result = PolicyType::insert_or_update_entry(
            key,
            will_evict,
            |value, is_insert| {
                if is_insert {
                    InsertOrUpdateAction::InsertOrUpdate(or_insert(value))
                } else {
                    InsertOrUpdateAction::TouchNoUpdate
                }
            },
            &mut self.metadata,
            &mut self.queue,
        );

        match result {
            InsertionResult::Inserted(ptr, evicted) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.insertions += 1;
                    self.statistics.misses += 1;

                    self.statistics.evictions += u64::from(will_evict);
                }

                (self.queue[ptr].value_mut(), evicted)
            }
            InsertionResult::FoundTouchedNoUpdate(ptr) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                (self.queue[ptr].value_mut(), None)
            }
            _ => unreachable!("Unexpected insertion result: {:?}", result),
        }
    }

    /// Gets a value from the cache, marking it as touched. If the key is not
    /// present, inserts the default value and returns a reference to it.
    ///
    /// This method will trigger eviction if the cache is at capacity and the
    /// key is not already present.
    ///
    /// # Type Requirements
    ///
    /// The value type must implement [`Default`].
    ///
    /// # Returns
    ///
    /// A tuple `(&Value, Option<Value>)` where the first element is a reference
    /// to the value (existing or newly inserted), and the second element is the
    /// evicted value if an eviction occurred.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, Vec<String>>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Get or insert default (empty Vec<String>)
    /// let (vec_ref, _) = cache.get_or_default(1);
    /// assert!(vec_ref.is_empty());
    ///
    /// // Modify the value through another method
    /// cache.get_mut(&1).unwrap().push("hello".to_string());
    ///
    /// // Subsequent calls return the existing value
    /// let (vec_ref, _) = cache.get_or_default(1);
    /// assert_eq!(vec_ref.len(), 1);
    /// assert_eq!(vec_ref[0], "hello");
    /// ```
    pub fn get_or_default(
        &mut self,
        key: Key,
    ) -> (&Value, Option<Value>)
    where
        Value: Default,
    {
        self.get_or_insert_with(key, |_| Value::default())
    }

    /// Gets a mutable value from the cache, marking it as touched. If the key
    /// is not present, inserts the default value and returns a mutable
    /// reference to it.
    ///
    /// This method will trigger eviction if the cache is at capacity and the
    /// key is not already present.
    ///
    /// # Type Requirements
    ///
    /// The value type must implement [`Default`].
    ///
    /// # Returns
    ///
    /// A tuple `(&mut Value, Option<Value>)` where the first element is a
    /// mutable reference to the value (existing or newly inserted), and the
    /// second element is the evicted value if an eviction occurred.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, Vec<String>>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Get or insert default and modify it immediately
    /// let (vec_ref, _) = cache.get_or_default_mut(1);
    /// vec_ref.push("hello".to_string());
    /// vec_ref.push("world".to_string());
    ///
    /// // Verify the changes were made
    /// assert_eq!(cache.get(&1).unwrap().len(), 2);
    /// assert_eq!(cache.get(&1).unwrap()[0], "hello");
    ///
    /// // Subsequent calls return the existing mutable value
    /// let (vec_ref, _) = cache.get_or_default_mut(1);
    /// vec_ref.clear();
    /// assert!(cache.get(&1).unwrap().is_empty());
    /// ```
    pub fn get_or_default_mut(
        &mut self,
        key: Key,
    ) -> (&mut Value, Option<Value>)
    where
        Value: Default,
    {
        self.get_or_insert_with_mut(key, |_| Value::default())
    }

    /// Inserts a key-value pair into the cache.
    ///
    /// If the key already exists, its value is updated and the entry is marked
    /// as touched. If the key is new and the cache is at capacity, the policy
    /// determines which entry is evicted to make room.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to insert or update
    /// * `value` - The value to associate with the key
    ///
    /// # Returns
    ///
    /// `Some(Value)` containing the evicted entry if the cache was at capacity
    /// and a new key was inserted. `None` otherwise (including the case where
    /// the key already existed and was updated in place).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Insert into empty cache — nothing evicted
    /// assert_eq!(cache.insert(1, "one".to_string()), None);
    ///
    /// // Update existing key — nothing evicted
    /// assert_eq!(cache.insert(1, "new_one".to_string()), None);
    ///
    /// // Fill the cache
    /// assert_eq!(cache.insert(2, "two".to_string()), None);
    ///
    /// // Insert when at capacity — evicts based on policy
    /// assert_eq!(
    ///     cache.insert(3, "three".to_string()),
    ///     Some("new_one".to_string())
    /// );
    /// ```
    pub fn insert(
        &mut self,
        key: Key,
        value: Value,
    ) -> Option<Value> {
        let will_evict = self.queue.len() == self.capacity.get();
        let result = PolicyType::insert_or_update_entry(
            key,
            will_evict,
            |_, _| InsertOrUpdateAction::InsertOrUpdate(value),
            &mut self.metadata,
            &mut self.queue,
        );

        match result {
            InsertionResult::Inserted(_, evicted) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.insertions += 1;
                    self.statistics.evictions += u64::from(will_evict);
                }

                evicted
            }
            InsertionResult::Updated(_) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                None
            }
            _ => unreachable!("Unexpected insertion result: {:?}", result),
        }
    }

    /// Inserts a key-value pair into the cache and returns a mutable reference
    /// to the inserted value along with any evicted entry.
    ///
    /// This is the mutable version of [`insert()`](Self::insert). If the key
    /// already exists, its value is updated and the entry is marked as touched.
    /// If the key is new and the cache is at capacity, the policy determines
    /// which entry is evicted to make room.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to insert or update
    /// * `value` - The value to associate with the key
    ///
    /// # Returns
    ///
    /// A tuple `(&mut Value, Option<Value>)` where the first element is a
    /// mutable reference to the inserted (or updated) value, and the second
    /// element is the evicted value if an eviction occurred.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Insert new value and modify it immediately
    /// let (value, evicted) = cache.insert_mut(1, "one".to_string());
    /// value.push_str("_modified");
    /// assert!(evicted.is_none());
    /// assert_eq!(cache.peek(&1), Some(&"one_modified".to_string()));
    ///
    /// // Update existing value
    /// let (value, evicted) = cache.insert_mut(1, "new_one".to_string());
    /// value.push_str("_updated");
    /// assert!(evicted.is_none());
    /// assert_eq!(cache.peek(&1), Some(&"new_one_updated".to_string()));
    ///
    /// // Insert when at capacity (evicts based on policy)
    /// cache.insert_mut(2, "two".to_string());
    /// let (value, evicted) = cache.insert_mut(3, "three".to_string());
    /// value.push_str("_latest");
    /// assert_eq!(evicted, Some("new_one_updated".to_string()));
    /// assert_eq!(
    ///     cache.into_iter().collect::<Vec<_>>(),
    ///     [(2, "two".to_string()), (3, "three_latest".to_string())]
    /// );
    /// ```
    pub fn insert_mut(
        &mut self,
        key: Key,
        value: Value,
    ) -> (&mut Value, Option<Value>) {
        let will_evict = self.queue.len() == self.capacity.get();
        let result = PolicyType::insert_or_update_entry(
            key,
            will_evict,
            |_, _| InsertOrUpdateAction::InsertOrUpdate(value),
            &mut self.metadata,
            &mut self.queue,
        );

        match result {
            InsertionResult::Inserted(ptr, evicted) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.insertions += 1;
                    self.statistics.evictions += u64::from(will_evict);
                }

                (self.queue[ptr].value_mut(), evicted)
            }
            InsertionResult::Updated(ptr) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                (self.queue[ptr].value_mut(), None)
            }
            _ => unreachable!("Unexpected insertion result: {:?}", result),
        }
    }

    /// The immutable version of `try_insert_or_update_mut`. See
    /// [`Self::try_insert_or_update_mut`] for details.
    pub fn try_insert_or_update(
        &mut self,
        key: Key,
        value: Value,
    ) -> Result<&Value, (Key, Value)> {
        self.try_insert_or_update_mut(key, value).map(|v| &*v)
    }

    /// Attempts to insert a key-value pair into the cache without triggering
    /// eviction, returning a mutable reference to the inserted value.
    ///
    /// This method only inserts the entry if the cache has available capacity.
    /// If the cache is at capacity, the insertion fails and the key-value pair
    /// is returned unchanged. Unlike [`insert_mut`](Self::insert_mut), this
    /// method will never evict existing entries.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to insert
    /// * `value` - The value to associate with the key
    ///
    /// # Returns
    ///
    /// * `Ok(&mut Value)` - A mutable reference to the inserted value if
    ///   successful
    /// * `Err((Key, Value))` - The original key-value pair if insertion failed
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, Vec<String>>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Successful insertion with immediate mutation
    /// let vec_ref = cache
    ///     .try_insert_or_update_mut(1, vec!["hello".to_string()])
    ///     .unwrap();
    /// vec_ref.push("world".to_string());
    /// assert_eq!(cache.get(&1).unwrap().len(), 2);
    ///
    /// // Fill remaining capacity
    /// cache
    ///     .try_insert_or_update_mut(2, vec!["foo".to_string()])
    ///     .unwrap();
    ///
    /// // Failed insertion when cache is at capacity
    /// let result = cache.try_insert_or_update_mut(3, vec!["bar".to_string()]);
    /// assert!(result.is_err());
    /// if let Err((key, value)) = result {
    ///     assert_eq!(key, 3);
    ///     assert_eq!(value, vec!["bar".to_string()]);
    /// }
    /// assert_eq!(cache.len(), 2); // Cache unchanged
    /// ```
    ///
    /// # Updating Existing Keys
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, Vec<i32>>::new(NonZeroUsize::new(1).unwrap());
    /// cache.insert(1, vec![1, 2, 3]);
    ///
    /// // Updating an existing key always succeeds and allows mutation
    /// let vec_ref = cache.try_insert_or_update_mut(1, vec![4, 5]).unwrap();
    /// vec_ref.push(6);
    /// assert_eq!(cache.get(&1).unwrap(), &vec![4, 5, 6]);
    /// ```
    pub fn try_insert_or_update_mut(
        &mut self,
        key: Key,
        value: Value,
    ) -> Result<&mut Value, (Key, Value)> {
        let will_evict = self.queue.len() == self.capacity.get();
        let result = PolicyType::insert_or_update_entry(
            key,
            false,
            |_, is_insert| {
                if is_insert && will_evict {
                    InsertOrUpdateAction::NoInsert(Some(value))
                } else {
                    InsertOrUpdateAction::InsertOrUpdate(value)
                }
            },
            &mut self.metadata,
            &mut self.queue,
        );

        match result {
            InsertionResult::Inserted(ptr, _) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.insertions += 1;
                }

                Ok(self.queue[ptr].value_mut())
            }
            InsertionResult::Updated(ptr) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                Ok(self.queue[ptr].value_mut())
            }
            InsertionResult::NotFoundNoInsert(k, v) => Err((k, v.unwrap())),
            _ => unreachable!("Unexpected insertion result: {:?}", result),
        }
    }

    /// The immutable version of `try_get_or_insert_with_mut`. See
    /// [`Self::try_get_or_insert_with_mut`] for details.
    pub fn try_get_or_insert_with(
        &mut self,
        key: Key,
        or_insert: impl FnOnce(&Key) -> Value,
    ) -> Result<&Value, Key> {
        self.try_get_or_insert_with_mut(key, or_insert).map(|v| &*v)
    }

    /// Attempts to get a mutable value from the cache or insert it using a
    /// closure, without triggering eviction of other entries.
    ///
    /// If the key exists, returns a mutable reference to the existing value and
    /// marks it as touched. If the key doesn't exist and the cache has
    /// available capacity, the closure is called to generate a value which
    /// is then inserted. If the cache is at capacity and the key doesn't
    /// exist, the operation fails and returns the key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up or insert
    /// * `or_insert` - A closure that generates the value if the key is not
    ///   found
    ///
    /// # Returns
    ///
    /// * `Ok(&mut Value)` - A mutable reference to the value if successful
    /// * `Err(Key)` - The original key if insertion failed due to capacity
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, Vec<String>>::new(NonZeroUsize::new(2).unwrap());
    ///
    /// // Insert new value and modify it immediately
    /// let vec_ref = cache
    ///     .try_get_or_insert_with_mut(1, |_| vec!["initial".to_string()])
    ///     .unwrap();
    /// vec_ref.push("added".to_string());
    /// assert_eq!(cache.get(&1).unwrap().len(), 2);
    ///
    /// // Get existing value and modify it further
    /// let vec_ref = cache
    ///     .try_get_or_insert_with_mut(1, |_| vec!["not-called".to_string()])
    ///     .unwrap();
    /// vec_ref.push("more".to_string());
    /// assert_eq!(cache.get(&1).unwrap().len(), 3);
    ///
    /// // Fill remaining capacity
    /// cache
    ///     .try_get_or_insert_with_mut(2, |_| vec!["second".to_string()])
    ///     .unwrap();
    ///
    /// // Fail when cache is at capacity and key doesn't exist
    /// let result = cache.try_get_or_insert_with_mut(3, |_| vec!["third".to_string()]);
    /// assert!(result.is_err());
    /// assert_eq!(result.unwrap_err(), 3);
    /// assert_eq!(cache.len(), 2); // Cache unchanged
    /// ```
    ///
    /// # Use Cases
    ///
    /// This method is particularly useful for scenarios where you need to:
    /// - Initialize complex data structures in-place
    /// - Accumulate data in existing cache entries
    /// - Avoid unnecessary allocations when the entry already exists
    ///
    /// ```rust
    /// use std::collections::HashMap;
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<String, HashMap<String, i32>>::new(NonZeroUsize::new(3).unwrap());
    ///
    /// // Build up a map incrementally
    /// let map_ref = cache
    ///     .try_get_or_insert_with_mut("counters".to_string(), |_| HashMap::new())
    ///     .unwrap();
    /// map_ref.insert("clicks".to_string(), 1);
    /// map_ref.insert("views".to_string(), 5);
    ///
    /// // Later, update the existing map
    /// let map_ref = cache
    ///     .try_get_or_insert_with_mut(
    ///         "counters".to_string(),
    ///         |_| HashMap::new(), // Not called since key exists
    ///     )
    ///     .unwrap();
    /// *map_ref.get_mut("clicks").unwrap() += 1;
    /// ```
    pub fn try_get_or_insert_with_mut(
        &mut self,
        key: Key,
        or_insert: impl FnOnce(&Key) -> Value,
    ) -> Result<&mut Value, Key> {
        let will_evict = self.queue.len() == self.capacity.get();

        let result = PolicyType::insert_or_update_entry(
            key,
            false,
            |key, is_insert| {
                if is_insert && !will_evict {
                    InsertOrUpdateAction::InsertOrUpdate(or_insert(key))
                } else if !is_insert {
                    InsertOrUpdateAction::TouchNoUpdate
                } else {
                    InsertOrUpdateAction::NoInsert(None)
                }
            },
            &mut self.metadata,
            &mut self.queue,
        );

        match result {
            InsertionResult::Inserted(ptr, _) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.insertions += 1;
                }

                Ok(self.queue[ptr].value_mut())
            }
            InsertionResult::Updated(ptr) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                Ok(self.queue[ptr].value_mut())
            }
            InsertionResult::NotFoundNoInsert(k, _) => Err(k),
            InsertionResult::FoundTouchedNoUpdate(ptr) => {
                #[cfg(feature = "statistics")]
                {
                    self.statistics.hits += 1;
                }

                Ok(self.queue[ptr].value_mut())
            }
        }
    }

    /// The immutable version of `get_mut`. See [`Self::get_mut`] for details.
    pub fn get(
        &mut self,
        key: &Key,
    ) -> Option<&Value> {
        self.get_mut(key).map(|v| &*v)
    }

    /// Gets a value from the cache, marking it as touched.
    ///
    /// This is the mutable version of [`get()`](Self::get). If the key exists,
    /// returns a mutable reference to the value and updates the entry's
    /// position in the eviction order according to the policy. If the key
    /// doesn't exist, returns `None` and the cache is unchanged.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up
    ///
    /// # Returns
    ///
    /// * `Some(&mut Value)` if the key exists
    /// * `None` if the key doesn't exist
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// // Get and modify the value, marking as recently used
    /// if let Some(value) = cache.get_mut(&1) {
    ///     value.push_str("_modified");
    /// }
    /// assert_eq!(cache.peek(&1), Some(&"one_modified".to_string()));
    ///
    /// // Non-existent key returns None
    /// assert_eq!(cache.get_mut(&3), None);
    ///
    /// assert_eq!(
    ///     cache.into_iter().collect::<Vec<_>>(),
    ///     vec![(2, "two".to_string()), (1, "one_modified".to_string())]
    /// );
    /// ```
    pub fn get_mut(
        &mut self,
        key: &Key,
    ) -> Option<&mut Value> {
        if let Some(index) = self.queue.get_ptr(key) {
            PolicyType::touch_entry(index, &mut self.metadata, &mut self.queue);

            #[cfg(feature = "statistics")]
            {
                self.statistics.hits += 1;
            }

            Some(self.queue[index].value_mut())
        } else {
            #[cfg(feature = "statistics")]
            {
                self.statistics.misses += 1;
            }
            None
        }
    }

    /// Removes and returns the entry that would be evicted next.
    ///
    /// This method removes and returns the entry at the "tail" of the eviction
    /// order. The specific entry removed depends on the policy:
    /// - Lru: Removes the least recently used entry
    /// - Mru: Removes the most recently used entry
    /// - Lfu: Removes the least frequently used entry
    /// - Fifo: Removes the first inserted entry
    /// - Lifo: Removes the last inserted entry
    /// - Random: Removes a randomly selected entry
    ///
    /// # Returns
    ///
    /// * `Some((Key, Value))` if the cache is not empty
    /// * `None` if the cache is empty
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// // Pop the least recently used entry
    /// let (key, value) = cache.pop().unwrap();
    /// assert_eq!(key, 1);
    /// assert_eq!(value, "one".to_string());
    /// assert_eq!(
    ///     cache.into_iter().collect::<Vec<_>>(),
    ///     vec![(2, "two".to_string())]
    /// );
    /// ```
    pub fn pop(&mut self) -> Option<(Key, Value)> {
        PolicyType::evict_entry(&mut self.metadata, &mut self.queue).map(|(key, entry)| {
            #[cfg(feature = "statistics")]
            {
                self.statistics.evictions += 1;
            }

            (key, entry.into_value())
        })
    }

    /// Removes a specific entry from the cache.
    ///
    /// If the key exists, removes it from the cache and returns the associated
    /// value. If the key doesn't exist, returns `None` and the cache is
    /// unchanged.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to remove from the cache
    ///
    /// # Returns
    ///
    /// * `Some(Value)` if the key existed and was removed
    /// * `None` if the key was not found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// assert_eq!(cache.remove(&1), Some("one".to_string()));
    /// assert_eq!(cache.remove(&1), None); // Already removed
    /// assert_eq!(
    ///     cache.into_iter().collect::<Vec<_>>(),
    ///     vec![(2, "two".to_string())]
    /// );
    /// ```
    pub fn remove(
        &mut self,
        key: &Key,
    ) -> Option<Value> {
        PolicyType::remove_key(key, &mut self.metadata, &mut self.queue)
            .map(|entry| entry.into_value())
    }

    /// Returns true if the cache contains no entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// assert!(cache.is_empty());
    ///
    /// cache.insert(1, "one".to_string());
    /// assert!(!cache.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Returns the number of entries currently in the cache.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// assert_eq!(cache.len(), 0);
    ///
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    /// assert_eq!(cache.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.queue.len()
    }

    /// Returns the maximum number of entries the cache can hold.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let cache = Lru::<i32, String>::new(NonZeroUsize::new(100).unwrap());
    /// assert_eq!(cache.capacity(), 100);
    /// assert_eq!(cache.len(), 0); // Empty but has capacity for 100
    /// ```
    pub fn capacity(&self) -> usize {
        self.capacity.get()
    }

    /// Sets a new capacity for the cache.
    ///
    /// If the new capacity is smaller than the current number of entries,
    /// entries will be evicted according to the cache's eviction policy
    /// until the cache size fits within the new capacity.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The new maximum number of entries the cache can hold.
    ///   Must be greater than zero.
    ///
    /// # Returns
    ///
    /// A vector of evicted entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    /// cache.insert(3, "three".to_string());
    /// assert_eq!(cache.len(), 3);
    /// assert_eq!(cache.capacity(), 3);
    ///
    /// // Increase capacity
    /// cache.set_capacity(NonZeroUsize::new(5).unwrap());
    /// assert_eq!(cache.capacity(), 5);
    /// assert_eq!(cache.len(), 3); // Existing entries remain
    ///
    /// // Decrease capacity - will evict entries
    /// cache.set_capacity(NonZeroUsize::new(2).unwrap());
    /// assert_eq!(cache.capacity(), 2);
    /// assert_eq!(cache.len(), 2); // One entry was evicted
    /// ```
    pub fn set_capacity(
        &mut self,
        capacity: NonZeroUsize,
    ) -> Vec<(Key, Value)> {
        assert!((capacity.get() as u32) < u32::MAX - 1, "Capacity too large");
        let mut evicted = Vec::with_capacity(self.queue.len().saturating_sub(capacity.get()));
        if capacity.get() < self.queue.len() {
            // If new capacity is smaller than current size, we need to evict
            // entries until we fit
            while self.queue.len() > capacity.get()
                && let Some(kv) = self.pop()
            {
                evicted.push(kv);
            }
        }

        self.capacity = capacity;
        evicted
    }

    /// Evicts entries from the cache until the size is reduced to the specified
    /// number.
    ///
    /// This method removes entries according to the cache's eviction policy
    /// until the cache contains at most `n` entries. If the cache already
    /// has `n` or fewer entries, no eviction occurs.
    ///
    /// # Arguments
    ///
    /// * `n` - The target number of entries to keep in the cache
    ///
    /// # Returns
    ///
    /// A vector containing all evicted key-value pairs in the order they were
    /// removed from the cache.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(5).unwrap());
    ///
    /// // Fill the cache
    /// for i in 1..=5 {
    ///     cache.insert(i, format!("value{}", i));
    /// }
    /// assert_eq!(cache.len(), 5);
    ///
    /// // Evict until only 2 entries remain
    /// let evicted = cache.evict_to_size(2);
    /// assert_eq!(cache.len(), 2);
    /// assert_eq!(evicted.len(), 3);
    ///
    /// // The evicted entries follow the cache's eviction policy
    /// // For LRU, oldest entries are evicted first
    /// assert_eq!(evicted[0], (1, "value1".to_string()));
    /// assert_eq!(evicted[1], (2, "value2".to_string()));
    /// assert_eq!(evicted[2], (3, "value3".to_string()));
    ///
    /// // Cache now contains the most recently used entries
    /// assert!(cache.contains_key(&4));
    /// assert!(cache.contains_key(&5));
    /// ```
    ///
    /// # Behavior with Different Cache Sizes
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// // No eviction when target size >= current size
    /// let evicted = cache.evict_to_size(5);
    /// assert_eq!(evicted.len(), 0);
    /// assert_eq!(cache.len(), 2);
    ///
    /// // Evict to exact current size
    /// let evicted = cache.evict_to_size(2);
    /// assert_eq!(evicted.len(), 0);
    /// assert_eq!(cache.len(), 2);
    ///
    /// // Evict to zero (clear cache)
    /// let evicted = cache.evict_to_size(0);
    /// assert_eq!(evicted.len(), 2);
    /// assert_eq!(cache.len(), 0);
    /// ```
    pub fn evict_to_size(
        &mut self,
        n: usize,
    ) -> Vec<(Key, Value)> {
        let mut evicted = Vec::with_capacity(n);
        while self.queue.len() > n
            && let Some(kv) = self.pop()
        {
            evicted.push(kv);
        }
        evicted
    }

    /// Evicts up to `n` entries from the cache according to the eviction
    /// policy.
    ///
    /// This method removes at most `n` entries from the cache, following the
    /// cache's eviction policy. If the cache contains fewer than `n` entries,
    /// all remaining entries are evicted.
    ///
    /// # Arguments
    ///
    /// * `n` - The maximum number of entries to evict
    ///
    /// # Returns
    ///
    /// A vector containing all evicted key-value pairs in the order they were
    /// removed from the cache. The vector will contain at most `n` entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(5).unwrap());
    ///
    /// // Fill the cache
    /// for i in 1..=5 {
    ///     cache.insert(i, format!("value{}", i));
    /// }
    /// assert_eq!(cache.len(), 5);
    ///
    /// // Evict exactly 3 entries
    /// let evicted = cache.evict_n_entries(3);
    /// assert_eq!(cache.len(), 2);
    /// assert_eq!(evicted.len(), 3);
    ///
    /// // For LRU, oldest entries are evicted first
    /// assert_eq!(evicted[0], (1, "value1".to_string()));
    /// assert_eq!(evicted[1], (2, "value2".to_string()));
    /// assert_eq!(evicted[2], (3, "value3".to_string()));
    ///
    /// // Cache retains the most recently used entries
    /// assert!(cache.contains_key(&4));
    /// assert!(cache.contains_key(&5));
    /// ```
    ///
    /// # Behavior with Edge Cases
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "one".to_string());
    /// cache.insert(2, "two".to_string());
    ///
    /// // Requesting more entries than available
    /// let evicted = cache.evict_n_entries(5);
    /// assert_eq!(evicted.len(), 2); // Only 2 entries were available
    /// assert_eq!(cache.len(), 0); // Cache is now empty
    ///
    /// // Evicting from empty cache
    /// let evicted = cache.evict_n_entries(3);
    /// assert_eq!(evicted.len(), 0); // No entries to evict
    /// assert_eq!(cache.len(), 0);
    ///
    /// // Evicting zero entries
    /// cache.insert(1, "one".to_string());
    /// let evicted = cache.evict_n_entries(0);
    /// assert_eq!(evicted.len(), 0); // No eviction requested
    /// assert_eq!(cache.len(), 1); // Cache unchanged
    /// ```
    pub fn evict_n_entries(
        &mut self,
        n: usize,
    ) -> Vec<(Key, Value)> {
        let mut evicted = Vec::with_capacity(n);
        for _ in 0..n {
            if let Some(kv) = self.pop() {
                evicted.push(kv);
            } else {
                break; // No more entries to evict
            }
        }
        evicted
    }

    /// Returns an iterator over cache entries in eviction order.
    ///
    /// The iterator yields key-value pairs `(&Key, &Value)` in the order they
    /// would be evicted from the cache, starting with the entry that would be
    /// evicted first. This allows you to inspect the cache's internal ordering
    /// and understand which entries are most at risk of eviction. This does not
    /// permute the order of the cache.
    ///
    /// The specific iteration order depends on the cache's eviction policy:
    ///
    /// ## Lru (Least Recently Used)
    /// Iterates from **least recently used** to **most recently used**:
    /// - First yielded: The entry accessed longest ago (would be evicted first)
    /// - Last yielded: The entry accessed most recently (would be evicted last)
    ///
    /// ## Mru (Most Recently Used)  
    /// Iterates from **most recently used** to **least recently used**:
    /// - First yielded: The entry accessed most recently (would be evicted
    ///   first)
    /// - Last yielded: The entry accessed longest ago (would be evicted last)
    ///
    /// ## Lfu (Least Frequently Used)
    /// Iterates from **least frequently used** to **most frequently used**:
    /// - Entries are ordered by access frequency (lower frequency first)
    /// - Ties are broken by insertion/access order within frequency buckets
    /// - First yielded: Entry with lowest access count (would be evicted first)
    /// - Last yielded: Entry with highest access count (would be evicted last)
    ///
    /// ## Fifo (First In, First Out)
    /// Iterates from **first inserted** to **last inserted**:
    /// - Entries are ordered by insertion time
    /// - First yielded: Entry inserted earliest (would be evicted first)
    /// - Last yielded: Entry inserted most recently (would be evicted last)
    /// - Access patterns do not affect iteration order
    ///
    /// ## Lifo (Last In, First Out)
    /// Iterates from **last inserted** to **first inserted**:
    /// - Entries are ordered by insertion time in reverse
    /// - First yielded: Entry inserted most recently (would be evicted first)
    /// - Last yielded: Entry inserted earliest (would be evicted last)
    /// - Access patterns do not affect iteration order
    ///
    /// ## Random
    /// Iterates in **random order** in debug builds, **arbitrary order** in
    /// release builds:
    /// - Debug builds: Order is randomized for testing purposes
    /// - Release builds: Order is arbitrary and depends on the pattern of
    ///   eviction and insertion.
    /// - The eviction order itself is always random regardless of iteration
    ///   order
    ///
    /// ## Sieve
    /// Iterates in **eviction order**:
    /// - Starts from the current hand position (next eviction candidate)
    /// - Simulates the eviction scanning process: skips visited entries once,
    ///   then includes them in order
    /// - Uses additional state tracking to maintain this logical ordering
    /// - **Higher iteration overhead** than other policies due to eviction
    ///   simulation
    ///
    /// # Time Complexity
    /// - Creating the iterator: **O(1)**
    /// - Iterating through all entries: **O(n)** where n is the cache size
    /// - Each `next()` call: **O(1)** for Lru/Mru/Fifo/Lifo/Random, **O(1)
    ///   amortized** for Lfu, **O(1) with higher constant overhead** for Sieve
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Lru: Iterates from least recently used to most recently used
    /// let items: Vec<_> = cache.iter().collect();
    /// assert_eq!(items, [(&"A", &1), (&"B", &2), (&"C", &3)]);
    /// ```
    ///
    /// ## After Access Pattern
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Access "A" to make it recently used
    /// cache.get(&"A");
    ///
    /// // Now "B" is least recently used, "A" is most recently used
    /// let items: Vec<_> = cache.iter().collect();
    /// assert_eq!(items, [(&"B", &2), (&"C", &3), (&"A", &1)]);
    /// ```
    ///
    /// ## Mru Policy Example
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Mru;
    ///
    /// let mut cache = Mru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Mru: Iterates from most recently used to least recently used
    /// let items: Vec<_> = cache.iter().collect();
    /// assert_eq!(items, [(&"C", &3), (&"B", &2), (&"A", &1)]);
    /// ```
    ///
    /// ## Lfu Policy Example
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lfu;
    ///
    /// let mut cache = Lfu::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Access "A" multiple times to increase its frequency
    /// cache.get(&"A");
    /// cache.get(&"A");
    /// cache.get(&"B"); // Access "B" once
    ///
    /// // Lfu: "C" (freq=0), "B" (freq=1), "A" (freq=2)
    /// let items: Vec<_> = cache.iter().collect();
    /// assert_eq!(items, [(&"C", &3), (&"B", &2), (&"A", &1)]);
    /// ```
    ///
    /// ## Consistency with `tail()`
    /// The first item from the iterator always matches `tail()` with the
    /// exception of the `Random` policy:
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    ///
    /// let tail_item = cache.tail();
    /// let first_iter_item = cache.iter().next();
    /// assert_eq!(tail_item, first_iter_item);
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = (&Key, &Value)> {
        PolicyType::iter(&self.metadata, &self.queue)
    }

    /// Returns an iterator over the keys in the cache in eviction order.
    ///
    /// This method returns an iterator that yields references to all keys
    /// currently stored in the cache. The keys are returned in the same order
    /// as [`iter()`](Self::iter), which follows the cache's eviction policy.
    ///
    /// # Eviction Order
    ///
    /// The iteration order depends on the cache's eviction policy:
    /// - **Lru**: Keys from least recently used to most recently used
    /// - **Mru**: Keys from most recently used to least recently used
    /// - **Lfu**: Keys from least frequently used to most frequently used
    /// - **Fifo**: Keys from first inserted to last inserted
    /// - **Lifo**: Keys from last inserted to first inserted
    /// - **Random**: Keys in random order (debug) or arbitrary order (release)
    /// - **Sieve**: Keys in eviction order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Get keys in Lru order (least recently used first)
    /// let keys: Vec<_> = cache.keys().collect();
    /// assert_eq!(keys, [&"A", &"B", &"C"]);
    /// ```
    pub fn keys(&self) -> impl Iterator<Item = &Key> {
        PolicyType::iter(&self.metadata, &self.queue).map(|(k, _)| k)
    }

    /// Returns an iterator over the values in the cache in eviction order.
    ///
    /// This method returns an iterator that yields references to all values
    /// currently stored in the cache. The values are returned in the same order
    /// as [`iter()`](Self::iter), which follows the cache's eviction policy.
    ///
    /// # Eviction Order
    ///
    /// The iteration order depends on the cache's eviction policy:
    /// - **Lru**: Values from least recently used to most recently used
    /// - **Mru**: Values from most recently used to least recently used
    /// - **Lfu**: Values from least frequently used to most frequently used
    /// - **Fifo**: Values from first inserted to last inserted
    /// - **Lifo**: Values from last inserted to first inserted
    /// - **Random**: Values in random order (debug) or arbitrary order
    ///   (release)
    /// - **Sieve**: Values following eviction order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert("A", 1);
    /// cache.insert("B", 2);
    /// cache.insert("C", 3);
    ///
    /// // Get values in Lru order (least recently used first)
    /// let values: Vec<_> = cache.values().collect();
    /// assert_eq!(values, [&1, &2, &3]);
    /// ```
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        PolicyType::iter(&self.metadata, &self.queue).map(|(_, v)| v)
    }

    /// Retains only the entries for which the predicate returns `true`.
    ///
    /// This iterates in **arbitrary order**. I.e. unlike `iter()`, the order of
    /// items you see is not guaranteed to match the eviction order.
    ///
    /// This method removes all entries from the cache for which the provided
    /// closure returns `false`. The predicate is called with a reference to
    /// each key and a mutable reference to each value, allowing for both
    /// filtering based on key/value content and in-place modification of
    /// retained values.
    ///
    /// The operation preserves the relative order of retained entries according
    /// to their original insertion order. This operation does not perturb the
    /// eviction order, with the exception of entries that are removed.
    ///
    /// # Arguments
    ///
    /// * `f` - A closure that takes `(&Key, &mut Value)` and returns `true` for
    ///   entries that should be kept, `false` for entries that should be
    ///   removed
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(5).unwrap());
    /// cache.insert(1, "apple".to_string());
    /// cache.insert(2, "banana".to_string());
    /// cache.insert(3, "cherry".to_string());
    /// cache.insert(4, "date".to_string());
    ///
    /// // Keep only entries where the key is even
    /// cache.retain(|&key, _value| key % 2 == 0);
    /// assert_eq!(
    ///     cache.into_iter().collect::<Vec<_>>(),
    ///     [(2, "banana".to_string()), (4, "date".to_string())]
    /// );
    /// ```
    pub fn retain<F>(
        &mut self,
        mut f: F,
    ) where
        F: FnMut(&Key, &mut Value) -> bool,
    {
        let mut next = self.queue.head_cursor_mut();
        while let Some((k, v)) = next.current_mut() {
            if !f(k, v.value_mut()) {
                let (ptr, _) = PolicyType::remove_entry(
                    next.ptr().unwrap(),
                    &mut self.metadata,
                    &mut self.queue,
                );
                if let Some(ptr) = ptr {
                    next = self.queue.ptr_cursor_mut(ptr);
                } else {
                    break;
                }
            } else {
                next.move_next();
                if next.at_head() {
                    break;
                }
            }
        }
    }

    /// Shrinks the internal storage to fit the current number of entries.
    pub fn shrink_to_fit(&mut self) {
        self.queue.shrink_to_fit();
    }
}

impl<K: Hash + Eq + std::fmt::Debug, Value: std::fmt::Debug, PolicyType: Policy<Value>>
    Cache<K, Value, PolicyType>
{
    #[doc(hidden)]
    #[cfg(all(debug_assertions, feature = "internal-debugging"))]
    pub fn debug_validate(&self) {
        PolicyType::debug_validate(&self.metadata, &self.queue);
    }
}

impl<K: Hash + Eq, V, PolicyType: Policy<V>> IntoIterator for Cache<K, V, PolicyType> {
    type IntoIter = PolicyType::IntoIter<K>;
    type Item = (K, V);

    /// Converts the cache into an iterator over key-value pairs.
    ///
    /// This method implements the standard library's `IntoIterator` trait,
    /// allowing caches to be consumed and converted into iterators. The
    /// iteration order follows the eviction policy's ordering:
    ///
    /// - **Lru**: From least recently used to most recently used
    /// - **Mru**: From most recently used to least recently used
    /// - **Lfu**: From least frequently used to most frequently used
    /// - **Fifo**: From first inserted to last inserted
    /// - **Lifo**: From last inserted to first inserted
    /// - **Random**: In random order (debug) or arbitrary order (release)
    /// - **Sieve**: Following eviction order.
    ///
    /// # Returns
    /// An iterator that yields `(K, V)` pairs in eviction order, consuming the
    /// cache.
    ///
    /// # Examples
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::new(NonZeroUsize::new(3).unwrap());
    /// cache.insert(1, "first");
    /// cache.insert(2, "second");
    /// cache.insert(3, "third");
    ///
    /// // Convert to iterator and collect all pairs
    /// let pairs: Vec<_> = cache.into_iter().collect();
    /// assert_eq!(pairs, [(1, "first"), (2, "second"), (3, "third")]);
    /// ```
    ///
    /// # Performance
    /// - Time complexity: O(n) where n is the number of cached items
    /// - Space complexity: O(n) for the iterator's internal state
    ///
    /// # Note
    /// This is a consuming operation - the cache cannot be used after calling
    /// `into_iter()`. Use `iter()` if you need to iterate without consuming the
    /// cache.
    fn into_iter(self) -> Self::IntoIter {
        PolicyType::into_iter(self.metadata, self.queue)
    }
}

impl<Key: Hash + Eq, Value, PolicyType: Policy<Value>> std::iter::FromIterator<(Key, Value)>
    for Cache<Key, Value, PolicyType>
{
    /// Creates a new cache from an iterator of key-value pairs.
    ///
    /// This method consumes the iterator and constructs a new cache, with a
    /// **capacity of at least 1** and at most the number of items in the
    /// iterator.
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (Key, Value)>,
    {
        let mut queue: LinkedHashMap<
            Key,
            <PolicyType::MetadataType as Metadata<Value>>::EntryType,
            RandomState,
        > = LinkedHashMap::default();
        let mut metadata = PolicyType::MetadataType::default();

        #[cfg(feature = "statistics")]
        let mut hits = 0;
        #[cfg(feature = "statistics")]
        let mut insertions = 0;

        for (key, value) in iter {
            let result = PolicyType::insert_or_update_entry(
                key,
                false,
                |_, _| InsertOrUpdateAction::InsertOrUpdate(value),
                &mut metadata,
                &mut queue,
            );
            match result {
                InsertionResult::Inserted(_, _) => {
                    #[cfg(feature = "statistics")]
                    {
                        insertions += 1;
                    }
                }
                InsertionResult::Updated(_) => {
                    #[cfg(feature = "statistics")]
                    {
                        hits += 1;
                    }
                }
                _ => unreachable!("Unexpected insertion result: {:?}", result),
            }
        }

        let capacity = NonZeroUsize::new(queue.len().max(1)).unwrap();
        Self {
            #[cfg(feature = "statistics")]
            statistics: Statistics {
                hits,
                insertions,
                evictions: 0,
                len: queue.len(),
                capacity,
                misses: 0,
            },
            queue,
            capacity,
            metadata,
        }
    }
}

impl<K: Hash + Eq, V, PolicyType: Policy<V>> Extend<(K, V)> for Cache<K, V, PolicyType> {
    /// Extends the cache with key-value pairs from an iterator.
    ///
    /// This method consumes the iterator and inserts each `(Key, Value)` pair
    /// into the cache. If the cache is at capacity, the policy determines which
    /// entry is evicted to make room for new entries.
    ///
    /// # Arguments
    ///
    /// * `iter` - An iterator of `(Key, Value)` pairs to insert into the cache
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    ///
    /// use evictor::Lru;
    ///
    /// let mut cache = Lru::<i32, String>::new(NonZeroUsize::new(3).unwrap());
    /// cache.extend(vec![(1, "one".to_string()), (2, "two".to_string())]);
    /// assert_eq!(cache.len(), 2);
    /// ```
    fn extend<I>(
        &mut self,
        iter: I,
    ) where
        I: IntoIterator<Item = (K, V)>,
    {
        for (key, value) in iter {
            self.insert(key, value);
        }
    }
}

#[cfg(test)]
mod tests {
    //! These are mostly just tests to make sure that if the stored k/v pairs
    //! implement various traits, the Cache also implements those traits.

    use ntest::timeout;

    #[test]
    #[timeout(1000)]
    fn test_lru_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LruPolicy;

        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_lfu_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LfuPolicy;

        let mut cache = Cache::<i32, String, LfuPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_mru_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::MruPolicy;
        let mut cache = Cache::<i32, String, MruPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_fifo_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::FifoPolicy;

        let mut cache = Cache::<i32, String, FifoPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_lifo_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LifoPolicy;

        let mut cache = Cache::<i32, String, LifoPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    #[cfg(feature = "rand")]
    fn test_random_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::RandomPolicy;

        let mut cache = Cache::<i32, String, RandomPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_sieve_cache_clone() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::SievePolicy;

        let mut cache = Cache::<i32, String, SievePolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.len(), 2);
        assert_eq!(cloned_cache.peek(&1), Some(&"one".to_string()));
        assert_eq!(cloned_cache.peek(&2), Some(&"two".to_string()));
    }

    #[test]
    #[timeout(1000)]
    fn test_lfu_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LfuPolicy;

        let mut cache = Cache::<i32, String, LfuPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    fn test_lru_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LruPolicy;

        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    fn test_mru_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::MruPolicy;

        let mut cache = Cache::<i32, String, MruPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    fn test_fifo_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::FifoPolicy;

        let mut cache = Cache::<i32, String, FifoPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    fn test_lifo_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::LifoPolicy;

        let mut cache = Cache::<i32, String, LifoPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    #[cfg(feature = "rand")]
    fn test_random_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::RandomPolicy;

        let mut cache = Cache::<i32, String, RandomPolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }

    #[test]
    #[timeout(1000)]
    fn test_sieve_cache_debug() {
        use std::num::NonZeroUsize;

        use crate::Cache;
        use crate::SievePolicy;

        let mut cache = Cache::<i32, String, SievePolicy>::new(NonZeroUsize::new(3).unwrap());
        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("Cache"));
        assert!(debug_str.contains("\"one\""));
        assert!(debug_str.contains("\"two\""));
    }
}

#[cfg(all(test, feature = "statistics"))]
mod statistics_tests {
    use ntest::timeout;

    use super::*;

    #[test]
    #[timeout(1000)]
    fn test_statistics_initialization() {
        let cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());
        let stats = cache.statistics();

        assert_eq!(stats.len, 0);
        assert_eq!(stats.capacity.get(), 3);
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.insertions, 0);
        assert_eq!(stats.evictions, 0);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_insertions_and_misses() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.insert(3, "three".to_string());

        let stats = cache.statistics();
        assert_eq!(stats.len, 3);
        assert_eq!(stats.insertions, 3);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.evictions, 0);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_hits() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        // Test hits with get
        cache.get(&1);
        cache.get(&2);
        cache.get(&1);

        let stats = cache.statistics();
        assert_eq!(stats.hits, 3);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.insertions, 2);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_misses_on_failed_get() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());

        // Miss on non-existent key
        cache.get(&999);
        cache.get(&888);

        let stats = cache.statistics();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.insertions, 1);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_evictions() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(2).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());

        let stats_before = cache.statistics();
        assert_eq!(stats_before.evictions, 0);

        // This should trigger an eviction
        cache.insert(3, "three".to_string());

        let stats_after = cache.statistics();
        assert_eq!(stats_after.evictions, 1);
        assert_eq!(stats_after.len, 2);
        assert_eq!(stats_after.insertions, 3);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_get_or_insert_with() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        // Insert through get_or_insert_with
        cache.get_or_insert_with(1, |_| "one".to_string());
        cache.get_or_insert_with(2, |_| "two".to_string());

        let stats = cache.statistics();
        assert_eq!(stats.insertions, 2);
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.hits, 0);

        // Hit through get_or_insert_with
        cache.get_or_insert_with(1, |_| "one_new".to_string());

        let stats = cache.statistics();
        assert_eq!(stats.insertions, 2);
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.hits, 1);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_try_insert() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(2).unwrap());

        // Successful insertions
        assert!(cache.try_insert_or_update(1, "one".to_string()).is_ok());
        assert!(cache.try_insert_or_update(2, "two".to_string()).is_ok());

        let stats = cache.statistics();
        assert_eq!(stats.insertions, 2);

        // Failed insertion (key already exists)
        assert_eq!(
            cache.try_insert_or_update(1, "one_new".to_string()),
            Ok(&"one_new".to_string())
        );

        let stats = cache.statistics();
        assert_eq!(stats.insertions, 2); // Should not increment
        assert_eq!(stats.hits, 1); // Should increment for the failed try_insert
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_reset() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.get(&1);
        cache.get(&999); // miss

        let stats_before = cache.statistics();
        assert!(stats_before.hits > 0);
        assert!(stats_before.misses > 0);
        assert!(stats_before.insertions > 0);

        cache.reset_statistics();

        let stats_after = cache.statistics();
        assert_eq!(stats_after.hits, 0);
        assert_eq!(stats_after.misses, 0);
        assert_eq!(stats_after.insertions, 0);
        assert_eq!(stats_after.evictions, 0);
        assert_eq!(stats_after.len, 2); // len should match current cache state
        assert_eq!(stats_after.capacity.get(), 3);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_remove() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.insert(3, "three".to_string());

        let stats_before = cache.statistics();
        assert_eq!(stats_before.len, 3);

        cache.remove(&2);

        let stats_after = cache.statistics();
        assert_eq!(stats_after.len, 2);
        // Remove shouldn't affect other statistics
        assert_eq!(stats_after.insertions, stats_before.insertions);
        assert_eq!(stats_after.hits, stats_before.hits);
        assert_eq!(stats_after.misses, stats_before.misses);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_clear() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.get(&1);

        let stats_before = cache.statistics();
        assert!(stats_before.len > 0);

        cache.clear();

        let stats_after = cache.statistics();
        assert_eq!(stats_after.len, 0);
        // Clear shouldn't affect historical statistics
        assert_eq!(stats_after.insertions, stats_before.insertions);
        assert_eq!(stats_after.hits, stats_before.hits);
        assert_eq!(stats_after.misses, stats_before.misses);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_set_capacity() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.insert(3, "three".to_string());

        let stats_before = cache.statistics();
        assert_eq!(stats_before.capacity.get(), 3);
        assert_eq!(stats_before.evictions, 0);

        // Set capacity to smaller size should trigger evictions
        let evicted = cache.set_capacity(NonZeroUsize::new(1).unwrap());
        assert_eq!(evicted.len(), 2); // Should evict 2 items

        let stats_after = cache.statistics();
        assert_eq!(stats_after.capacity.get(), 1);
        assert_eq!(stats_after.len, 1);
        assert_eq!(stats_after.evictions, 2); // Should evict 2 items
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_with_different_policies() {
        // Test with LFU policy
        let mut lfu_cache = Cache::<i32, String, LfuPolicy>::new(NonZeroUsize::new(2).unwrap());
        lfu_cache.insert(1, "one".to_string());
        lfu_cache.insert(2, "two".to_string());
        lfu_cache.get(&1); // Increase frequency of key 1
        lfu_cache.insert(3, "three".to_string()); // Should evict key 2 (least frequently used)

        let lfu_stats = lfu_cache.statistics();
        assert_eq!(lfu_stats.evictions, 1);
        assert_eq!(lfu_stats.hits, 1);
        assert_eq!(lfu_stats.insertions, 3);

        // Test with MRU policy
        let mut mru_cache = Cache::<i32, String, MruPolicy>::new(NonZeroUsize::new(2).unwrap());
        mru_cache.insert(1, "one".to_string());
        mru_cache.insert(2, "two".to_string());
        mru_cache.get(&1); // Make key 1 most recently used
        mru_cache.insert(3, "three".to_string()); // Should evict key 1 (most recently used)

        let mru_stats = mru_cache.statistics();
        assert_eq!(mru_stats.evictions, 1);
        assert_eq!(mru_stats.hits, 1);
        assert_eq!(mru_stats.insertions, 3);
    }

    #[test]
    #[timeout(1000)]
    fn test_statistics_clone() {
        let mut cache = Cache::<i32, String, LruPolicy>::new(NonZeroUsize::new(3).unwrap());

        cache.insert(1, "one".to_string());
        cache.insert(2, "two".to_string());
        cache.get(&1);
        cache.get(&999); // miss

        let cloned_cache = cache.clone();
        let original_stats = cache.statistics();
        let cloned_stats = cloned_cache.statistics();

        // Statistics should be identical after clone
        assert_eq!(original_stats.len, cloned_stats.len);
        assert_eq!(original_stats.capacity, cloned_stats.capacity);
        assert_eq!(original_stats.hits, cloned_stats.hits);
        assert_eq!(original_stats.misses, cloned_stats.misses);
        assert_eq!(original_stats.insertions, cloned_stats.insertions);
        assert_eq!(original_stats.evictions, cloned_stats.evictions);
    }
}