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
#![deny(missing_docs)]
use std::borrow::Borrow;
use std::collections::{hash_map, HashMap};
use std::hash::Hash;
use std::mem;
use std::ops::Deref;
use std::sync::Mutex;
pub mod sync {
use super::*;
#[derive(Debug)]
pub struct AppendOnlyHashMap<K, V>(Mutex<HashMap<K, Box<V>>>);
impl<K, V> AppendOnlyHashMap<K, V> {
pub fn new() -> Self {
AppendOnlyHashMap(Mutex::new(HashMap::new()))
}
pub fn with_capacity(capacity: usize) -> Self {
AppendOnlyHashMap(Mutex::new(HashMap::with_capacity(capacity)))
}
}
impl<K, V> AppendOnlyHashMap<K, V>
where
K: Eq + Hash,
{
pub fn get<'map, Q: ?Sized>(&'map self, key: &Q) -> Option<&'map V>
where
Q: Borrow<K>
{
let locked = self.0.lock().unwrap();
let value_ptr = locked.get(key.borrow())?.deref() as *const V;
mem::drop(locked);
Some(unsafe {
&*value_ptr
})
}
pub fn get_or_insert_with<'map, F>(&'map self, key: K, f: F) -> &'map V
where
F: FnOnce(&K) -> V
{
self.get_or_insert_with_fallible::<(), _>(key, |k| Ok(f(k))).unwrap()
}
pub fn get_or_insert_with_fallible<'map, E, F>(&'map self, key: K, f: F) -> Result<&'map V, E>
where
F: FnOnce(&K) -> Result<V, E>
{
let mut locked = self.0.lock().unwrap();
let value_ptr = match locked.entry(key) {
hash_map::Entry::Occupied(o) => o.get().deref() as *const V,
hash_map::Entry::Vacant(v) => {
let value = Box::new(f(v.key())?);
(*v.insert(value)).deref() as *const V
}
};
mem::drop(locked);
Ok(unsafe {
&*value_ptr
})
}
}
}