cachekit 0.7.0

High-performance cache primitives with pluggable eviction policies (LRU, LFU, FIFO, 2Q, Clock-PRO, S3-FIFO) and optional metrics.
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
//! Adaptive Replacement Cache (ARC) replacement policy.
//!
//! Implements the ARC algorithm, which automatically adapts between recency and
//! frequency preferences by maintaining four lists and adjusting a dynamic target
//! parameter based on access patterns.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │                           ArcCore<K, V> Layout                              │
//! │                                                                             │
//! │   ┌─────────────────────────────────────────────────────────────────────┐   │
//! │   │  index: HashMap<K, NonNull<Node>>    nodes: Allocated on heap       │   │
//! │   │                                                                     │   │
//! │   │  ┌──────────┬───────────┐           ┌────────┬──────────────────┐   │   │
//! │   │  │   Key    │  NodePtr  │           │ Node   │ key,val,list     │   │   │
//! │   │  ├──────────┼───────────┤           ├────────┼──────────────────┤   │   │
//! │   │  │  "page1" │   ptr_0   │──────────►│ Node0  │ k,v,T1           │   │   │
//! │   │  │  "page2" │   ptr_1   │──────────►│ Node1  │ k,v,T2           │   │   │
//! │   │  │  "page3" │   ptr_2   │──────────►│ Node2  │ k,v,T1           │   │   │
//! │   │  └──────────┴───────────┘           └────────┴──────────────────┘   │   │
//! │   └─────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! │   ┌─────────────────────────────────────────────────────────────────────┐   │
//! │   │                        List Organization                            │   │
//! │   │                                                                     │   │
//! │   │   T1 (Recency - Recent Once)          T2 (Frequency - Repeated)     │   │
//! │   │   ┌─────────────────────────┐          ┌─────────────────────────┐  │   │
//! │   │   │ MRU               LRU   │          │ MRU               LRU   │  │   │
//! │   │   │  ▼                  ▼   │          │  ▼                  ▼   │  │   │
//! │   │   │ [ptr_2] ◄──► [ptr_0] ◄┤ │          │ [ptr_1] ◄──► [...] ◄┤   │  │   │
//! │   │   │  new      older   evict │          │ hot          cold evict │  │   │
//! │   │   └─────────────────────────┘          └─────────────────────────┘  │   │
//! │   │                                                                     │   │
//! │   │   B1 (Ghost - evicted from T1)       B2 (Ghost - evicted from T2)   │   │
//! │   │   ┌─────────────────────────┐          ┌─────────────────────────┐  │   │
//! │   │   │ Keys only (no values)   │          │ Keys only (no values)   │  │   │
//! │   │   └─────────────────────────┘          └─────────────────────────┘  │   │
//! │   │                                                                     │   │
//! │   │   Adaptation Parameter: p (target size for T1)                      │   │
//! │   │   • Hit in B1 → increase p (favor recency)                          │   │
//! │   │   • Hit in B2 → decrease p (favor frequency)                        │   │
//! │   └─────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! └─────────────────────────────────────────────────────────────────────────────┘
//!
//! Insert Flow (new key, not in any list)
//! ────────────────────────────────────────
//!
//!   insert("new_key", value):
//!     1. Check index - not found
//!     2. Check ghost lists (B1/B2) for adaptation
//!     3. Create Node with ListKind::T1
//!     4. Allocate on heap → get NonNull<Node>
//!     5. Insert key→ptr into index
//!     6. Attach ptr to T1 MRU
//!     7. Evict if over capacity (replace algorithm)
//!
//! Access Flow (existing key in T1/T2)
//! ────────────────────────────────────
//!
//!   get("existing_key"):
//!     1. Lookup ptr in index
//!     2. Check node's list:
//!        - If T1: promote to T2 (move to T2 MRU)
//!        - If T2: move to MRU position within T2
//!     3. Return &value
//!
//! Ghost Hit Flow (key in B1/B2)
//! ──────────────────────────────
//!
//!   get("ghost_key"):
//!     1. Found in B1: increase p (favor recency)
//!     2. Found in B2: decrease p (favor frequency)
//!     3. Perform replacement to make space
//!     4. Insert into T2 (proven reuse)
//!     5. Remove from ghost list
//!
//! Eviction Flow (Replace Algorithm)
//! ──────────────────────────────────
//!
//!   replace():
//!     if |T1| >= max(1, p):
//!       evict from T1 LRU → move key to B1
//!     else:
//!       evict from T2 LRU → move key to B2
//! ```
//!
//! ## Key Components
//!
//! - [`ArcCore`]: Main ARC cache implementation
//! - Four lists: T1 (recent once), T2 (frequent), B1 (ghost for T1), B2 (ghost for T2)
//! - Adaptation parameter `p`: target size for T1 vs T2
//!
//! ## Operations
//!
//! | Operation   | Time   | Notes                                      |
//! |-------------|--------|--------------------------------------------|
//! | `get`       | O(1)   | May promote T1→T2 or adapt via ghost hit   |
//! | `insert`    | O(1)*  | *Amortized, may trigger evictions          |
//! | `contains`  | O(1)   | Index lookup only                          |
//! | `len`       | O(1)   | Returns T1 + T2 entries                    |
//! | `clear`     | O(n)   | Clears all structures                      |
//!
//! ## Algorithm Properties
//!
//! - **Adaptive**: Automatically balances recency vs frequency based on workload
//! - **Scan Resistant**: Ghost lists prevent one-time scans from polluting cache
//! - **Self-Tuning**: No manual parameter tuning required
//! - **Competitive**: O(1) operations, proven optimal in certain workload classes
//!
//! ## Use Cases
//!
//! - Database buffer pools with mixed access patterns
//! - File system caches
//! - Web caches with varying temporal/frequency characteristics
//! - Workloads where optimal recency/frequency balance is unknown
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::policy::arc::ArcCore;
//! use cachekit::traits::Cache;
//!
//! // Create ARC cache with 100 entry capacity
//! let mut cache = ArcCore::new(100);
//!
//! // Insert items (go to T1 - recent list)
//! cache.insert("page1", "content1");
//! cache.insert("page2", "content2");
//!
//! // First access promotes to T2 (frequent list)
//! assert_eq!(cache.get(&"page1"), Some(&"content1"));
//!
//! // Second access keeps in T2 (MRU position)
//! assert_eq!(cache.get(&"page1"), Some(&"content1"));
//!
//! assert_eq!(cache.len(), 2);
//! ```
//!
//! ## Thread Safety
//!
//! - [`ArcCore`]: Not thread-safe, designed for single-threaded use
//! - For concurrent access, wrap in external synchronization
//!
//! ## Implementation Notes
//!
//! - T1 uses LRU ordering (recent once entries)
//! - T2 uses LRU ordering (frequent entries)
//! - B1/B2 are ghost lists (keys only, no values)
//! - Default initial `p` is `capacity / 2`
//! - Ghost list sizes are each up to `capacity`
//! - Promotion from T1 to T2 happens on re-access
//!
//! ## References
//!
//! - Megiddo & Modha, "ARC: A Self-Tuning, Low Overhead Replacement Cache",
//!   FAST 2003
//! - Wikipedia: Cache replacement policies (ARC section)
//!
//! ## Performance Trade-offs
//!
//! - **When to Use**: Unknown or shifting workload patterns; need adaptive behavior
//! - **Memory Overhead**: 4 lists + ghost entries (up to 2× capacity in keys)
//! - **vs LRU**: Better on mixed workloads, slightly higher metadata overhead
//! - **vs 2Q/SLRU**: More adaptive, no manual tuning needed

use crate::ds::GhostList;
#[cfg(feature = "metrics")]
use crate::metrics::metrics_impl::ArcMetrics;
#[cfg(feature = "metrics")]
use crate::metrics::snapshot::ArcMetricsSnapshot;
#[cfg(feature = "metrics")]
use crate::metrics::traits::{ArcMetricsRecorder, CoreMetricsRecorder, MetricsSnapshotProvider};
use crate::traits::Cache;
use rustc_hash::FxHashMap;
use std::hash::Hash;
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::ptr::NonNull;

/// Indicates which list an entry resides in.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ListKind {
    /// Entry is in T1 (recent once).
    T1,
    /// Entry is in T2 (frequent).
    T2,
}

/// Node in the ARC linked list.
///
/// Cache-line optimized layout with pointers first.
#[repr(C)]
struct Node<K, V> {
    prev: Option<NonNull<Node<K, V>>>,
    next: Option<NonNull<Node<K, V>>>,
    list: ListKind,
    key: K,
    value: V,
}

/// Core Adaptive Replacement Cache (ARC) implementation.
///
/// Implements the ARC replacement algorithm with automatic adaptation between
/// recency and frequency preferences:
/// - **T1**: Recently accessed once (recency list)
/// - **T2**: Accessed multiple times (frequency list)
/// - **B1**: Ghost list for items evicted from T1
/// - **B2**: Ghost list for items evicted from T2
///
/// The cache maintains an adaptation parameter `p` that controls the target
/// size of T1 vs T2. Ghost hits in B1/B2 adjust `p` to favor recency or frequency.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Clone + Eq + Hash`
/// - `V`: Value type
///
/// # Example
///
/// ```
/// use cachekit::policy::arc::ArcCore;
/// use cachekit::traits::Cache;
///
/// // 100 capacity ARC cache
/// let mut cache = ArcCore::new(100);
///
/// // Insert goes to T1 (recent list)
/// cache.insert("key1", "value1");
/// assert!(cache.contains(&"key1"));
///
/// // First get promotes to T2 (frequent list)
/// cache.get(&"key1");
///
/// // Update existing key
/// cache.insert("key1", "new_value");
/// assert_eq!(cache.get(&"key1"), Some(&"new_value"));
/// ```
///
/// # Eviction Behavior
///
/// The replacement algorithm selects victims based on the adaptation parameter `p`:
/// - If `|T1| >= max(1, p)`: evict from T1 LRU, move key to B1
/// - Otherwise: evict from T2 LRU, move key to B2
///
/// # Implementation
///
/// Uses raw pointer linked lists for O(1) operations with minimal overhead.
/// Ghost lists track recently evicted keys to enable adaptation.
pub struct ArcCore<K, V> {
    /// Direct key -> node pointer mapping
    map: FxHashMap<K, NonNull<Node<K, V>>>,

    /// T1 list (recent once): head=MRU, tail=LRU
    t1_head: Option<NonNull<Node<K, V>>>,
    t1_tail: Option<NonNull<Node<K, V>>>,
    t1_len: usize,

    /// T2 list (frequent): head=MRU, tail=LRU
    t2_head: Option<NonNull<Node<K, V>>>,
    t2_tail: Option<NonNull<Node<K, V>>>,
    t2_len: usize,

    /// B1 ghost list (evicted from T1)
    b1: GhostList<K>,

    /// B2 ghost list (evicted from T2)
    b2: GhostList<K>,

    /// Adaptation parameter: target size for T1
    p: usize,

    /// Maximum total cache capacity
    capacity: usize,

    #[cfg(feature = "metrics")]
    metrics: ArcMetrics,
}

// SAFETY: The `NonNull<Node>` pointers are exclusively owned by this `ArcCore`
// instance. They are never aliased or exposed externally, and all mutation is
// gated behind `&mut self`, so transferring ownership between threads is safe
// when K and V are Send.
unsafe impl<K, V> Send for ArcCore<K, V>
where
    K: Send,
    V: Send,
{
}

// SAFETY: Shared references (`&ArcCore`) only expose `Cache` read-only methods
// (`contains`, `len`, `capacity`, `peek`), none of which dereference the internal
// `NonNull` pointers through interior mutability. Sharing `&ArcCore` across
// threads is safe when K and V are Sync.
unsafe impl<K, V> Sync for ArcCore<K, V>
where
    K: Sync,
    V: Sync,
{
}

impl<K, V> ArcCore<K, V> {
    /// Drops all heap-allocated nodes reachable from the T1 and T2 lists.
    fn drop_all_nodes(&mut self) {
        let mut current = self.t1_head;
        while let Some(node_ptr) = current {
            unsafe {
                current = node_ptr.as_ref().next;
                let _ = Box::from_raw(node_ptr.as_ptr());
            }
        }
        let mut current = self.t2_head;
        while let Some(node_ptr) = current {
            unsafe {
                current = node_ptr.as_ref().next;
                let _ = Box::from_raw(node_ptr.as_ptr());
            }
        }
    }

    /// Returns an iterator over all cached key-value pairs.
    ///
    /// Iterates over T1 entries first, then T2 entries, from MRU to LRU within
    /// each list. Does not modify access state.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(10);
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    ///
    /// let entries: Vec<_> = cache.iter().collect();
    /// assert_eq!(entries.len(), 2);
    /// ```
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter {
            current: self.t1_head,
            t2_head: self.t2_head,
            in_t2: false,
            remaining: self.t1_len + self.t2_len,
            _marker: PhantomData,
        }
    }

    /// Returns a mutable iterator over all cached key-value pairs.
    ///
    /// Keys are yielded as shared references; values as mutable references.
    /// Modifying values does not affect eviction ordering.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(10);
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    ///
    /// for (_key, value) in cache.iter_mut() {
    ///     *value += 10;
    /// }
    /// assert_eq!(cache.get(&"a"), Some(&11));
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        IterMut {
            current: self.t1_head,
            t2_head: self.t2_head,
            in_t2: false,
            remaining: self.t1_len + self.t2_len,
            _marker: PhantomData,
        }
    }
}

impl<K, V> ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Creates a new ARC cache with the specified capacity.
    ///
    /// # Arguments
    ///
    /// - `capacity`: Maximum number of entries in T1 + T2
    ///
    /// Ghost lists (B1/B2) can each hold up to `capacity` keys.
    /// Initial adaptation parameter `p` is set to `capacity / 2`.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// // 100 capacity ARC cache
    /// let cache: ArcCore<String, i32> = ArcCore::new(100);
    /// assert_eq!(cache.capacity(), 100);
    /// assert!(cache.is_empty());
    /// ```
    #[inline]
    pub fn new(capacity: usize) -> Self {
        Self {
            map: FxHashMap::with_capacity_and_hasher(capacity, Default::default()),
            t1_head: None,
            t1_tail: None,
            t1_len: 0,
            t2_head: None,
            t2_tail: None,
            t2_len: 0,
            b1: GhostList::new(capacity),
            b2: GhostList::new(capacity),
            p: capacity / 2,
            capacity,
            #[cfg(feature = "metrics")]
            metrics: ArcMetrics::default(),
        }
    }

    /// Detach a node from its current list (T1 or T2).
    #[inline(always)]
    fn detach(&mut self, node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_ref();
            let prev = node.prev;
            let next = node.next;
            let list = node.list;

            let (head, tail, len) = match list {
                ListKind::T1 => (&mut self.t1_head, &mut self.t1_tail, &mut self.t1_len),
                ListKind::T2 => (&mut self.t2_head, &mut self.t2_tail, &mut self.t2_len),
            };

            match prev {
                Some(mut p) => p.as_mut().next = next,
                None => *head = next,
            }

            match next {
                Some(mut n) => n.as_mut().prev = prev,
                None => *tail = prev,
            }

            *len -= 1;
        }
    }

    /// Attach a node at the head of T1 list (MRU position).
    #[inline(always)]
    fn attach_t1_head(&mut self, mut node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_mut();
            node.prev = None;
            node.next = self.t1_head;
            node.list = ListKind::T1;

            match self.t1_head {
                Some(mut h) => h.as_mut().prev = Some(node_ptr),
                None => self.t1_tail = Some(node_ptr),
            }

            self.t1_head = Some(node_ptr);
            self.t1_len += 1;
        }
    }

    /// Attach a node at the head of T2 list (MRU position).
    #[inline(always)]
    fn attach_t2_head(&mut self, mut node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_mut();
            node.prev = None;
            node.next = self.t2_head;
            node.list = ListKind::T2;

            match self.t2_head {
                Some(mut h) => h.as_mut().prev = Some(node_ptr),
                None => self.t2_tail = Some(node_ptr),
            }

            self.t2_head = Some(node_ptr);
            self.t2_len += 1;
        }
    }

    /// Replace: select a victim from T1 or T2 based on adaptation parameter p.
    ///
    /// This is the core ARC replacement algorithm.
    fn replace(&mut self, in_b2: bool) {
        #[cfg(feature = "metrics")]
        self.metrics.record_evict_call();

        // Decide whether to evict from T1 or T2
        let evict_from_t1 =
            if self.t1_len > 0 && (self.t1_len > self.p || (self.t1_len == self.p && in_b2)) {
                true
            } else if self.t2_len > 0 {
                false
            } else {
                self.t1_len > 0
            };

        if evict_from_t1 {
            if let Some(victim_ptr) = self.t1_tail {
                unsafe {
                    let victim = victim_ptr.as_ref();
                    let key = victim.key.clone();

                    self.detach(victim_ptr);
                    self.map.remove(&key);
                    self.b1.record(key.clone());
                    let _ = Box::from_raw(victim_ptr.as_ptr());

                    #[cfg(feature = "metrics")]
                    {
                        self.metrics.record_evicted_entry();
                        self.metrics.record_t1_eviction();
                    }
                }
            }
        } else if let Some(victim_ptr) = self.t2_tail {
            unsafe {
                let victim = victim_ptr.as_ref();
                let key = victim.key.clone();

                self.detach(victim_ptr);
                self.map.remove(&key);
                self.b2.record(key.clone());
                let _ = Box::from_raw(victim_ptr.as_ptr());

                #[cfg(feature = "metrics")]
                {
                    self.metrics.record_evicted_entry();
                    self.metrics.record_t2_eviction();
                }
            }
        }
    }

    /// Adapt parameter p based on ghost hit location.
    fn adapt(&mut self, in_b1: bool, in_b2: bool) {
        if in_b1 {
            let delta = if self.b2.len() >= self.b1.len() {
                1
            } else if !self.b1.is_empty() {
                ((self.b2.len() as f64 / self.b1.len() as f64).ceil() as usize).max(1)
            } else {
                1
            };
            self.p = (self.p + delta).min(self.capacity);

            #[cfg(feature = "metrics")]
            self.metrics.record_p_increase();
        } else if in_b2 {
            let delta = if self.b1.len() >= self.b2.len() {
                1
            } else if !self.b2.is_empty() {
                ((self.b1.len() as f64 / self.b2.len() as f64).ceil() as usize).max(1)
            } else {
                1
            };
            self.p = self.p.saturating_sub(delta);

            #[cfg(feature = "metrics")]
            self.metrics.record_p_decrease();
        }
    }

    /// Returns the current value of the adaptation parameter p.
    ///
    /// This represents the target size for T1. Higher values favor recency,
    /// lower values favor frequency.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    ///
    /// let cache: ArcCore<String, i32> = ArcCore::new(100);
    /// // Initial p is capacity / 2
    /// assert_eq!(cache.p_value(), 50);
    /// ```
    pub fn p_value(&self) -> usize {
        self.p
    }

    /// Returns the number of entries in T1 (recent once list).
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(100);
    /// cache.insert("key", "value");
    /// assert_eq!(cache.t1_len(), 1);  // New entries go to T1
    /// ```
    pub fn t1_len(&self) -> usize {
        self.t1_len
    }

    /// Returns the number of entries in T2 (frequent list).
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(100);
    /// cache.insert("key", "value");
    /// cache.get(&"key");  // Promotes to T2
    /// assert_eq!(cache.t2_len(), 1);
    /// ```
    pub fn t2_len(&self) -> usize {
        self.t2_len
    }

    /// Returns the number of keys in B1 (ghost list for T1 evictions).
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(2);
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    /// cache.insert("c", 3); // evicts "a" to B1
    /// assert_eq!(cache.b1_len(), 1);
    /// ```
    pub fn b1_len(&self) -> usize {
        self.b1.len()
    }

    /// Returns the number of keys in B2 (ghost list for T2 evictions).
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::arc::ArcCore;
    /// use cachekit::traits::Cache;
    ///
    /// let mut cache = ArcCore::new(2);
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    /// cache.get(&"a"); // promote to T2
    /// cache.get(&"b"); // promote to T2
    /// cache.insert("c", 3); // evicts T2 LRU to B2
    /// assert!(cache.b2_len() <= 1);
    /// ```
    pub fn b2_len(&self) -> usize {
        self.b2.len()
    }

    /// Validates internal invariants of the ARC cache.
    ///
    /// # Panics
    ///
    /// Panics if any of the following invariants are violated:
    /// - `len() == t1_len + t2_len`
    /// - `map.len() == t1_len + t2_len`
    /// - total entries do not exceed capacity
    /// - `p <= capacity`
    /// - ghost list sizes do not exceed capacity
    /// - linked-list counts match stored lengths
    /// - no node appears in both T1 and T2
    /// - no key appears in both the cache and a ghost list
    #[cfg(any(test, debug_assertions))]
    pub fn debug_validate_invariants(&self)
    where
        K: std::fmt::Debug,
    {
        // 1. Total length matches sum of T1 and T2
        assert_eq!(
            self.len(),
            self.t1_len + self.t2_len,
            "len() should equal t1_len + t2_len"
        );

        // 2. Map size equals total entries
        assert_eq!(
            self.map.len(),
            self.t1_len + self.t2_len,
            "map.len() should equal total entries"
        );

        // 3. Total entries don't exceed capacity
        assert!(
            self.t1_len + self.t2_len <= self.capacity,
            "total entries ({}) exceed capacity ({})",
            self.t1_len + self.t2_len,
            self.capacity
        );

        // 4. p is within valid range
        assert!(
            self.p <= self.capacity,
            "p ({}) exceeds capacity ({})",
            self.p,
            self.capacity
        );

        // 5. Ghost lists don't exceed capacity
        assert!(
            self.b1.len() <= self.capacity,
            "B1 length ({}) exceeds capacity ({})",
            self.b1.len(),
            self.capacity
        );
        assert!(
            self.b2.len() <= self.capacity,
            "B2 length ({}) exceeds capacity ({})",
            self.b2.len(),
            self.capacity
        );

        // 6. Count actual T1 entries
        let mut t1_count = 0;
        let mut current = self.t1_head;
        let mut visited_t1 = std::collections::HashSet::new();
        while let Some(node_ptr) = current {
            unsafe {
                let node = node_ptr.as_ref();

                // Check for cycles
                assert!(visited_t1.insert(node_ptr), "Cycle detected in T1 list");

                // Verify list kind
                assert_eq!(node.list, ListKind::T1, "Node in T1 has wrong list kind");

                // Verify node is in map
                assert!(self.map.contains_key(&node.key), "T1 node key not in map");

                t1_count += 1;
                current = node.next;
            }
        }
        assert_eq!(
            t1_count, self.t1_len,
            "T1 actual count doesn't match t1_len"
        );

        // 7. Count actual T2 entries
        let mut t2_count = 0;
        let mut current = self.t2_head;
        let mut visited_t2 = std::collections::HashSet::new();
        while let Some(node_ptr) = current {
            unsafe {
                let node = node_ptr.as_ref();

                // Check for cycles
                assert!(visited_t2.insert(node_ptr), "Cycle detected in T2 list");

                // Verify list kind
                assert_eq!(node.list, ListKind::T2, "Node in T2 has wrong list kind");

                // Verify node is in map
                assert!(self.map.contains_key(&node.key), "T2 node key not in map");

                t2_count += 1;
                current = node.next;
            }
        }
        assert_eq!(
            t2_count, self.t2_len,
            "T2 actual count doesn't match t2_len"
        );

        // 8. Verify no overlap between T1 and T2
        for t1_ptr in &visited_t1 {
            assert!(
                !visited_t2.contains(t1_ptr),
                "Node appears in both T1 and T2"
            );
        }

        // 9. Verify all map entries are accounted for in T1 or T2
        assert_eq!(
            visited_t1.len() + visited_t2.len(),
            self.map.len(),
            "Map contains entries not in T1 or T2"
        );

        // 10. Ghost lists don't contain keys that are in the cache
        for key in self.map.keys() {
            assert!(
                !self.b1.contains(key),
                "Key {:?} is in both cache and B1",
                key
            );
            assert!(
                !self.b2.contains(key),
                "Key {:?} is in both cache and B2",
                key
            );
        }
    }
}

impl<K, V> std::fmt::Debug for ArcCore<K, V>
where
    K: Clone + Eq + Hash + std::fmt::Debug,
    V: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArcCore")
            .field("capacity", &self.capacity)
            .field("t1_len", &self.t1_len)
            .field("t2_len", &self.t2_len)
            .field("b1_len", &self.b1.len())
            .field("b2_len", &self.b2.len())
            .field("p", &self.p)
            .field("total_len", &(self.t1_len + self.t2_len))
            .finish()
    }
}

impl<K, V> Cache<K, V> for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    fn contains(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    fn len(&self) -> usize {
        self.t1_len + self.t2_len
    }

    fn capacity(&self) -> usize {
        self.capacity
    }

    fn peek(&self, key: &K) -> Option<&V> {
        self.map
            .get(key)
            .map(|&node_ptr| unsafe { &(*node_ptr.as_ptr()).value })
    }

    fn get(&mut self, key: &K) -> Option<&V> {
        let node_ptr = match self.map.get(key) {
            Some(&ptr) => ptr,
            None => {
                #[cfg(feature = "metrics")]
                self.metrics.record_get_miss();
                return None;
            },
        };

        #[cfg(feature = "metrics")]
        self.metrics.record_get_hit();

        unsafe {
            let node = node_ptr.as_ref();

            match node.list {
                ListKind::T1 => {
                    #[cfg(feature = "metrics")]
                    self.metrics.record_t1_to_t2_promotion();

                    self.detach(node_ptr);
                    self.attach_t2_head(node_ptr);
                },
                ListKind::T2 => {
                    self.detach(node_ptr);
                    self.attach_t2_head(node_ptr);
                },
            }

            Some(&node_ptr.as_ref().value)
        }
    }

    fn insert(&mut self, key: K, value: V) -> Option<V> {
        #[cfg(feature = "metrics")]
        self.metrics.record_insert_call();

        if self.capacity == 0 {
            return None;
        }

        // Case 1: Key already in cache (T1 or T2)
        if let Some(&node_ptr) = self.map.get(&key) {
            #[cfg(feature = "metrics")]
            self.metrics.record_insert_update();

            unsafe {
                let mut node_ptr = node_ptr;
                let node = node_ptr.as_mut();
                let old_value = std::mem::replace(&mut node.value, value);

                match node.list {
                    ListKind::T1 => {
                        self.detach(node_ptr);
                        self.attach_t2_head(node_ptr);
                    },
                    ListKind::T2 => {
                        self.detach(node_ptr);
                        self.attach_t2_head(node_ptr);
                    },
                }

                return Some(old_value);
            }
        }

        let in_b1 = self.b1.contains(&key);
        let in_b2 = self.b2.contains(&key);

        // Case 2: Ghost hit in B1
        if in_b1 {
            #[cfg(feature = "metrics")]
            {
                self.metrics.record_b1_ghost_hit();
                self.metrics.record_insert_new();
            }

            self.adapt(true, false);
            self.b1.remove(&key);

            if self.t1_len + self.t2_len >= self.capacity {
                self.replace(false);
            }

            let node = Box::new(Node {
                prev: None,
                next: None,
                list: ListKind::T2,
                key: key.clone(),
                value,
            });
            let node_ptr = NonNull::new(Box::into_raw(node)).unwrap();
            self.map.insert(key, node_ptr);
            self.attach_t2_head(node_ptr);

            return None;
        }

        // Case 3: Ghost hit in B2
        if in_b2 {
            #[cfg(feature = "metrics")]
            {
                self.metrics.record_b2_ghost_hit();
                self.metrics.record_insert_new();
            }

            self.adapt(false, true);
            self.b2.remove(&key);

            if self.t1_len + self.t2_len >= self.capacity {
                self.replace(true);
            }

            let node = Box::new(Node {
                prev: None,
                next: None,
                list: ListKind::T2,
                key: key.clone(),
                value,
            });
            let node_ptr = NonNull::new(Box::into_raw(node)).unwrap();
            self.map.insert(key, node_ptr);
            self.attach_t2_head(node_ptr);

            return None;
        }

        // Case 4: Complete miss
        #[cfg(feature = "metrics")]
        self.metrics.record_insert_new();

        let l1_len = self.t1_len + self.b1.len();
        if l1_len >= self.capacity {
            if !self.b1.is_empty() {
                self.b1.evict_lru();
            }
            if self.t1_len + self.t2_len >= self.capacity {
                self.replace(false);
            }
        } else {
            let total = self.t1_len + self.t2_len + self.b1.len() + self.b2.len();
            if total >= 2 * self.capacity {
                self.b2.evict_lru();
            }
            if self.t1_len + self.t2_len >= self.capacity {
                self.replace(false);
            }
        }

        let node = Box::new(Node {
            prev: None,
            next: None,
            list: ListKind::T1,
            key: key.clone(),
            value,
        });
        let node_ptr = NonNull::new(Box::into_raw(node)).unwrap();
        self.map.insert(key, node_ptr);
        self.attach_t1_head(node_ptr);

        None
    }

    fn remove(&mut self, key: &K) -> Option<V> {
        let node_ptr = self.map.remove(key)?;

        self.detach(node_ptr);

        unsafe {
            let node = Box::from_raw(node_ptr.as_ptr());
            Some(node.value)
        }
    }

    fn clear(&mut self) {
        #[cfg(feature = "metrics")]
        self.metrics.record_clear();

        self.drop_all_nodes();
        self.map.clear();
        self.t1_head = None;
        self.t1_tail = None;
        self.t1_len = 0;
        self.t2_head = None;
        self.t2_tail = None;
        self.t2_len = 0;
        self.b1.clear();
        self.b2.clear();
        self.p = self.capacity / 2;
    }
}

impl<K, V> Drop for ArcCore<K, V> {
    fn drop(&mut self) {
        self.drop_all_nodes();
    }
}

impl<K, V> Clone for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
    V: Clone,
{
    fn clone(&self) -> Self {
        let mut new_cache = ArcCore::new(self.capacity);
        new_cache.p = self.p;
        new_cache.b1 = self.b1.clone();
        new_cache.b2 = self.b2.clone();

        // Rebuild T1 from tail (LRU) to head (MRU) so attach_t1_head
        // reproduces the original ordering.
        let mut t1_entries = Vec::with_capacity(self.t1_len);
        let mut current = self.t1_tail;
        while let Some(ptr) = current {
            unsafe {
                let node = ptr.as_ref();
                t1_entries.push((node.key.clone(), node.value.clone()));
                current = node.prev;
            }
        }
        for (key, value) in t1_entries {
            let node = Box::new(Node {
                prev: None,
                next: None,
                list: ListKind::T1,
                key: key.clone(),
                value,
            });
            let ptr = NonNull::new(Box::into_raw(node)).unwrap();
            new_cache.map.insert(key, ptr);
            new_cache.attach_t1_head(ptr);
        }

        // Rebuild T2 the same way.
        let mut t2_entries = Vec::with_capacity(self.t2_len);
        let mut current = self.t2_tail;
        while let Some(ptr) = current {
            unsafe {
                let node = ptr.as_ref();
                t2_entries.push((node.key.clone(), node.value.clone()));
                current = node.prev;
            }
        }
        for (key, value) in t2_entries {
            let node = Box::new(Node {
                prev: None,
                next: None,
                list: ListKind::T2,
                key: key.clone(),
                value,
            });
            let ptr = NonNull::new(Box::into_raw(node)).unwrap();
            new_cache.map.insert(key, ptr);
            new_cache.attach_t2_head(ptr);
        }

        #[cfg(feature = "metrics")]
        {
            new_cache.metrics = self.metrics;
        }

        new_cache
    }
}

impl<K, V> Default for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Returns an empty `ArcCore` with capacity 0.
    ///
    /// Use [`ArcCore::new`] to specify a capacity.
    fn default() -> Self {
        Self::new(0)
    }
}

#[cfg(feature = "metrics")]
impl<K, V> ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Returns a snapshot of cache metrics.
    pub fn metrics_snapshot(&self) -> ArcMetricsSnapshot {
        ArcMetricsSnapshot {
            get_calls: self.metrics.get_calls,
            get_hits: self.metrics.get_hits,
            get_misses: self.metrics.get_misses,
            insert_calls: self.metrics.insert_calls,
            insert_updates: self.metrics.insert_updates,
            insert_new: self.metrics.insert_new,
            evict_calls: self.metrics.evict_calls,
            evicted_entries: self.metrics.evicted_entries,
            t1_to_t2_promotions: self.metrics.t1_to_t2_promotions,
            b1_ghost_hits: self.metrics.b1_ghost_hits,
            b2_ghost_hits: self.metrics.b2_ghost_hits,
            p_increases: self.metrics.p_increases,
            p_decreases: self.metrics.p_decreases,
            t1_evictions: self.metrics.t1_evictions,
            t2_evictions: self.metrics.t2_evictions,
            cache_len: self.len(),
            capacity: self.capacity,
        }
    }
}

#[cfg(feature = "metrics")]
impl<K, V> MetricsSnapshotProvider<ArcMetricsSnapshot> for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    fn snapshot(&self) -> ArcMetricsSnapshot {
        self.metrics_snapshot()
    }
}

// ---------------------------------------------------------------------------
// Iterators
// ---------------------------------------------------------------------------

/// Iterator over shared references to cached key-value pairs.
///
/// Created by [`ArcCore::iter`]. Visits T1 entries (MRU to LRU) then T2.
pub struct Iter<'a, K, V> {
    current: Option<NonNull<Node<K, V>>>,
    t2_head: Option<NonNull<Node<K, V>>>,
    in_t2: bool,
    remaining: usize,
    _marker: PhantomData<&'a (K, V)>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(node_ptr) = self.current {
                unsafe {
                    let node = node_ptr.as_ref();
                    self.current = node.next;
                    self.remaining -= 1;
                    return Some((&node.key, &node.value));
                }
            } else if !self.in_t2 {
                self.in_t2 = true;
                self.current = self.t2_head;
            } else {
                return None;
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<K, V> ExactSizeIterator for Iter<'_, K, V> {}
impl<K, V> FusedIterator for Iter<'_, K, V> {}

/// Iterator over mutable references to cached values.
///
/// Created by [`ArcCore::iter_mut`]. Keys are shared; values are mutable.
pub struct IterMut<'a, K, V> {
    current: Option<NonNull<Node<K, V>>>,
    t2_head: Option<NonNull<Node<K, V>>>,
    in_t2: bool,
    remaining: usize,
    _marker: PhantomData<&'a mut (K, V)>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(mut node_ptr) = self.current {
                unsafe {
                    let node = node_ptr.as_mut();
                    self.current = node.next;
                    self.remaining -= 1;
                    return Some((&node.key, &mut node.value));
                }
            } else if !self.in_t2 {
                self.in_t2 = true;
                self.current = self.t2_head;
            } else {
                return None;
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}
impl<K, V> FusedIterator for IterMut<'_, K, V> {}

/// Owning iterator over cached key-value pairs.
///
/// Created by calling [`IntoIterator`] on an `ArcCore`.
pub struct IntoIter<K, V> {
    current: Option<NonNull<Node<K, V>>>,
    t2_head: Option<NonNull<Node<K, V>>>,
    in_t2: bool,
    remaining: usize,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(node_ptr) = self.current {
                unsafe {
                    let node = Box::from_raw(node_ptr.as_ptr());
                    self.current = node.next;
                    self.remaining -= 1;
                    return Some((node.key, node.value));
                }
            } else if !self.in_t2 {
                self.in_t2 = true;
                self.current = self.t2_head;
            } else {
                return None;
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
impl<K, V> FusedIterator for IntoIter<K, V> {}

impl<K, V> Drop for IntoIter<K, V> {
    fn drop(&mut self) {
        while self.next().is_some() {}
    }
}

// SAFETY: IntoIter exclusively owns its nodes (moved out of ArcCore).
unsafe impl<K: Send, V: Send> Send for IntoIter<K, V> {}
unsafe impl<K: Sync, V: Sync> Sync for IntoIter<K, V> {}

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

    fn into_iter(mut self) -> IntoIter<K, V> {
        let iter = IntoIter {
            current: self.t1_head,
            t2_head: self.t2_head,
            in_t2: false,
            remaining: self.t1_len + self.t2_len,
        };
        // Prevent Drop from double-freeing nodes the iterator now owns.
        self.t1_head = None;
        self.t1_tail = None;
        self.t1_len = 0;
        self.t2_head = None;
        self.t2_tail = None;
        self.t2_len = 0;
        iter
    }
}

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

    fn into_iter(self) -> Iter<'a, K, V> {
        self.iter()
    }
}

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

    fn into_iter(self) -> IterMut<'a, K, V> {
        self.iter_mut()
    }
}

impl<K, V> FromIterator<(K, V)> for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (lower, _) = iter.size_hint();
        let mut cache = ArcCore::new(lower);
        cache.extend(iter);
        cache
    }
}

impl<K, V> Extend<(K, V)> for ArcCore<K, V>
where
    K: Clone + Eq + Hash,
{
    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
        for (key, value) in iter {
            self.insert(key, value);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn arc_new_cache() {
        let cache: ArcCore<String, i32> = ArcCore::new(100);
        assert_eq!(cache.capacity(), 100);
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 0);
        assert_eq!(cache.b1_len(), 0);
        assert_eq!(cache.b2_len(), 0);
        assert_eq!(cache.p_value(), 50); // Initial p = capacity / 2
    }

    #[test]
    fn arc_insert_and_get() {
        let mut cache = ArcCore::new(10);

        // First insert goes to T1
        cache.insert("key1", "value1");
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.t1_len(), 1);
        assert_eq!(cache.t2_len(), 0);

        // Get promotes to T2
        assert_eq!(cache.get(&"key1"), Some(&"value1"));
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 1);

        // Second get keeps in T2
        assert_eq!(cache.get(&"key1"), Some(&"value1"));
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 1);
    }

    #[test]
    fn arc_update_existing() {
        let mut cache = ArcCore::new(10);

        cache.insert("key1", "value1");
        assert_eq!(cache.t1_len(), 1);

        // Update in T1 promotes to T2
        let old = cache.insert("key1", "new_value");
        assert_eq!(old, Some("value1"));
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 1);

        assert_eq!(cache.get(&"key1"), Some(&"new_value"));
    }

    #[test]
    fn arc_eviction_fills_ghost_lists() {
        let mut cache = ArcCore::new(2);

        // Fill cache
        cache.insert("a", 1);
        cache.insert("b", 2);
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.t1_len(), 2);

        // Insert third item triggers eviction
        cache.insert("c", 3);
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.t1_len(), 2); // c and b (a evicted)
        assert_eq!(cache.b1_len(), 1); // a moved to B1
        assert!(!cache.contains(&"a"));
    }

    #[test]
    fn arc_ghost_hit_promotes_to_t2() {
        let mut cache = ArcCore::new(2);

        // Fill and evict
        cache.insert("a", 1);
        cache.insert("b", 2);
        cache.insert("c", 3); // Evicts "a" to B1

        cache.debug_validate_invariants();

        assert!(!cache.contains(&"a"));
        assert_eq!(cache.b1_len(), 1);
        assert!(cache.b1.contains(&"a"));

        // Ghost hit on "a"
        // This should: remove "a" from B1, make space (evicting something else), insert "a" to T2
        cache.insert("a", 10);
        cache.debug_validate_invariants();

        println!(
            "After ghost hit: len={}, t1={}, t2={}, b1={}, b2={}",
            cache.len(),
            cache.t1_len(),
            cache.t2_len(),
            cache.b1_len(),
            cache.b2_len()
        );

        assert_eq!(
            cache.len(),
            2,
            "Cache length should be 2, got {}",
            cache.len()
        );
        assert_eq!(cache.t2_len(), 1); // "a" goes to T2 (ghost hit)
        assert!(!cache.b1.contains(&"a")); // "a" removed from B1
        // Note: B1 may still have entries from the eviction that happened to make space for "a"
    }

    #[test]
    fn arc_adaptation_increases_p() {
        let mut cache = ArcCore::new(4);
        let initial_p = cache.p_value();

        // Create scenario with B1 ghost hit
        cache.insert("a", 1);
        cache.insert("b", 2);
        cache.insert("c", 3);
        cache.insert("d", 4);
        cache.insert("e", 5); // Evicts "a" to B1

        println!(
            "Before ghost hit: p={}, t1={}, t2={}, b1={}, b2={}",
            cache.p_value(),
            cache.t1_len(),
            cache.t2_len(),
            cache.b1_len(),
            cache.b2_len()
        );
        println!("B1 contains a={}", cache.b1.contains(&"a"));

        // Ghost hit in B1 should increase p
        cache.insert("a", 10);

        println!(
            "After ghost hit: p={}, t1={}, t2={}, b1={}, b2={}",
            cache.p_value(),
            cache.t1_len(),
            cache.t2_len(),
            cache.b1_len(),
            cache.b2_len()
        );

        // Note: If b1.len() == b2.len() initially, delta would be 1
        // p should increase by at least 1
        assert!(
            cache.p_value() > initial_p,
            "Expected p to increase from {} but got {}",
            initial_p,
            cache.p_value()
        );
    }

    #[test]
    fn arc_remove() {
        let mut cache = ArcCore::new(10);

        cache.insert("key1", "value1");
        cache.insert("key2", "value2");
        assert_eq!(cache.len(), 2);

        let removed = cache.remove(&"key1");
        assert_eq!(removed, Some("value1"));
        assert_eq!(cache.len(), 1);
        assert!(!cache.contains(&"key1"));
        assert!(cache.contains(&"key2"));
    }

    #[test]
    fn arc_clear() {
        let mut cache = ArcCore::new(10);

        cache.insert("key1", "value1");
        cache.insert("key2", "value2");
        cache.get(&"key1"); // Promote to T2

        cache.clear();

        assert_eq!(cache.len(), 0);
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 0);
        assert_eq!(cache.b1_len(), 0);
        assert_eq!(cache.b2_len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn arc_contains() {
        let mut cache = ArcCore::new(10);

        assert!(!cache.contains(&"key1"));

        cache.insert("key1", "value1");
        assert!(cache.contains(&"key1"));

        cache.remove(&"key1");
        assert!(!cache.contains(&"key1"));
    }

    #[test]
    fn arc_promotion_t1_to_t2() {
        let mut cache = ArcCore::new(10);

        // Insert into T1
        cache.insert("key", "value");
        assert_eq!(cache.t1_len(), 1);
        assert_eq!(cache.t2_len(), 0);

        // First access promotes to T2
        cache.get(&"key");
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 1);

        // Second access stays in T2
        cache.get(&"key");
        assert_eq!(cache.t1_len(), 0);
        assert_eq!(cache.t2_len(), 1);
    }

    #[test]
    fn arc_multiple_entries() {
        let mut cache = ArcCore::new(5);

        for i in 0..5 {
            cache.insert(i, i * 10);
        }

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

        for i in 0..5 {
            assert_eq!(cache.get(&i), Some(&(i * 10)));
        }

        // All should be promoted to T2 after access
        assert_eq!(cache.t2_len(), 5);
        assert_eq!(cache.t1_len(), 0);
    }

    #[test]
    fn arc_eviction_and_ghost_tracking() {
        let mut cache = ArcCore::new(3);

        // Fill cache
        cache.insert(1, 100);
        cache.insert(2, 200);
        cache.insert(3, 300);

        // Access 1 and 2 to promote them to T2
        cache.get(&1);
        cache.get(&2);

        assert_eq!(cache.t1_len(), 1); // 3 remains in T1
        assert_eq!(cache.t2_len(), 2); // 1, 2 promoted to T2

        // Insert 4. With p=1, t1_len=1, t2_len=2:
        // Condition: t1_len > p → 1 > 1 is false
        // So we evict from T2 (not T1)
        // T2 has [2 (MRU), 1 (LRU)], so 1 gets evicted to B2
        cache.insert(4, 400);

        assert_eq!(cache.len(), 3);
        assert!(!cache.contains(&1)); // 1 was evicted (LRU of T2)
        assert!(cache.contains(&2)); // 2 remains (MRU of T2)
        assert!(cache.contains(&3)); // 3 remains (in T1)
        assert!(cache.contains(&4)); // 4 just inserted
        assert_eq!(cache.b2_len(), 1); // 1 moved to B2 (evicted from T2)
    }

    #[test]
    fn arc_zero_capacity() {
        let mut cache = ArcCore::new(0);
        assert_eq!(cache.capacity(), 0);
        assert_eq!(cache.len(), 0);

        cache.insert("key", "value");
        assert_eq!(cache.len(), 0);
        assert!(!cache.contains(&"key"));
    }

    // ==============================================
    // Regression Tests
    // ==============================================

    #[test]
    fn ghost_directory_size_within_two_times_capacity() {
        let c = 5usize;
        let mut cache: ArcCore<u64, u64> = ArcCore::new(c);

        for i in 0..c as u64 {
            cache.insert(i, i);
        }
        for i in 0..c as u64 {
            cache.get(&i);
        }
        for i in c as u64..2 * c as u64 {
            cache.insert(i, i);
        }
        for i in 2 * c as u64..3 * c as u64 {
            cache.insert(i, i);
        }
        for i in 2 * c as u64..3 * c as u64 {
            cache.get(&i);
        }
        for i in 3 * c as u64..8 * c as u64 {
            cache.insert(i, i);
        }

        let t = cache.t1_len() + cache.t2_len();
        let b = cache.b1_len() + cache.b2_len();
        let total = t + b;

        assert!(
            total <= 2 * c,
            "ARC directory size ({}) exceeds 2*capacity ({}). \
             B1={}, B2={}, T1={}, T2={}",
            total,
            2 * c,
            cache.b1_len(),
            cache.b2_len(),
            cache.t1_len(),
            cache.t2_len(),
        );
    }

    #[test]
    fn ghost_lists_bounded_when_cache_full() {
        let c = 10usize;
        let mut cache: ArcCore<u64, u64> = ArcCore::new(c);

        for i in 0..500u64 {
            cache.insert(i, i);
        }

        let t = cache.t1_len() + cache.t2_len();
        let b1 = cache.b1_len();
        let b2 = cache.b2_len();

        assert!(
            b1 + b2 <= c,
            "Ghost lists hold {} entries (B1={}, B2={}) while cache holds {} (T1+T2). \
             Paper requires B1+B2 <= {}",
            b1 + b2,
            b1,
            b2,
            t,
            c,
        );
    }
}