generational_cache/cache/
mod.rs

1//! Module providing abstractions to represent caches.
2
3/// The outcome of an eviction from a cache.
4///
5/// Evictions occur in cache implementations on insert operations in a maxed out cache. This happens
6/// to make space for the just inserted key/value pair.
7#[derive(Debug, PartialEq, Eq)]
8pub enum Eviction<K, V> {
9    /// Block eviction with evicted key/value pair on a key/value insertion with an unique key.
10    Block { key: K, value: V },
11
12    /// Value eviction on insertion with a key already existing in the cache.
13    Value(V),
14
15    /// No eviction when the cache is not maxed out.
16    None,
17}
18
19/// The outcome of a lookup query from a [`Cache`].
20#[derive(Debug, PartialEq, Eq)]
21pub enum Lookup<V> {
22    /// Cache hit.
23    Hit(V),
24
25    /// Cache miss.
26    Miss,
27}
28
29/// A size bounded map, where certain existing entries are evicted to make space for new entries.
30///
31/// Implementations follow a well defined criteria to decide which cache blocks to evict in which
32/// order. (e.g an LRU cache implementation would evict the least recently used cache blocks).
33pub trait Cache<K, V> {
34    /// Associated error type.
35    type Error;
36
37    /// Inserts the given key/value pair into this cache.
38    fn insert(&mut self, key: K, value: V) -> Result<Eviction<K, V>, Self::Error>;
39
40    /// Removes the key/value pair associated with the given key from this cache.
41    fn remove(&mut self, key: &K) -> Result<Lookup<V>, Self::Error>;
42
43    /// Removes `(self.len() - new_capacity)` cache blocks to fit the new capacity. If the
44    /// difference is non-positive no cache blocks are removed.
45    fn shrink(&mut self, new_capacity: usize) -> Result<(), Self::Error>;
46
47    /// Reserves additional memory to accomodate the given number of additional cache blocks.
48    fn reserve(&mut self, additional: usize) -> Result<(), Self::Error>;
49
50    /// Queries this cache to find the value associated with given key.
51    fn query(&mut self, key: &K) -> Result<Lookup<&V>, Self::Error>;
52
53    /// Returns the current capacity of this cache.
54    fn capacity(&self) -> usize;
55
56    /// Returns the number of key/value pairs stored in this cache.
57    fn len(&self) -> usize;
58
59    /// Returns whether this cache is maxed out.
60    ///
61    /// This method simply checks whether the current length of this cache equals its capacity.
62    fn is_maxed(&self) -> bool {
63        self.len() == self.capacity()
64    }
65
66    /// Returns whether this cache is empty.
67    fn is_empty(&self) -> bool {
68        self.len() == 0
69    }
70
71    /// Remove all items from this cache until it's empty.
72    fn clear(&mut self) -> Result<(), Self::Error>;
73}
74
75pub mod lru_cache;