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