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