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
use std::borrow::Borrow;
use std::cell::{Cell, UnsafeCell};
use std::collections::HashMap;
use std::hash::Hash;
use std::iter::FromIterator;
use std::ops::Index;
use stable_deref_trait::StableDeref;
pub struct FrozenMap<K, V> {
map: UnsafeCell<HashMap<K, V>>,
in_use: Cell<bool>,
}
impl<K: Eq + Hash, V> FrozenMap<K, V> {
pub fn new() -> Self {
Self {
map: UnsafeCell::new(Default::default()),
in_use: Cell::new(false)
}
}
}
impl<K: Eq + Hash, V: StableDeref> FrozenMap<K, V> {
pub fn insert(&self, k: K, v: V) -> &V::Target {
assert!(!self.in_use.get());
self.in_use.set(true);
let ret = unsafe {
let map = self.map.get();
&*(*map).entry(k).or_insert(v)
};
self.in_use.set(false);
ret
}
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V::Target>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
assert!(!self.in_use.get());
self.in_use.set(true);
let ret = unsafe {
let map = self.map.get();
(*map).get(k).map(|x| &**x)
};
self.in_use.set(false);
ret
}
pub fn into_map(self) -> HashMap<K, V> {
self.map.into_inner()
}
}
impl<K, V> From<HashMap<K, V>> for FrozenMap<K, V> {
fn from(map: HashMap<K, V>) -> Self {
Self {
map: UnsafeCell::new(map),
in_use: Cell::new(false)
}
}
}
impl<K: Eq + Hash, V: StableDeref> Index<K> for FrozenMap<K, V> {
type Output = V::Target;
fn index(&self, idx: K) -> &V::Target {
self.get(&idx).expect("attempted to index FrozenMap with unknown key")
}
}
impl<K: Eq + Hash, V> FromIterator<(K, V)> for FrozenMap<K, V> {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = (K, V)> {
let map: HashMap<_, _> = iter.into_iter().collect();
map.into()
}
}
impl<K: Eq + Hash, V:> Default for FrozenMap<K, V> {
fn default() -> Self {
FrozenMap::new()
}
}