cachekit 0.6.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
//! Fast LRU cache optimized for single-threaded performance.
//!
//! This implementation prioritizes raw speed over flexibility by:
//! - Storing values directly (no `Arc` wrapping)
//! - Using FxHashMap for fast hashing (same hasher used in rustc)
//! - Cache-line optimized node layout
//! - Aggressive inlining in hot paths
//!
//! ## When to Use
//!
//! Use `FastLru` when:
//! - Maximum single-threaded performance is critical
//! - Values don't need to be shared after eviction
//! - You don't need the policy/storage separation
//!
//! Use `LruCore` when:
//! - Values need to outlive eviction (via `Arc`)
//! - You need concurrent access (wrap in lock)
//! - You need pluggable storage backends
//!
//! ## Performance
//!
//! Compared to `LruCore`, `FastLru` is ~7-10x faster for get/insert operations
//! due to FxHash, reduced indirection, and no atomic reference counting.

use rustc_hash::FxHashMap;
use std::hash::Hash;
use std::mem;
use std::ptr::NonNull;

#[cfg(feature = "metrics")]
use crate::metrics::metrics_impl::LruMetrics;
#[cfg(feature = "metrics")]
use crate::metrics::snapshot::LruMetricsSnapshot;
#[cfg(feature = "metrics")]
use crate::metrics::traits::{
    CoreMetricsRecorder, LruMetricsReadRecorder, LruMetricsRecorder, MetricsSnapshotProvider,
};

/// A fast, single-threaded LRU cache.
///
/// Values are stored directly without `Arc` wrapping for maximum performance.
/// All operations are O(1) average case.
///
/// # Example
///
/// ```
/// use cachekit::policy::fast_lru::FastLru;
///
/// let mut cache = FastLru::new(3);
///
/// cache.insert(1, "one");
/// cache.insert(2, "two");
/// cache.insert(3, "three");
///
/// assert_eq!(cache.get(&1), Some(&"one"));
///
/// // Inserting a 4th item evicts the LRU (key 2, since 1 was just accessed)
/// cache.insert(4, "four");
/// assert_eq!(cache.get(&2), None);
/// ```
pub struct FastLru<K, V> {
    map: FxHashMap<K, NonNull<Node<K, V>>>,
    head: Option<NonNull<Node<K, V>>>,
    tail: Option<NonNull<Node<K, V>>>,
    capacity: usize,
    #[cfg(feature = "metrics")]
    metrics: LruMetrics,
}

/// Node in the LRU linked list.
///
/// Layout is optimized for cache locality:
/// - Linked list pointers (prev/next) are at the start for fast traversal
/// - Key and value follow, keeping the hot metadata together
/// - `#[repr(C)]` ensures predictable field ordering
#[repr(C)]
struct Node<K, V> {
    // Hot fields first - accessed during every list operation
    prev: Option<NonNull<Node<K, V>>>,
    next: Option<NonNull<Node<K, V>>>,
    // Key needed for map removal during eviction
    key: K,
    // Value accessed on get/peek
    value: V,
}

impl<K, V> FastLru<K, V>
where
    K: Eq + Hash + Clone,
{
    /// Creates a new cache with the specified capacity.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::fast_lru::FastLru;
    ///
    /// let cache: FastLru<u64, String> = FastLru::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()),
            head: None,
            tail: None,
            capacity,
            #[cfg(feature = "metrics")]
            metrics: LruMetrics::default(),
        }
    }

    /// Returns the number of entries in the cache.
    #[inline]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the cache is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Returns the maximum capacity.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns `true` if the key exists in the cache.
    ///
    /// Does not update LRU order.
    #[inline]
    pub fn contains(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    /// Gets a reference to a value, updating LRU order.
    ///
    /// Returns `None` if the key doesn't exist.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::fast_lru::FastLru;
    ///
    /// let mut cache = FastLru::new(10);
    /// cache.insert(1, "value");
    ///
    /// assert_eq!(cache.get(&1), Some(&"value"));
    /// assert_eq!(cache.get(&2), None);
    /// ```
    #[inline(always)]
    pub 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();

        // Move to front (MRU position)
        self.detach(node_ptr);
        self.attach_front(node_ptr);

        // SAFETY: node_ptr is valid as long as it's in the map
        Some(unsafe { &(*node_ptr.as_ptr()).value })
    }

    /// Gets a mutable reference to a value, updating LRU order.
    #[inline(always)]
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        let node_ptr = *self.map.get(key)?;

        self.detach(node_ptr);
        self.attach_front(node_ptr);

        // SAFETY: node_ptr is valid as long as it's in the map
        Some(unsafe { &mut (*node_ptr.as_ptr()).value })
    }

    /// Peeks at a value without updating LRU order.
    #[inline(always)]
    pub fn peek(&self, key: &K) -> Option<&V> {
        self.map
            .get(key)
            .map(|node_ptr| unsafe { &(*node_ptr.as_ptr()).value })
    }

    /// Inserts a key-value pair, returning the previous value if the key existed.
    ///
    /// If the cache is at capacity, evicts the least recently used item.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::fast_lru::FastLru;
    ///
    /// let mut cache = FastLru::new(2);
    ///
    /// assert_eq!(cache.insert(1, "a"), None);
    /// assert_eq!(cache.insert(2, "b"), None);
    /// assert_eq!(cache.insert(1, "A"), Some("a")); // Update returns old value
    ///
    /// cache.insert(3, "c"); // Evicts key 2 (LRU)
    /// assert!(!cache.contains(&2));
    /// ```
    #[inline(always)]
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        #[cfg(feature = "metrics")]
        self.metrics.record_insert_call();

        // Check for existing key
        if let Some(&node_ptr) = self.map.get(&key) {
            #[cfg(feature = "metrics")]
            self.metrics.record_insert_update();

            // Update existing value
            let old_value = unsafe {
                let node = node_ptr.as_ptr();
                mem::replace(&mut (*node).value, value)
            };

            // Move to front
            self.detach(node_ptr);
            self.attach_front(node_ptr);

            return Some(old_value);
        }

        // Evict if at capacity
        if self.capacity > 0 && self.map.len() >= self.capacity {
            #[cfg(feature = "metrics")]
            self.metrics.record_evict_call();

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

        // Don't insert if capacity is 0
        if self.capacity == 0 {
            return None;
        }

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

        // Create new node with optimized field order
        let node = Box::new(Node {
            prev: None,
            next: None,
            key: key.clone(),
            value,
        });
        let node_ptr = NonNull::new(Box::into_raw(node)).unwrap();

        // Add to map and list
        self.map.insert(key, node_ptr);
        self.attach_front(node_ptr);

        None
    }

    /// Removes a key from the cache, returning its value.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::fast_lru::FastLru;
    ///
    /// let mut cache = FastLru::new(10);
    /// cache.insert(1, "value");
    ///
    /// assert_eq!(cache.remove(&1), Some("value"));
    /// assert_eq!(cache.remove(&1), None);
    /// ```
    pub fn remove(&mut self, key: &K) -> Option<V> {
        let node_ptr = self.map.remove(key)?;

        self.detach(node_ptr);

        // SAFETY: We own the node after removing from map
        let node = unsafe { Box::from_raw(node_ptr.as_ptr()) };
        Some(node.value)
    }

    /// Removes and returns the least recently used item.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::fast_lru::FastLru;
    ///
    /// let mut cache = FastLru::new(10);
    /// cache.insert(1, "one");
    /// cache.insert(2, "two");
    ///
    /// // Access key 1 to make it MRU
    /// cache.get(&1);
    ///
    /// // Key 2 is now LRU
    /// assert_eq!(cache.pop_lru(), Some((2, "two")));
    /// ```
    pub fn pop_lru(&mut self) -> Option<(K, V)> {
        #[cfg(feature = "metrics")]
        self.metrics.record_pop_lru_call();

        let tail_ptr = self.tail?;

        // SAFETY: tail is valid if Some
        let key = unsafe { (*tail_ptr.as_ptr()).key.clone() };

        self.map.remove(&key);
        self.detach(tail_ptr);

        let node = unsafe { Box::from_raw(tail_ptr.as_ptr()) };

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

        Some((node.key, node.value))
    }

    /// Peeks at the least recently used item without removing it.
    pub fn peek_lru(&self) -> Option<(&K, &V)> {
        #[cfg(feature = "metrics")]
        (&self.metrics).record_peek_lru_call();

        self.tail.map(|node_ptr| {
            #[cfg(feature = "metrics")]
            (&self.metrics).record_peek_lru_found();

            unsafe {
                let node = node_ptr.as_ptr();
                (&(*node).key, &(*node).value)
            }
        })
    }

    /// Clears all entries from the cache.
    pub fn clear(&mut self) {
        #[cfg(feature = "metrics")]
        self.metrics.record_clear();

        while self.pop_lru().is_some() {}
    }

    /// Moves an existing entry to MRU position without returning its value.
    ///
    /// Returns `true` if the key existed and was touched.
    #[inline(always)]
    pub fn touch(&mut self, key: &K) -> bool {
        #[cfg(feature = "metrics")]
        self.metrics.record_touch_call();

        if let Some(&node_ptr) = self.map.get(key) {
            self.detach(node_ptr);
            self.attach_front(node_ptr);

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

            true
        } else {
            false
        }
    }

    // =========================================================================
    // Internal linked-list operations
    // =========================================================================

    /// Detaches a node from its current position in the list.
    #[inline(always)]
    fn detach(&mut self, node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_ptr();
            let prev = (*node).prev;
            let next = (*node).next;

            match prev {
                Some(prev_ptr) => (*prev_ptr.as_ptr()).next = next,
                None => self.head = next,
            }

            match next {
                Some(next_ptr) => (*next_ptr.as_ptr()).prev = prev,
                None => self.tail = prev,
            }

            (*node).prev = None;
            (*node).next = None;
        }
    }

    /// Attaches a node at the front (MRU position) of the list.
    #[inline(always)]
    fn attach_front(&mut self, node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_ptr();
            (*node).prev = None;
            (*node).next = self.head;

            match self.head {
                Some(head_ptr) => (*head_ptr.as_ptr()).prev = Some(node_ptr),
                None => self.tail = Some(node_ptr),
            }

            self.head = Some(node_ptr);
        }
    }
}

#[cfg(feature = "metrics")]
impl<K, V> FastLru<K, V>
where
    K: Eq + Hash + Clone,
{
    pub fn metrics_snapshot(&self) -> LruMetricsSnapshot {
        LruMetricsSnapshot {
            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,
            pop_lru_calls: self.metrics.pop_lru_calls,
            pop_lru_found: self.metrics.pop_lru_found,
            peek_lru_calls: self.metrics.peek_lru_calls.get(),
            peek_lru_found: self.metrics.peek_lru_found.get(),
            touch_calls: self.metrics.touch_calls,
            touch_found: self.metrics.touch_found,
            recency_rank_calls: self.metrics.recency_rank_calls.get(),
            recency_rank_found: self.metrics.recency_rank_found.get(),
            recency_rank_scan_steps: self.metrics.recency_rank_scan_steps.get(),
            cache_len: self.map.len(),
            capacity: self.capacity,
        }
    }
}

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

impl<K, V> Drop for FastLru<K, V> {
    fn drop(&mut self) {
        // Free all nodes
        let mut current = self.head;
        while let Some(node_ptr) = current {
            unsafe {
                let node = Box::from_raw(node_ptr.as_ptr());
                current = node.next;
            }
        }
    }
}

// SAFETY: FastLru is Send if K and V are Send
unsafe impl<K: Send, V: Send> Send for FastLru<K, V> {}

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

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

        assert!(cache.is_empty());
        assert_eq!(cache.capacity(), 3);

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

        assert_eq!(cache.len(), 3);
        assert_eq!(cache.get(&1), Some(&"one"));
        assert_eq!(cache.get(&2), Some(&"two"));
        assert_eq!(cache.get(&3), Some(&"three"));
    }

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

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

        // Access 1 to make it MRU
        cache.get(&1);

        // Insert 3, should evict 2 (LRU)
        cache.insert(3, "three");

        assert!(cache.contains(&1));
        assert!(!cache.contains(&2));
        assert!(cache.contains(&3));
    }

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

        cache.insert(1, "one");
        let old = cache.insert(1, "ONE");

        assert_eq!(old, Some("one"));
        assert_eq!(cache.get(&1), Some(&"ONE"));
        assert_eq!(cache.len(), 1);
    }

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

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

        assert_eq!(cache.remove(&1), Some("one"));
        assert_eq!(cache.remove(&1), None);
        assert_eq!(cache.len(), 1);
    }

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

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

        // 1 is LRU (inserted first, not accessed)
        assert_eq!(cache.pop_lru(), Some((1, "one")));
        assert_eq!(cache.pop_lru(), Some((2, "two")));
        assert_eq!(cache.pop_lru(), Some((3, "three")));
        assert_eq!(cache.pop_lru(), None);
    }

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

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

        // Touch 1 to make it MRU
        assert!(cache.touch(&1));

        // Insert 4, evicts 2 (now LRU)
        cache.insert(4, "four");

        assert!(cache.contains(&1));
        assert!(!cache.contains(&2));
    }

    #[test]
    fn test_zero_capacity() {
        let mut cache: FastLru<i32, &str> = FastLru::new(0);

        assert_eq!(cache.insert(1, "one"), None);
        assert!(cache.is_empty());
        assert_eq!(cache.get(&1), None);
    }

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

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

        cache.clear();

        assert!(cache.is_empty());
        assert_eq!(cache.get(&1), None);
    }

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

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

        // Peek doesn't change order
        assert_eq!(cache.peek(&1), Some(&"one"));

        // Insert 4, should evict 1 (still LRU because peek doesn't update)
        cache.insert(4, "four");

        assert!(!cache.contains(&1));
    }
}