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