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