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