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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#![deny(missing_docs, warnings)]
extern crate unsafe_any as uany;
use uany::{UnsafeAny, UnsafeAnyExt};
use std::any::{Any, TypeId};
use std::collections::{hash_map, HashMap};
use std::marker::PhantomData;
use Entry::{Occupied, Vacant};
#[derive(Default)]
pub struct TypeMap<A: ?Sized = UnsafeAny>
where A: UnsafeAnyExt {
data: HashMap<TypeId, Box<A>>
}
impl<A: ?Sized> Clone for TypeMap<A>
where A: UnsafeAnyExt, Box<A>: Clone {
fn clone(&self) -> TypeMap<A> {
TypeMap { data: self.data.clone() }
}
}
pub type SendMap = TypeMap<UnsafeAny + Send>;
pub type SyncMap = TypeMap<UnsafeAny + Sync>;
pub type ShareMap = TypeMap<UnsafeAny + Send + Sync>;
pub type CloneMap = TypeMap<CloneAny>;
fn _assert_types() {
fn _assert_send<T: Send>() { }
fn _assert_sync<T: Sync>() { }
fn _assert_clone<T: Clone>() { }
_assert_send::<SendMap>();
_assert_sync::<SyncMap>();
_assert_send::<ShareMap>();
_assert_sync::<ShareMap>();
_assert_clone::<CloneMap>();
}
pub trait Key: Any {
type Value: Any;
}
impl TypeMap {
pub fn new() -> TypeMap {
TypeMap {
data: HashMap::new()
}
}
pub fn insert<K: Key>(&mut self, val: K::Value) -> Option<<K as Key>::Value>
where <K as Key>::Value: Any {
self.data.insert(TypeId::of::<K>(), Box::new(val)).map(|v| unsafe {
*v.downcast_unchecked::<<K as Key>::Value>()
})
}
pub fn get<K: Key>(&self) -> Option<&<K as Key>::Value>
where <K as Key>::Value: Any {
self.data.get(&TypeId::of::<K>()).map(|v| unsafe {
v.downcast_ref_unchecked::<<K as Key>::Value>()
})
}
pub fn get_mut<K: Key>(&mut self) -> Option<&mut <K as Key>::Value>
where <K as Key>::Value: Any {
self.data.get_mut(&TypeId::of::<K>()).map(|v| unsafe {
v.downcast_mut_unchecked::<<K as Key>::Value>()
})
}
pub fn contains<K: Key>(&self) -> bool {
self.data.contains_key(&TypeId::of::<K>())
}
pub fn remove<K: Key>(&mut self) -> Option<<K as Key>::Value>
where <K as Key>::Value: Any {
self.data.remove(&TypeId::of::<K>()).map(|v| unsafe {
*v.downcast_unchecked::<<K as Key>::Value>()
})
}
pub fn entry<'a, K: Key>(&'a mut self) -> Entry<'a, K>
where <K as Key>::Value: Any {
match self.data.entry(TypeId::of::<K>()) {
hash_map::Entry::Occupied(e) => Occupied(OccupiedEntry { data: e, _marker: PhantomData }),
hash_map::Entry::Vacant(e) => Vacant(VacantEntry { data: e, _marker: PhantomData })
}
}
pub unsafe fn data(&self) -> &HashMap<TypeId, Box<UnsafeAny>> {
&self.data
}
pub unsafe fn data_mut(&mut self) -> &mut HashMap<TypeId, Box<UnsafeAny>> {
&mut self.data
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn clear(&mut self) {
self.data.clear()
}
}
trait AnyObjectClone {
fn clone_into_box(&self) -> Box<CloneAny>;
}
impl<T: Any + Clone> AnyObjectClone for T {
fn clone_into_box(&self) -> Box<CloneAny> {
Box::new(self.clone())
}
}
trait CloneAny: AnyObjectClone {}
impl<T: Any + Clone> CloneAny for T {}
impl Clone for Box<CloneAny> {
fn clone(&self) -> Box<CloneAny> {
self.clone_into_box()
}
}
unsafe impl UnsafeAnyExt for CloneAny { }
pub enum Entry<'a, K> {
Occupied(OccupiedEntry<'a, K>),
Vacant(VacantEntry<'a, K>)
}
pub struct OccupiedEntry<'a, K> {
data: hash_map::OccupiedEntry<'a, TypeId, Box<UnsafeAny>>,
_marker: PhantomData<K>
}
pub struct VacantEntry<'a, K> {
data: hash_map::VacantEntry<'a, TypeId, Box<UnsafeAny>>,
_marker: PhantomData<K>
}
impl<'a, K: Key> OccupiedEntry<'a, K> {
pub fn get(&self) -> &<K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
self.data.get().downcast_ref_unchecked()
}
}
pub fn get_mut(&mut self) -> &mut <K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
self.data.get_mut().downcast_mut_unchecked()
}
}
pub fn into_mut(self) -> &'a mut <K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
self.data.into_mut().downcast_mut_unchecked()
}
}
pub fn insert(&mut self, value: <K as Key>::Value) -> <K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
*self.data.insert(Box::new(value)).downcast_unchecked()
}
}
pub fn remove(self) -> <K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
*self.data.remove().downcast_unchecked()
}
}
}
impl<'a, K: Key> VacantEntry<'a, K> {
pub fn insert(self, value: <K as Key>::Value) -> &'a mut <K as Key>::Value
where <K as Key>::Value: Any {
unsafe {
self.data.insert(Box::new(value)).downcast_mut_unchecked()
}
}
}
#[cfg(test)]
mod test {
use super::{TypeMap, Key};
use super::Entry::{Occupied, Vacant};
#[derive(Debug, PartialEq)]
struct KeyType;
#[derive(Debug, PartialEq)]
struct Value(u8);
impl Key for KeyType { type Value = Value; }
#[test] fn test_pairing() {
let mut map = TypeMap::new();
map.insert::<KeyType>(Value(100));
assert_eq!(*map.get::<KeyType>().unwrap(), Value(100));
assert!(map.contains::<KeyType>());
}
#[test] fn test_remove() {
let mut map = TypeMap::new();
map.insert::<KeyType>(Value(10));
assert!(map.contains::<KeyType>());
map.remove::<KeyType>();
assert!(!map.contains::<KeyType>());
}
#[test] fn test_entry() {
let mut map = TypeMap::new();
map.insert::<KeyType>(Value(20));
match map.entry::<KeyType>() {
Occupied(e) => {
assert_eq!(e.get(), &Value(20));
assert_eq!(e.remove(), Value(20));
},
_ => panic!("Unable to locate inserted item.")
}
assert!(!map.contains::<KeyType>());
match map.entry::<KeyType>() {
Vacant(e) => {
e.insert(Value(2));
},
_ => panic!("Found non-existant entry.")
}
assert!(map.contains::<KeyType>());
}
}