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 pub use self::any
::Any
;
25 #[cfg(feature = "nightly")]
30 #[cfg_attr(feature = "clone", derive(Clone))]
31 #[cfg(feature = "nightly")]
34 #[cfg(feature = "nightly")]
35 impl HashState
for TypeIdState
{
36 type Hasher
= TypeIdHasher
;
38 fn hasher(&self) -> TypeIdHasher
{
39 TypeIdHasher
{ value
: 0 }
43 #[cfg(feature = "nightly")]
44 impl Hasher
for TypeIdHasher
{
46 fn write(&mut self, bytes
: &[u8]) {
47 // This expects to receive one and exactly one 64-bit value
48 debug_assert!(bytes
.len() == 8);
50 ptr
::copy_nonoverlapping(&mut self.value
, mem
::transmute(&bytes
[0]), 1)
55 fn finish(&self) -> u64 { self.value
}
59 /// The raw, underlying form of an AnyMap.
61 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
62 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
63 /// `AnyMap` interface instead, but there is the occasional use for this such as iteration over the
64 /// contents of an `AnyMap`. However, because you will then be dealing with `Any` trait objects, it
65 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
67 #[cfg_attr(feature = "clone", derive(Clone))]
68 pub struct RawAnyMap
{
69 #[cfg(feature = "nightly")]
70 inner
: HashMap
<TypeId
, Box
<Any
>, TypeIdState
>,
72 #[cfg(not(feature = "nightly"))]
73 inner
: HashMap
<TypeId
, Box
<Any
>>,
76 impl Default
for RawAnyMap
{
77 fn default() -> RawAnyMap
{
82 #[cfg(feature = "nightly")]
83 impl_common_methods
! {
84 field
: RawAnyMap
.inner
;
85 new() => HashMap
::with_hash_state(TypeIdState
);
86 with_capacity(capacity
) => HashMap
::with_capacity_and_hash_state(capacity
, TypeIdState
);
89 #[cfg(not(feature = "nightly"))]
90 impl_common_methods
! {
91 field
: RawAnyMap
.inner
;
92 new() => HashMap
::new();
93 with_capacity(capacity
) => HashMap
::with_capacity(capacity
);
96 /// RawAnyMap iterator.
99 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<Any
>>,
101 impl<'a
> Iterator
for Iter
<'a
> {
103 #[inline] fn next(&mut self) -> Option<&'a Any> { self.inner.next().map(|x| &**x.1) }
104 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
106 impl<'a
> ExactSizeIterator
for Iter
<'a
> {
107 #[inline] fn len(&self) -> usize { self.inner.len() }
110 /// RawAnyMap mutable iterator.
111 pub struct IterMut
<'a
> {
112 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<Any
>>,
114 impl<'a
> Iterator
for IterMut
<'a
> {
115 type Item
= &'a
mut Any
;
116 #[inline] fn next(&mut self) -> Option<&'a mut Any> { self.inner.next().map(|x| &mut **x.1) }
117 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
119 impl<'a
> ExactSizeIterator
for IterMut
<'a
> {
120 #[inline] fn len(&self) -> usize { self.inner.len() }
123 /// RawAnyMap move iterator.
124 pub struct IntoIter
{
125 inner
: hash_map
::IntoIter
<TypeId
, Box
<Any
>>,
127 impl Iterator
for IntoIter
{
128 type Item
= Box
<Any
>;
129 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
130 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
132 impl ExactSizeIterator
for IntoIter
{
133 #[inline] fn len(&self) -> usize { self.inner.len() }
136 /// RawAnyMap drain iterator.
137 #[cfg(feature = "nightly")]
138 pub struct Drain
<'a
> {
139 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<Any
>>,
141 #[cfg(feature = "nightly")]
142 impl<'a
> Iterator
for Drain
<'a
> {
143 type Item
= Box
<Any
>;
144 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
145 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
147 #[cfg(feature = "nightly")]
148 impl<'a
> ExactSizeIterator
for Drain
<'a
> {
149 #[inline] fn len(&self) -> usize { self.inner.len() }
153 /// An iterator visiting all entries in arbitrary order.
155 /// Iterator element type is `&Any`.
157 pub fn iter(&self) -> Iter
{
159 inner
: self.inner
.iter(),
163 /// An iterator visiting all entries in arbitrary order.
165 /// Iterator element type is `&mut Any`.
167 pub fn iter_mut(&mut self) -> IterMut
{
169 inner
: self.inner
.iter_mut(),
173 /// Creates a consuming iterator, that is, one that moves each item
174 /// out of the map in arbitrary order. The map cannot be used after
177 /// Iterator element type is `Box<Any>`.
179 pub fn into_iter(self) -> IntoIter
{
181 inner
: self.inner
.into_iter(),
185 /// Clears the map, returning all items as an iterator.
187 /// Iterator element type is `Box<Any>`.
189 /// Keeps the allocated memory for reuse.
191 #[cfg(feature = "nightly")]
192 pub fn drain(&mut self) -> Drain
{
194 inner
: self.inner
.drain(),
198 /// Gets the entry for the given type in the collection for in-place manipulation.
199 pub fn entry(&mut self, key
: TypeId
) -> Entry
{
200 match self.inner
.entry(key
) {
201 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
204 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
210 /// Returns a reference to the value corresponding to the key.
212 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
213 /// form *must* match those for the key type.
214 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&Any
>
215 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
216 self.inner
.get(k
).map(|x
| &**x
)
219 /// Returns true if the map contains a value for the specified key.
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.
223 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
224 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
225 self.inner
.contains_key(k
)
228 /// Returns a mutable reference to the value corresponding to the key.
230 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
231 /// form *must* match those for the key type.
232 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut Any
>
233 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
234 self.inner
.get_mut(k
).map(|x
| &mut **x
)
237 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
238 /// that value is returned. Otherwise, None is returned.
240 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
241 /// the value. If they do not, memory safety may be violated.
242 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<Any
>) -> Option
<Box
<Any
>> {
243 self.inner
.insert(key
, value
)
246 /// Removes a key from the map, returning the value at the key if the key was previously in the
249 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
250 /// form *must* match those for the key type.
251 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<Any
>>
252 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
258 impl<Q
> Index
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
261 fn index
<'a
>(&'a
self, index
: Q
) -> &'a Any
{
262 self.get(&index
).expect("no entry found for key")
266 impl<Q
> IndexMut
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
267 fn index_mut
<'a
>(&'a
mut self, index
: Q
) -> &'a
mut Any
{
268 self.get_mut(&index
).expect("no entry found for key")
272 impl IntoIterator
for RawAnyMap
{
273 type Item
= Box
<Any
>;
274 type IntoIter
= IntoIter
;
276 fn into_iter(self) -> IntoIter
{
281 /// A view into a single occupied location in a `RawAnyMap`.
282 pub struct OccupiedEntry
<'a
> {
283 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<Any
>>,
286 /// A view into a single empty location in a `RawAnyMap`.
287 pub struct VacantEntry
<'a
> {
288 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<Any
>>,
291 /// A view into a single location in an AnyMap, which may be vacant or occupied.
293 /// An occupied Entry
294 Occupied(OccupiedEntry
<'a
>),
296 Vacant(VacantEntry
<'a
>),
300 /// Ensures a value is in the entry by inserting the default if empty, and returns
301 /// a mutable reference to the value in the entry.
303 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
304 /// the type ID of `value`. If they do not, memory safety may be violated.
305 pub unsafe fn or_insert(self, default: Box
<Any
>) -> &'a
mut Any
{
307 Entry
::Occupied(inner
) => inner
.into_mut(),
308 Entry
::Vacant(inner
) => inner
.insert(default),
312 /// Ensures a value is in the entry by inserting the result of the default function if empty,
313 /// and returns a mutable reference to the value in the entry.
315 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
316 /// the type ID of `value`. If they do not, memory safety may be violated.
317 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<Any
>>(self, default: F
) -> &'a
mut Any
{
319 Entry
::Occupied(inner
) => inner
.into_mut(),
320 Entry
::Vacant(inner
) => inner
.insert(default()),
325 impl<'a
> OccupiedEntry
<'a
> {
326 /// Gets a reference to the value in the entry.
327 pub fn get(&self) -> &Any
{
331 /// Gets a mutable reference to the value in the entry.
332 pub fn get_mut(&mut self) -> &mut Any
{
333 &mut **self.inner
.get_mut()
336 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
337 /// with a lifetime bound to the collection itself.
338 pub fn into_mut(self) -> &'a
mut Any
{
339 &mut **self.inner
.into_mut()
342 /// Sets the value of the entry, and returns the entry's old value.
344 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
345 /// the type ID of `value`. If they do not, memory safety may be violated.
346 pub unsafe fn insert(&mut self, value
: Box
<Any
>) -> Box
<Any
> {
347 self.inner
.insert(value
)
350 /// Takes the value out of the entry, and returns it.
351 pub fn remove(self) -> Box
<Any
> {
356 impl<'a
> VacantEntry
<'a
> {
357 /// Sets the value of the entry with the VacantEntry's key,
358 /// and returns a mutable reference to it
360 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
361 /// the type ID of `value`. If they do not, memory safety may be violated.
362 pub unsafe fn insert(self, value
: Box
<Any
>) -> &'a
mut Any
{
363 &mut **self.inner
.insert(value
)