d32af5f2aa4327826844727c183a09f47c247fb7
[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 = "nightly", 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::{RawAnyMap, Any};
14 use unchecked_any::UncheckedAnyExt;
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 $t {
23 /// Create an empty collection.
24 #[inline]
25 pub fn new() -> $t {
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 {
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 mod unchecked_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 /// ```rust
93 /// # use anymap::AnyMap;
94 /// let mut data = AnyMap::new();
95 /// assert_eq!(data.get(), None::<&i32>);
96 /// data.insert(42i32);
97 /// assert_eq!(data.get(), Some(&42i32));
98 /// data.remove::<i32>();
99 /// assert_eq!(data.get::<i32>(), None);
100 ///
101 /// #[derive(Clone, PartialEq, Debug)]
102 /// struct Foo {
103 /// str: String,
104 /// }
105 ///
106 /// assert_eq!(data.get::<Foo>(), None);
107 /// data.insert(Foo { str: format!("foo") });
108 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
109 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
110 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
111 /// ```
112 ///
113 /// Values containing non-static references are not permitted.
114 #[derive(Debug)]
115 #[cfg_attr(feature = "clone", derive(Clone))]
116 pub struct AnyMap {
117 raw: RawAnyMap,
118 }
119
120 impl_common_methods! {
121 field: AnyMap.raw;
122 new() => RawAnyMap::new();
123 with_capacity(capacity) => RawAnyMap::with_capacity(capacity);
124 }
125
126 impl AnyMap {
127 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
128 pub fn get<T: Any>(&self) -> Option<&T> {
129 self.raw.get(&TypeId::of::<T>())
130 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
131 }
132
133 /// Returns a mutable reference to the value stored in the collection for the type `T`,
134 /// if it exists.
135 pub fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
136 self.raw.get_mut(&TypeId::of::<T>())
137 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
138 }
139
140 /// Sets the value stored in the collection for the type `T`.
141 /// If the collection already had a value of type `T`, that value is returned.
142 /// Otherwise, `None` is returned.
143 pub fn insert<T: Any>(&mut self, value: T) -> Option<T> {
144 unsafe {
145 self.raw.insert(TypeId::of::<T>(), Box::new(value))
146 .map(|any| *any.downcast_unchecked::<T>())
147 }
148 }
149
150 /// Removes the `T` value from the collection,
151 /// returning it if there was one or `None` if there was not.
152 pub fn remove<T: Any>(&mut self) -> Option<T> {
153 self.raw.remove(&TypeId::of::<T>())
154 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
155 }
156
157 /// Returns true if the collection contains a value of type `T`.
158 #[inline]
159 pub fn contains<T: Any>(&self) -> bool {
160 self.raw.contains_key(&TypeId::of::<T>())
161 }
162
163 /// Gets the entry for the given type in the collection for in-place manipulation
164 pub fn entry<T: Any>(&mut self) -> Entry<T> {
165 match self.raw.entry(TypeId::of::<T>()) {
166 raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
167 inner: e,
168 type_: PhantomData,
169 }),
170 raw::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
171 inner: e,
172 type_: PhantomData,
173 }),
174 }
175 }
176 }
177
178 impl AsRef<RawAnyMap> for AnyMap {
179 fn as_ref(&self) -> &RawAnyMap {
180 &self.raw
181 }
182 }
183
184 impl AsMut<RawAnyMap> for AnyMap {
185 fn as_mut(&mut self) -> &mut RawAnyMap {
186 &mut self.raw
187 }
188 }
189
190 impl Into<RawAnyMap> for AnyMap {
191 fn into(self) -> RawAnyMap {
192 self.raw
193 }
194 }
195
196 /// A view into a single occupied location in an `AnyMap`.
197 pub struct OccupiedEntry<'a, V: 'a> {
198 inner: raw::OccupiedEntry<'a>,
199 type_: PhantomData<V>,
200 }
201
202 /// A view into a single empty location in an `AnyMap`.
203 pub struct VacantEntry<'a, V: 'a> {
204 inner: raw::VacantEntry<'a>,
205 type_: PhantomData<V>,
206 }
207
208 /// A view into a single location in an `AnyMap`, which may be vacant or occupied.
209 pub enum Entry<'a, V: 'a> {
210 /// An occupied Entry
211 Occupied(OccupiedEntry<'a, V>),
212 /// A vacant Entry
213 Vacant(VacantEntry<'a, V>),
214 }
215
216 impl<'a, V: Any + Clone> Entry<'a, V> {
217 /// Ensures a value is in the entry by inserting the default if empty, and returns
218 /// a mutable reference to the value in the entry.
219 pub fn or_insert(self, default: V) -> &'a mut V {
220 match self {
221 Entry::Occupied(inner) => inner.into_mut(),
222 Entry::Vacant(inner) => inner.insert(default),
223 }
224 }
225
226 /// Ensures a value is in the entry by inserting the result of the default function if empty,
227 /// and returns a mutable reference to the value in the entry.
228 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
229 match self {
230 Entry::Occupied(inner) => inner.into_mut(),
231 Entry::Vacant(inner) => inner.insert(default()),
232 }
233 }
234 }
235
236 impl<'a, V: Any> OccupiedEntry<'a, V> {
237 /// Gets a reference to the value in the entry
238 pub fn get(&self) -> &V {
239 unsafe { self.inner.get().downcast_ref_unchecked() }
240 }
241
242 /// Gets a mutable reference to the value in the entry
243 pub fn get_mut(&mut self) -> &mut V {
244 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
245 }
246
247 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
248 /// with a lifetime bound to the collection itself
249 pub fn into_mut(self) -> &'a mut V {
250 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
251 }
252
253 /// Sets the value of the entry, and returns the entry's old value
254 pub fn insert(&mut self, value: V) -> V {
255 unsafe { *self.inner.insert(Box::new(value)).downcast_unchecked() }
256 }
257
258 /// Takes the value out of the entry, and returns it
259 pub fn remove(self) -> V {
260 unsafe { *self.inner.remove().downcast_unchecked() }
261 }
262 }
263
264 impl<'a, V: Any> VacantEntry<'a, V> {
265 /// Sets the value of the entry with the VacantEntry's key,
266 /// and returns a mutable reference to it
267 pub fn insert(self, value: V) -> &'a mut V {
268 unsafe { self.inner.insert(Box::new(value)).downcast_mut_unchecked() }
269 }
270 }
271
272 #[bench]
273 fn bench_insertion(b: &mut ::test::Bencher) {
274 b.iter(|| {
275 let mut data = AnyMap::new();
276 for _ in 0..100 {
277 let _ = data.insert(42);
278 }
279 })
280 }
281
282 #[bench]
283 fn bench_get_missing(b: &mut ::test::Bencher) {
284 b.iter(|| {
285 let data = AnyMap::new();
286 for _ in 0..100 {
287 assert_eq!(data.get(), None::<&i32>);
288 }
289 })
290 }
291
292 #[bench]
293 fn bench_get_present(b: &mut ::test::Bencher) {
294 b.iter(|| {
295 let mut data = AnyMap::new();
296 let _ = data.insert(42);
297 // These inner loops are a feeble attempt to drown the other factors.
298 for _ in 0..100 {
299 assert_eq!(data.get(), Some(&42));
300 }
301 })
302 }
303
304 #[cfg(test)]
305 mod tests {
306 use {AnyMap, Entry};
307
308 #[derive(Clone, Debug, PartialEq)] struct A(i32);
309 #[derive(Clone, Debug, PartialEq)] struct B(i32);
310 #[derive(Clone, Debug, PartialEq)] struct C(i32);
311 #[derive(Clone, Debug, PartialEq)] struct D(i32);
312 #[derive(Clone, Debug, PartialEq)] struct E(i32);
313 #[derive(Clone, Debug, PartialEq)] struct F(i32);
314 #[derive(Clone, Debug, PartialEq)] struct J(i32);
315
316 #[test]
317 fn test_entry() {
318 let mut map: AnyMap = AnyMap::new();
319 assert_eq!(map.insert(A(10)), None);
320 assert_eq!(map.insert(B(20)), None);
321 assert_eq!(map.insert(C(30)), None);
322 assert_eq!(map.insert(D(40)), None);
323 assert_eq!(map.insert(E(50)), None);
324 assert_eq!(map.insert(F(60)), None);
325
326 // Existing key (insert)
327 match map.entry::<A>() {
328 Entry::Vacant(_) => unreachable!(),
329 Entry::Occupied(mut view) => {
330 assert_eq!(view.get(), &A(10));
331 assert_eq!(view.insert(A(100)), A(10));
332 }
333 }
334 assert_eq!(map.get::<A>().unwrap(), &A(100));
335 assert_eq!(map.len(), 6);
336
337
338 // Existing key (update)
339 match map.entry::<B>() {
340 Entry::Vacant(_) => unreachable!(),
341 Entry::Occupied(mut view) => {
342 let v = view.get_mut();
343 let new_v = B(v.0 * 10);
344 *v = new_v;
345 }
346 }
347 assert_eq!(map.get::<B>().unwrap(), &B(200));
348 assert_eq!(map.len(), 6);
349
350
351 // Existing key (remove)
352 match map.entry::<C>() {
353 Entry::Vacant(_) => unreachable!(),
354 Entry::Occupied(view) => {
355 assert_eq!(view.remove(), C(30));
356 }
357 }
358 assert_eq!(map.get::<C>(), None);
359 assert_eq!(map.len(), 5);
360
361
362 // Inexistent key (insert)
363 match map.entry::<J>() {
364 Entry::Occupied(_) => unreachable!(),
365 Entry::Vacant(view) => {
366 assert_eq!(*view.insert(J(1000)), J(1000));
367 }
368 }
369 assert_eq!(map.get::<J>().unwrap(), &J(1000));
370 assert_eq!(map.len(), 6);
371
372 // Entry.or_insert on existing key
373 map.entry::<B>().or_insert(B(71)).0 += 1;
374 assert_eq!(map.get::<B>().unwrap(), &B(201));
375 assert_eq!(map.len(), 6);
376
377 // Entry.or_insert on nonexisting key
378 map.entry::<C>().or_insert(C(300)).0 += 1;
379 assert_eq!(map.get::<C>().unwrap(), &C(301));
380 assert_eq!(map.len(), 7);
381 }
382
383 #[cfg(feature = "clone")]
384 #[test]
385 fn test_clone() {
386 let mut map = AnyMap::new();
387 let _ = map.insert(A(1));
388 let _ = map.insert(B(2));
389 let _ = map.insert(D(3));
390 let _ = map.insert(E(4));
391 let _ = map.insert(F(5));
392 let _ = map.insert(J(6));
393 let map2 = map.clone();
394 assert_eq!(map2.len(), 6);
395 assert_eq!(map2.get::<A>(), Some(&A(1)));
396 assert_eq!(map2.get::<B>(), Some(&B(2)));
397 assert_eq!(map2.get::<C>(), None);
398 assert_eq!(map2.get::<D>(), Some(&D(3)));
399 assert_eq!(map2.get::<E>(), Some(&E(4)));
400 assert_eq!(map2.get::<F>(), Some(&F(5)));
401 assert_eq!(map2.get::<J>(), Some(&J(6)));
402 }
403
404 #[cfg(feature = "concurrent")]
405 #[test]
406 fn test_concurrent() {
407 fn assert_concurrent<T: Send + Sync>() { }
408 assert_concurrent::<AnyMap>();
409 }
410 }