threadsafe_lru/
lib.rs

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
#![deny(unsafe_code)]

/// # threadsafe-lru
///
/// This is a thread-safe implementation of an LRU (Least Recently Used) cache in Rust.
/// The `LruCache` struct uses sharding to improve concurrency by splitting the cache into
/// multiple smaller segments, each protected by a mutex.
///
/// ## Example Usage
///
/// ```rust
/// use threadsafe_lru::LruCache;
///
/// fn main() {
///     // Create a new LRU cache with 4 shards and capacity of 2 per shard
///     let cache = LruCache::new(4, 2);
///
///     // Insert items into the cache
///     let five = 5;
///     let six = 6;
///     assert_eq!(cache.insert(five, 10), None);
///     assert_eq!(cache.insert(six, 20), None);
///
///     // Retrieve an item from the cache
///     assert_eq!(cache.get(&five), Some(10));
///
///     // Promote an item to make it more recently used
///     cache.promote(&five);
///
///     // Remove an item from the cache
///     assert_eq!(cache.remove(&five), Some(10));
/// }
/// ```
///
/// In this example, a new `LruCache` is created with 4 shards and a capacity of 2 entries per shard.
/// Items are inserted using the `insert` method.
/// The `get` method retrieves an item by key, promoting it to the most recently used position.
/// Finally, the `remove` method deletes an item from the cache.
///
/// This implementation ensures that operations on different keys can be performed concurrently
/// without causing race conditions due to shared state.
///
use std::{
    borrow::Borrow,
    hash::{DefaultHasher, Hash, Hasher},
    sync::{
        atomic::{AtomicUsize, Ordering},
        Mutex,
    },
};

use hashbrown::HashMap;
use indexlist::{Index, IndexList};

// A thread-safe LRU
pub struct LruCache<K, V> {
    shards: Vec<Mutex<Shard<K, V>>>,
    count: AtomicUsize,
    shards_count: usize,
    cap_per_shard: usize,
}

struct Shard<K, V> {
    entries: HashMap<K, (Index<K>, V)>,
    order: IndexList<K>,
    count: usize,
}

impl<K, V> LruCache<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Creates a new instance of `LruCache`.
    ///
    /// The cache is divided into multiple shards to improve concurrency by distributing the entries
    /// across different locks.
    ///
    /// # Arguments
    ///
    /// * `shards_count` - The number of shards in the cache. Each shard acts as an independent LRU
    ///                    with its own capacity and order list.
    /// * `cap_per_shard` - The capacity for each shard, representing the maximum number of items it
    ///                     can hold before evicting the least recently used item(s).
    ///
    /// # Returns
    ///
    /// A new instance of `LruCache`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache: LruCache<i32, i32> = LruCache::new(4, 2); // Creates a cache with 4 shards and capacity of 2 entries per shard.
    /// ```
    pub fn new(shards_count: usize, cap_per_shard: usize) -> LruCache<K, V> {
        let mut shards = Vec::default();
        for _ in 0..shards_count {
            shards.push(Mutex::new(Shard {
                entries: HashMap::with_capacity(cap_per_shard),
                order: IndexList::with_capacity(cap_per_shard),
                count: 0,
            }));
        }
        LruCache {
            shards,
            count: AtomicUsize::default(),
            shards_count,
            cap_per_shard,
        }
    }

    /// Inserts a new key-value pair into the cache.
    ///
    /// If the key already exists in the cache, its value is updated and it is promoted to the most
    /// recently used position.
    /// If inserting the new item causes the cache to exceed its capacity, the least recently used
    /// item will be evicted from its shard.
    ///
    /// # Arguments
    ///
    /// * `k` - The key to insert or update.
    /// * `v` - The value associated with the key.
    ///
    /// # Returns
    ///
    /// If the key already existed in the cache and was updated, the previous value is returned.
    /// Otherwise, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// assert_eq!(cache.insert(five, 10), None); // Inserts a new key-value pair
    /// assert_eq!(cache.insert(six, 20), None); // Inserts another new key-value pair
    /// assert_eq!(cache.insert(five, 30), Some(10)); // Updates an existing key with a new value and returns the old value
    /// ```
    pub fn insert(&self, k: K, v: V) -> Option<V> {
        let mut shard = self.shards[self.shard(&k)].lock().unwrap();
        let index = shard.entries.get(&k).map(|v| v.0);
        if shard.count == self.cap_per_shard && index.is_none() {
            if let Some(index) = shard.order.head_index() {
                shard.entries.remove(&k);
                shard.order.remove(index);
                self.count.fetch_sub(1, Ordering::Relaxed);
                shard.count -= 1;
            }
        }

        match index {
            Some(index) => {
                shard.order.remove(index);
                let index = shard.order.push_back(k.clone());
                shard.entries.insert(k, (index, v)).map(|v| v.1)
            }
            None => {
                let index = shard.order.push_back(k.clone());
                shard.entries.insert(k, (index, v));
                self.count.fetch_add(1, Ordering::Relaxed);
                shard.count += 1;
                None
            }
        }
    }

    /// Retrieves a value from the cache by key.
    ///
    /// When a key is accessed using this method, it is promoted to the most recently used position
    /// in its shard. If the key does not exist in the cache, `None` is returned.
    ///
    /// # Arguments
    ///
    /// * `k` - The key of the item to retrieve.
    ///
    /// # Returns
    ///
    /// The value associated with the key if it exists; otherwise, `None`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// assert_eq!(cache.insert(five, 10), None);
    /// assert_eq!(cache.get(&five), Some(10));
    /// ```
    ///
    /// This method ensures that frequently accessed items remain more accessible while older or less
    /// frequently accessed items are evicted when necessary.

    pub fn get<Q>(&self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized + ToOwned<Owned = K>,
        V: Clone,
    {
        let mut shard = self.shards[self.shard(k)].lock().unwrap();
        let index = shard.entries.get(k).map(|e| e.0);
        match index {
            Some(index) => {
                shard.order.remove(index);
                shard.order.push_back(k.to_owned());
                shard.entries.get(k).map(|e| e.1.clone())
            }
            None => None,
        }
    }

    /// Retrieves and mutates a value from the cache by key.
    ///
    /// When a key is accessed using this method, it is promoted to the most recently used position
    /// in its shard. If the key does not exist in the cache, `None` is returned.
    ///
    /// This function provides mutable access to the value associated with a given key, allowing you
    /// to modify its contents directly without needing to retrieve and re-insert it into the cache.
    ///
    /// # Arguments
    ///
    /// * `k` - The key of the item to retrieve and mutate.
    /// * `func` - A closure that takes a mutable reference to the value (if present) and allows
    ///            for in-place modifications.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// assert_eq!(cache.insert(five, 10), None);
    /// cache.get_mut(&five, |v| {
    ///   if let Some(v) = v {
    ///      *v += 1
    ///    }
    /// });
    /// ```
    ///
    /// This method ensures that frequently accessed items remain more accessible while older or less
    /// frequently accessed items are evicted when necessary.
    pub fn get_mut<Q, F>(&self, k: &Q, mut func: F)
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized + ToOwned<Owned = K>,
        F: FnMut(Option<&mut V>),
    {
        let mut shard = self.shards[self.shard(k)].lock().unwrap();
        let index = shard.entries.get(k).map(|e| e.0);
        if let Some(index) = index {
            shard.order.remove(index);
            shard.order.push_back(k.to_owned());
            func(shard.entries.get_mut(k).map(|e| &mut e.1));
        }
    }

    /// Removes a key-value pair from the cache by key.
    ///
    /// When an item is removed from the cache using this method, its corresponding entry is deleted
    /// along with any references to it in the order list. If the key does not exist in the cache,
    /// `None` is returned.
    ///
    /// This operation ensures that the cache maintains its integrity and correctly tracks the number of items stored.
    ///
    /// # Arguments
    ///
    /// * `k` - The key of the item to remove.
    ///
    /// # Returns
    ///
    /// The value associated with the key if it existed; otherwise, `None`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// assert_eq!(cache.insert(five, 10), None); // Inserts a new key-value pair
    /// assert_eq!(cache.insert(six, 20), None); // Inserts another new key-value pair
    ///
    /// assert_eq!(cache.remove(&five), Some(10)); // Removes the item with key five and returns its value
    /// assert_eq!(cache.get(&five), None); // Key five no longer exists in the cache
    /// ```
    ///
    pub fn remove<Q>(&self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        let mut shard = self.shards[self.shard(k)].lock().unwrap();
        let entry = shard.entries.remove(k);
        match entry {
            Some((index, value)) => {
                shard.order.remove(index);
                self.count.fetch_sub(1, Ordering::Relaxed);
                shard.count -= 1;
                Some(value)
            }
            None => None,
        }
    }

    /// Promotes a key-value pair in the cache to the most recently used position.
    ///
    /// When an item is accessed using this method, it is promoted to the most recently used position
    /// in its shard. If the key does not exist in the cache, no action is taken.
    ///
    /// # Arguments
    ///
    /// * `k` - The key of the item to promote.
    ///
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    /// let seven = 7;
    ///
    /// assert_eq!(cache.insert(five, 10), None); // Inserts a new key-value pair
    /// assert_eq!(cache.insert(six, 20), None); // Inserts another new key-value pair
    ///
    /// cache.promote(&five);
    ///
    /// assert_eq!(cache.insert(seven, 30), None); // Inserts another new key-value pair
    /// assert_eq!(cache.get(&five), Some(10)); // Retrieving the promoted item
    /// ```
    ///
    pub fn promote<Q>(&self, k: &Q)
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized + ToOwned<Owned = K>,
    {
        let mut shard = self.shards[self.shard(k)].lock().unwrap();
        let index = shard.entries.get(k).map(|v| v.0);
        if let Some(index) = index {
            shard.order.remove(index);
            shard.order.push_back(k.to_owned());
        }
    }

    /// Returns the total number of key-value pairs currently stored in the cache.
    ///
    /// This method provides a quick way to check how many items are present in the cache without
    /// iterating over its contents.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// assert_eq!(cache.insert(five, 10), None); // Inserts a new key-value pair
    /// assert_eq!(cache.len(), 1); // Cache now has one item
    ///
    /// cache.insert(six, 20);
    /// assert_eq!(cache.len(), 2); // Cache now has two items
    ///
    /// cache.remove(&five);
    /// assert_eq!(cache.len(), 1); // Cache now has only one item
    ///
    /// let new_cache: LruCache<i32, i32> = LruCache::new(4, 2);
    /// assert_eq!(new_cache.len(), 0); // New cache is empty
    /// ```
    ///
    pub fn len(&self) -> usize {
        self.count.load(Ordering::Relaxed)
    }

    /// Checks if the cache is empty.
    ///
    /// This method provides a quick way to determine whether the cache contains any key-value pairs
    /// without iterating over its contents.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use threadsafe_lru::LruCache;
    ///
    /// let cache = LruCache::new(4, 2);
    ///
    /// assert!(cache.is_empty()); // Cache is empty upon creation
    ///
    /// let five = 5;
    /// let six = 6;
    ///
    /// cache.insert(five, 10); // Inserting a key-value pair
    /// assert!(!cache.is_empty()); // Cache is no longer empty
    ///
    /// cache.remove(&five); // Removing the key-value pair
    /// assert!(cache.is_empty()); // Cache is empty again after removal
    /// ```
    ///
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn shard<Q>(&self, k: &Q) -> usize
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        let mut hasher = DefaultHasher::new();
        k.hash(&mut hasher);
        hasher.finish() as usize % self.shards_count
    }
}

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

    #[test]
    fn test_new() {
        let shards_count = 4;
        let cap_per_shard = 10;

        let cache: LruCache<u8, u8> = LruCache::new(shards_count, cap_per_shard);
        assert_eq!(cache.shards.len(), shards_count);

        for shard in &cache.shards {
            let lock = shard.lock().unwrap();
            assert!(lock.entries.capacity() >= cap_per_shard);
            assert_eq!(lock.count, 0);
        }

        assert_eq!(cache.shards_count, shards_count);
        assert_eq!(cache.cap_per_shard, cap_per_shard);
    }

    #[test]
    fn test_insert() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        let nine = 9;
        assert_eq!(cache.shard(&five), cache.shard(&six));
        assert_eq!(cache.shard(&five), cache.shard(&nine));

        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.insert(five, 10), Some(10));
        assert_eq!(cache.count.load(Ordering::Relaxed), 1);
        assert_eq!(cache.insert(six, 20), None);
        assert_eq!(cache.count.load(Ordering::Relaxed), 2);
        assert_eq!(cache.insert(nine, 30), None);
        assert_eq!(cache.count.load(Ordering::Relaxed), 2);
        assert_eq!(cache.insert(six, 20), Some(20));
        assert_eq!(cache.count.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn test_get() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        assert_eq!(cache.shard(&five), cache.shard(&six));
        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.insert(six, 20), None);

        assert_eq!(cache.get(&five), Some(10));
        assert_eq!(cache.get(&six), Some(20));

        let shard = cache.shards[cache.shard(&five)].lock().unwrap();
        assert_eq!(shard.order.head(), Some(&five));
        assert_eq!(shard.order.tail(), Some(&six));

        assert_eq!(cache.get(&3), None);

        assert_eq!(cache.count.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn test_get_mut() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        assert_eq!(cache.shard(&five), cache.shard(&six));
        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.insert(six, 20), None);

        cache.get_mut(&five, |v| {
            if let Some(v) = v {
                *v = 30
            }
        });
        assert_eq!(cache.get(&five), Some(30));
        assert_eq!(cache.count.load(Ordering::Relaxed), 2);

        let shard = cache.shards[cache.shard(&five)].lock().unwrap();
        assert_eq!(shard.order.tail(), Some(&five));
        assert_eq!(shard.order.head(), Some(&six));

        cache.get_mut(&3, |v| {
            if let Some(v) = v {
                *v = 10
            }
        });
        assert_eq!(cache.count.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn test_remove() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        assert_eq!(cache.shard(&five), cache.shard(&six));
        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.insert(six, 20), None);

        assert_eq!(cache.remove(&five), Some(10));
        assert_eq!(cache.count.load(Ordering::Relaxed), 1);
        let shard = cache.shards[cache.shard(&six)].lock().unwrap();
        assert!(!shard.entries.contains_key(&five));
        assert_eq!(shard.order.head(), Some(&six));
        drop(shard);

        assert_eq!(cache.remove(&5), None);
        assert_eq!(cache.count.load(Ordering::Relaxed), 1);

        let new_cache: LruCache<i32, i32> = LruCache::new(shards_count, cap_per_shard);
        assert_eq!(new_cache.remove(&five), None);
        assert_eq!(new_cache.count.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn test_promote() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        assert_eq!(cache.shard(&five), cache.shard(&six));
        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.insert(six, 20), None);

        let shard = cache.shards[cache.shard(&five)].lock().unwrap();
        assert_eq!(shard.order.head(), Some(&five));
        assert_eq!(shard.order.tail(), Some(&six));
        drop(shard);

        cache.promote(&five);
        let shard = cache.shards[cache.shard(&five)].lock().unwrap();
        assert_eq!(shard.order.head(), Some(&six));
        assert_eq!(shard.order.tail(), Some(&five));
        drop(shard);

        assert_eq!(cache.get(&five), Some(10));
        let shard = cache.shards[cache.shard(&five)].lock().unwrap();
        assert_eq!(shard.order.head(), Some(&six));
        assert_eq!(shard.order.tail(), Some(&five));
        drop(shard);
    }

    #[test]
    fn test_is_empty() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        let five = 5;
        assert_eq!(cache.insert(five, 10), None);
        assert!(!cache.is_empty());
        assert_eq!(cache.len(), 1);

        cache.remove(&five);
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_len() {
        let shards_count = 4;
        let cap_per_shard = 2;

        let cache = LruCache::new(shards_count, cap_per_shard);

        let five = 5;
        let six = 6;
        assert_eq!(cache.insert(five, 10), None);
        assert_eq!(cache.len(), 1);

        cache.insert(six, 20);
        assert_eq!(cache.len(), 2);

        cache.remove(&five);
        assert_eq!(cache.len(), 1);

        let new_cache: LruCache<i32, i32> = LruCache::new(shards_count, cap_per_shard);
        assert_eq!(new_cache.len(), 0);
    }

    #[test]
    fn test_concurrent_access() {
        use std::sync::Arc;
        use std::thread;

        let shards_count = 4;
        let cap_per_shard = 2;

        let cache: Arc<LruCache<i32, i32>> = Arc::new(LruCache::new(shards_count, cap_per_shard));

        const THREAD_COUNT: usize = 10;
        const OPERATIONS_PER_THREAD: usize = 100;

        let mut handles = vec![];

        for _ in 0..THREAD_COUNT {
            let cache = Arc::clone(&cache);

            let handle = thread::spawn(move || {
                for _ in 0..OPERATIONS_PER_THREAD {
                    let key = rand::random::<i32>();
                    let value = rand::random::<i32>();

                    let op_type = rand::random::<u8>() % 3;
                    match op_type {
                        0 => {
                            cache.insert(key, value);
                        }
                        1 => {
                            cache.get(&key);
                        }
                        2 => {
                            cache.remove(&key);
                        }
                        _ => unreachable!(),
                    }
                }
            });

            handles.push(handle);
        }

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