1 //! The raw form of a `Map`, allowing untyped access.
3 //! All relevant details are in the `RawMap` struct.
6 use std
::borrow
::Borrow
;
7 use std
::collections
::hash_map
::{self, HashMap
};
9 use std
::hash
::{Hasher
, BuildHasherDefault
};
12 use std
::ops
::{Index
, IndexMut
};
15 use any
::{Any
, UncheckedAnyExt
};
22 impl Hasher
for TypeIdHasher
{
24 fn write(&mut self, bytes
: &[u8]) {
25 // This expects to receive one and exactly one 64-bit value
26 debug_assert!(bytes
.len() == 8);
28 ptr
::copy_nonoverlapping(&bytes
[0] as *const u8 as *const u64, &mut self.value
, 1)
33 fn finish(&self) -> u64 { self.value
}
38 fn verify_hashing_with(type_id
: TypeId
) {
39 let mut hasher
= TypeIdHasher
::default();
40 type_id
.hash(&mut hasher
);
41 assert_eq!(hasher
.finish(), unsafe { mem
::transmute
::<TypeId
, u64>(type_id
) });
43 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
44 verify_hashing_with(TypeId
::of
::<usize>());
45 verify_hashing_with(TypeId
::of
::<()>());
46 verify_hashing_with(TypeId
::of
::<str>());
47 verify_hashing_with(TypeId
::of
::<&str>());
48 verify_hashing_with(TypeId
::of
::<Vec
<u8>>());
51 /// The raw, underlying form of a `Map`.
53 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
54 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
55 /// `Map` interface instead, but there is the occasional use for this such as iteration over the
56 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
57 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
59 pub struct RawMap
<A
: ?Sized
+ UncheckedAnyExt
= Any
> {
60 inner
: HashMap
<TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>,
63 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
64 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for RawMap
<A
> where Box
<A
>: Clone
{
66 fn clone(&self) -> RawMap
<A
> {
68 inner
: self.inner
.clone(),
73 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for RawMap
<A
> {
75 fn default() -> RawMap
<A
> {
80 impl_common_methods
! {
82 new() => HashMap
::with_hasher(Default
::default());
83 with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default());
86 /// `RawMap` iterator.
88 pub struct Iter
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
89 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>,
91 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Iter
<'a
, A
> {
93 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
94 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
96 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Iter
<'a
, A
> {
97 #[inline] fn len(&self) -> usize { self.inner.len() }
100 /// `RawMap` mutable iterator.
101 pub struct IterMut
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
102 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>,
104 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IterMut
<'a
, A
> {
105 type Item
= &'a
mut A
;
106 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
107 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
109 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IterMut
<'a
, A
> {
110 #[inline] fn len(&self) -> usize { self.inner.len() }
113 /// `RawMap` move iterator.
114 pub struct IntoIter
<A
: ?Sized
+ UncheckedAnyExt
> {
115 inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>,
117 impl<A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IntoIter
<A
> {
119 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
120 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
122 impl<A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IntoIter
<A
> {
123 #[inline] fn len(&self) -> usize { self.inner.len() }
126 /// `RawMap` drain iterator.
127 pub struct Drain
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
128 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>,
130 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Drain
<'a
, A
> {
132 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
133 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
135 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Drain
<'a
, A
> {
136 #[inline] fn len(&self) -> usize { self.inner.len() }
139 impl<A
: ?Sized
+ UncheckedAnyExt
> RawMap
<A
> {
140 /// An iterator visiting all entries in arbitrary order.
142 /// Iterator element type is `&Any`.
144 pub fn iter(&self) -> Iter
<A
> {
146 inner
: self.inner
.iter(),
150 /// An iterator visiting all entries in arbitrary order.
152 /// Iterator element type is `&mut Any`.
154 pub fn iter_mut(&mut self) -> IterMut
<A
> {
156 inner
: self.inner
.iter_mut(),
160 /// Clears the map, returning all items as an iterator.
162 /// Iterator element type is `Box<Any>`.
164 /// Keeps the allocated memory for reuse.
166 pub fn drain(&mut self) -> Drain
<A
> {
168 inner
: self.inner
.drain(),
172 /// Gets the entry for the given type in the collection for in-place manipulation.
174 pub fn entry(&mut self, key
: TypeId
) -> Entry
<A
> {
175 match self.inner
.entry(key
) {
176 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
179 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
185 /// Returns a reference to the value corresponding to the key.
187 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
188 /// form *must* match those for the key type.
190 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&A
>
191 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
192 self.inner
.get(k
).map(|x
| &**x
)
195 /// Returns true if the map contains a value for the specified key.
197 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
198 /// form *must* match those for the key type.
200 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
201 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
202 self.inner
.contains_key(k
)
205 /// Returns a mutable reference to the value corresponding to the key.
207 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
208 /// form *must* match those for the key type.
210 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut A
>
211 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
212 self.inner
.get_mut(k
).map(|x
| &mut **x
)
215 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
216 /// that value is returned. Otherwise, None is returned.
218 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
219 /// the value. If they do not, memory safety may be violated.
221 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> {
222 self.inner
.insert(key
, value
)
225 /// Removes a key from the map, returning the value at the key if the key was previously in the
228 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
229 /// form *must* match those for the key type.
231 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>>
232 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
238 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
242 fn index(&self, index
: Q
) -> &A
{
243 self.get(&index
).expect("no entry found for key")
247 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
249 fn index_mut(&mut self, index
: Q
) -> &mut A
{
250 self.get_mut(&index
).expect("no entry found for key")
254 impl<A
: ?Sized
+ UncheckedAnyExt
> IntoIterator
for RawMap
<A
> {
256 type IntoIter
= IntoIter
<A
>;
259 fn into_iter(self) -> IntoIter
<A
> {
261 inner
: self.inner
.into_iter(),
266 /// A view into a single occupied location in a `RawMap`.
267 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
268 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
271 /// A view into a single empty location in a `RawMap`.
272 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
273 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
276 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
277 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
278 /// An occupied Entry
279 Occupied(OccupiedEntry
<'a
, A
>),
281 Vacant(VacantEntry
<'a
, A
>),
284 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Entry
<'a
, A
> {
285 /// Ensures a value is in the entry by inserting the default if empty, and returns
286 /// a mutable reference to the value in the entry.
288 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
289 /// the type ID of `value`. If they do not, memory safety may be violated.
291 pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a
mut A
{
293 Entry
::Occupied(inner
) => inner
.into_mut(),
294 Entry
::Vacant(inner
) => inner
.insert(default),
298 /// Ensures a value is in the entry by inserting the result of the default function if empty,
299 /// and returns a mutable reference to the value in the entry.
301 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
302 /// the type ID of `value`. If they do not, memory safety may be violated.
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.
334 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
335 /// the type ID of `value`. If they do not, memory safety may be violated.
337 pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> {
338 self.inner
.insert(value
)
341 /// Takes the value out of the entry, and returns it.
343 pub fn remove(self) -> Box
<A
> {
348 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> VacantEntry
<'a
, A
> {
349 /// Sets the value of the entry with the VacantEntry's key,
350 /// and returns a mutable reference to it
352 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
353 /// the type ID of `value`. If they do not, memory safety may be violated.
355 pub unsafe fn insert(self, value
: Box
<A
>) -> &'a
mut A
{
356 &mut **self.inner
.insert(value
)