kapot_cache/backend/policy/lru/
mod.rs1pub mod lru_cache;
19
20use crate::backend::policy::CachePolicyPutResult;
21use crate::backend::CachePolicy;
22use std::fmt::Debug;
23use std::hash::Hash;
24use std::marker::PhantomData;
25
26pub trait LruCachePolicy: CachePolicy {
27 fn get_lru(&mut self, k: &Self::K) -> Option<Self::V>;
30
31 fn put_lru(
37 &mut self,
38 k: Self::K,
39 v: Self::V,
40 ) -> CachePolicyPutResult<Self::K, Self::V>;
41
42 fn pop_lru(&mut self) -> Option<(Self::K, Self::V)>;
46}
47
48pub trait ResourceCounter: Debug + Send + 'static {
49 type K: Clone + Eq + Hash + Ord + Debug + Send + 'static;
51
52 type V: Clone + Debug + Send + 'static;
54
55 fn consume(&mut self, k: &Self::K, v: &Self::V);
57
58 fn restore(&mut self, k: &Self::K, v: &Self::V);
60
61 fn exceed_capacity(&self) -> bool;
63}
64
65#[derive(Debug, Clone, Copy)]
66pub struct DefaultResourceCounter<K, V>
67where
68 K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
69 V: Clone + Debug + Send + 'static,
70{
71 max_num: usize,
72 current_num: usize,
73 _key_marker: PhantomData<K>,
74 _value_marker: PhantomData<V>,
75}
76
77impl<K, V> DefaultResourceCounter<K, V>
78where
79 K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
80 V: Clone + Debug + Send + 'static,
81{
82 pub fn new(capacity: usize) -> Self {
83 Self {
84 max_num: capacity,
85 current_num: 0,
86 _key_marker: PhantomData,
87 _value_marker: PhantomData,
88 }
89 }
90}
91
92impl<K, V> ResourceCounter for DefaultResourceCounter<K, V>
93where
94 K: Clone + Eq + Hash + Ord + Debug + Send + 'static,
95 V: Clone + Debug + Send + 'static,
96{
97 type K = K;
98 type V = V;
99
100 fn consume(&mut self, _k: &Self::K, _v: &Self::V) {
101 self.current_num += 1;
102 }
103
104 fn restore(&mut self, _k: &Self::K, _v: &Self::V) {
105 self.current_num -= 1;
106 }
107
108 fn exceed_capacity(&self) -> bool {
109 self.current_num > self.max_num
110 }
111}