-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdropmap.rs
More file actions
79 lines (72 loc) · 1.93 KB
/
Copy pathdropmap.rs
File metadata and controls
79 lines (72 loc) · 1.93 KB
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
use std::sync::atomic::{AtomicPtr, Ordering::SeqCst};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use dashmap::{DashMap, DashMapRefAny};
// swap interval (in secs)
// const SWAP_INTERVAL: u64 = 20;
struct MapPointer<K, V>
where
K: std::cmp::Eq + std::hash::Hash + Clone + 'static,
V: 'static,
{
pub inner: AtomicPtr<DashMap<K, V>>,
}
impl<K, V> MapPointer<K, V>
where
K: std::cmp::Eq + std::hash::Hash + Clone + 'static,
V: 'static,
{
fn new() -> MapPointer<K, V> {
let map = Box::new(DashMap::default());
let inner = AtomicPtr::new(Box::into_raw(map));
MapPointer { inner }
}
}
impl<K, V> Drop for MapPointer<K, V>
where
K: std::cmp::Eq + std::hash::Hash + Clone + 'static,
V: 'static,
{
fn drop(&mut self) {
unsafe {
let _: DashMap<K, V> = *self.inner.load(SeqCst);
}
}
}
#[derive(Clone)]
pub struct DropMap<K, V>
where
K: std::cmp::Eq + std::hash::Hash + Clone + 'static,
V: 'static,
{
new: Arc<MapPointer<K, V>>,
old: Arc<MapPointer<K, V>>,
}
impl<K, V> DropMap<K, V>
where
K: std::cmp::Eq + std::hash::Hash + Clone + 'static,
V: 'static,
{
pub fn new(swap_interval: u64) -> Self {
let new = Arc::new(MapPointer::new());
let old = Arc::new(MapPointer::new());
let new_cpy = new.clone();
let old_cpy = old.clone();
thread::spawn(move || loop {
unsafe {
thread::sleep(Duration::from_secs(swap_interval));
let old_ptr = old_cpy.inner.swap(new_cpy.inner.load(SeqCst), SeqCst);
(*old_ptr).clear();
new_cpy.inner.store(old_ptr, SeqCst);
}
});
DropMap { new, old }
}
pub fn get_or_insert(&self, key: &K, value: V) -> DashMapRefAny<'_, K, V> {
unsafe {
let new = self.new.inner.load(SeqCst);
(*new).get_or_insert(key, value)
}
}
}