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