Weighter

Trait Weighter 

Source
pub trait Weighter<Key, Val> {
    // Required method
    fn weight(&self, key: &Key, val: &Val) -> u64;
}
Expand description

Defines the weight of a cache entry.

§Example

use quick_cache::{sync::Cache, Weighter};

#[derive(Clone)]
struct StringWeighter;

impl Weighter<u64, String> for StringWeighter {
    fn weight(&self, _key: &u64, val: &String) -> u64 {
        // Be cautious out about zero weights!
        val.len() as u64
    }
}

let cache = Cache::with_weighter(100, 100_000, StringWeighter);
cache.insert(1, "1".to_string());

Required Methods§

Source

fn weight(&self, key: &Key, val: &Val) -> u64

Returns the weight of the cache item.

For performance reasons this function should be trivially cheap as it’s called during the cache eviction routine. If weight is expensive to calculate, consider caching it alongside the value.

Zero (0) weight items are allowed and will be ignored when looking for eviction candidates. Such items can only be manually removed or overwritten.

Note that this it’s undefined behavior for a cache item to change its weight. The only exception to this is when Lifecycle::before_evict is called.

It’s also undefined behavior in release mode if summing of weights overflow, although this is unlikely to be a problem in pratice.

Implementors§

Source§

impl<Key, Val> Weighter<Key, Val> for UnitWeighter