e75de32c5f326bc95f1507617ae2ccf06c0d404f
[anymap] / src / raw.rs
1 //! The raw form of an AnyMap, allowing untyped access.
2 //!
3 //! All relevant details are in the `RawAnyMap` struct.
4
5 use std::any::TypeId;
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;
12 use std::mem;
13 use std::ops::{Index, IndexMut};
14 use std::ptr;
15
16 #[cfg(not(feature = "clone"))]
17 pub use std::any::Any;
18 #[cfg(feature = "clone")]
19 pub use with_clone::Any;
20
21 struct TypeIdHasher {
22 value: u64,
23 }
24
25 #[cfg_attr(feature = "clone", derive(Clone))]
26 struct TypeIdState;
27
28 impl HashState for TypeIdState {
29 type Hasher = TypeIdHasher;
30
31 fn hasher(&self) -> TypeIdHasher {
32 TypeIdHasher { value: 0 }
33 }
34 }
35
36 impl Hasher for TypeIdHasher {
37 #[inline(always)]
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);
41 unsafe {
42 ptr::copy_nonoverlapping(&mut self.value, mem::transmute(&bytes[0]), 1)
43 }
44 }
45
46 #[inline(always)]
47 fn finish(&self) -> u64 { self.value }
48 }
49
50
51 /// The raw, underlying form of an AnyMap.
52 ///
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.
58 #[derive(Debug)]
59 #[cfg_attr(feature = "clone", derive(Clone))]
60 pub struct RawAnyMap {
61 inner: HashMap<TypeId, Box<Any>, TypeIdState>,
62 }
63
64 impl Default for RawAnyMap {
65 fn default() -> RawAnyMap {
66 RawAnyMap::new()
67 }
68 }
69
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);
74 }
75
76 /// RawAnyMap iterator.
77 #[derive(Clone)]
78 pub struct Iter<'a> {
79 inner: hash_map::Iter<'a, TypeId, Box<Any>>,
80 }
81 impl<'a> Iterator for Iter<'a> {
82 type Item = &'a Any;
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() }
85 }
86 impl<'a> ExactSizeIterator for Iter<'a> {
87 #[inline] fn len(&self) -> usize { self.inner.len() }
88 }
89
90 /// RawAnyMap mutable iterator.
91 pub struct IterMut<'a> {
92 inner: hash_map::IterMut<'a, TypeId, Box<Any>>,
93 }
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() }
98 }
99 impl<'a> ExactSizeIterator for IterMut<'a> {
100 #[inline] fn len(&self) -> usize { self.inner.len() }
101 }
102
103 /// RawAnyMap move iterator.
104 pub struct IntoIter {
105 inner: hash_map::IntoIter<TypeId, Box<Any>>,
106 }
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() }
111 }
112 impl ExactSizeIterator for IntoIter {
113 #[inline] fn len(&self) -> usize { self.inner.len() }
114 }
115
116 /// RawAnyMap drain iterator.
117 pub struct Drain<'a> {
118 inner: hash_map::Drain<'a, TypeId, Box<Any>>,
119 }
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() }
124 }
125 impl<'a> ExactSizeIterator for Drain<'a> {
126 #[inline] fn len(&self) -> usize { self.inner.len() }
127 }
128
129 impl RawAnyMap {
130 /// An iterator visiting all entries in arbitrary order.
131 ///
132 /// Iterator element type is `&Any`.
133 #[inline]
134 pub fn iter(&self) -> Iter {
135 Iter {
136 inner: self.inner.iter(),
137 }
138 }
139
140 /// An iterator visiting all entries in arbitrary order.
141 ///
142 /// Iterator element type is `&mut Any`.
143 #[inline]
144 pub fn iter_mut(&mut self) -> IterMut {
145 IterMut {
146 inner: self.inner.iter_mut(),
147 }
148 }
149
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
152 /// calling this.
153 ///
154 /// Iterator element type is `Box<Any>`.
155 #[inline]
156 pub fn into_iter(self) -> IntoIter {
157 IntoIter {
158 inner: self.inner.into_iter(),
159 }
160 }
161
162 /// Clears the map, returning all items as an iterator.
163 ///
164 /// Iterator element type is `Box<Any>`.
165 ///
166 /// Keeps the allocated memory for reuse.
167 #[inline]
168 pub fn drain(&mut self) -> Drain {
169 Drain {
170 inner: self.inner.drain(),
171 }
172 }
173
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 {
178 inner: e,
179 }),
180 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
181 inner: e,
182 }),
183 }
184 }
185
186 /// Returns a reference to the value corresponding to the key.
187 ///
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)
193 }
194
195 /// Returns true if the map contains a value for the specified key.
196 ///
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)
202 }
203
204 /// Returns a mutable reference to the value corresponding to the key.
205 ///
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)
211 }
212
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.
215 ///
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)
220 }
221
222 /// Removes a key from the map, returning the value at the key if the key was previously in the
223 /// map.
224 ///
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 {
229 self.inner.remove(k)
230 }
231
232 }
233
234 impl<Q> Index<Q> for RawAnyMap where TypeId: Borrow<Q>, Q: Eq + Hash {
235 type Output = Any;
236
237 fn index<'a>(&'a self, index: Q) -> &'a Any {
238 self.get(&index).expect("no entry found for key")
239 }
240 }
241
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")
245 }
246 }
247
248 impl IntoIterator for RawAnyMap {
249 type Item = Box<Any>;
250 type IntoIter = IntoIter;
251
252 fn into_iter(self) -> IntoIter {
253 self.into_iter()
254 }
255 }
256
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>>,
260 }
261
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>>,
265 }
266
267 /// A view into a single location in an AnyMap, which may be vacant or occupied.
268 pub enum Entry<'a> {
269 /// An occupied Entry
270 Occupied(OccupiedEntry<'a>),
271 /// A vacant Entry
272 Vacant(VacantEntry<'a>),
273 }
274
275 impl<'a> Entry<'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.
278 ///
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 {
282 match self {
283 Entry::Occupied(inner) => inner.into_mut(),
284 Entry::Vacant(inner) => inner.insert(default),
285 }
286 }
287
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.
290 ///
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 {
294 match self {
295 Entry::Occupied(inner) => inner.into_mut(),
296 Entry::Vacant(inner) => inner.insert(default()),
297 }
298 }
299 }
300
301 impl<'a> OccupiedEntry<'a> {
302 /// Gets a reference to the value in the entry.
303 pub fn get(&self) -> &Any {
304 &**self.inner.get()
305 }
306
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()
310 }
311
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()
316 }
317
318 /// Sets the value of the entry, and returns the entry's old value.
319 ///
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)
324 }
325
326 /// Takes the value out of the entry, and returns it.
327 pub fn remove(self) -> Box<Any> {
328 self.inner.remove()
329 }
330 }
331
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
335 ///
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)
340 }
341 }