cache_mod/cache.rs
1//! The [`Cache`] trait — the common contract every cache type in this crate
2//! implements.
3
4use core::hash::Hash;
5
6/// The common read / write / evict contract every cache type in this crate
7/// implements.
8///
9/// All methods take `&self` (not `&mut self`) so a cache instance can be
10/// shared across threads and across `.await` points without external locking.
11/// Implementations use interior mutability.
12///
13/// # Access semantics
14///
15/// - [`get`](Self::get) is an **access**: it may update the eviction order
16/// (e.g. promoting the entry to most-recently-used).
17/// - [`contains_key`](Self::contains_key) is a **query** only: it must not
18/// update the eviction order.
19/// - [`insert`](Self::insert) is an access on the inserted key.
20/// - [`remove`](Self::remove) is destructive and does not update order.
21///
22/// # Example
23///
24/// ```
25/// use cache_mod::{Cache, LruCache};
26///
27/// let cache: LruCache<&'static str, u32> = LruCache::new(4).expect("capacity > 0");
28///
29/// assert_eq!(cache.insert("a", 1), None);
30/// assert_eq!(cache.get(&"a"), Some(1));
31/// assert!(cache.contains_key(&"a"));
32/// assert_eq!(cache.len(), 1);
33///
34/// assert_eq!(cache.remove(&"a"), Some(1));
35/// assert!(cache.is_empty());
36/// ```
37pub trait Cache<K, V>
38where
39 K: Eq + Hash,
40 V: Clone,
41{
42 /// Returns the value associated with `key`, if any, and counts as an
43 /// access for the purposes of the eviction policy.
44 fn get(&self, key: &K) -> Option<V>;
45
46 /// Inserts `value` under `key`. Returns the previously-stored value if
47 /// `key` was already present.
48 ///
49 /// May evict one or more existing entries to make room, according to
50 /// the cache's eviction policy.
51 fn insert(&self, key: K, value: V) -> Option<V>;
52
53 /// Removes the entry for `key` and returns the value if present.
54 fn remove(&self, key: &K) -> Option<V>;
55
56 /// Returns `true` if the cache currently holds an entry for `key`.
57 ///
58 /// Unlike [`get`](Self::get), this method does **not** count as an
59 /// access — eviction order is left unchanged.
60 fn contains_key(&self, key: &K) -> bool;
61
62 /// Number of entries currently stored.
63 fn len(&self) -> usize;
64
65 /// Returns `true` when the cache holds no entries.
66 fn is_empty(&self) -> bool {
67 self.len() == 0
68 }
69
70 /// Removes every entry. Capacity is preserved.
71 fn clear(&self);
72
73 /// Configured capacity bound.
74 ///
75 /// The unit depends on the implementation:
76 /// - `LruCache`, `LfuCache`, `TtlCache`, `TinyLfuCache` — maximum number of entries.
77 /// - `SizedCache` — maximum total byte-weight across entries.
78 fn capacity(&self) -> usize;
79}