1 //! The raw form of an AnyMap, allowing untyped access.
3 //! All relevant details are in the `RawAnyMap` struct.
6 use std
::borrow
::Borrow
;
7 use std
::collections
::hash_map
::{self, HashMap
};
8 #[cfg(feature = "nightly")]
9 use std
::collections
::hash_state
::HashState
;
10 use std
::default::Default
;
12 #[cfg(feature = "nightly")]
13 use std
::hash
::Hasher
;
14 use std
::iter
::IntoIterator
;
15 #[cfg(feature = "nightly")]
17 use std
::ops
::{Index
, IndexMut
};
18 #[cfg(feature = "nightly")]
21 #[cfg(not(feature = "clone"))]
22 pub use std
::any
::Any
;
23 #[cfg(feature = "clone")]
24 pub use with_clone
::Any
;
26 #[cfg(feature = "nightly")]
31 #[cfg_attr(feature = "clone", derive(Clone))]
32 #[cfg(feature = "nightly")]
35 #[cfg(feature = "nightly")]
36 impl HashState
for TypeIdState
{
37 type Hasher
= TypeIdHasher
;
39 fn hasher(&self) -> TypeIdHasher
{
40 TypeIdHasher
{ value
: 0 }
44 #[cfg(feature = "nightly")]
45 impl Hasher
for TypeIdHasher
{
47 fn write(&mut self, bytes
: &[u8]) {
48 // This expects to receive one and exactly one 64-bit value
49 debug_assert!(bytes
.len() == 8);
51 ptr
::copy_nonoverlapping(&mut self.value
, mem
::transmute(&bytes
[0]), 1)
56 fn finish(&self) -> u64 { self.value
}
60 /// The raw, underlying form of an AnyMap.
62 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
63 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
64 /// `AnyMap` interface instead, but there is the occasional use for this such as iteration over the
65 /// contents of an `AnyMap`. However, because you will then be dealing with `Any` trait objects, it
66 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
68 #[cfg_attr(feature = "clone", derive(Clone))]
69 pub struct RawAnyMap
{
70 #[cfg(feature = "nightly")]
71 inner
: HashMap
<TypeId
, Box
<Any
>, TypeIdState
>,
73 #[cfg(not(feature = "nightly"))]
74 inner
: HashMap
<TypeId
, Box
<Any
>>,
77 impl Default
for RawAnyMap
{
78 fn default() -> RawAnyMap
{
83 #[cfg(feature = "nightly")]
84 impl_common_methods
! {
85 field
: RawAnyMap
.inner
;
86 new() => HashMap
::with_hash_state(TypeIdState
);
87 with_capacity(capacity
) => HashMap
::with_capacity_and_hash_state(capacity
, TypeIdState
);
90 #[cfg(not(feature = "nightly"))]
91 impl_common_methods
! {
92 field
: RawAnyMap
.inner
;
93 new() => HashMap
::new();
94 with_capacity(capacity
) => HashMap
::with_capacity(capacity
);
97 /// RawAnyMap iterator.
100 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<Any
>>,
102 impl<'a
> Iterator
for Iter
<'a
> {
104 #[inline] fn next(&mut self) -> Option<&'a Any> { self.inner.next().map(|x| &**x.1) }
105 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
107 impl<'a
> ExactSizeIterator
for Iter
<'a
> {
108 #[inline] fn len(&self) -> usize { self.inner.len() }
111 /// RawAnyMap mutable iterator.
112 pub struct IterMut
<'a
> {
113 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<Any
>>,
115 impl<'a
> Iterator
for IterMut
<'a
> {
116 type Item
= &'a
mut Any
;
117 #[inline] fn next(&mut self) -> Option<&'a mut Any> { self.inner.next().map(|x| &mut **x.1) }
118 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
120 impl<'a
> ExactSizeIterator
for IterMut
<'a
> {
121 #[inline] fn len(&self) -> usize { self.inner.len() }
124 /// RawAnyMap move iterator.
125 pub struct IntoIter
{
126 inner
: hash_map
::IntoIter
<TypeId
, Box
<Any
>>,
128 impl Iterator
for IntoIter
{
129 type Item
= Box
<Any
>;
130 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
131 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
133 impl ExactSizeIterator
for IntoIter
{
134 #[inline] fn len(&self) -> usize { self.inner.len() }
137 /// RawAnyMap drain iterator.
138 #[cfg(feature = "nightly")]
139 pub struct Drain
<'a
> {
140 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<Any
>>,
142 #[cfg(feature = "nightly")]
143 impl<'a
> Iterator
for Drain
<'a
> {
144 type Item
= Box
<Any
>;
145 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
146 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
148 #[cfg(feature = "nightly")]
149 impl<'a
> ExactSizeIterator
for Drain
<'a
> {
150 #[inline] fn len(&self) -> usize { self.inner.len() }
154 /// An iterator visiting all entries in arbitrary order.
156 /// Iterator element type is `&Any`.
158 pub fn iter(&self) -> Iter
{
160 inner
: self.inner
.iter(),
164 /// An iterator visiting all entries in arbitrary order.
166 /// Iterator element type is `&mut Any`.
168 pub fn iter_mut(&mut self) -> IterMut
{
170 inner
: self.inner
.iter_mut(),
174 /// Creates a consuming iterator, that is, one that moves each item
175 /// out of the map in arbitrary order. The map cannot be used after
178 /// Iterator element type is `Box<Any>`.
180 pub fn into_iter(self) -> IntoIter
{
182 inner
: self.inner
.into_iter(),
186 /// Clears the map, returning all items as an iterator.
188 /// Iterator element type is `Box<Any>`.
190 /// Keeps the allocated memory for reuse.
192 #[cfg(feature = "nightly")]
193 pub fn drain(&mut self) -> Drain
{
195 inner
: self.inner
.drain(),
199 /// Gets the entry for the given type in the collection for in-place manipulation.
200 pub fn entry(&mut self, key
: TypeId
) -> Entry
{
201 match self.inner
.entry(key
) {
202 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
205 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
211 /// Returns a reference to the value corresponding to the key.
213 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
214 /// form *must* match those for the key type.
215 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&Any
>
216 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
217 self.inner
.get(k
).map(|x
| &**x
)
220 /// Returns true if the map contains a value for the specified key.
222 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
223 /// form *must* match those for the key type.
224 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
225 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
226 self.inner
.contains_key(k
)
229 /// Returns a mutable reference to the value corresponding to the key.
231 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
232 /// form *must* match those for the key type.
233 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut Any
>
234 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
235 self.inner
.get_mut(k
).map(|x
| &mut **x
)
238 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
239 /// that value is returned. Otherwise, None is returned.
241 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
242 /// the value. If they do not, memory safety may be violated.
243 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<Any
>) -> Option
<Box
<Any
>> {
244 self.inner
.insert(key
, value
)
247 /// Removes a key from the map, returning the value at the key if the key was previously in the
250 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
251 /// form *must* match those for the key type.
252 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<Any
>>
253 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
259 impl<Q
> Index
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
262 fn index
<'a
>(&'a
self, index
: Q
) -> &'a Any
{
263 self.get(&index
).expect("no entry found for key")
267 impl<Q
> IndexMut
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
268 fn index_mut
<'a
>(&'a
mut self, index
: Q
) -> &'a
mut Any
{
269 self.get_mut(&index
).expect("no entry found for key")
273 impl IntoIterator
for RawAnyMap
{
274 type Item
= Box
<Any
>;
275 type IntoIter
= IntoIter
;
277 fn into_iter(self) -> IntoIter
{
282 /// A view into a single occupied location in a `RawAnyMap`.
283 pub struct OccupiedEntry
<'a
> {
284 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<Any
>>,
287 /// A view into a single empty location in a `RawAnyMap`.
288 pub struct VacantEntry
<'a
> {
289 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<Any
>>,
292 /// A view into a single location in an AnyMap, which may be vacant or occupied.
294 /// An occupied Entry
295 Occupied(OccupiedEntry
<'a
>),
297 Vacant(VacantEntry
<'a
>),
301 /// Ensures a value is in the entry by inserting the default if empty, and returns
302 /// a mutable reference to the value in the entry.
304 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
305 /// the type ID of `value`. If they do not, memory safety may be violated.
306 pub unsafe fn or_insert(self, default: Box
<Any
>) -> &'a
mut Any
{
308 Entry
::Occupied(inner
) => inner
.into_mut(),
309 Entry
::Vacant(inner
) => inner
.insert(default),
313 /// Ensures a value is in the entry by inserting the result of the default function if empty,
314 /// and returns a mutable reference to the value in the entry.
316 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
317 /// the type ID of `value`. If they do not, memory safety may be violated.
318 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<Any
>>(self, default: F
) -> &'a
mut Any
{
320 Entry
::Occupied(inner
) => inner
.into_mut(),
321 Entry
::Vacant(inner
) => inner
.insert(default()),
326 impl<'a
> OccupiedEntry
<'a
> {
327 /// Gets a reference to the value in the entry.
328 pub fn get(&self) -> &Any
{
332 /// Gets a mutable reference to the value in the entry.
333 pub fn get_mut(&mut self) -> &mut Any
{
334 &mut **self.inner
.get_mut()
337 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
338 /// with a lifetime bound to the collection itself.
339 pub fn into_mut(self) -> &'a
mut Any
{
340 &mut **self.inner
.into_mut()
343 /// Sets the value of the entry, and returns the entry's old value.
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.
347 pub unsafe fn insert(&mut self, value
: Box
<Any
>) -> Box
<Any
> {
348 self.inner
.insert(value
)
351 /// Takes the value out of the entry, and returns it.
352 pub fn remove(self) -> Box
<Any
> {
357 impl<'a
> VacantEntry
<'a
> {
358 /// Sets the value of the entry with the VacantEntry's key,
359 /// and returns a mutable reference to it
361 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
362 /// the type ID of `value`. If they do not, memory safety may be violated.
363 pub unsafe fn insert(self, value
: Box
<Any
>) -> &'a
mut Any
{
364 &mut **self.inner
.insert(value
)