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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
use crossbeam_epoch::{Atomic, Owned};
use smallvec::alloc::fmt::{Debug, Display, Formatter};
use std::collections::hash_map::IntoIter;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::option::Option::Some;
use std::sync::atomic::Ordering::SeqCst;
pub struct MetricMap<K, V> {
data: Atomic<HashMap<K, V>>,
}
impl<K, V> fmt::Debug for MetricMap<K, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("MetricMap").field("data", &self.data).finish()
}
}
impl<K, V> Default for MetricMap<K, V>
where
K: Eq + Hash + Clone + Debug,
V: Clone + Display,
{
fn default() -> Self {
Self::new()
}
}
impl<K, V> MetricMap<K, V>
where
K: Eq + Hash + Clone + Debug,
V: Clone + Display,
{
pub fn new() -> Self {
MetricMap {
data: Atomic::new(HashMap::<K, V>::new()),
}
}
pub fn store_or_modify<F: Fn(&K, &V) -> V>(&self, key: &K, value: V, on_modify: F) {
let guard = crossbeam_epoch::pin();
loop {
let shared = self.data.load(SeqCst, &guard);
let mut new_hash = HashMap::new();
match unsafe { shared.as_ref() } {
Some(old_hash) => {
new_hash = old_hash.clone();
if let Some(old_value) = new_hash.get(key) {
let new_value = on_modify(key, old_value);
new_hash.insert(key.clone(), new_value.clone());
} else {
new_hash.insert(key.clone(), value.clone());
}
}
None => {
new_hash.insert(key.clone(), value.clone());
}
}
let owned = Owned::new(new_hash);
match self.data.compare_and_set(shared, owned, SeqCst, &guard) {
Ok(_) => {
unsafe {
guard.defer_destroy(shared);
break;
}
}
Err(_e) => {}
}
}
}
pub fn load(&self, key: &K) -> Option<V> {
let guard = crossbeam_epoch::pin();
let shared = self.data.load(SeqCst, &guard);
let hmap = unsafe { shared.as_ref().unwrap() };
match hmap.get(key) {
Some(value) => Some(value.clone()),
None => None,
}
}
#[cfg(test)]
pub fn delete(&self, key: K) {
let guard = crossbeam_epoch::pin();
loop {
let shared = self.data.load(SeqCst, &guard);
let old_hash = unsafe { shared.as_ref().unwrap() };
let mut new_hash = HashMap::new();
for (k, v) in old_hash {
if k.clone() == key {
continue;
}
new_hash.insert(k.clone(), v.clone());
}
let owned = Owned::new(new_hash);
match self.data.compare_and_set(shared, owned, SeqCst, &guard) {
Ok(_) => unsafe {
guard.defer_destroy(shared);
break;
},
Err(_e) => {
}
}
}
}
pub fn iterator(&self) -> Option<IntoIter<K, V>> {
let guard = crossbeam_epoch::pin();
let shared = self.data.load(SeqCst, &guard);
match unsafe { shared.as_ref() } {
Some(map) => Some(map.clone().into_iter()),
None => None,
}
}
}
#[cfg(test)]
mod tests {
use crate::metrics::metricmap::MetricMap;
use async_std::task;
use smallvec::alloc::sync::Arc;
use std::ops::Add;
#[test]
pub fn test_store_and_modify() {
let key = String::from("abc");
let map = Arc::new(MetricMap::new());
task::block_on(async {
let inside_future_map = map.clone();
for index in 0..16 {
let k = key.clone();
let inside_map = inside_future_map.clone();
task::spawn(async move { inside_map.store_or_modify(&k, index, |_, value| value.add(index)) }).await;
}
});
assert_eq!(map.load(&key), Some(120))
}
#[test]
pub fn test_delete() {
let key = String::from("abc");
let map = Arc::new(MetricMap::new());
task::block_on(async {
let delete_map = map.clone();
for index in 0..18 {
let k = key.clone();
let inside_map = delete_map.clone();
task::spawn(async move { inside_map.store_or_modify(&k, index, |_, value| value.add(index)) }).await;
}
map.delete(key.clone());
assert_eq!(map.load(&key), None);
for index in 0..20 {
let inside_map = delete_map.clone();
let k = key.clone();
task::spawn(async move { inside_map.store_or_modify(&k, index, |_, value| value.add(index)) }).await;
}
});
map.delete(key.clone());
assert_eq!(map.load(&key), None)
}
}