add test
This commit is contained in:
parent
9f07224f9a
commit
a8bb902bd0
|
@ -55,13 +55,31 @@ pub struct LFUCache<K: Eq + PartialEq + Copy, V, const N: usize> {
|
|||
time: usize
|
||||
}
|
||||
|
||||
impl<K: Eq + PartialEq + Copy, V, const N: usize> LFUCache<K, V, N> {
|
||||
fn init(data: [Node<K, V>; N]) -> Self {
|
||||
Self {
|
||||
data,
|
||||
size: N,
|
||||
time: 0
|
||||
}
|
||||
}
|
||||
// todo: 用 `maybuninit`
|
||||
fn empty(data: [Node<K, V>; N]) -> Self {
|
||||
Self {
|
||||
data,
|
||||
size: 0,
|
||||
time: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Eq + PartialEq + Copy, V, const N: usize> Cache for LFUCache<K, V, N> {
|
||||
type Key = K;
|
||||
type Value = V;
|
||||
fn get(&mut self, key: &Self::Key) -> Option<&Self::Value> {
|
||||
self.time += 1;
|
||||
let time = self.time;
|
||||
self.data.iter_mut().find(|i| i.key == *key).map(|node| {
|
||||
self.data[0..self.size].iter_mut().find(|i| i.key == *key).map(|node| {
|
||||
// 更新结点时间和访问次数
|
||||
node.time = time;
|
||||
node.cnt += 1;
|
||||
|
@ -83,7 +101,7 @@ impl<K: Eq + PartialEq + Copy, V, const N: usize> Cache for LFUCache<K, V, N> {
|
|||
self.data[self.size].cnt = 1;
|
||||
self.data[self.size].time = self.time;
|
||||
self.size += 1;
|
||||
} else {
|
||||
} else { // 缓存已满
|
||||
// 顺序排序
|
||||
self.data[0..self.size].sort_by(|a, b| a.cmp(b));
|
||||
// 淘汰第一项
|
||||
|
@ -94,9 +112,30 @@ impl<K: Eq + PartialEq + Copy, V, const N: usize> Cache for LFUCache<K, V, N> {
|
|||
}
|
||||
node.key = *key;
|
||||
node.value = value;
|
||||
node.cnt = 0;
|
||||
node.cnt = 1;
|
||||
node.time = self.time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn lfu_cache_test() {
|
||||
let nodes = [Node::new(0, 0); 2];
|
||||
let mut lfu_cache = LFUCache::empty(nodes);
|
||||
|
||||
assert!(lfu_cache.get(&0).is_none());
|
||||
assert!(lfu_cache.get(&1).is_none());
|
||||
assert!(lfu_cache.get(&2).is_none());
|
||||
lfu_cache.put(&1, 1, |_ , _| {});
|
||||
lfu_cache.put(&2, 2, |_ , _| {});
|
||||
assert_eq!(lfu_cache.get(&1).map(|v| *v), Some(1));
|
||||
lfu_cache.put(&3, 3, |_ , _| {});
|
||||
assert_eq!(lfu_cache.get(&2), None);
|
||||
assert_eq!(lfu_cache.get(&3).map(|v| *v), Some(3));
|
||||
lfu_cache.put(&4, 4, |_ , _| {});
|
||||
assert_eq!(lfu_cache.get(&1), None);
|
||||
assert_eq!(lfu_cache.get(&3).map(|v| *v), Some(3));
|
||||
assert_eq!(lfu_cache.get(&4).map(|v| *v), Some(4));
|
||||
}
|
Loading…
Reference in New Issue