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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use parking_lot::RwLock;
use std::{collections::HashMap, fmt, sync::Arc};
#[derive(Debug, Clone)]
pub struct Cache<K, V> {
values: Arc<RwLock<HashMap<K, V>>>,
limit: usize,
name: String,
}
impl<K, V> Cache<K, V> {
pub fn new(name: &str, limit: usize) -> Self {
Self {
values: Arc::new(RwLock::new(HashMap::with_capacity(limit / 2))),
limit,
name: name.to_string(),
}
}
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<V>
where
K: std::hash::Hash + std::cmp::Eq + std::borrow::Borrow<Q>,
Q: std::hash::Hash + std::cmp::Eq,
V: Clone,
{
self.values.read().get(key).cloned()
}
pub fn get_or_insert<F>(&self, key: K, f: F) -> V
where
K: std::hash::Hash + std::cmp::Eq,
V: Clone,
F: FnOnce() -> V,
{
if let Some(value) = self.get(&key) {
return value;
}
let mut cache = self.values.write();
let value = f();
cache.insert(key, value.clone());
if cache.len() < self.limit {
return value;
}
debug!(target: "txpool", "{}Cache: reached limit.", self.name().to_string());
trace_time!("txpool_cache:clear");
let remaining: Vec<_> = cache.drain().skip(self.limit / 2).collect();
for (k, v) in remaining {
cache.insert(k, v);
}
value
}
pub fn clear(&self) {
self.values.write().clear();
}
pub fn len(&self) -> usize {
self.values.read().len()
}
pub fn limit(&self) -> usize {
self.limit
}
pub fn name(&self) -> &str {
&self.name
}
}
pub(super) struct CachedClient<'a, C: 'a, K, V> {
client: &'a C,
cache: &'a Cache<K, V>,
}
impl<'a, C: 'a, K, V> Clone for CachedClient<'a, C, K, V> {
fn clone(&self) -> Self {
Self {
client: self.client,
cache: self.cache,
}
}
}
impl<'a, C: 'a, K, V> fmt::Debug for CachedClient<'a, C, K, V> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("CachedClient")
.field("name", &self.cache.name())
.field("cache", &self.cache.len())
.field("limit", &self.cache.limit())
.finish()
}
}
impl<'a, C: 'a, K, V> CachedClient<'a, C, K, V> {
pub fn new(client: &'a C, cache: &'a Cache<K, V>) -> Self {
Self { client, cache }
}
pub fn cache(&self) -> &'a Cache<K, V> {
self.cache
}
pub fn client(&self) -> &'a C {
self.client
}
}