saluki_common/cache/
weight.rs

1// NOTE: We're wrapping the `Weighter` trait from `quick_cache` to provide an abstracted interface over `quick_cache`,
2// so that we can more easily swap out the underlying cache implementation in the future if needed.
3
4/// Calculates the weight of cache items.
5pub trait Weighter<K, V> {
6    /// Returns the weight of the cache item.
7    ///
8    /// For performance reasons, this function should be as cheap as possible, as it will be called during the cache
9    /// eviction routine. If the weight is expensive to calculate, consider caching it alongside the value.
10    ///
11    /// Zero (0) weight items are allowed and will be ignored when looking for eviction candidates. Such items can only
12    /// be manually removed or overwritten.
13    fn item_weight(&self, key: &K, value: &V) -> u64;
14}
15
16/// Wrapper struct to translate from `Weighter` to `quick_cache::Weighter`.
17#[derive(Clone)]
18pub(super) struct WrappedWeighter<W>(W);
19
20impl<W> From<W> for WrappedWeighter<W> {
21    fn from(weighter: W) -> Self {
22        Self(weighter)
23    }
24}
25
26impl<W, K, V> quick_cache::Weighter<K, V> for WrappedWeighter<W>
27where
28    W: Weighter<K, V>,
29{
30    fn weight(&self, key: &K, value: &V) -> u64 {
31        self.0.item_weight(key, value)
32    }
33}
34
35/// Weights items equally, assigning a weight of one to each item.
36///
37/// Caches using this weighter will hold `n` items, where `n` is the configured capacity of the cache.
38#[derive(Clone, Default)]
39pub struct ItemCountWeighter;
40
41impl<K, V> Weighter<K, V> for ItemCountWeighter {
42    fn item_weight(&self, _key: &K, _value: &V) -> u64 {
43        1
44    }
45}