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