dbd5e2cb120e2bf8700754ed87dfa925e7853da1
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
};
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 assert!(bytes
.len() == 8);
26 self.value
= u64::from(bytes
[0]) | u64::from(bytes
[1]) << 8 |
27 u64::from(bytes
[2]) << 16 | u64::from(bytes
[3]) << 24 |
28 u64::from(bytes
[4]) << 32 | u64::from(bytes
[5]) << 40 |
29 u64::from(bytes
[6]) << 48 | u64::from(bytes
[7]) << 56;
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_common_methods
! {
75 new() => HashMap
::with_hasher(Default
::default());
76 with_capacity(capacity
) => HashMap
::with_capacity_and_hasher(capacity
, Default
::default());
79 /// `RawMap` iterator.
81 pub struct Iter
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
82 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<A
>>,
84 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Iter
<'a
, A
> {
86 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
87 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
89 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Iter
<'a
, A
> {
90 #[inline] fn len(&self) -> usize { self.inner.len() }
93 /// `RawMap` mutable iterator.
94 pub struct IterMut
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
95 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<A
>>,
97 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IterMut
<'a
, A
> {
98 type Item
= &'a
mut A
;
99 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
100 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
102 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IterMut
<'a
, A
> {
103 #[inline] fn len(&self) -> usize { self.inner.len() }
106 /// `RawMap` move iterator.
107 pub struct IntoIter
<A
: ?Sized
+ UncheckedAnyExt
> {
108 inner
: hash_map
::IntoIter
<TypeId
, Box
<A
>>,
110 impl<A
: ?Sized
+ UncheckedAnyExt
> Iterator
for IntoIter
<A
> {
112 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
113 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
115 impl<A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for IntoIter
<A
> {
116 #[inline] fn len(&self) -> usize { self.inner.len() }
119 /// `RawMap` drain iterator.
120 pub struct Drain
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
121 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<A
>>,
123 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Iterator
for Drain
<'a
, A
> {
125 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
126 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
128 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> ExactSizeIterator
for Drain
<'a
, A
> {
129 #[inline] fn len(&self) -> usize { self.inner.len() }
132 impl<A
: ?Sized
+ UncheckedAnyExt
> RawMap
<A
> {
133 /// An iterator visiting all entries in arbitrary order.
135 /// Iterator element type is `&Any`.
137 pub fn iter(&self) -> Iter
<A
> {
139 inner
: self.inner
.iter(),
143 /// An iterator visiting all entries in arbitrary order.
145 /// Iterator element type is `&mut Any`.
147 pub fn iter_mut(&mut self) -> IterMut
<A
> {
149 inner
: self.inner
.iter_mut(),
153 /// Clears the map, returning all items as an iterator.
155 /// Iterator element type is `Box<Any>`.
157 /// Keeps the allocated memory for reuse.
159 pub fn drain(&mut self) -> Drain
<A
> {
161 inner
: self.inner
.drain(),
165 /// Gets the entry for the given type in the collection for in-place manipulation.
167 pub fn entry(&mut self, key
: TypeId
) -> Entry
<A
> {
168 match self.inner
.entry(key
) {
169 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
172 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
178 /// Returns a reference to the value corresponding to the key.
180 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
181 /// form *must* match those for the key type.
183 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&A
>
184 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
185 self.inner
.get(k
).map(|x
| &**x
)
188 /// Returns true if the map contains a value for the specified key.
190 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
191 /// form *must* match those for the key type.
193 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
194 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
195 self.inner
.contains_key(k
)
198 /// Returns a mutable reference to the value corresponding to the key.
200 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
201 /// 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.
214 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<A
>) -> Option
<Box
<A
>> {
215 self.inner
.insert(key
, value
)
218 /// Removes a key from the map, returning the value at the key if the key was previously in the
221 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
222 /// form *must* match those for the key type.
224 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<A
>>
225 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
231 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> Index
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
235 fn index(&self, index
: Q
) -> &A
{
236 self.get(&index
).expect("no entry found for key")
240 impl<A
: ?Sized
+ UncheckedAnyExt
, Q
> IndexMut
<Q
> for RawMap
<A
> where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
242 fn index_mut(&mut self, index
: Q
) -> &mut A
{
243 self.get_mut(&index
).expect("no entry found for key")
247 impl<A
: ?Sized
+ UncheckedAnyExt
> IntoIterator
for RawMap
<A
> {
249 type IntoIter
= IntoIter
<A
>;
252 fn into_iter(self) -> IntoIter
<A
> {
254 inner
: self.inner
.into_iter(),
259 /// A view into a single occupied location in a `RawMap`.
260 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
261 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
264 /// A view into a single empty location in a `RawMap`.
265 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
266 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
269 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
270 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
> {
271 /// An occupied Entry
272 Occupied(OccupiedEntry
<'a
, A
>),
274 Vacant(VacantEntry
<'a
, A
>),
277 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> Entry
<'a
, A
> {
278 /// Ensures a value is in the entry by inserting the default if empty, and returns
279 /// a mutable reference to the value in the entry.
281 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
282 /// the type ID of `value`. If they do not, memory safety may be violated.
284 pub unsafe fn or_insert(self, default: Box
<A
>) -> &'a
mut A
{
286 Entry
::Occupied(inner
) => inner
.into_mut(),
287 Entry
::Vacant(inner
) => inner
.insert(default),
291 /// Ensures a value is in the entry by inserting the result of the default function if empty,
292 /// and returns a mutable reference to the value in the entry.
294 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
295 /// the type ID of `value`. If they do not, memory safety may be violated.
297 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<A
>>(self, default: F
) -> &'a
mut A
{
299 Entry
::Occupied(inner
) => inner
.into_mut(),
300 Entry
::Vacant(inner
) => inner
.insert(default()),
305 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> OccupiedEntry
<'a
, A
> {
306 /// Gets a reference to the value in the entry.
308 pub fn get(&self) -> &A
{
312 /// Gets a mutable reference to the value in the entry.
314 pub fn get_mut(&mut self) -> &mut A
{
315 &mut **self.inner
.get_mut()
318 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
319 /// with a lifetime bound to the collection itself.
321 pub fn into_mut(self) -> &'a
mut A
{
322 &mut **self.inner
.into_mut()
325 /// Sets the value of the entry, and returns the entry's old value.
327 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
328 /// the type ID of `value`. If they do not, memory safety may be violated.
330 pub unsafe fn insert(&mut self, value
: Box
<A
>) -> Box
<A
> {
331 self.inner
.insert(value
)
334 /// Takes the value out of the entry, and returns it.
336 pub fn remove(self) -> Box
<A
> {
341 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
> VacantEntry
<'a
, A
> {
342 /// Sets the value of the entry with the VacantEntry's key,
343 /// and returns a mutable reference to it
345 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
346 /// the type ID of `value`. If they do not, memory safety may be violated.
348 pub unsafe fn insert(self, value
: Box
<A
>) -> &'a
mut A
{
349 &mut **self.inner
.insert(value
)