1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::{borrow::Borrow, hash::Hash, time::Instant};
use parking_lot::Mutex;
pub type LruCache<K, V> = Mutex<lru_cache::LruCache<K, LruItem<V>, ahash::RandomState>>;
#[derive(Debug, Clone)]
pub struct LruItem<V> {
item: V,
valid_until: Instant,
}
pub trait DnsCache<K, V>: Sized {
fn with_capacity(capacity: usize) -> Self;
fn get<Q: ?Sized>(&self, name: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq;
fn insert(&self, name: K, value: V, valid_until: Instant) -> V;
}
impl<K: Hash + Eq, V: Clone> DnsCache<K, V> for LruCache<K, V> {
fn with_capacity(capacity: usize) -> Self {
Mutex::new(lru_cache::LruCache::with_hasher(
capacity,
ahash::RandomState::new(),
))
}
fn get<Q: ?Sized>(&self, name: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let mut cache = self.lock();
let entry = cache.get_mut(name)?;
if entry.valid_until >= Instant::now() {
entry.item.clone().into()
} else {
cache.remove(name);
None
}
}
fn insert(&self, name: K, item: V, valid_until: Instant) -> V {
self.lock().insert(
name,
LruItem {
item: item.clone(),
valid_until,
},
);
item
}
}