lru_cache_map/
meter.rs

1//! Define the Meter trait to track cache resource usage.
2
3use std::borrow::Borrow;
4
5/// A trait for measuring the size of a cache item.
6///
7/// `Meter` is used to provide the cache an additional method to track the resource usage, other
8/// than counting cache items. This is useful when the cache items differ in size.
9///
10/// In most cases, using `usize` as `Measure` would be good enough.
11pub trait Meter<K, V> {
12    /// The type used to store measurements.
13    type Measure: Default
14        + Copy
15        + Ord
16        + std::fmt::Display
17        + std::ops::Add<Output = Self::Measure>
18        + std::ops::Sub<Output = Self::Measure>;
19
20    /// Calculate the size of `key` and `value`.
21    fn measure<Q: ?Sized>(&self, key: &Q, value: &V) -> Self::Measure
22    where
23        K: Borrow<Q>;
24}
25
26/// A Meter that measures cache size by counting object number.
27pub struct Count;
28
29impl<K, V> Meter<K, V> for Count {
30    type Measure = usize;
31
32    fn measure<Q: ?Sized>(&self, _: &Q, _: &V) -> Self::Measure
33    where
34        K: Borrow<Q>,
35    {
36        1
37    }
38}