7d537832e424fef9862570295188644663260743
[anymap] / src / raw.rs
1 //! The raw form of a `Map`, allowing untyped access.
2 //!
3 //! All relevant details are in the `RawMap` struct.
4
5 use std::any::TypeId;
6 use std::borrow::Borrow;
7 use std::collections::hash_map::{self, HashMap};
8 use std::hash::Hash;
9 use std::hash::{Hasher, BuildHasherDefault};
10 use std::mem;
11 use std::ops::{Index, IndexMut};
12 use std::ptr;
13
14 use any::{Any, UncheckedAnyExt};
15
16 #[derive(Default)]
17 struct TypeIdHasher {
18 value: u64,
19 }
20
21 impl Hasher for TypeIdHasher {
22 #[inline]
23 fn write(&mut self, bytes: &[u8]) {
24 // This expects to receive one and exactly one 64-bit value
25 debug_assert!(bytes.len() == 8);
26 unsafe {
27 ptr::copy_nonoverlapping(mem::transmute(&bytes[0]), &mut self.value, 1)
28 }
29 }
30
31 #[inline]
32 fn finish(&self) -> u64 { self.value }
33 }
34
35 #[test]
36 fn type_id_hasher() {
37 fn verify_hashing_with(type_id: TypeId) {
38 let mut hasher = TypeIdHasher::default();
39 type_id.hash(&mut hasher);
40 assert_eq!(hasher.finish(), unsafe { mem::transmute::<TypeId, u64>(type_id) });
41 }
42 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
43 verify_hashing_with(TypeId::of::<usize>());
44 verify_hashing_with(TypeId::of::<()>());
45 verify_hashing_with(TypeId::of::<str>());
46 verify_hashing_with(TypeId::of::<&str>());
47 verify_hashing_with(TypeId::of::<Vec<u8>>());
48 }
49
50 /// The raw, underlying form of a `Map`.
51 ///
52 /// At its essence, this is a wrapper around `HashMap<TypeId, Box<Any>>`, with the portions that
53 /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe
54 /// `Map` interface instead, but there is the occasional use for this such as iteration over the
55 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
56 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
57 #[derive(Debug)]
58 pub struct RawMap<A: ?Sized + UncheckedAnyExt = Any> {
59 inner: HashMap<TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
60 }
61
62 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
63 impl<A: ?Sized + UncheckedAnyExt> Clone for RawMap<A> where Box<A>: Clone {
64 #[inline]
65 fn clone(&self) -> RawMap<A> {
66 RawMap {
67 inner: self.inner.clone(),
68 }
69 }
70 }
71
72 impl<A: ?Sized + UncheckedAnyExt> Default for RawMap<A> {
73 #[inline]
74 fn default() -> RawMap<A> {
75 RawMap::new()
76 }
77 }
78
79 impl_common_methods! {
80 field: RawMap.inner;
81 new() => HashMap::with_hasher(Default::default());
82 with_capacity(capacity) => HashMap::with_capacity_and_hasher(capacity, Default::default());
83 }
84
85 /// `RawMap` iterator.
86 #[derive(Clone)]
87 pub struct Iter<'a, A: ?Sized + UncheckedAnyExt> {
88 inner: hash_map::Iter<'a, TypeId, Box<A>>,
89 }
90 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Iter<'a, A> {
91 type Item = &'a A;
92 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
93 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
94 }
95 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Iter<'a, A> {
96 #[inline] fn len(&self) -> usize { self.inner.len() }
97 }
98
99 /// `RawMap` mutable iterator.
100 pub struct IterMut<'a, A: ?Sized + UncheckedAnyExt> {
101 inner: hash_map::IterMut<'a, TypeId, Box<A>>,
102 }
103 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for IterMut<'a, A> {
104 type Item = &'a mut A;
105 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
106 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
107 }
108 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IterMut<'a, A> {
109 #[inline] fn len(&self) -> usize { self.inner.len() }
110 }
111
112 /// `RawMap` move iterator.
113 pub struct IntoIter<A: ?Sized + UncheckedAnyExt> {
114 inner: hash_map::IntoIter<TypeId, Box<A>>,
115 }
116 impl<A: ?Sized + UncheckedAnyExt> Iterator for IntoIter<A> {
117 type Item = Box<A>;
118 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
119 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
120 }
121 impl<A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IntoIter<A> {
122 #[inline] fn len(&self) -> usize { self.inner.len() }
123 }
124
125 /// `RawMap` drain iterator.
126 pub struct Drain<'a, A: ?Sized + UncheckedAnyExt> {
127 inner: hash_map::Drain<'a, TypeId, Box<A>>,
128 }
129 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Drain<'a, A> {
130 type Item = Box<A>;
131 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
132 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
133 }
134 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Drain<'a, A> {
135 #[inline] fn len(&self) -> usize { self.inner.len() }
136 }
137
138 impl<A: ?Sized + UncheckedAnyExt> RawMap<A> {
139 /// An iterator visiting all entries in arbitrary order.
140 ///
141 /// Iterator element type is `&Any`.
142 #[inline]
143 pub fn iter(&self) -> Iter<A> {
144 Iter {
145 inner: self.inner.iter(),
146 }
147 }
148
149 /// An iterator visiting all entries in arbitrary order.
150 ///
151 /// Iterator element type is `&mut Any`.
152 #[inline]
153 pub fn iter_mut(&mut self) -> IterMut<A> {
154 IterMut {
155 inner: self.inner.iter_mut(),
156 }
157 }
158
159 /// Clears the map, returning all items as an iterator.
160 ///
161 /// Iterator element type is `Box<Any>`.
162 ///
163 /// Keeps the allocated memory for reuse.
164 #[inline]
165 pub fn drain(&mut self) -> Drain<A> {
166 Drain {
167 inner: self.inner.drain(),
168 }
169 }
170
171 /// Gets the entry for the given type in the collection for in-place manipulation.
172 #[inline]
173 pub fn entry(&mut self, key: TypeId) -> Entry<A> {
174 match self.inner.entry(key) {
175 hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
176 inner: e,
177 }),
178 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
179 inner: e,
180 }),
181 }
182 }
183
184 /// Returns a reference to the value corresponding to the key.
185 ///
186 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
187 /// form *must* match those for the key type.
188 #[inline]
189 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&A>
190 where TypeId: Borrow<Q>, Q: Hash + Eq {
191 self.inner.get(k).map(|x| &**x)
192 }
193
194 /// Returns true if the map contains a value for the specified key.
195 ///
196 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
197 /// form *must* match those for the key type.
198 #[inline]
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 #[inline]
209 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut A>
210 where TypeId: Borrow<Q>, Q: Hash + Eq {
211 self.inner.get_mut(k).map(|x| &mut **x)
212 }
213
214 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
215 /// that value is returned. Otherwise, None is returned.
216 ///
217 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
218 /// the value. If they do not, memory safety may be violated.
219 #[inline]
220 pub unsafe fn insert(&mut self, key: TypeId, value: Box<A>) -> Option<Box<A>> {
221 self.inner.insert(key, value)
222 }
223
224 /// Removes a key from the map, returning the value at the key if the key was previously in the
225 /// map.
226 ///
227 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
228 /// form *must* match those for the key type.
229 #[inline]
230 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<Box<A>>
231 where TypeId: Borrow<Q>, Q: Hash + Eq {
232 self.inner.remove(k)
233 }
234
235 }
236
237 impl<A: ?Sized + UncheckedAnyExt, Q> Index<Q> for RawMap<A> where TypeId: Borrow<Q>, Q: Eq + Hash {
238 type Output = A;
239
240 #[inline]
241 fn index(&self, index: Q) -> &A {
242 self.get(&index).expect("no entry found for key")
243 }
244 }
245
246 impl<A: ?Sized + UncheckedAnyExt, Q> IndexMut<Q> for RawMap<A> where TypeId: Borrow<Q>, Q: Eq + Hash {
247 #[inline]
248 fn index_mut(&mut self, index: Q) -> &mut A {
249 self.get_mut(&index).expect("no entry found for key")
250 }
251 }
252
253 impl<A: ?Sized + UncheckedAnyExt> IntoIterator for RawMap<A> {
254 type Item = Box<A>;
255 type IntoIter = IntoIter<A>;
256
257 #[inline]
258 fn into_iter(self) -> IntoIter<A> {
259 IntoIter {
260 inner: self.inner.into_iter(),
261 }
262 }
263 }
264
265 /// A view into a single occupied location in a `RawMap`.
266 pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt> {
267 inner: hash_map::OccupiedEntry<'a, TypeId, Box<A>>,
268 }
269
270 /// A view into a single empty location in a `RawMap`.
271 pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt> {
272 inner: hash_map::VacantEntry<'a, TypeId, Box<A>>,
273 }
274
275 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
276 pub enum Entry<'a, A: ?Sized + UncheckedAnyExt> {
277 /// An occupied Entry
278 Occupied(OccupiedEntry<'a, A>),
279 /// A vacant Entry
280 Vacant(VacantEntry<'a, A>),
281 }
282
283 impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> {
284 /// Ensures a value is in the entry by inserting the default if empty, and returns
285 /// a mutable reference to the value in the entry.
286 ///
287 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
288 /// the type ID of `value`. If they do not, memory safety may be violated.
289 #[inline]
290 pub unsafe fn or_insert(self, default: Box<A>) -> &'a mut A {
291 match self {
292 Entry::Occupied(inner) => inner.into_mut(),
293 Entry::Vacant(inner) => inner.insert(default),
294 }
295 }
296
297 /// Ensures a value is in the entry by inserting the result of the default function if empty,
298 /// and returns a mutable reference to the value in the entry.
299 ///
300 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
301 /// the type ID of `value`. If they do not, memory safety may be violated.
302 #[inline]
303 pub unsafe fn or_insert_with<F: FnOnce() -> Box<A>>(self, default: F) -> &'a mut A {
304 match self {
305 Entry::Occupied(inner) => inner.into_mut(),
306 Entry::Vacant(inner) => inner.insert(default()),
307 }
308 }
309 }
310
311 impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> {
312 /// Gets a reference to the value in the entry.
313 #[inline]
314 pub fn get(&self) -> &A {
315 &**self.inner.get()
316 }
317
318 /// Gets a mutable reference to the value in the entry.
319 #[inline]
320 pub fn get_mut(&mut self) -> &mut A {
321 &mut **self.inner.get_mut()
322 }
323
324 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
325 /// with a lifetime bound to the collection itself.
326 #[inline]
327 pub fn into_mut(self) -> &'a mut A {
328 &mut **self.inner.into_mut()
329 }
330
331 /// Sets the value of the entry, and returns the entry's old value.
332 ///
333 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
334 /// the type ID of `value`. If they do not, memory safety may be violated.
335 #[inline]
336 pub unsafe fn insert(&mut self, value: Box<A>) -> Box<A> {
337 self.inner.insert(value)
338 }
339
340 /// Takes the value out of the entry, and returns it.
341 #[inline]
342 pub fn remove(self) -> Box<A> {
343 self.inner.remove()
344 }
345 }
346
347 impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> {
348 /// Sets the value of the entry with the VacantEntry's key,
349 /// and returns a mutable reference to it
350 ///
351 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
352 /// the type ID of `value`. If they do not, memory safety may be violated.
353 #[inline]
354 pub unsafe fn insert(self, value: Box<A>) -> &'a mut A {
355 &mut **self.inner.insert(value)
356 }
357 }