7d537832e424fef9862570295188644663260743
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
};
11 use std
::ops
::{Index
, IndexMut
};
14 use any
::{Any
, UncheckedAnyExt
};
21 impl Hasher
for TypeIdHasher
{
23 fn write(&mut self, bytes
: &[u8]) {
24 // This expects to receive one and exactly one 64-bit value
25 debug_assert!(bytes
.len() == 8);
27 ptr
::copy_nonoverlapping(mem
::transmute(&bytes
[0]), &mut self.value
, 1)
32 fn finish(&self) -> u64 { self.value
}
37 fn verify_hashing_with(type_id
: TypeId
) {
38 let mut hasher
= TypeIdHasher
::default();
39 type_id
.hash(&mut hasher
);
40 assert_eq!(hasher
.finish(), unsafe { mem
::transmute
::<TypeId
, u64>(type_id
) });
42 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
43 verify_hashing_with(TypeId
::of
::<usize>());
44 verify_hashing_with(TypeId
::of
::<()>());
45 verify_hashing_with(TypeId
::of
::<str>());
46 verify_hashing_with(TypeId
::of
::<&str>());
47 verify_hashing_with(TypeId
::of
::<Vec
<u8>>());
50 /// The raw, underlying form of a `Map`.
52 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
53 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
54 /// `Map` interface instead, but there is the occasional use for this such as iteration over the
55 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
56 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
58 pub struct RawMap
<A
: ?Sized
+ UncheckedAnyExt
= Any
> {
59 inner
: HashMap
<TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>,
62 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
63 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for RawMap
<A
> where Box
<A
>: Clone
{
65 fn clone(&self) -> RawMap
<A
> {
67 inner
: self.inner
.clone(),
72 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for RawMap
<A
> {
74 fn default() -> RawMap
<A
> {
79 impl_common_methods
! {
81 new() => HashMap
::with_hasher(Default
::default());
82 with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default());
85 /// `RawMap` iterator.
87 pub struct Iter
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
88 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>,
90 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Iter
<'a
, A
> {
92 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
93 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
95 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Iter
<'a
, A
> {
96 #[inline] fn len(&self) -> usize { self.inner.len() }
99 /// `RawMap` mutable iterator.
100 pub struct IterMut
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
101 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>,
103 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IterMut
<'a
, A
> {
104 type Item
= &'a
mut A
;
105 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
106 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
108 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IterMut
<'a
, A
> {
109 #[inline] fn len(&self) -> usize { self.inner.len() }
112 /// `RawMap` move iterator.
113 pub struct IntoIter
<A
: ?Sized
+ UncheckedAnyExt
> {
114 inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>,
116 impl<A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IntoIter
<A
> {
118 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
119 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
121 impl<A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IntoIter
<A
> {
122 #[inline] fn len(&self) -> usize { self.inner.len() }
125 /// `RawMap` drain iterator.
126 pub struct Drain
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
127 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>,
129 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Drain
<'a
, A
> {
131 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
132 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
134 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Drain
<'a
, A
> {
135 #[inline] fn len(&self) -> usize { self.inner.len() }
138 impl<A
: ?Sized
+ UncheckedAnyExt
> RawMap
<A
> {
139 /// An iterator visiting all entries in arbitrary order.
141 /// Iterator element type is `&Any`.
143 pub fn iter(&self) -> Iter
<A
> {
145 inner
: self.inner
.iter(),
149 /// An iterator visiting all entries in arbitrary order.
151 /// Iterator element type is `&mut Any`.
153 pub fn iter_mut(&mut self) -> IterMut
<A
> {
155 inner
: self.inner
.iter_mut(),
159 /// Clears the map, returning all items as an iterator.
161 /// Iterator element type is `Box<Any>`.
163 /// Keeps the allocated memory for reuse.
165 pub fn drain(&mut self) -> Drain
<A
> {
167 inner
: self.inner
.drain(),
171 /// Gets the entry for the given type in the collection for in-place manipulation.
173 pub fn entry(&mut self, key
: TypeId
) -> Entry
<A
> {
174 match self.inner
.entry(key
) {
175 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
178 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
184 /// Returns a reference to the value corresponding to the key.
186 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
187 /// form *must* match those for the key type.
189 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&A
>
190 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
191 self.inner
.get(k
).map(|x
| &**x
)
194 /// Returns true if the map contains a value for the specified key.
196 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
197 /// form *must* match those for the key type.
199 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
200 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
201 self.inner
.contains_key(k
)
204 /// Returns a mutable reference to the value corresponding to the key.
206 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
207 /// form *must* match those for the key type.
209 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut A
>
210 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
211 self.inner
.get_mut(k
).map(|x
| &mut **x
)
214 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
215 /// that value is returned. Otherwise, None is returned.
217 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
218 /// the value. If they do not, memory safety may be violated.
220 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> {
221 self.inner
.insert(key
, value
)
224 /// Removes a key from the map, returning the value at the key if the key was previously in the
227 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
228 /// form *must* match those for the key type.
230 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>>
231 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
237 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
241 fn index(&self, index
: Q
) -> &A
{
242 self.get(&index
).expect("no entry found for key")
246 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
248 fn index_mut(&mut self, index
: Q
) -> &mut A
{
249 self.get_mut(&index
).expect("no entry found for key")
253 impl<A
: ?Sized
+ UncheckedAnyExt
> IntoIterator
for RawMap
<A
> {
255 type IntoIter
= IntoIter
<A
>;
258 fn into_iter(self) -> IntoIter
<A
> {
260 inner
: self.inner
.into_iter(),
265 /// A view into a single occupied location in a `RawMap`.
266 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
267 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
270 /// A view into a single empty location in a `RawMap`.
271 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
272 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
275 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
276 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
277 /// An occupied Entry
278 Occupied(OccupiedEntry
<'a
, A
>),
280 Vacant(VacantEntry
<'a
, A
>),
283 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Entry
<'a
, A
> {
284 /// Ensures a value is in the entry by inserting the default if empty, and returns
285 /// a mutable reference to the value in the entry.
287 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
288 /// the type ID of `value`. If they do not, memory safety may be violated.
290 pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a
mut A
{
292 Entry
::Occupied(inner
) => inner
.into_mut(),
293 Entry
::Vacant(inner
) => inner
.insert(default),
297 /// Ensures a value is in the entry by inserting the result of the default function if empty,
298 /// and returns a mutable reference to the value in the entry.
300 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
301 /// the type ID of `value`. If they do not, memory safety may be violated.
303 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<A
>>(self, default: F
) -> &'a
mut A
{
305 Entry
::Occupied(inner
) => inner
.into_mut(),
306 Entry
::Vacant(inner
) => inner
.insert(default()),
311 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> OccupiedEntry
<'a
, A
> {
312 /// Gets a reference to the value in the entry.
314 pub fn get(&self) -> &A
{
318 /// Gets a mutable reference to the value in the entry.
320 pub fn get_mut(&mut self) -> &mut A
{
321 &mut **self.inner
.get_mut()
324 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
325 /// with a lifetime bound to the collection itself.
327 pub fn into_mut(self) -> &'a
mut A
{
328 &mut **self.inner
.into_mut()
331 /// Sets the value of the entry, and returns the entry's old value.
333 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
334 /// the type ID of `value`. If they do not, memory safety may be violated.
336 pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> {
337 self.inner
.insert(value
)
340 /// Takes the value out of the entry, and returns it.
342 pub fn remove(self) -> Box
<A
> {
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
351 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
352 /// the type ID of `value`. If they do not, memory safety may be violated.
354 pub unsafe fn insert(self, value
: Box
<A
>) -> &'a
mut A
{
355 &mut **self.inner
.insert(value
)