31a78e4a2d9bc780e40e6b1c05559dfb6242c991
[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(always)]
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(always)]
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 fn clone(&self) -> RawMap<A> {
65 RawMap {
66 inner: self.inner.clone(),
67 }
68 }
69 }
70
71 impl<A: ?Sized + UncheckedAnyExt> Default for RawMap<A> {
72 fn default() -> RawMap<A> {
73 RawMap::new()
74 }
75 }
76
77 impl_common_methods! {
78 field: RawMap.inner;
79 new() => HashMap::with_hasher(Default::default());
80 with_capacity(capacity) => HashMap::with_capacity_and_hasher(capacity, Default::default());
81 }
82
83 /// RawMap iterator.
84 #[derive(Clone)]
85 pub struct Iter<'a, A: ?Sized + UncheckedAnyExt> {
86 inner: hash_map::Iter<'a, TypeId, Box<A>>,
87 }
88 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Iter<'a, A> {
89 type Item = &'a A;
90 #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) }
91 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
92 }
93 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Iter<'a, A> {
94 #[inline] fn len(&self) -> usize { self.inner.len() }
95 }
96
97 /// RawMap mutable iterator.
98 pub struct IterMut<'a, A: ?Sized + UncheckedAnyExt> {
99 inner: hash_map::IterMut<'a, TypeId, Box<A>>,
100 }
101 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for IterMut<'a, A> {
102 type Item = &'a mut A;
103 #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) }
104 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
105 }
106 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IterMut<'a, A> {
107 #[inline] fn len(&self) -> usize { self.inner.len() }
108 }
109
110 /// RawMap move iterator.
111 pub struct IntoIter<A: ?Sized + UncheckedAnyExt> {
112 inner: hash_map::IntoIter<TypeId, Box<A>>,
113 }
114 impl<A: ?Sized + UncheckedAnyExt> Iterator for IntoIter<A> {
115 type Item = Box<A>;
116 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
117 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
118 }
119 impl<A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IntoIter<A> {
120 #[inline] fn len(&self) -> usize { self.inner.len() }
121 }
122
123 /// RawMap drain iterator.
124 pub struct Drain<'a, A: ?Sized + UncheckedAnyExt> {
125 inner: hash_map::Drain<'a, TypeId, Box<A>>,
126 }
127 impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Drain<'a, A> {
128 type Item = Box<A>;
129 #[inline] fn next(&mut self) -> Option<Box<A>> { self.inner.next().map(|x| x.1) }
130 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
131 }
132 impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Drain<'a, A> {
133 #[inline] fn len(&self) -> usize { self.inner.len() }
134 }
135
136 impl<A: ?Sized + UncheckedAnyExt> RawMap<A> {
137 /// An iterator visiting all entries in arbitrary order.
138 ///
139 /// Iterator element type is `&Any`.
140 #[inline]
141 pub fn iter(&self) -> Iter<A> {
142 Iter {
143 inner: self.inner.iter(),
144 }
145 }
146
147 /// An iterator visiting all entries in arbitrary order.
148 ///
149 /// Iterator element type is `&mut Any`.
150 #[inline]
151 pub fn iter_mut(&mut self) -> IterMut<A> {
152 IterMut {
153 inner: self.inner.iter_mut(),
154 }
155 }
156
157 /// Clears the map, returning all items as an iterator.
158 ///
159 /// Iterator element type is `Box<Any>`.
160 ///
161 /// Keeps the allocated memory for reuse.
162 #[inline]
163 pub fn drain(&mut self) -> Drain<A> {
164 Drain {
165 inner: self.inner.drain(),
166 }
167 }
168
169 /// Gets the entry for the given type in the collection for in-place manipulation.
170 pub fn entry(&mut self, key: TypeId) -> Entry<A> {
171 match self.inner.entry(key) {
172 hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
173 inner: e,
174 }),
175 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
176 inner: e,
177 }),
178 }
179 }
180
181 /// Returns a reference to the value corresponding to the key.
182 ///
183 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
184 /// form *must* match those for the key type.
185 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&A>
186 where TypeId: Borrow<Q>, Q: Hash + Eq {
187 self.inner.get(k).map(|x| &**x)
188 }
189
190 /// Returns true if the map contains a value for the specified key.
191 ///
192 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
193 /// form *must* match those for the key type.
194 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
195 where TypeId: Borrow<Q>, Q: Hash + Eq {
196 self.inner.contains_key(k)
197 }
198
199 /// Returns a mutable reference to the value corresponding to the key.
200 ///
201 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
202 /// form *must* match those for the key type.
203 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut A>
204 where TypeId: Borrow<Q>, Q: Hash + Eq {
205 self.inner.get_mut(k).map(|x| &mut **x)
206 }
207
208 /// Inserts a key-value pair from the map. If the key already had a value present in the map,
209 /// that value is returned. Otherwise, None is returned.
210 ///
211 /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
212 /// the value. If they do not, memory safety may be violated.
213 pub unsafe fn insert(&mut self, key: TypeId, value: Box<A>) -> Option<Box<A>> {
214 self.inner.insert(key, value)
215 }
216
217 /// Removes a key from the map, returning the value at the key if the key was previously in the
218 /// map.
219 ///
220 /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
221 /// form *must* match those for the key type.
222 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<Box<A>>
223 where TypeId: Borrow<Q>, Q: Hash + Eq {
224 self.inner.remove(k)
225 }
226
227 }
228
229 impl<A: ?Sized + UncheckedAnyExt, Q> Index<Q> for RawMap<A> where TypeId: Borrow<Q>, Q: Eq + Hash {
230 type Output = A;
231
232 fn index<'a>(&'a self, index: Q) -> &'a A {
233 self.get(&index).expect("no entry found for key")
234 }
235 }
236
237 impl<A: ?Sized + UncheckedAnyExt, Q> IndexMut<Q> for RawMap<A> where TypeId: Borrow<Q>, Q: Eq + Hash {
238 fn index_mut<'a>(&'a mut self, index: Q) -> &'a mut A {
239 self.get_mut(&index).expect("no entry found for key")
240 }
241 }
242
243 impl<A: ?Sized + UncheckedAnyExt> IntoIterator for RawMap<A> {
244 type Item = Box<A>;
245 type IntoIter = IntoIter<A>;
246
247 fn into_iter(self) -> IntoIter<A> {
248 IntoIter {
249 inner: self.inner.into_iter(),
250 }
251 }
252 }
253
254 /// A view into a single occupied location in a `RawMap`.
255 pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt> {
256 inner: hash_map::OccupiedEntry<'a, TypeId, Box<A>>,
257 }
258
259 /// A view into a single empty location in a `RawMap`.
260 pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt> {
261 inner: hash_map::VacantEntry<'a, TypeId, Box<A>>,
262 }
263
264 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
265 pub enum Entry<'a, A: ?Sized + UncheckedAnyExt> {
266 /// An occupied Entry
267 Occupied(OccupiedEntry<'a, A>),
268 /// A vacant Entry
269 Vacant(VacantEntry<'a, A>),
270 }
271
272 impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> {
273 /// Ensures a value is in the entry by inserting the default if empty, and returns
274 /// a mutable reference to the value in the entry.
275 ///
276 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
277 /// the type ID of `value`. If they do not, memory safety may be violated.
278 pub unsafe fn or_insert(self, default: Box<A>) -> &'a mut A {
279 match self {
280 Entry::Occupied(inner) => inner.into_mut(),
281 Entry::Vacant(inner) => inner.insert(default),
282 }
283 }
284
285 /// Ensures a value is in the entry by inserting the result of the default function if empty,
286 /// and returns a mutable reference to the value in the entry.
287 ///
288 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
289 /// the type ID of `value`. If they do not, memory safety may be violated.
290 pub unsafe fn or_insert_with<F: FnOnce() -> Box<A>>(self, default: F) -> &'a mut A {
291 match self {
292 Entry::Occupied(inner) => inner.into_mut(),
293 Entry::Vacant(inner) => inner.insert(default()),
294 }
295 }
296 }
297
298 impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> {
299 /// Gets a reference to the value in the entry.
300 pub fn get(&self) -> &A {
301 &**self.inner.get()
302 }
303
304 /// Gets a mutable reference to the value in the entry.
305 pub fn get_mut(&mut self) -> &mut A {
306 &mut **self.inner.get_mut()
307 }
308
309 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
310 /// with a lifetime bound to the collection itself.
311 pub fn into_mut(self) -> &'a mut A {
312 &mut **self.inner.into_mut()
313 }
314
315 /// Sets the value of the entry, and returns the entry's old value.
316 ///
317 /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
318 /// the type ID of `value`. If they do not, memory safety may be violated.
319 pub unsafe fn insert(&mut self, value: Box<A>) -> Box<A> {
320 self.inner.insert(value)
321 }
322
323 /// Takes the value out of the entry, and returns it.
324 pub fn remove(self) -> Box<A> {
325 self.inner.remove()
326 }
327 }
328
329 impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> {
330 /// Sets the value of the entry with the VacantEntry's key,
331 /// and returns a mutable reference to it
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 pub unsafe fn insert(self, value: Box<A>) -> &'a mut A {
336 &mut **self.inner.insert(value)
337 }
338 }