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