pub mod lru_cache;
use crate::backend::policy::CachePolicyPutResult;
use crate::backend::CachePolicy;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
pub trait LruCachePolicy: CachePolicy {
fn get_lru(&mut self, k: &Self::K) -> Option<Self::V>;
fn put_lru(
&mut self,
k: Self::K,
v: Self::V,
) -> CachePolicyPutResult<Self::K, Self::V>;
fn pop_lru(&mut self) -> Option<(Self::K, Self::V)>;
}
pub trait ResourceCounter: Debug + Send + 'static {
type K: Clone + Eq + Hash + Ord + Debug + Send + 'static;
type V: Clone + Debug + Send + 'static;
fn consume(&mut self, k: &Self::K, v: &Self::V);
fn restore(&mut self, k: &Self::K, v: &Self::V);
fn exceed_capacity(&self) -> bool;
}
#[derive(Debug, Clone, Copy)]
pub struct DefaultResourceCounter<K, V>
where
K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
V: Clone + Debug + Send + 'static,
{
max_num: usize,
current_num: usize,
_key_marker: PhantomData<K>,
_value_marker: PhantomData<V>,
}
impl<K, V> DefaultResourceCounter<K, V>
where
K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
V: Clone + Debug + Send + 'static,
{
pub fn new(capacity: usize) -> Self {
Self {
max_num: capacity,
current_num: 0,
_key_marker: PhantomData,
_value_marker: PhantomData,
}
}
}
impl<K, V> ResourceCounter for DefaultResourceCounter<K, V>
where
K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
V: Clone + Debug + Send + 'static,
{
type K = K;
type V = V;
fn consume(&mut self, _k: &Self::K, _v: &Self::V) {
self.current_num += 1;
}
fn restore(&mut self, _k: &Self::K, _v: &Self::V) {
self.current_num -= 1;
}
fn exceed_capacity(&self) -> bool {
self.current_num > self.max_num
}
}