b5ae44a59108ae5f447c8c16e9d120db4b4371bf
[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(core, std_misc))]
4 #![cfg_attr(test, feature(test))]
5 #![warn(missing_docs, unused_results)]
6
7 #[cfg(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 #[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 #[bench]
304 fn bench_get_missing(b: &mut ::test::Bencher) {
305 b.iter(|| {
306 let data = AnyMap::new();
307 for _ in 0..100 {
308 assert_eq!(data.get(), None::<&i32>);
309 }
310 })
311 }
312
313 #[bench]
314 fn bench_get_present(b: &mut ::test::Bencher) {
315 b.iter(|| {
316 let mut data = AnyMap::new();
317 let _ = data.insert(42);
318 // These inner loops are a feeble attempt to drown the other factors.
319 for _ in 0..100 {
320 assert_eq!(data.get(), Some(&42));
321 }
322 })
323 }
324
325 #[cfg(test)]
326 mod tests {
327 use {Map, AnyMap, Entry};
328 use any::{Any, CloneAny};
329
330 #[derive(Clone, Debug, PartialEq)] struct A(i32);
331 #[derive(Clone, Debug, PartialEq)] struct B(i32);
332 #[derive(Clone, Debug, PartialEq)] struct C(i32);
333 #[derive(Clone, Debug, PartialEq)] struct D(i32);
334 #[derive(Clone, Debug, PartialEq)] struct E(i32);
335 #[derive(Clone, Debug, PartialEq)] struct F(i32);
336 #[derive(Clone, Debug, PartialEq)] struct J(i32);
337
338 #[test]
339 fn test_entry() {
340 let mut map: AnyMap = AnyMap::new();
341 assert_eq!(map.insert(A(10)), None);
342 assert_eq!(map.insert(B(20)), None);
343 assert_eq!(map.insert(C(30)), None);
344 assert_eq!(map.insert(D(40)), None);
345 assert_eq!(map.insert(E(50)), None);
346 assert_eq!(map.insert(F(60)), None);
347
348 // Existing key (insert)
349 match map.entry::<A>() {
350 Entry::Vacant(_) => unreachable!(),
351 Entry::Occupied(mut view) => {
352 assert_eq!(view.get(), &A(10));
353 assert_eq!(view.insert(A(100)), A(10));
354 }
355 }
356 assert_eq!(map.get::<A>().unwrap(), &A(100));
357 assert_eq!(map.len(), 6);
358
359
360 // Existing key (update)
361 match map.entry::<B>() {
362 Entry::Vacant(_) => unreachable!(),
363 Entry::Occupied(mut view) => {
364 let v = view.get_mut();
365 let new_v = B(v.0 * 10);
366 *v = new_v;
367 }
368 }
369 assert_eq!(map.get::<B>().unwrap(), &B(200));
370 assert_eq!(map.len(), 6);
371
372
373 // Existing key (remove)
374 match map.entry::<C>() {
375 Entry::Vacant(_) => unreachable!(),
376 Entry::Occupied(view) => {
377 assert_eq!(view.remove(), C(30));
378 }
379 }
380 assert_eq!(map.get::<C>(), None);
381 assert_eq!(map.len(), 5);
382
383
384 // Inexistent key (insert)
385 match map.entry::<J>() {
386 Entry::Occupied(_) => unreachable!(),
387 Entry::Vacant(view) => {
388 assert_eq!(*view.insert(J(1000)), J(1000));
389 }
390 }
391 assert_eq!(map.get::<J>().unwrap(), &J(1000));
392 assert_eq!(map.len(), 6);
393
394 // Entry.or_insert on existing key
395 map.entry::<B>().or_insert(B(71)).0 += 1;
396 assert_eq!(map.get::<B>().unwrap(), &B(201));
397 assert_eq!(map.len(), 6);
398
399 // Entry.or_insert on nonexisting key
400 map.entry::<C>().or_insert(C(300)).0 += 1;
401 assert_eq!(map.get::<C>().unwrap(), &C(301));
402 assert_eq!(map.len(), 7);
403 }
404
405 #[test]
406 fn test_clone() {
407 let mut map: Map<CloneAny> = Map::new();
408 let _ = map.insert(A(1));
409 let _ = map.insert(B(2));
410 let _ = map.insert(D(3));
411 let _ = map.insert(E(4));
412 let _ = map.insert(F(5));
413 let _ = map.insert(J(6));
414 let map2 = map.clone();
415 assert_eq!(map2.len(), 6);
416 assert_eq!(map2.get::<A>(), Some(&A(1)));
417 assert_eq!(map2.get::<B>(), Some(&B(2)));
418 assert_eq!(map2.get::<C>(), None);
419 assert_eq!(map2.get::<D>(), Some(&D(3)));
420 assert_eq!(map2.get::<E>(), Some(&E(4)));
421 assert_eq!(map2.get::<F>(), Some(&F(5)));
422 assert_eq!(map2.get::<J>(), Some(&J(6)));
423 }
424
425 #[test]
426 fn test_varieties() {
427 fn assert_send<T: Send>() { }
428 fn assert_sync<T: Sync>() { }
429 fn assert_clone<T: Clone>() { }
430 fn assert_debug<T: ::std::fmt::Debug>() { }
431 assert_send::<Map<Any + Send>>();
432 assert_send::<Map<Any + Send + Sync>>();
433 assert_sync::<Map<Any + Sync>>();
434 assert_sync::<Map<Any + Send + Sync>>();
435 assert_debug::<Map<Any>>();
436 assert_debug::<Map<Any + Send>>();
437 assert_debug::<Map<Any + Sync>>();
438 assert_debug::<Map<Any + Send + Sync>>();
439 assert_send::<Map<CloneAny + Send>>();
440 assert_send::<Map<CloneAny + Send + Sync>>();
441 assert_sync::<Map<CloneAny + Sync>>();
442 assert_sync::<Map<CloneAny + Send + Sync>>();
443 assert_clone::<Map<CloneAny + Send>>();
444 assert_clone::<Map<CloneAny + Send + Sync>>();
445 assert_clone::<Map<CloneAny + Sync>>();
446 assert_clone::<Map<CloneAny + Send + Sync>>();
447 assert_debug::<Map<CloneAny>>();
448 assert_debug::<Map<CloneAny + Send>>();
449 assert_debug::<Map<CloneAny + Sync>>();
450 assert_debug::<Map<CloneAny + Send + Sync>>();
451 }
452 }