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