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 use std
::collections
::hash_state
::HashState
;
9 use std
::default::Default
;
10 use std
::hash
::{Hash
, Hasher
};
11 use std
::iter
::IntoIterator
;
13 use std
::ops
::{Index
, IndexMut
};
16 #[cfg(not(feature = "clone"))]
17 pub use std
::any
::Any
;
18 #[cfg(feature = "clone")]
19 pub use with_clone
::Any
;
25 #[cfg_attr(feature = "clone", derive(Clone))]
28 impl HashState
for TypeIdState
{
29 type Hasher
= TypeIdHasher
;
31 fn hasher(&self) -> TypeIdHasher
{
32 TypeIdHasher
{ value
: 0 }
36 impl Hasher
for TypeIdHasher
{
38 fn write(&mut self, bytes
: &[u8]) {
39 // This expects to receive one and exactly one 64-bit value
40 debug_assert!(bytes
.len() == 8);
42 ptr
::copy_nonoverlapping(&mut self.value
, mem
::transmute(&bytes
[0]), 1)
47 fn finish(&self) -> u64 { self.value
}
51 /// The raw, underlying form of an AnyMap.
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 /// `AnyMap` interface instead, but there is the occasional use for this such as iteration over the
56 /// contents of an `AnyMap`. 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 #[cfg_attr(feature = "clone", derive(Clone))]
60 pub struct RawAnyMap
{
61 inner
: HashMap
<TypeId
, Box
<Any
>, TypeIdState
>,
64 impl Default
for RawAnyMap
{
65 fn default() -> RawAnyMap
{
70 impl_common_methods
! {
71 field
: RawAnyMap
.inner
;
72 new() => HashMap
::with_hash_state(TypeIdState
);
73 with_capacity(capacity
) => HashMap
::with_capacity_and_hash_state(capacity
, TypeIdState
);
76 /// RawAnyMap iterator.
79 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<Any
>>,
81 impl<'a
> Iterator
for Iter
<'a
> {
83 #[inline] fn next(&mut self) -> Option<&'a Any> { self.inner.next().map(|x| &**x.1) }
84 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
86 impl<'a
> ExactSizeIterator
for Iter
<'a
> {
87 #[inline] fn len(&self) -> usize { self.inner.len() }
90 /// RawAnyMap mutable iterator.
91 pub struct IterMut
<'a
> {
92 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<Any
>>,
94 impl<'a
> Iterator
for IterMut
<'a
> {
95 type Item
= &'a
mut Any
;
96 #[inline] fn next(&mut self) -> Option<&'a mut Any> { self.inner.next().map(|x| &mut **x.1) }
97 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
99 impl<'a
> ExactSizeIterator
for IterMut
<'a
> {
100 #[inline] fn len(&self) -> usize { self.inner.len() }
103 /// RawAnyMap move iterator.
104 pub struct IntoIter
{
105 inner
: hash_map
::IntoIter
<TypeId
, Box
<Any
>>,
107 impl Iterator
for IntoIter
{
108 type Item
= Box
<Any
>;
109 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
110 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
112 impl ExactSizeIterator
for IntoIter
{
113 #[inline] fn len(&self) -> usize { self.inner.len() }
116 /// RawAnyMap drain iterator.
117 pub struct Drain
<'a
> {
118 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<Any
>>,
120 impl<'a
> Iterator
for Drain
<'a
> {
121 type Item
= Box
<Any
>;
122 #[inline] fn next(&mut self) -> Option<Box<Any>> { self.inner.next().map(|x| x.1) }
123 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
125 impl<'a
> ExactSizeIterator
for Drain
<'a
> {
126 #[inline] fn len(&self) -> usize { self.inner.len() }
130 /// An iterator visiting all entries in arbitrary order.
132 /// Iterator element type is `&Any`.
134 pub fn iter(&self) -> Iter
{
136 inner
: self.inner
.iter(),
140 /// An iterator visiting all entries in arbitrary order.
142 /// Iterator element type is `&mut Any`.
144 pub fn iter_mut(&mut self) -> IterMut
{
146 inner
: self.inner
.iter_mut(),
150 /// Creates a consuming iterator, that is, one that moves each item
151 /// out of the map in arbitrary order. The map cannot be used after
154 /// Iterator element type is `Box<Any>`.
156 pub fn into_iter(self) -> IntoIter
{
158 inner
: self.inner
.into_iter(),
162 /// Clears the map, returning all items as an iterator.
164 /// Iterator element type is `Box<Any>`.
166 /// Keeps the allocated memory for reuse.
168 pub fn drain(&mut self) -> Drain
{
170 inner
: self.inner
.drain(),
174 /// Gets the entry for the given type in the collection for in-place manipulation.
175 pub fn entry(&mut self, key
: TypeId
) -> Entry
{
176 match self.inner
.entry(key
) {
177 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
180 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
186 /// Returns a reference to the value corresponding to the key.
188 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
189 /// form *must* match those for the key type.
190 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&Any
>
191 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
192 self.inner
.get(k
).map(|x
| &**x
)
195 /// Returns true if the map contains a value for the specified key.
197 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
198 /// 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.
208 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut Any
>
209 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
210 self.inner
.get_mut(k
).map(|x
| &mut **x
)
213 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
214 /// that value is returned. Otherwise, None is returned.
216 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
217 /// the value. If they do not, memory safety may be violated.
218 pub unsafe fn insert(&mut self, key
: TypeId
, value
: Box
<Any
>) -> Option
<Box
<Any
>> {
219 self.inner
.insert(key
, value
)
222 /// Removes a key from the map, returning the value at the key if the key was previously in the
225 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
226 /// form *must* match those for the key type.
227 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<Box
<Any
>>
228 where TypeId
: Borrow
<Q
>, Q
: Hash
+ Eq
{
234 impl<Q
> Index
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
237 fn index
<'a
>(&'a
self, index
: Q
) -> &'a Any
{
238 self.get(&index
).expect("no entry found for key")
242 impl<Q
> IndexMut
<Q
> for RawAnyMap
where TypeId
: Borrow
<Q
>, Q
: Eq
+ Hash
{
243 fn index_mut
<'a
>(&'a
mut self, index
: Q
) -> &'a
mut Any
{
244 self.get_mut(&index
).expect("no entry found for key")
248 impl IntoIterator
for RawAnyMap
{
249 type Item
= Box
<Any
>;
250 type IntoIter
= IntoIter
;
252 fn into_iter(self) -> IntoIter
{
257 /// A view into a single occupied location in a `RawAnyMap`.
258 pub struct OccupiedEntry
<'a
> {
259 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<Any
>>,
262 /// A view into a single empty location in a `RawAnyMap`.
263 pub struct VacantEntry
<'a
> {
264 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<Any
>>,
267 /// A view into a single location in an AnyMap, which may be vacant or occupied.
269 /// An occupied Entry
270 Occupied(OccupiedEntry
<'a
>),
272 Vacant(VacantEntry
<'a
>),
276 /// Ensures a value is in the entry by inserting the default if empty, and returns
277 /// a mutable reference to the value in the entry.
279 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
280 /// the type ID of `value`. If they do not, memory safety may be violated.
281 pub unsafe fn or_insert(self, default: Box
<Any
>) -> &'a
mut Any
{
283 Entry
::Occupied(inner
) => inner
.into_mut(),
284 Entry
::Vacant(inner
) => inner
.insert(default),
288 /// Ensures a value is in the entry by inserting the result of the default function if empty,
289 /// and returns a mutable reference to the value in the entry.
291 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
292 /// the type ID of `value`. If they do not, memory safety may be violated.
293 pub unsafe fn or_insert_with
<F
: FnOnce() -> Box
<Any
>>(self, default: F
) -> &'a
mut Any
{
295 Entry
::Occupied(inner
) => inner
.into_mut(),
296 Entry
::Vacant(inner
) => inner
.insert(default()),
301 impl<'a
> OccupiedEntry
<'a
> {
302 /// Gets a reference to the value in the entry.
303 pub fn get(&self) -> &Any
{
307 /// Gets a mutable reference to the value in the entry.
308 pub fn get_mut(&mut self) -> &mut Any
{
309 &mut **self.inner
.get_mut()
312 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
313 /// with a lifetime bound to the collection itself.
314 pub fn into_mut(self) -> &'a
mut Any
{
315 &mut **self.inner
.into_mut()
318 /// Sets the value of the entry, and returns the entry's old value.
320 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
321 /// the type ID of `value`. If they do not, memory safety may be violated.
322 pub unsafe fn insert(&mut self, value
: Box
<Any
>) -> Box
<Any
> {
323 self.inner
.insert(value
)
326 /// Takes the value out of the entry, and returns it.
327 pub fn remove(self) -> Box
<Any
> {
332 impl<'a
> VacantEntry
<'a
> {
333 /// Sets the value of the entry with the VacantEntry's key,
334 /// and returns a mutable reference to it
336 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
337 /// the type ID of `value`. If they do not, memory safety may be violated.
338 pub unsafe fn insert(self, value
: Box
<Any
>) -> &'a
mut Any
{
339 &mut **self.inner
.insert(value
)