cache-rs 0.4.0

A high-performance, memory-efficient cache implementation supporting multiple eviction policies including LRU, LFU, LFUDA, SLRU and GDSF
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
//! Least Frequently Used with Dynamic Aging (LFUDA) Cache Implementation
//!
//! LFUDA is an enhanced LFU algorithm that addresses the "cache pollution" problem
//! by incorporating a global age factor. This allows the cache to gradually forget
//! old access patterns, enabling new popular items to compete fairly against
//! historically popular but now cold items.
//!
//! # How the Algorithm Works
//!
//! LFUDA maintains a **global age** that increases whenever an item is evicted.
//! Each item's priority is the sum of its access frequency and the age at which
//! it was last accessed. This elegant mechanism ensures that:
//!
//! 1. Recently accessed items get a "boost" from the current global age
//! 2. Old items with high frequency but no recent access gradually become eviction candidates
//! 3. New items can compete fairly against established items
//!
//! ## Mathematical Formulation
//!
//! ```text
//! For each cache entry i:
//!   - F_i = access frequency of item i
//!   - A_i = global age when item i was last accessed
//!   - Priority_i = F_i + A_i
//!
//! On eviction:
//!   - Select item j where Priority_j = min{Priority_i for all i}
//!   - Set global_age = Priority_j
//!
//! On access:
//!   - Increment F_i
//!   - Update A_i = global_age (item gets current age)
//! ```
//!
//! ## Data Structure
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │                           LFUDA Cache (global_age=100)                       │
//! │                                                                              │
//! │  HashMap<K, *Node>              BTreeMap<Priority, List>                     │
//! │  ┌──────────────┐              ┌─────────────────────────────────────────┐   │
//! │  │ "hot" ──────────────────────│ pri=115: [hot]    (freq=5, age=110)     │   │
//! │  │ "warm" ─────────────────────│ pri=103: [warm]   (freq=3, age=100)     │   │
//! │  │ "stale" ────────────────────│ pri=60:  [stale]  (freq=50, age=10) ←LFU│   │
//! │  └──────────────┘              └─────────────────────────────────────────┘   │
//! │                                        ▲                                     │
//! │                                        │                                     │
//! │                                   min_priority=60                            │
//! │                                                                              │
//! │  Note: "stale" has high frequency (50) but low age (10), making it the      │
//! │        eviction candidate despite being historically popular.                │
//! └─────────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Operations
//!
//! | Operation | Action | Time |
//! |-----------|--------|------|
//! | `get(key)` | Increment frequency, update age to global_age | O(log P) |
//! | `put(key, value)` | Insert with priority=global_age+1, evict min priority | O(log P) |
//! | `remove(key)` | Remove from priority list | O(log P) |
//!
//! ## Aging Example
//!
//! ```text
//! global_age = 0
//!
//! put("a", 1)    →  a: freq=1, age=0, priority=1
//! get("a") x10   →  a: freq=11, age=0, priority=11
//! put("b", 2)    →  b: freq=1, age=0, priority=1
//! put("c", 3)    →  c: freq=1, age=0, priority=1
//!
//! [Cache full, add "d"]
//! - Evict min priority (b or c with priority=1)
//! - Set global_age = 1
//!
//! put("d", 4)    →  d: freq=1, age=1, priority=2
//!
//! [Many evictions later, global_age = 100]
//! - "a" still has priority=11 (no recent access)
//! - New item "e" gets priority=101
//! - "a" becomes eviction candidate despite high frequency!
//! ```
//!
//! # Dual-Limit Capacity
//!
//! This implementation supports two independent limits:
//!
//! - **`max_entries`**: Maximum number of items
//! - **`max_size`**: Maximum total size of content
//!
//! Eviction occurs when **either** limit would be exceeded.
//!
//! # Performance Characteristics
//!
//! | Metric | Value |
//! |--------|-------|
//! | Get | O(log P) |
//! | Put | O(log P) amortized |
//! | Remove | O(log P) |
//! | Memory per entry | ~110 bytes overhead + key×2 + value |
//!
//! Where P = number of distinct priority values. Since priority = frequency + age,
//! P can grow with the number of entries. BTreeMap provides O(log P) lookups.
//!
//! Slightly higher overhead than LFU due to age tracking per entry.
//!
//! # When to Use LFUDA
//!
//! **Good for:**
//! - Long-running caches where item popularity changes over time
//! - Web caches, CDN caches with evolving content popularity
//! - Systems that need frequency-based eviction but must adapt to trends
//! - Preventing "cache pollution" from historically popular but now stale items
//!
//! **Not ideal for:**
//! - Short-lived caches (aging doesn't have time to take effect)
//! - Static popularity patterns (pure LFU is simpler and equally effective)
//! - Strictly recency-based workloads (use LRU instead)
//!
//! # LFUDA vs LFU
//!
//! | Aspect | LFU | LFUDA |
//! |--------|-----|-------|
//! | Adapts to popularity changes | No | Yes |
//! | Memory overhead | Lower | Slightly higher |
//! | Complexity | Simpler | More complex |
//! | Best for | Stable patterns | Evolving patterns |
//!
//! # Thread Safety
//!
//! `LfudaCache` is **not thread-safe**. For concurrent access, either:
//! - Wrap with `Mutex` or `RwLock`
//! - Use `ConcurrentLfudaCache` (requires `concurrent` feature)
//!
//! # Examples
//!
//! ## Basic Usage
//!
//! ```
//! use cache_rs::LfudaCache;
//! use cache_rs::config::LfudaCacheConfig;
//! use core::num::NonZeroUsize;
//!
//! let config = LfudaCacheConfig {
//!     capacity: NonZeroUsize::new(3).unwrap(),
//!     initial_age: 0,
//!     max_size: u64::MAX,
//! };
//! let mut cache = LfudaCache::init(config, None);
//!
//! cache.put("a", 1, 1);
//! cache.put("b", 2, 1);
//! cache.put("c", 3, 1);
//!
//! // Access "a" to increase its priority
//! assert_eq!(cache.get(&"a"), Some(&1));
//! assert_eq!(cache.get(&"a"), Some(&1));
//!
//! // Add new item - lowest priority item evicted
//! cache.put("d", 4, 1);
//!
//! // "a" survives due to higher priority (frequency + age)
//! assert_eq!(cache.get(&"a"), Some(&1));
//! ```
//!
//! ## Long-Running Cache with Aging
//!
//! ```
//! use cache_rs::LfudaCache;
//! use cache_rs::config::LfudaCacheConfig;
//! use core::num::NonZeroUsize;
//!
//! let config = LfudaCacheConfig {
//!     capacity: NonZeroUsize::new(100).unwrap(),
//!     initial_age: 0,
//!     max_size: u64::MAX,
//! };
//! let mut cache = LfudaCache::init(config, None);
//!
//! // Populate cache with initial data
//! for i in 0..100 {
//!     cache.put(i, i * 10, 1);
//! }
//!
//! // Access some items frequently
//! for _ in 0..50 {
//!     cache.get(&0);  // Item 0 becomes very popular
//! }
//!
//! // Later: new content arrives, old content ages out
//! for i in 100..200 {
//!     cache.put(i, i * 10, 1);  // Each insert may evict old items
//! }
//!
//! // Item 0 may eventually be evicted if not accessed recently,
//! // despite its historical popularity - this is the power of LFUDA!
//! ```

extern crate alloc;

use crate::config::LfudaCacheConfig;
use crate::entry::CacheEntry;
use crate::list::{List, ListEntry};
use crate::metrics::{CacheMetrics, LfudaCacheMetrics};

/// Metadata for LFUDA (LFU with Dynamic Aging) cache entries.
///
/// LFUDA is similar to LFU but addresses the "aging problem" where old
/// frequently-used items can prevent new items from being cached.
/// The age factor is maintained at the cache level, not per-entry.
///
/// # Algorithm
///
/// Entry priority = frequency + age_at_insertion
/// - When an item is evicted, global_age = evicted_item.priority
/// - New items start with current global_age as their insertion age
///
/// # Examples
///
/// ```
/// use cache_rs::lfuda::LfudaMeta;
///
/// let meta = LfudaMeta::new(1, 10); // frequency=1, age_at_insertion=10
/// assert_eq!(meta.frequency, 1);
/// assert_eq!(meta.age_at_insertion, 10);
/// assert_eq!(meta.priority(), 11);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LfudaMeta {
    /// Access frequency count.
    pub frequency: u64,
    /// Age value when this item was inserted (snapshot of global_age).
    pub age_at_insertion: u64,
}

impl LfudaMeta {
    /// Creates a new LFUDA metadata with the specified initial frequency and age.
    ///
    /// # Arguments
    ///
    /// * `frequency` - Initial frequency value (usually 1 for new items)
    /// * `age_at_insertion` - The global_age at the time of insertion
    #[inline]
    pub fn new(frequency: u64, age_at_insertion: u64) -> Self {
        Self {
            frequency,
            age_at_insertion,
        }
    }

    /// Increments the frequency counter and returns the new value.
    #[inline]
    pub fn increment(&mut self) -> u64 {
        self.frequency += 1;
        self.frequency
    }

    /// Calculates the effective priority (frequency + age_at_insertion).
    #[inline]
    pub fn priority(&self) -> u64 {
        self.frequency + self.age_at_insertion
    }
}
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::hash::{BuildHasher, Hash};
use core::num::NonZeroUsize;

#[cfg(feature = "hashbrown")]
use hashbrown::DefaultHashBuilder;
#[cfg(feature = "hashbrown")]
use hashbrown::HashMap;

#[cfg(not(feature = "hashbrown"))]
use std::collections::hash_map::RandomState as DefaultHashBuilder;
#[cfg(not(feature = "hashbrown"))]
use std::collections::HashMap;

/// Internal LFUDA segment containing the actual cache algorithm.
///
/// This is shared between `LfudaCache` (single-threaded) and
/// `ConcurrentLfudaCache` (multi-threaded). All algorithm logic is
/// implemented here to avoid code duplication.
///
/// Uses `CacheEntry<K, V, LfudaMeta>` for unified entry management with built-in
/// size tracking, timestamps, and LFUDA-specific metadata (frequency + age_at_insertion).
///
/// # Safety
///
/// This struct contains raw pointers in the `map` field.
/// These pointers are always valid as long as:
/// - The pointer was obtained from a `priority_lists` entry's `add()` call
/// - The node has not been removed from the list
/// - The segment has not been dropped
pub(crate) struct LfudaSegment<K, V, S = DefaultHashBuilder> {
    /// Configuration for the LFUDA cache (includes capacity and max_size)
    config: LfudaCacheConfig,

    /// Global age value that increases when items are evicted
    global_age: u64,

    /// Current minimum effective priority in the cache
    min_priority: u64,

    /// Map from keys to their node pointer.
    /// All metadata (frequency, age, size) is stored in CacheEntry.
    map: HashMap<K, *mut ListEntry<CacheEntry<K, V, LfudaMeta>>, S>,

    /// Map from effective priority to list of items with that priority
    /// Items within each priority list are ordered by recency (LRU within priority)
    priority_lists: BTreeMap<u64, List<CacheEntry<K, V, LfudaMeta>>>,

    /// Metrics tracking for this cache instance
    metrics: LfudaCacheMetrics,

    /// Current total size of cached content (sum of entry sizes)
    current_size: u64,
}

// SAFETY: LfudaSegment owns all data and raw pointers point only to nodes owned by
// `priority_lists`. Concurrent access is safe when wrapped in proper synchronization primitives.
unsafe impl<K: Send, V: Send, S: Send> Send for LfudaSegment<K, V, S> {}

// SAFETY: All mutation requires &mut self; shared references cannot cause data races.
unsafe impl<K: Send, V: Send, S: Sync> Sync for LfudaSegment<K, V, S> {}

impl<K: Hash + Eq, V: Clone, S: BuildHasher> LfudaSegment<K, V, S> {
    /// Creates a new LFUDA segment from a configuration.
    ///
    /// This is the **recommended** way to create an LFUDA segment. All configuration
    /// is specified through the [`LfudaCacheConfig`] struct.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration specifying capacity, initial age, and optional size limit
    /// * `hasher` - Hash builder for the internal HashMap
    #[allow(dead_code)] // Used by concurrent module when feature is enabled
    pub(crate) fn init(config: LfudaCacheConfig, hasher: S) -> Self {
        let map_capacity = config.capacity.get().next_power_of_two();
        LfudaSegment {
            config,
            global_age: config.initial_age as u64,
            min_priority: 0,
            map: HashMap::with_capacity_and_hasher(map_capacity, hasher),
            priority_lists: BTreeMap::new(),
            metrics: LfudaCacheMetrics::new(config.max_size),
            current_size: 0,
        }
    }

    /// Returns the maximum number of key-value pairs the segment can hold.
    #[inline]
    pub(crate) fn cap(&self) -> NonZeroUsize {
        self.config.capacity
    }

    /// Returns the current number of key-value pairs in the segment.
    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the segment contains no key-value pairs.
    #[inline]
    pub(crate) fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Returns the current global age value.
    #[inline]
    pub(crate) fn global_age(&self) -> u64 {
        self.global_age
    }

    /// Returns the current total size of cached content.
    #[inline]
    pub(crate) fn current_size(&self) -> u64 {
        self.current_size
    }

    /// Returns the maximum content size the cache can hold.
    #[inline]
    pub(crate) fn max_size(&self) -> u64 {
        self.config.max_size
    }

    /// Returns a reference to the metrics for this segment.
    #[inline]
    pub(crate) fn metrics(&self) -> &LfudaCacheMetrics {
        &self.metrics
    }

    /// Records a cache miss for metrics tracking
    #[inline]
    pub(crate) fn record_miss(&mut self, object_size: u64) {
        self.metrics.core.record_miss(object_size);
    }

    /// Updates the priority of an item and moves it to the appropriate priority list.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `node` is a valid pointer to a ListEntry that exists
    /// in this cache's priority_lists and has not been freed.
    unsafe fn update_priority_by_node(
        &mut self,
        node: *mut ListEntry<CacheEntry<K, V, LfudaMeta>>,
        old_priority: u64,
    ) -> *mut ListEntry<CacheEntry<K, V, LfudaMeta>>
    where
        K: Clone + Hash + Eq,
    {
        // SAFETY: node is guaranteed to be valid by the caller's contract
        let entry = (*node).get_value();
        let key_cloned = entry.key.clone();

        // Get current node from map
        let node = *self.map.get(&key_cloned).unwrap();

        // Calculate new priority after incrementing frequency
        let meta = &(*node).get_value().metadata.algorithm;
        let new_priority = (meta.frequency + 1) + meta.age_at_insertion;

        // If priority hasn't changed, just move to front of the same list
        if old_priority == new_priority {
            self.priority_lists
                .get_mut(&old_priority)
                .unwrap()
                .move_to_front(node);
            return node;
        }

        // Remove from old priority list
        let boxed_entry = self
            .priority_lists
            .get_mut(&old_priority)
            .unwrap()
            .remove(node)
            .unwrap();

        // Clean up empty old priority list and update min_priority if necessary
        if self.priority_lists.get(&old_priority).unwrap().is_empty() {
            self.priority_lists.remove(&old_priority);
            if old_priority == self.min_priority {
                self.min_priority = new_priority;
            }
        }

        // Update frequency in the entry's metadata
        let entry_ptr = Box::into_raw(boxed_entry);
        (*entry_ptr).get_value_mut().metadata.algorithm.frequency += 1;

        // Ensure the new priority list exists
        let capacity = self.config.capacity;
        self.priority_lists
            .entry(new_priority)
            .or_insert_with(|| List::new(capacity));

        // Add to the front of the new priority list (most recently used within that priority)
        self.priority_lists
            .get_mut(&new_priority)
            .unwrap()
            .attach_from_other_list(entry_ptr);

        // Update the map with the new node pointer
        *self.map.get_mut(&key_cloned).unwrap() = entry_ptr;

        entry_ptr
    }

    /// Returns a reference to the value corresponding to the key.
    pub(crate) fn get<Q>(&mut self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q> + Clone,
        Q: ?Sized + Hash + Eq,
    {
        if let Some(&node) = self.map.get(key) {
            unsafe {
                // SAFETY: node comes from our map
                let entry = (*node).get_value();
                let meta = &entry.metadata.algorithm;
                let old_priority = meta.priority();
                self.metrics.core.record_hit(entry.metadata.size);

                let new_node = self.update_priority_by_node(node, old_priority);
                let new_entry = (*new_node).get_value();
                Some(&new_entry.value)
            }
        } else {
            None
        }
    }

    /// Returns a mutable reference to the value corresponding to the key.
    pub(crate) fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q> + Clone,
        Q: ?Sized + Hash + Eq,
    {
        if let Some(&node) = self.map.get(key) {
            unsafe {
                // SAFETY: node comes from our map
                let entry = (*node).get_value();
                let meta = &entry.metadata.algorithm;
                let old_priority = meta.priority();
                self.metrics.core.record_hit(entry.metadata.size);

                let new_priority = (meta.frequency + 1) + meta.age_at_insertion;
                self.metrics.record_frequency_increment(new_priority);

                let new_node = self.update_priority_by_node(node, old_priority);
                let new_entry = (*new_node).get_value_mut();
                Some(&mut new_entry.value)
            }
        } else {
            None
        }
    }

    /// Inserts a key-value pair into the segment.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to insert
    /// * `value` - The value to insert
    /// * `size` - Optional size in bytes. Use `SIZE_UNIT` (1) for count-based caching.
    ///
    /// Returns evicted entries, or `None` if no entries were evicted.
    /// Note: Replacing an existing key does not return the old value.
    pub(crate) fn put(&mut self, key: K, value: V, size: u64) -> Option<Vec<(K, V)>>
    where
        K: Clone,
    {
        // If key already exists, update it
        if let Some(&node) = self.map.get(&key) {
            unsafe {
                // SAFETY: node comes from our map
                let entry = (*node).get_value();
                let meta = &entry.metadata.algorithm;
                let priority = meta.priority();
                let old_size = entry.metadata.size;

                // Create new CacheEntry with same frequency and age
                let new_entry = CacheEntry::with_algorithm_metadata(
                    key.clone(),
                    value,
                    size,
                    LfudaMeta::new(meta.frequency, meta.age_at_insertion),
                );

                let _old_entry = self
                    .priority_lists
                    .get_mut(&priority)
                    .unwrap()
                    .update(node, new_entry, true);

                // Update size tracking
                self.current_size = self.current_size.saturating_sub(old_size);
                self.current_size += size;
                self.metrics.core.record_size_change(old_size, size);
                self.metrics.core.bytes_written_to_cache += size;

                // Replacement is not eviction - don't return the old value
                return None;
            }
        }

        let mut evicted = Vec::new();

        // Add new item with frequency 1 and current global age
        let frequency: u64 = 1;
        let age_at_insertion = self.global_age;
        let priority = frequency + age_at_insertion;

        // Evict while entry count limit OR size limit would be exceeded
        while self.len() >= self.config.capacity.get()
            || (self.current_size + size > self.config.max_size && !self.map.is_empty())
        {
            if let Some(entry) = self.evict() {
                self.metrics.core.evictions += 1;
                evicted.push(entry);
            } else {
                break;
            }
        }

        self.min_priority = if self.is_empty() {
            priority
        } else {
            core::cmp::min(self.min_priority, priority)
        };

        // Ensure priority list exists
        let capacity = self.config.capacity;
        self.priority_lists
            .entry(priority)
            .or_insert_with(|| List::new(capacity));

        // Create CacheEntry with LfudaMeta
        let cache_entry = CacheEntry::with_algorithm_metadata(
            key.clone(),
            value,
            size,
            LfudaMeta::new(frequency, age_at_insertion),
        );

        if let Some(node) = self
            .priority_lists
            .get_mut(&priority)
            .unwrap()
            .add(cache_entry)
        {
            self.map.insert(key, node);
            self.current_size += size;

            self.metrics.core.record_insertion(size);
            self.metrics.record_frequency_increment(priority);
            if age_at_insertion > 0 {
                self.metrics.record_aging_benefit(age_at_insertion);
            }
        }

        if evicted.is_empty() {
            None
        } else {
            Some(evicted)
        }
    }

    /// Removes a key from the segment, returning the value if the key was present.
    pub(crate) fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        let node = self.map.remove(key)?;

        unsafe {
            // SAFETY: node comes from our map; take_value moves the value out
            // and Box::from_raw frees memory (MaybeUninit won't double-drop).
            // Read priority before removal — needed to find the correct priority list
            let priority = (*node).get_value().metadata.algorithm.priority();

            let boxed_entry = self.priority_lists.get_mut(&priority)?.remove(node)?;
            let entry_ptr = Box::into_raw(boxed_entry);
            let cache_entry = (*entry_ptr).take_value();
            let removed_size = cache_entry.metadata.size;
            let _ = Box::from_raw(entry_ptr);

            self.current_size = self.current_size.saturating_sub(removed_size);
            self.metrics.core.record_removal(removed_size);

            // Clean up empty priority list and update min_priority if necessary
            if self.priority_lists.get(&priority).unwrap().is_empty() {
                self.priority_lists.remove(&priority);
                if priority == self.min_priority {
                    self.min_priority = self
                        .priority_lists
                        .keys()
                        .copied()
                        .next()
                        .unwrap_or(self.global_age);
                }
            }

            Some(cache_entry.value)
        }
    }

    /// Clears the segment, removing all key-value pairs.
    pub(crate) fn clear(&mut self) {
        self.map.clear();
        self.priority_lists.clear();
        self.global_age = 0;
        self.min_priority = 0;
        self.current_size = 0;
    }

    /// Check if key exists without updating its priority or access metadata.
    ///
    /// Unlike `get()`, this method does NOT update the entry's frequency
    /// or access metadata.
    #[inline]
    pub(crate) fn contains<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.map.contains_key(key)
    }

    /// Returns a reference to the value without updating priority or access metadata.
    ///
    /// Unlike `get()`, this method does NOT increment the entry's frequency,
    /// change its priority, or move it between priority lists.
    pub(crate) fn peek<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        let &node = self.map.get(key)?;
        unsafe {
            // SAFETY: node comes from our map, so it's a valid pointer
            let entry = (*node).get_value();
            Some(&entry.value)
        }
    }

    /// Removes and returns the eviction candidate (lowest priority entry).
    ///
    /// Also updates the global age to the evicted item's priority (LFUDA aging).
    ///
    /// This method does **not** increment the eviction counter in metrics.
    /// Eviction metrics are only recorded when the cache internally evicts
    /// entries to make room during `put()` operations.
    ///
    /// Returns `None` if the cache is empty.
    fn evict(&mut self) -> Option<(K, V)> {
        if self.is_empty() {
            return None;
        }

        // Find the actual minimum non-empty priority list.
        // self.min_priority may be stale if remove() left empty lists behind.
        let min_key = loop {
            if let Some(min_priority_list) = self.priority_lists.get(&self.min_priority) {
                if !min_priority_list.is_empty() {
                    break self.min_priority;
                }
                // Clean up empty list and advance
                let stale = self.min_priority;
                self.priority_lists.remove(&stale);
                self.min_priority = self
                    .priority_lists
                    .keys()
                    .copied()
                    .next()
                    .unwrap_or(self.global_age);
            } else {
                // min_priority doesn't exist in the map, recalculate
                self.min_priority = self
                    .priority_lists
                    .keys()
                    .copied()
                    .next()
                    .unwrap_or(self.global_age);
                // If there are still no lists, the cache is effectively empty
                if self.priority_lists.is_empty() {
                    return None;
                }
            }
        };

        let min_priority_list = self.priority_lists.get_mut(&min_key)?;
        let old_entry = min_priority_list.remove_last()?;
        let is_list_empty = min_priority_list.is_empty();

        unsafe {
            // SAFETY: take_value moves the CacheEntry out by value.
            // Box::from_raw frees memory (MaybeUninit won't double-drop).
            let entry_ptr = Box::into_raw(old_entry);
            let cache_entry = (*entry_ptr).take_value();
            let evicted_size = cache_entry.metadata.size;
            let evicted_priority = cache_entry.metadata.algorithm.priority();

            // Update global age to the evicted item's priority (LFUDA aging)
            self.global_age = evicted_priority;
            self.metrics.record_aging_event(self.global_age);

            self.map.remove(&cache_entry.key);
            self.current_size = self.current_size.saturating_sub(evicted_size);
            self.metrics.core.record_removal(evicted_size);

            // Update min_priority if the list is now empty
            if is_list_empty {
                self.priority_lists.remove(&self.min_priority);
                self.min_priority = self
                    .priority_lists
                    .keys()
                    .copied()
                    .next()
                    .unwrap_or(self.global_age);
            }

            let _ = Box::from_raw(entry_ptr);
            Some((cache_entry.key, cache_entry.value))
        }
    }
}

// Implement Debug for LfudaSegment manually since it contains raw pointers
impl<K, V, S> core::fmt::Debug for LfudaSegment<K, V, S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("LfudaSegment")
            .field("capacity", &self.config.capacity)
            .field("len", &self.map.len())
            .field("global_age", &self.global_age)
            .field("min_priority", &self.min_priority)
            .finish()
    }
}

/// An implementation of a Least Frequently Used with Dynamic Aging (LFUDA) cache.
///
/// LFUDA improves upon LFU by adding an aging mechanism that prevents old frequently-used
/// items from blocking new items indefinitely. Each item's effective priority is calculated
/// as (access_frequency + age_at_insertion), where age_at_insertion is the global age
/// value when the item was first inserted.
///
/// When an item is evicted, the global age is set to the evicted item's effective priority,
/// ensuring that new items start with a competitive priority.
///
/// # Examples
///
/// ```
/// use cache_rs::lfuda::LfudaCache;
/// use cache_rs::config::LfudaCacheConfig;
/// use core::num::NonZeroUsize;
///
/// // Create an LFUDA cache with capacity 3
/// let config = LfudaCacheConfig {
///     capacity: NonZeroUsize::new(3).unwrap(),
///     initial_age: 0,
///     max_size: u64::MAX,
/// };
/// let mut cache = LfudaCache::init(config, None);
///
/// // Add some items
/// cache.put("a", 1, 1);
/// cache.put("b", 2, 1);
/// cache.put("c", 3, 1);
///
/// // Access "a" multiple times to increase its frequency
/// assert_eq!(cache.get(&"a"), Some(&1));
/// assert_eq!(cache.get(&"a"), Some(&1));
///
/// // Add more items to trigger aging
/// cache.put("d", 4, 1); // This will evict an item and increase global age
/// cache.put("e", 5, 1); // New items benefit from the increased age
/// ```
#[derive(Debug)]
pub struct LfudaCache<K, V, S = DefaultHashBuilder> {
    segment: LfudaSegment<K, V, S>,
}

impl<K: Hash + Eq, V: Clone, S: BuildHasher> LfudaCache<K, V, S> {
    /// Returns the maximum number of key-value pairs the cache can hold.
    #[inline]
    pub fn cap(&self) -> NonZeroUsize {
        self.segment.cap()
    }

    /// Returns the current number of key-value pairs in the cache.
    #[inline]
    pub fn len(&self) -> usize {
        self.segment.len()
    }

    /// Returns `true` if the cache contains no key-value pairs.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.segment.is_empty()
    }

    /// Returns the current total size of cached content.
    #[inline]
    pub fn current_size(&self) -> u64 {
        self.segment.current_size()
    }

    /// Returns the maximum content size the cache can hold.
    #[inline]
    pub fn max_size(&self) -> u64 {
        self.segment.max_size()
    }

    /// Returns the current global age value.
    #[inline]
    pub fn global_age(&self) -> u64 {
        self.segment.global_age()
    }

    /// Records a cache miss for metrics tracking (to be called by simulation system)
    #[inline]
    pub fn record_miss(&mut self, object_size: u64) {
        self.segment.record_miss(object_size);
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the cache's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// Accessing an item increases its frequency count.
    #[inline]
    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q> + Clone,
        Q: ?Sized + Hash + Eq,
    {
        self.segment.get(key)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the cache's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// Accessing an item increases its frequency count.
    #[inline]
    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q> + Clone,
        Q: ?Sized + Hash + Eq,
    {
        self.segment.get_mut(key)
    }

    /// Inserts a key-value pair into the cache.
    ///
    /// If the key already exists, it is replaced. If at capacity, the item with the
    /// lowest effective priority is evicted and the global age is updated to the
    /// evicted item's effective priority.
    ///
    /// New items are inserted with a frequency of 1 and `age_at_insertion` set to the
    /// current `global_age`.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to insert
    /// * `value` - The value to insert
    /// * `size` - Optional size in bytes for size-aware caching. Use `SIZE_UNIT` (1) for count-based caching.
    ///
    /// # Returns
    ///
    /// - `Some(vec)` containing evicted entries (not replaced entries)
    /// - `None` if no entries were evicted (zero allocation)
    #[inline]
    pub fn put(&mut self, key: K, value: V, size: u64) -> Option<Vec<(K, V)>>
    where
        K: Clone,
    {
        self.segment.put(key, value, size)
    }

    /// Removes a key from the cache, returning the value at the key if the key was previously in the cache.
    ///
    /// The key may be any borrowed form of the cache's key type, but
    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
    /// the key type.
    #[inline]
    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
        V: Clone,
    {
        self.segment.remove(key)
    }

    /// Clears the cache, removing all key-value pairs.
    /// Resets the global age to 0.
    #[inline]
    pub fn clear(&mut self) {
        self.segment.clear()
    }

    /// Check if key exists without updating its priority or access metadata.
    ///
    /// Unlike `get()`, this method does NOT update the entry's frequency
    /// or access metadata. Useful for existence checks without affecting
    /// cache eviction order.
    ///
    /// # Example
    ///
    /// ```
    /// use cache_rs::lfuda::LfudaCache;
    /// use cache_rs::config::LfudaCacheConfig;
    /// use core::num::NonZeroUsize;
    ///
    /// let config = LfudaCacheConfig {
    ///     capacity: NonZeroUsize::new(2).unwrap(),
    ///     initial_age: 0,
    ///     max_size: u64::MAX,
    /// };
    /// let mut cache = LfudaCache::init(config, None);
    /// cache.put("a", 1, 1);
    /// cache.put("b", 2, 1);
    ///
    /// // contains() does NOT update priority
    /// assert!(cache.contains(&"a"));
    /// ```
    #[inline]
    pub fn contains<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.segment.contains(key)
    }

    /// Returns a reference to the value without updating priority or access metadata.
    ///
    /// Unlike [`get()`](Self::get), this does NOT increment the entry's frequency,
    /// change its priority, or move it between priority lists.
    ///
    /// # Example
    ///
    /// ```
    /// use cache_rs::lfuda::LfudaCache;
    /// use cache_rs::config::LfudaCacheConfig;
    /// use core::num::NonZeroUsize;
    ///
    /// let config = LfudaCacheConfig {
    ///     capacity: NonZeroUsize::new(3).unwrap(),
    ///     initial_age: 0,
    ///     max_size: u64::MAX,
    /// };
    /// let mut cache = LfudaCache::init(config, None);
    /// cache.put("a", 1, 1);
    ///
    /// // peek does not change priority
    /// assert_eq!(cache.peek(&"a"), Some(&1));
    /// assert_eq!(cache.peek(&"missing"), None);
    /// ```
    #[inline]
    pub fn peek<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.segment.peek(key)
    }
}

impl<K: Hash + Eq, V: Clone, S: BuildHasher> CacheMetrics for LfudaCache<K, V, S> {
    fn metrics(&self) -> BTreeMap<String, f64> {
        self.segment.metrics().metrics()
    }

    fn algorithm_name(&self) -> &'static str {
        self.segment.metrics().algorithm_name()
    }
}

impl<K: Hash + Eq, V> LfudaCache<K, V>
where
    V: Clone,
{
    /// Creates a new LFUDA cache from a configuration.
    ///
    /// This is the **recommended** way to create an LFUDA cache. All configuration
    /// is specified through the [`LfudaCacheConfig`] struct, which uses a builder
    /// pattern for optional parameters.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration specifying capacity and optional size limit/initial age
    ///
    /// # Example
    ///
    /// ```
    /// use cache_rs::LfudaCache;
    /// use cache_rs::config::LfudaCacheConfig;
    /// use core::num::NonZeroUsize;
    ///
    /// // Simple capacity-only cache
    /// let config = LfudaCacheConfig {
    ///     capacity: NonZeroUsize::new(100).unwrap(),
    ///     initial_age: 0,
    ///     max_size: u64::MAX,
    /// };
    /// let mut cache: LfudaCache<&str, i32> = LfudaCache::init(config, None);
    /// cache.put("key", 42, 1);
    ///
    /// // Cache with size limit
    /// let config = LfudaCacheConfig {
    ///     capacity: NonZeroUsize::new(1000).unwrap(),
    ///     initial_age: 100,
    ///     max_size: 10 * 1024 * 1024,  // 10MB
    /// };
    /// let cache: LfudaCache<String, Vec<u8>> = LfudaCache::init(config, None);
    /// ```
    pub fn init(
        config: LfudaCacheConfig,
        hasher: Option<DefaultHashBuilder>,
    ) -> LfudaCache<K, V, DefaultHashBuilder> {
        LfudaCache {
            segment: LfudaSegment::init(config, hasher.unwrap_or_default()),
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use alloc::string::ToString;

    use super::*;
    use crate::config::LfudaCacheConfig;
    use alloc::string::String;

    /// Helper to create an LfudaCache with the given capacity
    fn make_cache<K: Hash + Eq + Clone, V: Clone>(cap: usize) -> LfudaCache<K, V> {
        let config = LfudaCacheConfig {
            capacity: NonZeroUsize::new(cap).unwrap(),
            initial_age: 0,
            max_size: u64::MAX,
        };
        LfudaCache::init(config, None)
    }

    #[test]
    fn test_lfuda_basic() {
        let mut cache = make_cache(3);

        // Add items
        assert_eq!(cache.put("a", 1, 1), None);
        assert_eq!(cache.put("b", 2, 1), None);
        assert_eq!(cache.put("c", 3, 1), None);

        // Access "a" multiple times to increase its frequency
        assert_eq!(cache.get(&"a"), Some(&1));
        assert_eq!(cache.get(&"a"), Some(&1));

        // Access "b" once
        assert_eq!(cache.get(&"b"), Some(&2));

        // Add a new item, should evict "c" (lowest effective priority)
        let evicted = cache.put("d", 4, 1);
        assert!(evicted.is_some());
        let (evicted_key, evicted_val) = evicted.unwrap()[0];
        assert_eq!(evicted_key, "c");
        assert_eq!(evicted_val, 3);

        // Check remaining items
        assert_eq!(cache.get(&"a"), Some(&1));
        assert_eq!(cache.get(&"b"), Some(&2));
        assert_eq!(cache.get(&"d"), Some(&4));
        assert_eq!(cache.get(&"c"), None); // evicted
    }

    #[test]
    fn test_lfuda_aging() {
        let mut cache = make_cache(2);

        // Add items and access them
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);

        // Access "a" many times
        for _ in 0..10 {
            cache.get(&"a");
        }

        // Initially, global age should be 0
        assert_eq!(cache.global_age(), 0);

        // Fill cache and cause eviction
        let evicted = cache.put("c", 3, 1);
        assert!(evicted.is_some());

        // Global age should have increased after eviction
        assert!(cache.global_age() > 0);

        // New items should benefit from the increased global age
        cache.put("d", 4, 1);

        // The new item should start with competitive priority due to aging
        assert!(cache.len() <= cache.cap().get());
    }

    #[test]
    fn test_lfuda_priority_calculation() {
        let mut cache = make_cache(3);

        cache.put("a", 1, 1);
        assert_eq!(cache.global_age(), 0);

        // Access "a" to increase its frequency
        cache.get(&"a");

        // Add more items
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Force eviction to increase global age
        let evicted = cache.put("d", 4, 1);
        assert!(evicted.is_some());

        // Global age should now be greater than 0
        assert!(cache.global_age() > 0);
    }

    #[test]
    fn test_lfuda_update_existing() {
        let mut cache = make_cache(2);

        cache.put("a", 1, 1);
        cache.get(&"a"); // Increase frequency

        // Update existing key - replacement returns None
        let old_value = cache.put("a", 10, 1);
        assert!(old_value.is_none());

        // Add another item
        cache.put("b", 2, 1);
        cache.put("c", 3, 1); // Should evict "b" because "a" has higher effective priority

        assert_eq!(cache.get(&"a"), Some(&10));
        assert_eq!(cache.get(&"c"), Some(&3));
        assert_eq!(cache.get(&"b"), None);
    }

    #[test]
    fn test_lfuda_remove() {
        let mut cache = make_cache(3);

        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Remove item
        assert_eq!(cache.remove(&"b"), Some(2));
        assert_eq!(cache.remove(&"b"), None);

        // Check remaining items
        assert_eq!(cache.get(&"a"), Some(&1));
        assert_eq!(cache.get(&"c"), Some(&3));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lfuda_clear() {
        let mut cache = make_cache(3);

        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Force some aging
        cache.get(&"a");
        cache.put("d", 4, 1); // This should increase global_age

        let age_before_clear = cache.global_age();
        assert!(age_before_clear > 0);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
        assert_eq!(cache.global_age(), 0); // Should reset to 0

        // Should be able to add items after clear
        cache.put("e", 5, 1);
        assert_eq!(cache.get(&"e"), Some(&5));
    }

    #[test]
    fn test_lfuda_get_mut() {
        let mut cache = make_cache(2);

        cache.put("a", 1, 1);

        // Modify value using get_mut
        if let Some(value) = cache.get_mut(&"a") {
            *value = 10;
        }

        assert_eq!(cache.get(&"a"), Some(&10));
    }

    #[test]
    fn test_lfuda_complex_values() {
        let mut cache = make_cache(2);

        #[derive(Debug, Clone, PartialEq)]
        struct ComplexValue {
            id: usize,
            data: String,
        }

        // Add complex values
        cache.put(
            "a",
            ComplexValue {
                id: 1,
                data: "a-data".to_string(),
            },
            1,
        );

        cache.put(
            "b",
            ComplexValue {
                id: 2,
                data: "b-data".to_string(),
            },
            1,
        );

        // Modify a value using get_mut
        if let Some(value) = cache.get_mut(&"a") {
            value.id = 100;
            value.data = "a-modified".to_string();
        }

        // Check the modified value
        let a = cache.get(&"a").unwrap();
        assert_eq!(a.id, 100);
        assert_eq!(a.data, "a-modified");
    }

    #[test]
    fn test_lfuda_aging_advantage() {
        let mut cache = make_cache(2);

        // Add and heavily access an old item
        cache.put("old", 1, 1);
        for _ in 0..100 {
            cache.get(&"old");
        }

        // Fill cache
        cache.put("temp", 2, 1);

        // Force eviction to age the cache
        let _evicted = cache.put("new1", 3, 1);
        let age_after_first_eviction = cache.global_age();

        // Add more items to further age the cache
        let _evicted = cache.put("new2", 4, 1);
        let age_after_second_eviction = cache.global_age();

        // The global age should have increased
        assert!(age_after_second_eviction >= age_after_first_eviction);

        // Now add a brand new item - it should benefit from the aging
        cache.put("newer", 5, 1);

        // The newer item should be able to compete despite the old item's high frequency
        assert!(cache.len() <= cache.cap().get());
    }

    /// Test to validate the fix for Stacked Borrows violations detected by Miri.
    #[test]
    fn test_miri_stacked_borrows_fix() {
        let mut cache = make_cache(10);

        // Insert some items
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Access items multiple times to trigger priority updates
        for _ in 0..3 {
            assert_eq!(cache.get(&"a"), Some(&1));
            assert_eq!(cache.get(&"b"), Some(&2));
            assert_eq!(cache.get(&"c"), Some(&3));
        }

        assert_eq!(cache.len(), 3);

        // Test with get_mut as well
        if let Some(val) = cache.get_mut(&"a") {
            *val += 10;
        }
        assert_eq!(cache.get(&"a"), Some(&11));
    }

    // Test that LfudaSegment works correctly (internal tests)
    #[test]
    fn test_lfuda_segment_directly() {
        let config = LfudaCacheConfig {
            capacity: NonZeroUsize::new(3).unwrap(),
            initial_age: 0,
            max_size: u64::MAX,
        };
        let mut segment: LfudaSegment<&str, i32, DefaultHashBuilder> =
            LfudaSegment::init(config, DefaultHashBuilder::default());

        assert_eq!(segment.len(), 0);
        assert!(segment.is_empty());
        assert_eq!(segment.cap().get(), 3);
        assert_eq!(segment.global_age(), 0);

        segment.put("a", 1, 1);
        segment.put("b", 2, 1);
        assert_eq!(segment.len(), 2);

        // Access to increase frequency
        assert_eq!(segment.get(&"a"), Some(&1));
        assert_eq!(segment.get(&"b"), Some(&2));
    }

    #[test]
    fn test_lfuda_concurrent_access() {
        extern crate std;
        use std::sync::{Arc, Mutex};
        use std::thread;
        use std::vec::Vec;

        let cache = Arc::new(Mutex::new(make_cache::<String, i32>(100)));
        let num_threads = 4;
        let ops_per_thread = 100;

        let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();

        for t in 0..num_threads {
            let cache = Arc::clone(&cache);
            handles.push(thread::spawn(move || {
                for i in 0..ops_per_thread {
                    let key = std::format!("key_{}_{}", t, i);
                    let mut guard = cache.lock().unwrap();
                    guard.put(key.clone(), i, 1);
                    let _ = guard.get(&key);
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let mut guard = cache.lock().unwrap();
        assert!(guard.len() <= 100);
        guard.clear(); // Clean up for MIRI
    }

    #[test]
    fn test_lfuda_size_aware_tracking() {
        let mut cache = make_cache(10);

        assert_eq!(cache.current_size(), 0);
        assert_eq!(cache.max_size(), u64::MAX);

        cache.put("a", 1, 100);
        cache.put("b", 2, 200);
        cache.put("c", 3, 150);

        assert_eq!(cache.current_size(), 450);
        assert_eq!(cache.len(), 3);

        // Clear should reset size
        cache.clear();
        assert_eq!(cache.current_size(), 0);
    }

    #[test]
    fn test_lfuda_init_constructor() {
        let config = LfudaCacheConfig {
            capacity: NonZeroUsize::new(1000).unwrap(),
            initial_age: 0,
            max_size: 1024 * 1024,
        };
        let cache: LfudaCache<String, i32> = LfudaCache::init(config, None);

        assert_eq!(cache.current_size(), 0);
        assert_eq!(cache.max_size(), 1024 * 1024);
    }

    #[test]
    fn test_lfuda_with_limits_constructor() {
        let config = LfudaCacheConfig {
            capacity: NonZeroUsize::new(100).unwrap(),
            initial_age: 0,
            max_size: 1024 * 1024,
        };
        let cache: LfudaCache<String, String> = LfudaCache::init(config, None);

        assert_eq!(cache.current_size(), 0);
        assert_eq!(cache.max_size(), 1024 * 1024);
        assert_eq!(cache.cap().get(), 100);
    }

    #[test]
    fn test_lfuda_contains_non_promoting() {
        let mut cache = make_cache(2);
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);

        // contains() should return true for existing keys
        assert!(cache.contains(&"a"));
        assert!(cache.contains(&"b"));
        assert!(!cache.contains(&"c"));

        // Access "b" to increase its priority
        cache.get(&"b");

        // contains() should NOT increase priority of "a"
        assert!(cache.contains(&"a"));

        // Adding "c" should evict "a" (lowest priority), not "b"
        cache.put("c", 3, 1);
        assert!(!cache.contains(&"a")); // "a" was evicted
        assert!(cache.contains(&"b")); // "b" still exists
        assert!(cache.contains(&"c")); // "c" was just added
    }

    #[test]
    fn test_put_returns_none_when_no_eviction() {
        let mut cache = make_cache(10);
        assert!(cache.put("a", 1, 1).is_none());
        assert!(cache.put("b", 2, 1).is_none());
    }

    #[test]
    fn test_put_returns_single_eviction() {
        let mut cache = make_cache(2);
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        let result = cache.put("c", 3, 1);
        assert!(result.is_some());
        let evicted = result.unwrap();
        assert_eq!(evicted.len(), 1);
    }

    #[test]
    fn test_put_replacement_returns_none() {
        let mut cache = make_cache(10);
        cache.put("a", 1, 1);
        // Replacement is not eviction - returns None
        let result = cache.put("a", 2, 1);
        assert!(result.is_none());
        // Value should be updated
        assert_eq!(cache.get(&"a"), Some(&2));
    }

    #[test]
    fn test_put_returns_multiple_evictions_size_based() {
        let config = LfudaCacheConfig {
            capacity: NonZeroUsize::new(10).unwrap(),
            initial_age: 0,
            max_size: 100,
        };
        let mut cache = LfudaCache::init(config, None);
        for i in 0..10 {
            cache.put(i, i, 10);
        }
        let result = cache.put(99, 99, 50);
        let evicted = result.unwrap();
        assert_eq!(evicted.len(), 5);
    }

    #[test]
    fn test_lfuda_remove_cleans_up_empty_priority_lists() {
        // Regression test: remove() should clean up empty priority lists
        // from BTreeMap to avoid memory leaks and stale entries.
        let mut cache = make_cache(5);

        // Insert items that will have different priorities
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Access "a" to bump its frequency (changes priority)
        cache.get(&"a");
        cache.get(&"a");

        // Remove items and verify cache stays consistent
        cache.remove(&"b");
        cache.remove(&"c");

        // Cache should still work correctly after removals
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.get(&"a"), Some(&1));

        // Insert new items - should not hit stale empty lists
        cache.put("d", 4, 1);
        cache.put("e", 5, 1);
        assert_eq!(cache.len(), 3);
    }

    #[test]
    fn test_lfuda_remove_non_min_priority_cleans_up() {
        // Verify that removing items at non-minimum priorities also cleans up empty lists.
        let mut cache = make_cache(5);

        cache.put("a", 1, 1);
        cache.put("b", 2, 1);
        cache.put("c", 3, 1);

        // Access "a" many times - it will have a higher priority
        for _ in 0..5 {
            cache.get(&"a");
        }

        // Remove "a" (high priority) - the high-priority list should be cleaned up
        cache.remove(&"a");
        assert_eq!(cache.len(), 2);

        // Remaining items should still be accessible
        assert_eq!(cache.get(&"b"), Some(&2));
        assert_eq!(cache.get(&"c"), Some(&3));
    }

    #[test]
    fn test_lfuda_update_priority_cleans_up_empty_lists() {
        // Regression test: update_priority_by_node() should clean up empty
        // priority lists when moving a node to a new priority.
        let mut cache = make_cache(5);

        // Insert items at the same initial priority
        cache.put("a", 1, 1);
        cache.put("b", 2, 1);

        // Access "a" to move it to a new priority list.
        // If "a" was the only item at that priority, the old list should be removed.
        cache.get(&"a");

        // Now access "b" to also move it
        cache.get(&"b");

        // Both should still be accessible
        assert_eq!(cache.get(&"a"), Some(&1));
        assert_eq!(cache.get(&"b"), Some(&2));

        // Insert more items and verify eviction works correctly
        cache.put("c", 3, 1);
        cache.put("d", 4, 1);
        cache.put("e", 5, 1);
        assert_eq!(cache.len(), 5);

        // Force eviction - should work without issues from stale empty lists
        cache.put("f", 6, 1);
        assert_eq!(cache.len(), 5);
    }
}