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