5095829c44b43c315b5b4b24f5edda691be4e9ab
[anymap] / src / lib.rs
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
2
3 #![cfg_attr(feature = "unstable", feature(drain, hashmap_hasher, raw))]
4 #![cfg_attr(all(feature = "unstable", test), feature(test))]
5 #![warn(missing_docs, unused_results)]
6
7 #[cfg(all(feature = "unstable", test))]
8 extern crate test;
9
10 use std::any::TypeId;
11 use std::marker::PhantomData;
12
13 use raw::RawMap;
14 use any::{UncheckedAnyExt, IntoBox, Any};
15
16 macro_rules! impl_common_methods {
17 (
18 field: $t:ident.$field:ident;
19 new() => $new:expr;
20 with_capacity($with_capacity_arg:ident) => $with_capacity:expr;
21 ) => {
22 impl<A: ?Sized + UncheckedAnyExt> $t<A> {
23 /// Create an empty collection.
24 #[inline]
25 pub fn new() -> $t<A> {
26 $t {
27 $field: $new,
28 }
29 }
30
31 /// Creates an empty collection with the given initial capacity.
32 #[inline]
33 pub fn with_capacity($with_capacity_arg: usize) -> $t<A> {
34 $t {
35 $field: $with_capacity,
36 }
37 }
38
39 /// Returns the number of elements the collection can hold without reallocating.
40 #[inline]
41 pub fn capacity(&self) -> usize {
42 self.$field.capacity()
43 }
44
45 /// Reserves capacity for at least `additional` more elements to be inserted
46 /// in the collection. The collection may reserve more space to avoid
47 /// frequent reallocations.
48 ///
49 /// # Panics
50 ///
51 /// Panics if the new allocation size overflows `usize`.
52 #[inline]
53 pub fn reserve(&mut self, additional: usize) {
54 self.$field.reserve(additional)
55 }
56
57 /// Shrinks the capacity of the collection as much as possible. It will drop
58 /// down as much as possible while maintaining the internal rules
59 /// and possibly leaving some space in accordance with the resize policy.
60 #[inline]
61 pub fn shrink_to_fit(&mut self) {
62 self.$field.shrink_to_fit()
63 }
64
65 /// Returns the number of items in the collection.
66 #[inline]
67 pub fn len(&self) -> usize {
68 self.$field.len()
69 }
70
71 /// Returns true if there are no items in the collection.
72 #[inline]
73 pub fn is_empty(&self) -> bool {
74 self.$field.is_empty()
75 }
76
77 /// Removes all items from the collection. Keeps the allocated memory for reuse.
78 #[inline]
79 pub fn clear(&mut self) {
80 self.$field.clear()
81 }
82 }
83 }
84 }
85
86 pub mod any;
87 pub mod raw;
88
89 /// A collection containing zero or one values for any given type and allowing convenient,
90 /// type-safe access to those values.
91 ///
92 /// The type parameter `A` allows you to use a different value type; normally you will want it to
93 /// be `anymap::any::Any`, but there are other choices:
94 ///
95 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
96 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
97 ///
98 /// ```rust
99 /// # use anymap::AnyMap;
100 /// let mut data = AnyMap::new();
101 /// assert_eq!(data.get(), None::<&i32>);
102 /// data.insert(42i32);
103 /// assert_eq!(data.get(), Some(&42i32));
104 /// data.remove::<i32>();
105 /// assert_eq!(data.get::<i32>(), None);
106 ///
107 /// #[derive(Clone, PartialEq, Debug)]
108 /// struct Foo {
109 /// str: String,
110 /// }
111 ///
112 /// assert_eq!(data.get::<Foo>(), None);
113 /// data.insert(Foo { str: format!("foo") });
114 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
115 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
116 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
117 /// ```
118 ///
119 /// Values containing non-static references are not permitted.
120 #[derive(Debug)]
121 pub struct Map<A: ?Sized + UncheckedAnyExt = Any> {
122 raw: RawMap<A>,
123 }
124
125 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
126 impl<A: ?Sized + UncheckedAnyExt> Clone for Map<A> where Box<A>: Clone {
127 fn clone(&self) -> Map<A> {
128 Map {
129 raw: self.raw.clone(),
130 }
131 }
132 }
133
134 /// The most common type of `Map`: just using `Any`.
135 ///
136 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
137 /// doesn’t seem to be happy to infer that it should go with the default value.
138 /// It’s a bit sad, really. Ah well, I guess this approach will do.
139 pub type AnyMap = Map<Any>;
140
141 impl_common_methods! {
142 field: Map.raw;
143 new() => RawMap::new();
144 with_capacity(capacity) => RawMap::with_capacity(capacity);
145 }
146
147 impl<A: ?Sized + UncheckedAnyExt> Map<A> {
148 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
149 pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
150 self.raw.get(&TypeId::of::<T>())
151 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
152 }
153
154 /// Returns a mutable reference to the value stored in the collection for the type `T`,
155 /// if it exists.
156 pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T> {
157 self.raw.get_mut(&TypeId::of::<T>())
158 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
159 }
160
161 /// Sets the value stored in the collection for the type `T`.
162 /// If the collection already had a value of type `T`, that value is returned.
163 /// Otherwise, `None` is returned.
164 pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
165 unsafe {
166 self.raw.insert(TypeId::of::<T>(), value.into_box())
167 .map(|any| *any.downcast_unchecked::<T>())
168 }
169 }
170
171 /// Removes the `T` value from the collection,
172 /// returning it if there was one or `None` if there was not.
173 pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
174 self.raw.remove(&TypeId::of::<T>())
175 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
176 }
177
178 /// Returns true if the collection contains a value of type `T`.
179 #[inline]
180 pub fn contains<T: IntoBox<A>>(&self) -> bool {
181 self.raw.contains_key(&TypeId::of::<T>())
182 }
183
184 /// Gets the entry for the given type in the collection for in-place manipulation
185 pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<A, T> {
186 match self.raw.entry(TypeId::of::<T>()) {
187 raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
188 inner: e,
189 type_: PhantomData,
190 }),
191 raw::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
192 inner: e,
193 type_: PhantomData,
194 }),
195 }
196 }
197 }
198
199 impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
200 fn as_ref(&self) -> &RawMap<A> {
201 &self.raw
202 }
203 }
204
205 impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
206 fn as_mut(&mut self) -> &mut RawMap<A> {
207 &mut self.raw
208 }
209 }
210
211 impl<A: ?Sized + UncheckedAnyExt> Into<RawMap<A>> for Map<A> {
212 fn into(self) -> RawMap<A> {
213 self.raw
214 }
215 }
216
217 /// A view into a single occupied location in an `Map`.
218 pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
219 inner: raw::OccupiedEntry<'a, A>,
220 type_: PhantomData<V>,
221 }
222
223 /// A view into a single empty location in an `Map`.
224 pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
225 inner: raw::VacantEntry<'a, A>,
226 type_: PhantomData<V>,
227 }
228
229 /// A view into a single location in an `Map`, which may be vacant or occupied.
230 pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
231 /// An occupied Entry
232 Occupied(OccupiedEntry<'a, A, V>),
233 /// A vacant Entry
234 Vacant(VacantEntry<'a, A, V>),
235 }
236
237 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A> + Clone> Entry<'a, A, V> {
238 /// Ensures a value is in the entry by inserting the default if empty, and returns
239 /// a mutable reference to the value in the entry.
240 pub fn or_insert(self, default: V) -> &'a mut V {
241 match self {
242 Entry::Occupied(inner) => inner.into_mut(),
243 Entry::Vacant(inner) => inner.insert(default),
244 }
245 }
246
247 /// Ensures a value is in the entry by inserting the result of the default function if empty,
248 /// and returns a mutable reference to the value in the entry.
249 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
250 match self {
251 Entry::Occupied(inner) => inner.into_mut(),
252 Entry::Vacant(inner) => inner.insert(default()),
253 }
254 }
255 }
256
257 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> OccupiedEntry<'a, A, V> {
258 /// Gets a reference to the value in the entry
259 pub fn get(&self) -> &V {
260 unsafe { self.inner.get().downcast_ref_unchecked() }
261 }
262
263 /// Gets a mutable reference to the value in the entry
264 pub fn get_mut(&mut self) -> &mut V {
265 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
266 }
267
268 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
269 /// with a lifetime bound to the collection itself
270 pub fn into_mut(self) -> &'a mut V {
271 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
272 }
273
274 /// Sets the value of the entry, and returns the entry's old value
275 pub fn insert(&mut self, value: V) -> V {
276 unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() }
277 }
278
279 /// Takes the value out of the entry, and returns it
280 pub fn remove(self) -> V {
281 unsafe { *self.inner.remove().downcast_unchecked() }
282 }
283 }
284
285 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> VacantEntry<'a, A, V> {
286 /// Sets the value of the entry with the VacantEntry's key,
287 /// and returns a mutable reference to it
288 pub fn insert(self, value: V) -> &'a mut V {
289 unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() }
290 }
291 }
292
293 #[cfg(feature = "unstable")]
294 #[bench]
295 fn bench_insertion(b: &mut ::test::Bencher) {
296 b.iter(|| {
297 let mut data = AnyMap::new();
298 for _ in 0..100 {
299 let _ = data.insert(42);
300 }
301 })
302 }
303
304 #[cfg(feature = "unstable")]
305 #[bench]
306 fn bench_get_missing(b: &mut ::test::Bencher) {
307 b.iter(|| {
308 let data = AnyMap::new();
309 for _ in 0..100 {
310 assert_eq!(data.get(), None::<&i32>);
311 }
312 })
313 }
314
315 #[cfg(feature = "unstable")]
316 #[bench]
317 fn bench_get_present(b: &mut ::test::Bencher) {
318 b.iter(|| {
319 let mut data = AnyMap::new();
320 let _ = data.insert(42);
321 // These inner loops are a feeble attempt to drown the other factors.
322 for _ in 0..100 {
323 assert_eq!(data.get(), Some(&42));
324 }
325 })
326 }
327
328 #[cfg(test)]
329 mod tests {
330 use {Map, AnyMap, Entry};
331 use any::{Any, CloneAny};
332
333 #[derive(Clone, Debug, PartialEq)] struct A(i32);
334 #[derive(Clone, Debug, PartialEq)] struct B(i32);
335 #[derive(Clone, Debug, PartialEq)] struct C(i32);
336 #[derive(Clone, Debug, PartialEq)] struct D(i32);
337 #[derive(Clone, Debug, PartialEq)] struct E(i32);
338 #[derive(Clone, Debug, PartialEq)] struct F(i32);
339 #[derive(Clone, Debug, PartialEq)] struct J(i32);
340
341 #[test]
342 fn test_entry() {
343 let mut map: AnyMap = AnyMap::new();
344 assert_eq!(map.insert(A(10)), None);
345 assert_eq!(map.insert(B(20)), None);
346 assert_eq!(map.insert(C(30)), None);
347 assert_eq!(map.insert(D(40)), None);
348 assert_eq!(map.insert(E(50)), None);
349 assert_eq!(map.insert(F(60)), None);
350
351 // Existing key (insert)
352 match map.entry::<A>() {
353 Entry::Vacant(_) => unreachable!(),
354 Entry::Occupied(mut view) => {
355 assert_eq!(view.get(), &A(10));
356 assert_eq!(view.insert(A(100)), A(10));
357 }
358 }
359 assert_eq!(map.get::<A>().unwrap(), &A(100));
360 assert_eq!(map.len(), 6);
361
362
363 // Existing key (update)
364 match map.entry::<B>() {
365 Entry::Vacant(_) => unreachable!(),
366 Entry::Occupied(mut view) => {
367 let v = view.get_mut();
368 let new_v = B(v.0 * 10);
369 *v = new_v;
370 }
371 }
372 assert_eq!(map.get::<B>().unwrap(), &B(200));
373 assert_eq!(map.len(), 6);
374
375
376 // Existing key (remove)
377 match map.entry::<C>() {
378 Entry::Vacant(_) => unreachable!(),
379 Entry::Occupied(view) => {
380 assert_eq!(view.remove(), C(30));
381 }
382 }
383 assert_eq!(map.get::<C>(), None);
384 assert_eq!(map.len(), 5);
385
386
387 // Inexistent key (insert)
388 match map.entry::<J>() {
389 Entry::Occupied(_) => unreachable!(),
390 Entry::Vacant(view) => {
391 assert_eq!(*view.insert(J(1000)), J(1000));
392 }
393 }
394 assert_eq!(map.get::<J>().unwrap(), &J(1000));
395 assert_eq!(map.len(), 6);
396
397 // Entry.or_insert on existing key
398 map.entry::<B>().or_insert(B(71)).0 += 1;
399 assert_eq!(map.get::<B>().unwrap(), &B(201));
400 assert_eq!(map.len(), 6);
401
402 // Entry.or_insert on nonexisting key
403 map.entry::<C>().or_insert(C(300)).0 += 1;
404 assert_eq!(map.get::<C>().unwrap(), &C(301));
405 assert_eq!(map.len(), 7);
406 }
407
408 #[test]
409 fn test_clone() {
410 let mut map: Map<CloneAny> = Map::new();
411 let _ = map.insert(A(1));
412 let _ = map.insert(B(2));
413 let _ = map.insert(D(3));
414 let _ = map.insert(E(4));
415 let _ = map.insert(F(5));
416 let _ = map.insert(J(6));
417 let map2 = map.clone();
418 assert_eq!(map2.len(), 6);
419 assert_eq!(map2.get::<A>(), Some(&A(1)));
420 assert_eq!(map2.get::<B>(), Some(&B(2)));
421 assert_eq!(map2.get::<C>(), None);
422 assert_eq!(map2.get::<D>(), Some(&D(3)));
423 assert_eq!(map2.get::<E>(), Some(&E(4)));
424 assert_eq!(map2.get::<F>(), Some(&F(5)));
425 assert_eq!(map2.get::<J>(), Some(&J(6)));
426 }
427
428 #[test]
429 fn test_varieties() {
430 fn assert_send<T: Send>() { }
431 fn assert_sync<T: Sync>() { }
432 fn assert_clone<T: Clone>() { }
433 fn assert_debug<T: ::std::fmt::Debug>() { }
434 assert_send::<Map<Any + Send>>();
435 assert_send::<Map<Any + Send + Sync>>();
436 assert_sync::<Map<Any + Sync>>();
437 assert_sync::<Map<Any + Send + Sync>>();
438 assert_debug::<Map<Any>>();
439 assert_debug::<Map<Any + Send>>();
440 assert_debug::<Map<Any + Sync>>();
441 assert_debug::<Map<Any + Send + Sync>>();
442 assert_send::<Map<CloneAny + Send>>();
443 assert_send::<Map<CloneAny + Send + Sync>>();
444 assert_sync::<Map<CloneAny + Sync>>();
445 assert_sync::<Map<CloneAny + Send + Sync>>();
446 assert_clone::<Map<CloneAny + Send>>();
447 assert_clone::<Map<CloneAny + Send + Sync>>();
448 assert_clone::<Map<CloneAny + Sync>>();
449 assert_clone::<Map<CloneAny + Send + Sync>>();
450 assert_debug::<Map<CloneAny>>();
451 assert_debug::<Map<CloneAny + Send>>();
452 assert_debug::<Map<CloneAny + Sync>>();
453 assert_debug::<Map<CloneAny + Send + Sync>>();
454 }
455 }