caches/cache_api.rs
1//! The basic APIs for Cache implementation.
2use crate::PutResult;
3use core::borrow::Borrow;
4use core::hash::Hash;
5
6/// Cache contains the basic APIs for a cache.
7/// All of caches in this crate implement this trait.
8pub trait Cache<K: Hash + Eq, V> {
9 /// Puts a key-value pair into cache, returns a [`PutResult`].
10 ///
11 /// [`PutResult`]: struct.PutResult.html
12 fn put(&mut self, k: K, v: V) -> PutResult<K, V>;
13
14 /// Returns a reference to the value of the key in the cache or `None` if it
15 /// is not present in the cache. Update the cache if it exists.
16 fn get<Q>(&mut self, k: &Q) -> Option<&V>
17 where
18 K: Borrow<Q>,
19 Q: Hash + Eq + ?Sized;
20
21 /// Returns a mutable reference to the value of the key in the cache or `None` if it
22 /// is not present in the cache. Update the cache if it exists.
23 fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
24 where
25 K: Borrow<Q>,
26 Q: Hash + Eq + ?Sized;
27
28 /// Returns a reference to the value corresponding to the key in the cache or `None` if it is
29 /// not present in the cache. Unlike `get`, `peek` does not update the cache so the key's
30 /// position will be unchanged.
31 fn peek<Q>(&self, k: &Q) -> Option<&V>
32 where
33 K: Borrow<Q>,
34 Q: Hash + Eq + ?Sized;
35
36 /// Returns a mutable reference to the value corresponding to the key in the cache or `None` if it is
37 /// not present in the cache. Unlike `get_mut`, `peek_mut` does not update the cache so the key's
38 /// position will be unchanged.
39 fn peek_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
40 where
41 K: Borrow<Q>,
42 Q: Hash + Eq + ?Sized;
43
44 /// Returns a bool indicating whether the given key is in the cache. Does not update the
45 /// cache.
46 fn contains<Q>(&self, k: &Q) -> bool
47 where
48 K: Borrow<Q>,
49 Q: Hash + Eq + ?Sized;
50
51 /// Removes and returns the value corresponding to the key from the cache or
52 /// `None` if it does not exist.
53 fn remove<Q>(&mut self, k: &Q) -> Option<V>
54 where
55 K: Borrow<Q>,
56 Q: Hash + Eq + ?Sized;
57
58 /// Clears the contents of the cache.
59 fn purge(&mut self);
60
61 /// Returns the number of key-value pairs that are currently in the the cache.
62 fn len(&self) -> usize;
63
64 /// Returns the maximum number of key-value pairs the cache can hold.
65 fn cap(&self) -> usize;
66
67 /// Returns a bool indicating whether the cache is empty or not.
68 fn is_empty(&self) -> bool;
69}
70
71/// Implement this trait for Cache to support resize.
72pub trait ResizableCache {
73 /// Resizes the cache. If the new capacity is smaller than the size of the current
74 /// cache any entries past the new capacity are discarded.
75 ///
76 /// Returns the number of discarded entries
77 fn resize(&mut self, cap: usize) -> u64;
78}