2b490d81583f03f6ae268dab1aaa8b67f9f3718f
[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 core::any::{Any, TypeId};
6 use core::borrow::Borrow;
7 use std::collections::hash_map::{self, HashMap};
8 use core::convert::TryInto;
9 use core::hash::Hash;
10 use core::hash::{Hasher, BuildHasherDefault};
11 use core::ops::{Index, IndexMut};
12
13 use crate::any::UncheckedAnyExt;
14
15 #[derive(Default)]
16 struct TypeIdHasher {
17 value: u64,
18 }
19
20 impl Hasher for TypeIdHasher {
21 #[inline]
22 fn write(&mut self, bytes: &[u8]) {
23 // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
24 // that changing, but I don’t want to depend on something that isn’t expressly part of the
25 // contract for safety. But I’m OK with release builds putting everything in one bucket
26 // if it *did* change (and debug builds panicking).
27 debug_assert_eq!(bytes.len(), 8);
28 let _ = bytes.try_into()
29 .map(|array| self.value = u64::from_ne_bytes(array));
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 // SAFETY: u64 is valid for all bit patterns.
42 assert_eq!(hasher.finish(), unsafe { core::mem::transmute::<TypeId, u64>(type_id) });
43 }
44 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
45 verify_hashing_with(TypeId::of::<usize>());
46 verify_hashing_with(TypeId::of::<()>());
47 verify_hashing_with(TypeId::of::<str>());
48 verify_hashing_with(TypeId::of::<&str>());
49 verify_hashing_with(TypeId::of::<Vec<u8>>());
50 }
51
52 /// The raw, underlying form of a `Map`.
53 ///
54 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
55 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
56 /// `Map` interface instead, but there is the occasional use for this such as iteration over the
57 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
58 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
59 #[derive(Debug)]
60 pub struct RawMap<A: ?Sized + UncheckedAnyExt = dyn Any> {
61 inner: HashMap<TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
62 }
63
64 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
65 impl<A: ?Sized + UncheckedAnyExt> Clone for RawMap<A> where Box<A>: Clone {
66 #[inline]
67 fn clone(&self) -> RawMap<A> {
68 RawMap {
69 inner: self.inner.clone(),
70 }
71 }
72 }
73
74 impl_common_methods! {
75 field: RawMap.inner;
76 new() => HashMap::with_hasher(Default::default());
77 with_capacity(capacity) => HashMap::with_capacity_and_hasher(capacity, Default::default());
78 }
79
80 /// `RawMap` iterator.
81 #[derive(Clone)]
82 pub struct Iter<'a, A: ?Sized + UncheckedAnyExt> {
83 inner: hash_map::Iter<'a, TypeId, Box<A>>,
84 }
85 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Iter<'a, A> {
86 type Item = &'a A;
87 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
88 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
89 }
90 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Iter<'a, A> {
91 #[inline] fn len(&self) -> usize { self.inner.len() }
92 }
93
94 /// `RawMap` mutable iterator.
95 pub struct IterMut<'a, A: ?Sized + UncheckedAnyExt> {
96 inner: hash_map::IterMut<'a, TypeId, Box<A>>,
97 }
98 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for IterMut<'a, A> {
99 type Item = &'a mut A;
100 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
101 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
102 }
103 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IterMut<'a, A> {
104 #[inline] fn len(&self) -> usize { self.inner.len() }
105 }
106
107 /// `RawMap` move iterator.
108 pub struct IntoIter<A: ?Sized + UncheckedAnyExt> {
109 inner: hash_map::IntoIter<TypeId, Box<A>>,
110 }
111 impl<A: ?Sized + UncheckedAnyExt> Iterator for IntoIter<A> {
112 type Item = Box<A>;
113 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
114 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
115 }
116 impl<A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IntoIter<A> {
117 #[inline] fn len(&self) -> usize { self.inner.len() }
118 }
119
120 /// `RawMap` drain iterator.
121 pub struct Drain<'a, A: ?Sized + UncheckedAnyExt> {
122 inner: hash_map::Drain<'a, TypeId, Box<A>>,
123 }
124 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Drain<'a, A> {
125 type Item = Box<A>;
126 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
127 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
128 }
129 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Drain<'a, A> {
130 #[inline] fn len(&self) -> usize { self.inner.len() }
131 }
132
133 impl<A: ?Sized + UncheckedAnyExt> RawMap<A> {
134 /// An iterator visiting all entries in arbitrary order.
135 ///
136 /// Iterator element type is `&Any`.
137 #[inline]
138 pub fn iter(&self) -> Iter<A> {
139 Iter {
140 inner: self.inner.iter(),
141 }
142 }
143
144 /// An iterator visiting all entries in arbitrary order.
145 ///
146 /// Iterator element type is `&mut Any`.
147 #[inline]
148 pub fn iter_mut(&mut self) -> IterMut<A> {
149 IterMut {
150 inner: self.inner.iter_mut(),
151 }
152 }
153
154 /// Clears the map, returning all items as an iterator.
155 ///
156 /// Iterator element type is `Box<Any>`.
157 ///
158 /// Keeps the allocated memory for reuse.
159 #[inline]
160 pub fn drain(&mut self) -> Drain<A> {
161 Drain {
162 inner: self.inner.drain(),
163 }
164 }
165
166 /// Gets the entry for the given type in the collection for in-place manipulation.
167 #[inline]
168 pub fn entry(&mut self, key: TypeId) -> Entry<A> {
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 #[inline]
184 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&A>
185 where TypeId: Borrow<Q>, Q: Hash + Eq {
186 self.inner.get(k).map(|x| &**x)
187 }
188
189 /// Returns true if the map contains a value for the specified key.
190 ///
191 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
192 /// form *must* match those for the key type.
193 #[inline]
194 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
195 where TypeId: Borrow<Q>, Q: Hash + Eq {
196 self.inner.contains_key(k)
197 }
198
199 /// Returns a mutable reference to the value corresponding to the key.
200 ///
201 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
202 /// form *must* match those for the key type.
203 #[inline]
204 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut A>
205 where TypeId: Borrow<Q>, Q: Hash + Eq {
206 self.inner.get_mut(k).map(|x| &mut **x)
207 }
208
209 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
210 /// that value is returned. Otherwise, `None` is returned.
211 ///
212 /// # Safety
213 ///
214 /// `key` and the type ID of `value` must match, or *undefined behaviour* occurs.
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 /// # Safety
284 ///
285 /// The type ID of `default` must match the entry’s key, or *undefined behaviour* occurs.
286 #[inline]
287 pub unsafe fn or_insert(self, default: Box<A>) -> &'a mut A {
288 match self {
289 Entry::Occupied(inner) => inner.into_mut(),
290 Entry::Vacant(inner) => inner.insert(default),
291 }
292 }
293
294 /// Ensures a value is in the entry by inserting the result of the default function if empty,
295 /// and returns a mutable reference to the value in the entry.
296 ///
297 /// # Safety
298 ///
299 /// The type ID of the value returned by `default` must match the entry’s key,
300 /// or *undefined behaviour* occurs.
301 #[inline]
302 pub unsafe fn or_insert_with<F: FnOnce() -> Box<A>>(self, default: F) -> &'a mut A {
303 match self {
304 Entry::Occupied(inner) => inner.into_mut(),
305 Entry::Vacant(inner) => inner.insert(default()),
306 }
307 }
308 }
309
310 impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> {
311 /// Gets a reference to the value in the entry.
312 #[inline]
313 pub fn get(&self) -> &A {
314 &**self.inner.get()
315 }
316
317 /// Gets a mutable reference to the value in the entry.
318 #[inline]
319 pub fn get_mut(&mut self) -> &mut A {
320 &mut **self.inner.get_mut()
321 }
322
323 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
324 /// with a lifetime bound to the collection itself.
325 #[inline]
326 pub fn into_mut(self) -> &'a mut A {
327 &mut **self.inner.into_mut()
328 }
329
330 /// Sets the value of the entry, and returns the entry's old value.
331 ///
332 /// # Safety
333 ///
334 /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
335 #[inline]
336 pub unsafe fn insert(&mut self, value: Box<A>) -> Box<A> {
337 self.inner.insert(value)
338 }
339
340 /// Takes the value out of the entry, and returns it.
341 #[inline]
342 pub fn remove(self) -> Box<A> {
343 self.inner.remove()
344 }
345 }
346
347 impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> {
348 /// Sets the value of the entry with the VacantEntry's key,
349 /// and returns a mutable reference to it.
350 ///
351 /// # Safety
352 ///
353 /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
354 #[inline]
355 pub unsafe fn insert(self, value: Box<A>) -> &'a mut A {
356 &mut **self.inner.insert(value)
357 }
358 }