0ce7266bf4fb6df0a0c96e5c4b4c343f214e20c8
[anymap] / src / raw.rs
1 //! The raw form of an AnyMap, allowing untyped access.
2 //!
3 //! All relevant details are in the `RawAnyMap` struct.
4
5 use std::any::{Any, TypeId};
6 use std::borrow::Borrow;
7 use std::collections::hash_map::{self, HashMap};
8 use std::collections::hash_state::HashState;
9 use std::default::Default;
10 use std::hash::{Hash, Hasher};
11 use std::iter::IntoIterator;
12 use std::mem;
13 use std::ops::{Index, IndexMut};
14 use std::ptr;
15
16 struct TypeIdHasher {
17 value: u64,
18 }
19
20 struct TypeIdState;
21
22 impl HashState for TypeIdState {
23 type Hasher = TypeIdHasher;
24
25 fn hasher(&self) -> TypeIdHasher {
26 TypeIdHasher { value: 0 }
27 }
28 }
29
30 impl Hasher for TypeIdHasher {
31 #[inline(always)]
32 fn write(&mut self, bytes: &[u8]) {
33 // This expects to receive one and exactly one 64-bit value
34 debug_assert!(bytes.len() == 8);
35 unsafe {
36 ptr::copy_nonoverlapping(&mut self.value, mem::transmute(&bytes[0]), 1)
37 }
38 }
39
40 #[inline(always)]
41 fn finish(&self) -> u64 { self.value }
42 }
43
44
45 /// The raw, underlying form of an AnyMap.
46 ///
47 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
48 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
49 /// `AnyMap` interface instead, but there is the occasional use for this such as iteration over the
50 /// contents of an `AnyMap`. However, because you will then be dealing with `Any` trait objects, it
51 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
52 #[derive(Debug)]
53 pub struct RawAnyMap {
54 inner: HashMap<TypeId, Box<Any>, TypeIdState>,
55 }
56
57 impl Default for RawAnyMap {
58 fn default() -> RawAnyMap {
59 RawAnyMap::new()
60 }
61 }
62
63 impl_common_methods! {
64 field: RawAnyMap.inner;
65 new() => HashMap::with_hash_state(TypeIdState);
66 with_capacity(capacity) => HashMap::with_capacity_and_hash_state(capacity, TypeIdState);
67 }
68
69 /// RawAnyMap iterator.
70 #[derive(Clone)]
71 pub struct Iter<'a> {
72 inner: hash_map::Iter<'a, TypeId, Box<Any>>,
73 }
74 impl<'a> Iterator for Iter<'a> {
75 type Item = &'a Any;
76 #[inline] fn next(&mut self) -> Option<&'a Any> { self.inner.next().map(|x| &**x.1) }
77 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
78 }
79 impl<'a> ExactSizeIterator for Iter<'a> {
80 #[inline] fn len(&self) -> usize { self.inner.len() }
81 }
82
83 /// RawAnyMap mutable iterator.
84 pub struct IterMut<'a> {
85 inner: hash_map::IterMut<'a, TypeId, Box<Any>>,
86 }
87 impl<'a> Iterator for IterMut<'a> {
88 type Item = &'a mut Any;
89 #[inline] fn next(&mut self) -> Option<&'a mut Any> { self.inner.next().map(|x| &mut **x.1) }
90 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
91 }
92 impl<'a> ExactSizeIterator for IterMut<'a> {
93 #[inline] fn len(&self) -> usize { self.inner.len() }
94 }
95
96 /// RawAnyMap move iterator.
97 pub struct IntoIter {
98 inner: hash_map::IntoIter<TypeId, Box<Any>>,
99 }
100 impl Iterator for IntoIter {
101 type Item = Box<Any>;
102 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
103 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
104 }
105 impl ExactSizeIterator for IntoIter {
106 #[inline] fn len(&self) -> usize { self.inner.len() }
107 }
108
109 /// RawAnyMap drain iterator.
110 pub struct Drain<'a> {
111 inner: hash_map::Drain<'a, TypeId, Box<Any>>,
112 }
113 impl<'a> Iterator for Drain<'a> {
114 type Item = Box<Any>;
115 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
116 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
117 }
118 impl<'a> ExactSizeIterator for Drain<'a> {
119 #[inline] fn len(&self) -> usize { self.inner.len() }
120 }
121
122 impl RawAnyMap {
123 /// An iterator visiting all entries in arbitrary order.
124 ///
125 /// Iterator element type is `&Any`.
126 #[inline]
127 pub fn iter(&self) -> Iter {
128 Iter {
129 inner: self.inner.iter(),
130 }
131 }
132
133 /// An iterator visiting all entries in arbitrary order.
134 ///
135 /// Iterator element type is `&mut Any`.
136 #[inline]
137 pub fn iter_mut(&mut self) -> IterMut {
138 IterMut {
139 inner: self.inner.iter_mut(),
140 }
141 }
142
143 /// Creates a consuming iterator, that is, one that moves each item
144 /// out of the map in arbitrary order. The map cannot be used after
145 /// calling this.
146 ///
147 /// Iterator element type is `Box<Any>`.
148 #[inline]
149 pub fn into_iter(self) -> IntoIter {
150 IntoIter {
151 inner: self.inner.into_iter(),
152 }
153 }
154
155 /// Clears the map, returning all items as an iterator.
156 ///
157 /// Iterator element type is `Box<Any>`.
158 ///
159 /// Keeps the allocated memory for reuse.
160 #[inline]
161 pub fn drain(&mut self) -> Drain {
162 Drain {
163 inner: self.inner.drain(),
164 }
165 }
166
167 /// Gets the entry for the given type in the collection for in-place manipulation.
168 pub fn entry(&mut self, key: TypeId) -> Entry {
169 match self.inner.entry(key) {
170 hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
171 inner: e,
172 }),
173 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
174 inner: e,
175 }),
176 }
177 }
178
179 /// Returns a reference to the value corresponding to the key.
180 ///
181 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
182 /// form *must* match those for the key type.
183 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&Any>
184 where TypeId: Borrow<Q>, Q: Hash + Eq {
185 self.inner.get(k).map(|x| &**x)
186 }
187
188 /// Returns true if the map contains a value for the specified key.
189 ///
190 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
191 /// form *must* match those for the key type.
192 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
193 where TypeId: Borrow<Q>, Q: Hash + Eq {
194 self.inner.contains_key(k)
195 }
196
197 /// Returns a mutable reference to the value corresponding to the key.
198 ///
199 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
200 /// form *must* match those for the key type.
201 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut Any>
202 where TypeId: Borrow<Q>, Q: Hash + Eq {
203 self.inner.get_mut(k).map(|x| &mut **x)
204 }
205
206 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
207 /// that value is returned. Otherwise, None is returned.
208 ///
209 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
210 /// the value. If they do not, memory safety may be violated.
211 pub unsafe fn insert(&mut self, key: TypeId, value: Box<Any>) -> Option<Box<Any>> {
212 self.inner.insert(key, value)
213 }
214
215 /// Removes a key from the map, returning the value at the key if the key was previously in the
216 /// map.
217 ///
218 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
219 /// form *must* match those for the key type.
220 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<Box<Any>>
221 where TypeId: Borrow<Q>, Q: Hash + Eq {
222 self.inner.remove(k)
223 }
224
225 }
226
227 impl<Q> Index<Q> for RawAnyMap where TypeId: Borrow<Q>, Q: Eq + Hash {
228 type Output = Any;
229
230 fn index<'a>(&'a self, index: Q) -> &'a Any {
231 self.get(&index).expect("no entry found for key")
232 }
233 }
234
235 impl<Q> IndexMut<Q> for RawAnyMap where TypeId: Borrow<Q>, Q: Eq + Hash {
236 fn index_mut<'a>(&'a mut self, index: Q) -> &'a mut Any {
237 self.get_mut(&index).expect("no entry found for key")
238 }
239 }
240
241 impl IntoIterator for RawAnyMap {
242 type Item = Box<Any>;
243 type IntoIter = IntoIter;
244
245 fn into_iter(self) -> IntoIter {
246 self.into_iter()
247 }
248 }
249
250 /// A view into a single occupied location in a `RawAnyMap`.
251 pub struct OccupiedEntry<'a> {
252 inner: hash_map::OccupiedEntry<'a, TypeId, Box<Any>>,
253 }
254
255 /// A view into a single empty location in a `RawAnyMap`.
256 pub struct VacantEntry<'a> {
257 inner: hash_map::VacantEntry<'a, TypeId, Box<Any>>,
258 }
259
260 /// A view into a single location in an AnyMap, which may be vacant or occupied.
261 pub enum Entry<'a> {
262 /// An occupied Entry
263 Occupied(OccupiedEntry<'a>),
264 /// A vacant Entry
265 Vacant(VacantEntry<'a>),
266 }
267
268 impl<'a> Entry<'a> {
269 /// Ensures a value is in the entry by inserting the default if empty, and returns
270 /// a mutable reference to the value in the entry.
271 ///
272 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
273 /// the type ID of `value`. If they do not, memory safety may be violated.
274 pub unsafe fn or_insert(self, default: Box<Any>) -> &'a mut Any {
275 match self {
276 Entry::Occupied(inner) => inner.into_mut(),
277 Entry::Vacant(inner) => inner.insert(default),
278 }
279 }
280
281 /// Ensures a value is in the entry by inserting the result of the default function if empty,
282 /// and returns a mutable reference to the value in the entry.
283 ///
284 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
285 /// the type ID of `value`. If they do not, memory safety may be violated.
286 pub unsafe fn or_insert_with<F: FnOnce() -> Box<Any>>(self, default: F) -> &'a mut Any {
287 match self {
288 Entry::Occupied(inner) => inner.into_mut(),
289 Entry::Vacant(inner) => inner.insert(default()),
290 }
291 }
292 }
293
294 impl<'a> OccupiedEntry<'a> {
295 /// Gets a reference to the value in the entry.
296 pub fn get(&self) -> &Any {
297 &**self.inner.get()
298 }
299
300 /// Gets a mutable reference to the value in the entry.
301 pub fn get_mut(&mut self) -> &mut Any {
302 &mut **self.inner.get_mut()
303 }
304
305 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
306 /// with a lifetime bound to the collection itself.
307 pub fn into_mut(self) -> &'a mut Any {
308 &mut **self.inner.into_mut()
309 }
310
311 /// Sets the value of the entry, and returns the entry's old value.
312 ///
313 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
314 /// the type ID of `value`. If they do not, memory safety may be violated.
315 pub unsafe fn insert(&mut self, value: Box<Any>) -> Box<Any> {
316 self.inner.insert(value)
317 }
318
319 /// Takes the value out of the entry, and returns it.
320 pub fn remove(self) -> Box<Any> {
321 self.inner.remove()
322 }
323 }
324
325 impl<'a> VacantEntry<'a> {
326 /// Sets the value of the entry with the VacantEntry's key,
327 /// and returns a mutable reference to it
328 ///
329 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
330 /// the type ID of `value`. If they do not, memory safety may be violated.
331 pub unsafe fn insert(self, value: Box<Any>) -> &'a mut Any {
332 &mut **self.inner.insert(value)
333 }
334 }