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