b103bd7f96b3c1eaf4d21bd28fefc6da81214953
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
{
64 fn clone(&self) -> RawMap
<A
> {
66 inner
: self.inner
.clone(),
71 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for RawMap
<A
> {
72 fn default() -> RawMap
<A
> {
77 impl_common_methods
! {
79 new() => HashMap
::with_hasher(Default
::default());
80 with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default());
85 pub struct Iter
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
86 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>,
88 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Iter
<'a
, A
> {
90 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
91 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
93 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Iter
<'a
, A
> {
94 #[inline] fn len(&self) -> usize { self.inner.len() }
97 /// RawMap mutable iterator.
98 pub struct IterMut
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
99 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>,
101 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IterMut
<'a
, A
> {
102 type Item
= &'a
mut A
;
103 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
104 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
106 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IterMut
<'a
, A
> {
107 #[inline] fn len(&self) -> usize { self.inner.len() }
110 /// RawMap move iterator.
111 pub struct IntoIter
<A
: ?Sized
+ UncheckedAnyExt
> {
112 inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>,
114 impl<A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IntoIter
<A
> {
116 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
117 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
119 impl<A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IntoIter
<A
> {
120 #[inline] fn len(&self) -> usize { self.inner.len() }
123 /// RawMap drain iterator.
124 pub struct Drain
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
125 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>,
127 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Drain
<'a
, A
> {
129 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
130 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
132 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Drain
<'a
, A
> {
133 #[inline] fn len(&self) -> usize { self.inner.len() }
136 impl<A
: ?Sized
+ UncheckedAnyExt
> RawMap
<A
> {
137 /// An iterator visiting all entries in arbitrary order.
139 /// Iterator element type is `&Any`.
141 pub fn iter(&self) -> Iter
<A
> {
143 inner
: self.inner
.iter(),
147 /// An iterator visiting all entries in arbitrary order.
149 /// Iterator element type is `&mut Any`.
151 pub fn iter_mut(&mut self) -> IterMut
<A
> {
153 inner
: self.inner
.iter_mut(),
157 /// Clears the map, returning all items as an iterator.
159 /// Iterator element type is `Box<Any>`.
161 /// Keeps the allocated memory for reuse.
163 pub fn drain(&mut self) -> Drain
<A
> {
165 inner
: self.inner
.drain(),
169 /// 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.
185 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&A
>
186 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
187 self.inner
.get(k
).map(|x
| &**x
)
190 /// Returns true if the map contains a value for the specified key.
192 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
193 /// form *must* match those for the key type.
194 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
195 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
196 self.inner
.contains_key(k
)
199 /// Returns a mutable reference to the value corresponding to the key.
201 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
202 /// form *must* match those for the key type.
203 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut A
>
204 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
205 self.inner
.get_mut(k
).map(|x
| &mut **x
)
208 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
209 /// that value is returned. Otherwise, None is returned.
211 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
212 /// the value. If they do not, memory safety may be violated.
213 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> {
214 self.inner
.insert(key
, value
)
217 /// Removes a key from the map, returning the value at the key if the key was previously in the
220 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
221 /// form *must* match those for the key type.
222 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>>
223 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
229 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
232 fn index(&self, index
: Q
) -> &A
{
233 self.get(&index
).expect("no entry found for key")
237 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
238 fn index_mut(&mut self, index
: Q
) -> &mut A
{
239 self.get_mut(&index
).expect("no entry found for key")
243 impl<A
: ?Sized
+ UncheckedAnyExt
> IntoIterator
for RawMap
<A
> {
245 type IntoIter
= IntoIter
<A
>;
247 fn into_iter(self) -> IntoIter
<A
> {
249 inner
: self.inner
.into_iter(),
254 /// A view into a single occupied location in a `RawMap`.
255 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
256 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
259 /// A view into a single empty location in a `RawMap`.
260 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
261 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
264 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
265 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
266 /// An occupied Entry
267 Occupied(OccupiedEntry
<'a
, A
>),
269 Vacant(VacantEntry
<'a
, A
>),
272 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Entry
<'a
, A
> {
273 /// Ensures a value is in the entry by inserting the default if empty, and returns
274 /// a mutable reference to the value in the entry.
276 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
277 /// the type ID of `value`. If they do not, memory safety may be violated.
278 pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a
mut A
{
280 Entry
::Occupied(inner
) => inner
.into_mut(),
281 Entry
::Vacant(inner
) => inner
.insert(default),
285 /// Ensures a value is in the entry by inserting the result of the default function if empty,
286 /// and returns 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.
290 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<A
>>(self, default: F
) -> &'a
mut A
{
292 Entry
::Occupied(inner
) => inner
.into_mut(),
293 Entry
::Vacant(inner
) => inner
.insert(default()),
298 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> OccupiedEntry
<'a
, A
> {
299 /// Gets a reference to the value in the entry.
300 pub fn get(&self) -> &A
{
304 /// Gets a mutable reference to the value in the entry.
305 pub fn get_mut(&mut self) -> &mut A
{
306 &mut **self.inner
.get_mut()
309 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
310 /// with a lifetime bound to the collection itself.
311 pub fn into_mut(self) -> &'a
mut A
{
312 &mut **self.inner
.into_mut()
315 /// Sets the value of the entry, and returns the entry's old value.
317 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
318 /// the type ID of `value`. If they do not, memory safety may be violated.
319 pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> {
320 self.inner
.insert(value
)
323 /// Takes the value out of the entry, and returns it.
324 pub fn remove(self) -> Box
<A
> {
329 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> VacantEntry
<'a
, A
> {
330 /// Sets the value of the entry with the VacantEntry's key,
331 /// and returns a mutable reference to it
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.
335 pub unsafe fn insert(self, value
: Box
<A
>) -> &'a
mut A
{
336 &mut **self.inner
.insert(value
)