light_cache/
policy.rs

1use std::hash::BuildHasher;
2use parking_lot::MutexGuard;
3
4use crate::LightCache;
5
6pub mod lru;
7pub mod noop;
8pub mod ttl;
9
10mod linked_arena;
11
12pub use noop::NoopPolicy;
13pub use ttl::TtlPolicy;
14pub use lru::LruPolicy;
15
16/// A [Policy] augments accsess to a [LightCache] instance, managing the entry and eviction of items in the cache.
17///
18/// A policy usally requires shared mutable state, therefore the [`Policy::Inner`] type is used to represent this.
19pub trait Policy<K, V>: Sized {
20    /// The inner type of this policy, likely behind a lock
21    type Inner: Prune<K, V, Self>;
22
23    /// # Panics
24    /// This method will panic if the lock is poisoned
25    fn lock_inner(&self) -> MutexGuard<'_, Self::Inner>;
26    
27    fn get<S: BuildHasher>(&self, key: &K, cache: &LightCache<K, V, S, Self>) -> Option<V>;
28
29    fn insert<S: BuildHasher>(&self, key: K, value: V, cache: &LightCache<K, V, S, Self>) -> Option<V>;
30
31    fn remove<S: BuildHasher>(&self, key: &K, cache: &LightCache<K, V, S, Self>) -> Option<V>;
32
33    fn lock_and_prune<S: BuildHasher>(&self, cache: &LightCache<K, V, S, Self>) -> MutexGuard<'_, Self::Inner> {
34        let mut lock = self.lock_inner();
35        lock.prune(cache);
36
37        lock
38    }
39}
40
41/// [Prune] should control how entries are expired (not nescessarily evicted) from the cache
42pub trait Prune<K, V, P> {
43    /// Prune is typically be called before any operation on the cache
44    fn prune<S: BuildHasher>(&mut self, cache: &LightCache<K, V, S, P>);
45}