1ae1a6c09d6e7b53bd6e60876cccaec3a83cb37e
[anymap] / src / raw / mod.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 #[cfg(feature = "nightly")]
9 use std::collections::hash_state::HashState;
10 use std::default::Default;
11 use std::hash::Hash;
12 #[cfg(feature = "nightly")]
13 use std::hash::Hasher;
14 use std::iter::IntoIterator;
15 #[cfg(feature = "nightly")]
16 use std::mem;
17 use std::ops::{Index, IndexMut};
18 #[cfg(feature = "nightly")]
19 use std::ptr;
20
21 pub use self::any::Any;
22
23 mod any;
24
25 #[cfg(feature = "nightly")]
26 struct TypeIdHasher {
27 value: u64,
28 }
29
30 #[cfg_attr(feature = "clone", derive(Clone))]
31 #[cfg(feature = "nightly")]
32 struct TypeIdState;
33
34 #[cfg(feature = "nightly")]
35 impl HashState for TypeIdState {
36 type Hasher = TypeIdHasher;
37
38 fn hasher(&self) -> TypeIdHasher {
39 TypeIdHasher { value: 0 }
40 }
41 }
42
43 #[cfg(feature = "nightly")]
44 impl Hasher for TypeIdHasher {
45 #[inline(always)]
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);
49 unsafe {
50 ptr::copy_nonoverlapping(&mut self.value, mem::transmute(&bytes[0]), 1)
51 }
52 }
53
54 #[inline(always)]
55 fn finish(&self) -> u64 { self.value }
56 }
57
58
59 /// The raw, underlying form of an AnyMap.
60 ///
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.
66 #[derive(Debug)]
67 #[cfg_attr(feature = "clone", derive(Clone))]
68 pub struct RawAnyMap {
69 #[cfg(feature = "nightly")]
70 inner: HashMap<TypeId, Box<Any>, TypeIdState>,
71
72 #[cfg(not(feature = "nightly"))]
73 inner: HashMap<TypeId, Box<Any>>,
74 }
75
76 impl Default for RawAnyMap {
77 fn default() -> RawAnyMap {
78 RawAnyMap::new()
79 }
80 }
81
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);
87 }
88
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);
94 }
95
96 /// RawAnyMap iterator.
97 #[derive(Clone)]
98 pub struct Iter<'a> {
99 inner: hash_map::Iter<'a, TypeId, Box<Any>>,
100 }
101 impl<'a> Iterator for Iter<'a> {
102 type Item = &'a Any;
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() }
105 }
106 impl<'a> ExactSizeIterator for Iter<'a> {
107 #[inline] fn len(&self) -> usize { self.inner.len() }
108 }
109
110 /// RawAnyMap mutable iterator.
111 pub struct IterMut<'a> {
112 inner: hash_map::IterMut<'a, TypeId, Box<Any>>,
113 }
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() }
118 }
119 impl<'a> ExactSizeIterator for IterMut<'a> {
120 #[inline] fn len(&self) -> usize { self.inner.len() }
121 }
122
123 /// RawAnyMap move iterator.
124 pub struct IntoIter {
125 inner: hash_map::IntoIter<TypeId, Box<Any>>,
126 }
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() }
131 }
132 impl ExactSizeIterator for IntoIter {
133 #[inline] fn len(&self) -> usize { self.inner.len() }
134 }
135
136 /// RawAnyMap drain iterator.
137 #[cfg(feature = "nightly")]
138 pub struct Drain<'a> {
139 inner: hash_map::Drain<'a, TypeId, Box<Any>>,
140 }
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() }
146 }
147 #[cfg(feature = "nightly")]
148 impl<'a> ExactSizeIterator for Drain<'a> {
149 #[inline] fn len(&self) -> usize { self.inner.len() }
150 }
151
152 impl RawAnyMap {
153 /// An iterator visiting all entries in arbitrary order.
154 ///
155 /// Iterator element type is `&Any`.
156 #[inline]
157 pub fn iter(&self) -> Iter {
158 Iter {
159 inner: self.inner.iter(),
160 }
161 }
162
163 /// An iterator visiting all entries in arbitrary order.
164 ///
165 /// Iterator element type is `&mut Any`.
166 #[inline]
167 pub fn iter_mut(&mut self) -> IterMut {
168 IterMut {
169 inner: self.inner.iter_mut(),
170 }
171 }
172
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
175 /// calling this.
176 ///
177 /// Iterator element type is `Box<Any>`.
178 #[inline]
179 pub fn into_iter(self) -> IntoIter {
180 IntoIter {
181 inner: self.inner.into_iter(),
182 }
183 }
184
185 /// Clears the map, returning all items as an iterator.
186 ///
187 /// Iterator element type is `Box<Any>`.
188 ///
189 /// Keeps the allocated memory for reuse.
190 #[inline]
191 #[cfg(feature = "nightly")]
192 pub fn drain(&mut self) -> Drain {
193 Drain {
194 inner: self.inner.drain(),
195 }
196 }
197
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 {
202 inner: e,
203 }),
204 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
205 inner: e,
206 }),
207 }
208 }
209
210 /// Returns a reference to the value corresponding to the key.
211 ///
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)
217 }
218
219 /// Returns true if the map contains a value for the specified key.
220 ///
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)
226 }
227
228 /// Returns a mutable reference to the value corresponding to the key.
229 ///
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)
235 }
236
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.
239 ///
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)
244 }
245
246 /// Removes a key from the map, returning the value at the key if the key was previously in the
247 /// map.
248 ///
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 {
253 self.inner.remove(k)
254 }
255
256 }
257
258 impl<Q> Index<Q> for RawAnyMap where TypeId: Borrow<Q>, Q: Eq + Hash {
259 type Output = Any;
260
261 fn index<'a>(&'a self, index: Q) -> &'a Any {
262 self.get(&index).expect("no entry found for key")
263 }
264 }
265
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")
269 }
270 }
271
272 impl IntoIterator for RawAnyMap {
273 type Item = Box<Any>;
274 type IntoIter = IntoIter;
275
276 fn into_iter(self) -> IntoIter {
277 self.into_iter()
278 }
279 }
280
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>>,
284 }
285
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>>,
289 }
290
291 /// A view into a single location in an AnyMap, which may be vacant or occupied.
292 pub enum Entry<'a> {
293 /// An occupied Entry
294 Occupied(OccupiedEntry<'a>),
295 /// A vacant Entry
296 Vacant(VacantEntry<'a>),
297 }
298
299 impl<'a> Entry<'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.
302 ///
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 {
306 match self {
307 Entry::Occupied(inner) => inner.into_mut(),
308 Entry::Vacant(inner) => inner.insert(default),
309 }
310 }
311
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.
314 ///
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 {
318 match self {
319 Entry::Occupied(inner) => inner.into_mut(),
320 Entry::Vacant(inner) => inner.insert(default()),
321 }
322 }
323 }
324
325 impl<'a> OccupiedEntry<'a> {
326 /// Gets a reference to the value in the entry.
327 pub fn get(&self) -> &Any {
328 &**self.inner.get()
329 }
330
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()
334 }
335
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()
340 }
341
342 /// Sets the value of the entry, and returns the entry's old value.
343 ///
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)
348 }
349
350 /// Takes the value out of the entry, and returns it.
351 pub fn remove(self) -> Box<Any> {
352 self.inner.remove()
353 }
354 }
355
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
359 ///
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)
364 }
365 }