081edd4bd2845400f1f3ad00ea23e9d33167362c
   1 //! The raw form of a `Map`, allowing untyped access. 
   3 //! All relevant details are in the `RawMap` struct. 
   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
; 
  15 use core
::hash
::{Hasher
, BuildHasherDefault
}; 
  16 use core
::ops
::{Index
, IndexMut
}; 
  18 use crate::any
::UncheckedAnyExt
; 
  25 impl Hasher 
for TypeIdHasher 
{ 
  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
)); 
  38     fn finish(&self) -> u64 { self.value 
} 
  43     #
[cfg(not(feature 
= "std"))] 
  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
) }); 
  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>>()); 
  59 /// The raw, underlying form of a `Map`. 
  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. 
  67 pub struct RawMap
<A
: ?Sized 
+ UncheckedAnyExt 
= dyn Any
> { 
  68     inner
: HashMap
<TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>, 
  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 
{ 
  74     fn clone(&self) -> RawMap
<A
> { 
  76             inner
: self.inner
.clone(), 
  81 impl_common_methods
! { 
  83     new() => HashMap
::with_hasher(Default
::default()); 
  84     with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default()); 
  87 /// `RawMap` iterator. 
  89 pub struct Iter
<'a
, A
: ?Sized 
+ UncheckedAnyExt
> { 
  90     inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>, 
  92 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> Iterator 
for Iter
<'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() } 
  97 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> ExactSizeIterator 
for Iter
<'a
, A
> { 
  98     #
[inline
] fn len(&self) -> usize { self.inner
.len() } 
 101 /// `RawMap` mutable iterator. 
 102 pub struct IterMut
<'a
, A
: ?Sized 
+ UncheckedAnyExt
> { 
 103     inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>, 
 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() } 
 110 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> ExactSizeIterator 
for IterMut
<'a
, A
> { 
 111     #
[inline
] fn len(&self) -> usize { self.inner
.len() } 
 114 /// `RawMap` move iterator. 
 115 pub struct IntoIter
<A
: ?Sized 
+ UncheckedAnyExt
> { 
 116     inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>, 
 118 impl<A
: ?Sized 
+ UncheckedAnyExt
> Iterator 
for IntoIter
<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() } 
 123 impl<A
: ?Sized 
+ UncheckedAnyExt
> ExactSizeIterator 
for IntoIter
<A
> { 
 124     #
[inline
] fn len(&self) -> usize { self.inner
.len() } 
 127 /// `RawMap` drain iterator. 
 128 pub struct Drain
<'a
, A
: ?Sized 
+ UncheckedAnyExt
> { 
 129     inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>, 
 131 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> Iterator 
for Drain
<'a
, 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() } 
 136 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> ExactSizeIterator 
for Drain
<'a
, A
> { 
 137     #
[inline
] fn len(&self) -> usize { self.inner
.len() } 
 140 impl<A
: ?Sized 
+ UncheckedAnyExt
> RawMap
<A
> { 
 141     /// An iterator visiting all entries in arbitrary order. 
 143     /// Iterator element type is `&Any`. 
 145     pub fn iter(&self) -> Iter
<A
> { 
 147             inner
: self.inner
.iter(), 
 151     /// An iterator visiting all entries in arbitrary order. 
 153     /// Iterator element type is `&mut Any`. 
 155     pub fn iter_mut(&mut self) -> IterMut
<A
> { 
 157             inner
: self.inner
.iter_mut(), 
 161     /// Clears the map, returning all items as an iterator. 
 163     /// Iterator element type is `Box<Any>`. 
 165     /// Keeps the allocated memory for reuse. 
 167     pub fn drain(&mut self) -> Drain
<A
> { 
 169             inner
: self.inner
.drain(), 
 173     /// Gets the entry for the given type in the collection for in-place manipulation. 
 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 
{ 
 180             hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry 
{ 
 186     /// Returns a reference to the value corresponding to the key. 
 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. 
 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
) 
 196     /// Returns true if the map contains a value for the specified key. 
 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. 
 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
) 
 206     /// Returns a mutable reference to the value corresponding to the key. 
 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. 
 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
) 
 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. 
 221     /// `key` and the type ID of `value` must match, or *undefined behaviour* occurs. 
 223     pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> { 
 224         self.inner
.insert(key
, value
) 
 227     /// Removes a key from the map, returning the value at the key if the key was previously in the 
 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. 
 233     pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>> 
 234     where TypeId
: Borrow
<Q
>, Q
: Hash 
+ Eq 
{ 
 240 impl<A
: ?Sized 
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq 
+ Hash 
{ 
 244     fn index(&self, index
: Q
) -> &A 
{ 
 245         self.get(&index
).expect("no entry found for key") 
 249 impl<A
: ?Sized 
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq 
+ Hash 
{ 
 251     fn index_mut(&mut self, index
: Q
) -> &mut A 
{ 
 252         self.get_mut(&index
).expect("no entry found for key") 
 256 impl<A
: ?Sized 
+ UncheckedAnyExt
> IntoIterator 
for RawMap
<A
> { 
 258     type IntoIter 
= IntoIter
<A
>; 
 261     fn into_iter(self) -> IntoIter
<A
> { 
 263             inner
: self.inner
.into_iter(), 
 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
>>, 
 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
>>, 
 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
>), 
 289     Vacant(VacantEntry
<'a
, A
>), 
 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. 
 298     /// The type ID of `default` must match the entry’s key, or *undefined behaviour* occurs. 
 300     pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a 
mut A 
{ 
 302             Entry
::Occupied(inner
) => inner
.into_mut(), 
 303             Entry
::Vacant(inner
) => inner
.insert(default), 
 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. 
 312     /// The type ID of the value returned by `default` must match the entry’s key, 
 313     /// or *undefined behaviour* occurs. 
 315     pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<A
>>(self, default: F
) -> &'a 
mut A 
{ 
 317             Entry
::Occupied(inner
) => inner
.into_mut(), 
 318             Entry
::Vacant(inner
) => inner
.insert(default()), 
 323 impl<'a
, A
: ?Sized 
+ UncheckedAnyExt
> OccupiedEntry
<'a
, A
> { 
 324     /// Gets a reference to the value in the entry. 
 326     pub fn get(&self) -> &A 
{ 
 330     /// Gets a mutable reference to the value in the entry. 
 332     pub fn get_mut(&mut self) -> &mut A 
{ 
 333         &mut **self.inner
.get_mut() 
 336     /// Converts the OccupiedEntry into a mutable reference to the value in the entry 
 337     /// with a lifetime bound to the collection itself. 
 339     pub fn into_mut(self) -> &'a 
mut A 
{ 
 340         &mut **self.inner
.into_mut() 
 343     /// Sets the value of the entry, and returns the entry's old value. 
 347     /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs. 
 349     pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> { 
 350         self.inner
.insert(value
) 
 353     /// Takes the value out of the entry, and returns it. 
 355     pub fn remove(self) -> Box
<A
> { 
 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. 
 366     /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs. 
 368     pub unsafe fn insert(self, value
: Box
<A
>) -> &'a 
mut A 
{ 
 369         &mut **self.inner
.insert(value
)