e6e989f7e6b7d89779bc8a144d5b30f7ee24167c
1 //! The raw form of a `Map`, allowing untyped access.
3 //! All relevant details are in the `RawMap` struct.
5 use std
::any
::{Any
, TypeId
};
6 use std
::borrow
::Borrow
;
7 use std
::collections
::hash_map
::{self, HashMap
};
8 use std
::convert
::TryInto
;
10 use std
::hash
::{Hasher
, BuildHasherDefault
};
13 use std
::ops
::{Index
, IndexMut
};
15 use crate::any
::UncheckedAnyExt
;
22 impl Hasher
for TypeIdHasher
{
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
));
35 fn finish(&self) -> u64 { self.value
}
40 fn verify_hashing_with(type_id
: TypeId
) {
41 let mut hasher
= TypeIdHasher
::default();
42 type_id
.hash(&mut hasher
);
43 // SAFETY: u64 is valid for all bit patterns.
44 assert_eq!(hasher
.finish(), unsafe { mem
::transmute
::<TypeId
, u64>(type_id
) });
46 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
47 verify_hashing_with(TypeId
::of
::<usize>());
48 verify_hashing_with(TypeId
::of
::<()>());
49 verify_hashing_with(TypeId
::of
::<str>());
50 verify_hashing_with(TypeId
::of
::<&str>());
51 verify_hashing_with(TypeId
::of
::<Vec
<u8>>());
54 /// The raw, underlying form of a `Map`.
56 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
57 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
58 /// `Map` interface instead, but there is the occasional use for this such as iteration over the
59 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
60 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
62 pub struct RawMap
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
63 inner
: HashMap
<TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>,
66 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
67 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for RawMap
<A
> where Box
<A
>: Clone
{
69 fn clone(&self) -> RawMap
<A
> {
71 inner
: self.inner
.clone(),
76 impl_common_methods
! {
78 new() => HashMap
::with_hasher(Default
::default());
79 with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default());
82 /// `RawMap` iterator.
84 pub struct Iter
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
85 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>,
87 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Iter
<'a
, A
> {
89 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
90 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
92 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Iter
<'a
, A
> {
93 #[inline] fn len(&self) -> usize { self.inner.len() }
96 /// `RawMap` mutable iterator.
97 pub struct IterMut
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
98 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>,
100 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IterMut
<'a
, A
> {
101 type Item
= &'a
mut A
;
102 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
103 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
105 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IterMut
<'a
, A
> {
106 #[inline] fn len(&self) -> usize { self.inner.len() }
109 /// `RawMap` move iterator.
110 pub struct IntoIter
<A
: ?Sized
+ UncheckedAnyExt
> {
111 inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>,
113 impl<A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IntoIter
<A
> {
115 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
116 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
118 impl<A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IntoIter
<A
> {
119 #[inline] fn len(&self) -> usize { self.inner.len() }
122 /// `RawMap` drain iterator.
123 pub struct Drain
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
124 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>,
126 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Drain
<'a
, A
> {
128 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
129 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
131 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Drain
<'a
, A
> {
132 #[inline] fn len(&self) -> usize { self.inner.len() }
135 impl<A
: ?Sized
+ UncheckedAnyExt
> RawMap
<A
> {
136 /// An iterator visiting all entries in arbitrary order.
138 /// Iterator element type is `&Any`.
140 pub fn iter(&self) -> Iter
<A
> {
142 inner
: self.inner
.iter(),
146 /// An iterator visiting all entries in arbitrary order.
148 /// Iterator element type is `&mut Any`.
150 pub fn iter_mut(&mut self) -> IterMut
<A
> {
152 inner
: self.inner
.iter_mut(),
156 /// Clears the map, returning all items as an iterator.
158 /// Iterator element type is `Box<Any>`.
160 /// Keeps the allocated memory for reuse.
162 pub fn drain(&mut self) -> Drain
<A
> {
164 inner
: self.inner
.drain(),
168 /// Gets the entry for the given type in the collection for in-place manipulation.
170 pub fn entry(&mut self, key
: TypeId
) -> Entry
<A
> {
171 match self.inner
.entry(key
) {
172 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
175 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
181 /// Returns a reference to the value corresponding to the key.
183 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
184 /// form *must* match those for the key type.
186 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&A
>
187 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
188 self.inner
.get(k
).map(|x
| &**x
)
191 /// Returns true if the map contains a value for the specified key.
193 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
194 /// form *must* match those for the key type.
196 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
197 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
198 self.inner
.contains_key(k
)
201 /// Returns a mutable reference to the value corresponding to the key.
203 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
204 /// form *must* match those for the key type.
206 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut A
>
207 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
208 self.inner
.get_mut(k
).map(|x
| &mut **x
)
211 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
212 /// that value is returned. Otherwise, `None` is returned.
216 /// `key` and the type ID of `value` must match, or *undefined behaviour* occurs.
218 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> {
219 self.inner
.insert(key
, value
)
222 /// Removes a key from the map, returning the value at the key if the key was previously in the
225 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
226 /// form *must* match those for the key type.
228 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>>
229 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
235 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
239 fn index(&self, index
: Q
) -> &A
{
240 self.get(&index
).expect("no entry found for key")
244 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
246 fn index_mut(&mut self, index
: Q
) -> &mut A
{
247 self.get_mut(&index
).expect("no entry found for key")
251 impl<A
: ?Sized
+ UncheckedAnyExt
> IntoIterator
for RawMap
<A
> {
253 type IntoIter
= IntoIter
<A
>;
256 fn into_iter(self) -> IntoIter
<A
> {
258 inner
: self.inner
.into_iter(),
263 /// A view into a single occupied location in a `RawMap`.
264 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
265 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
268 /// A view into a single empty location in a `RawMap`.
269 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
270 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
273 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
274 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
275 /// An occupied Entry
276 Occupied(OccupiedEntry
<'a
, A
>),
278 Vacant(VacantEntry
<'a
, A
>),
281 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Entry
<'a
, A
> {
282 /// Ensures a value is in the entry by inserting the default if empty, and returns
283 /// a mutable reference to the value in the entry.
287 /// The type ID of `default` must match the entry’s key, or *undefined behaviour* occurs.
289 pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a
mut A
{
291 Entry
::Occupied(inner
) => inner
.into_mut(),
292 Entry
::Vacant(inner
) => inner
.insert(default),
296 /// Ensures a value is in the entry by inserting the result of the default function if empty,
297 /// and returns a mutable reference to the value in the entry.
301 /// The type ID of the value returned by `default` must match the entry’s key,
302 /// or *undefined behaviour* occurs.
304 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<A
>>(self, default: F
) -> &'a
mut A
{
306 Entry
::Occupied(inner
) => inner
.into_mut(),
307 Entry
::Vacant(inner
) => inner
.insert(default()),
312 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> OccupiedEntry
<'a
, A
> {
313 /// Gets a reference to the value in the entry.
315 pub fn get(&self) -> &A
{
319 /// Gets a mutable reference to the value in the entry.
321 pub fn get_mut(&mut self) -> &mut A
{
322 &mut **self.inner
.get_mut()
325 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
326 /// with a lifetime bound to the collection itself.
328 pub fn into_mut(self) -> &'a
mut A
{
329 &mut **self.inner
.into_mut()
332 /// Sets the value of the entry, and returns the entry's old value.
336 /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
338 pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> {
339 self.inner
.insert(value
)
342 /// Takes the value out of the entry, and returns it.
344 pub fn remove(self) -> Box
<A
> {
349 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> VacantEntry
<'a
, A
> {
350 /// Sets the value of the entry with the VacantEntry's key,
351 /// and returns a mutable reference to it.
355 /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
357 pub unsafe fn insert(self, value
: Box
<A
>) -> &'a
mut A
{
358 &mut **self.inner
.insert(value
)