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
use std::any::{Any, TypeId};
use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
use polymap::PolyMap;
pub struct TypeMap<S = RandomState> {
map: PolyMap<TypeId, S>,
}
impl TypeMap<RandomState> {
pub fn new() -> TypeMap {
TypeMap{map: PolyMap::new()}
}
pub fn with_capacity(n: usize) -> TypeMap {
TypeMap{map: PolyMap::with_capacity(n)}
}
}
impl<S: BuildHasher> TypeMap<S> {
pub fn with_hasher(hash_builder: S) -> TypeMap<S> {
TypeMap{
map: PolyMap::with_hasher(hash_builder),
}
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn contains<T: Any>(&self) -> bool {
self.map.contains_key(&TypeId::of::<T>())
}
pub fn capacity(&self) -> usize {
self.map.capacity()
}
pub fn get<T: Any>(&self) -> Option<&T> {
self.map.get(&TypeId::of::<T>())
}
pub fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
self.map.get_mut(&TypeId::of::<T>())
}
pub fn insert<T: Any>(&mut self, t: T) -> Option<T> {
self.map.insert(TypeId::of::<T>(), t)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn remove<T: Any>(&mut self) -> Option<T> {
self.map.remove(&TypeId::of::<T>())
}
pub fn reserve(&mut self, additional: usize) {
self.map.reserve(additional);
}
pub fn shrink_to_fit(&mut self) {
self.map.shrink_to_fit();
}
}
impl<S: BuildHasher + Default> Default for TypeMap<S> {
fn default() -> TypeMap<S> {
TypeMap::with_hasher(S::default())
}
}
#[cfg(test)]
mod test {
use super::TypeMap;
#[derive(Debug, Eq, PartialEq)]
struct Foo {
a: i32,
b: i32,
}
#[test]
fn test_typemap() {
let mut m = TypeMap::new();
m.insert(123);
m.insert(456_u32);
m.insert("foo");
m.insert(Foo{a: 1, b: 2});
assert_eq!(m.get::<i32>(), Some(&123));
assert_eq!(m.get::<u32>(), Some(&456));
assert_eq!(m.get::<&str>(), Some(&"foo"));
assert_eq!(m.get::<Foo>(), Some(&Foo{a: 1, b: 2}));
}
}