80769813c38a83755283ce5f92d5b91125ce2ec4
[anymap] / src / lib.rs
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
2
3 #![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::{Any, TypeId};
11 use std::marker::PhantomData;
12
13 use raw::RawAnyMap;
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(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 pub struct AnyMap {
116 raw: RawAnyMap,
117 }
118
119 impl_common_methods! {
120 field: AnyMap.raw;
121 new() => RawAnyMap::new();
122 with_capacity(capacity) => RawAnyMap::with_capacity(capacity);
123 }
124
125 impl AnyMap {
126 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
127 pub fn get<T: Any>(&self) -> Option<&T> {
128 self.raw.get(&TypeId::of::<T>())
129 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
130 }
131
132 /// Returns a mutable reference to the value stored in the collection for the type `T`,
133 /// if it exists.
134 pub fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
135 self.raw.get_mut(&TypeId::of::<T>())
136 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
137 }
138
139 /// Sets the value stored in the collection for the type `T`.
140 /// If the collection already had a value of type `T`, that value is returned.
141 /// Otherwise, `None` is returned.
142 pub fn insert<T: Any>(&mut self, value: T) -> Option<T> {
143 unsafe {
144 self.raw.insert(TypeId::of::<T>(), Box::new(value))
145 .map(|any| *any.downcast_unchecked::<T>())
146 }
147 }
148
149 /// Removes the `T` value from the collection,
150 /// returning it if there was one or `None` if there was not.
151 pub fn remove<T: Any>(&mut self) -> Option<T> {
152 self.raw.remove(&TypeId::of::<T>())
153 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
154 }
155
156 /// Returns true if the collection contains a value of type `T`.
157 #[inline]
158 pub fn contains<T: Any>(&self) -> bool {
159 self.raw.contains_key(&TypeId::of::<T>())
160 }
161
162 /// Gets the entry for the given type in the collection for in-place manipulation
163 pub fn entry<T: Any>(&mut self) -> Entry<T> {
164 match self.raw.entry(TypeId::of::<T>()) {
165 raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
166 inner: e,
167 type_: PhantomData,
168 }),
169 raw::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
170 inner: e,
171 type_: PhantomData,
172 }),
173 }
174 }
175
176 /// Get a reference to the raw untyped map underlying the `AnyMap`.
177 ///
178 /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
179 /// just find a use for it occasionally.
180 #[inline]
181 pub fn as_raw(&self) -> &RawAnyMap {
182 &self.raw
183 }
184
185 /// Get a mutable reference to the raw untyped map underlying the `AnyMap`.
186 ///
187 /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
188 /// just find a use for it occasionally.
189 #[inline]
190 pub fn as_raw_mut(&mut self) -> &mut RawAnyMap {
191 &mut self.raw
192 }
193
194 /// Convert the `AnyMap` into the raw untyped map that underlyies it.
195 ///
196 /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
197 /// just find a use for it occasionally.
198 #[inline]
199 pub fn into_raw(self) -> RawAnyMap {
200 self.raw
201 }
202
203 /// Convert a raw untyped map into an `AnyMap`.
204 ///
205 /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
206 /// just find a use for it occasionally.
207 #[inline]
208 pub fn from_raw(raw: RawAnyMap) -> AnyMap {
209 AnyMap {
210 raw: raw,
211 }
212 }
213 }
214
215 /// A view into a single occupied location in an `AnyMap`.
216 pub struct OccupiedEntry<'a, V: 'a> {
217 inner: raw::OccupiedEntry<'a>,
218 type_: PhantomData<V>,
219 }
220
221 /// A view into a single empty location in an `AnyMap`.
222 pub struct VacantEntry<'a, V: 'a> {
223 inner: raw::VacantEntry<'a>,
224 type_: PhantomData<V>,
225 }
226
227 /// A view into a single location in an `AnyMap`, which may be vacant or occupied.
228 pub enum Entry<'a, V: 'a> {
229 /// An occupied Entry
230 Occupied(OccupiedEntry<'a, V>),
231 /// A vacant Entry
232 Vacant(VacantEntry<'a, V>),
233 }
234
235 impl<'a, V: Any + Clone> Entry<'a, V> {
236 /// Ensures a value is in the entry by inserting the default if empty, and returns
237 /// a mutable reference to the value in the entry.
238 pub fn or_insert(self, default: V) -> &'a mut V {
239 match self {
240 Entry::Occupied(inner) => inner.into_mut(),
241 Entry::Vacant(inner) => inner.insert(default),
242 }
243 }
244
245 /// Ensures a value is in the entry by inserting the result of the default function if empty,
246 /// and returns a mutable reference to the value in the entry.
247 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
248 match self {
249 Entry::Occupied(inner) => inner.into_mut(),
250 Entry::Vacant(inner) => inner.insert(default()),
251 }
252 }
253 }
254
255 impl<'a, V: Any> OccupiedEntry<'a, V> {
256 /// Gets a reference to the value in the entry
257 pub fn get(&self) -> &V {
258 unsafe { self.inner.get().downcast_ref_unchecked() }
259 }
260
261 /// Gets a mutable reference to the value in the entry
262 pub fn get_mut(&mut self) -> &mut V {
263 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
264 }
265
266 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
267 /// with a lifetime bound to the collection itself
268 pub fn into_mut(self) -> &'a mut V {
269 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
270 }
271
272 /// Sets the value of the entry, and returns the entry's old value
273 pub fn insert(&mut self, value: V) -> V {
274 unsafe { *self.inner.insert(Box::new(value)).downcast_unchecked() }
275 }
276
277 /// Takes the value out of the entry, and returns it
278 pub fn remove(self) -> V {
279 unsafe { *self.inner.remove().downcast_unchecked() }
280 }
281 }
282
283 impl<'a, V: Any> VacantEntry<'a, V> {
284 /// Sets the value of the entry with the VacantEntry's key,
285 /// and returns a mutable reference to it
286 pub fn insert(self, value: V) -> &'a mut V {
287 unsafe { self.inner.insert(Box::new(value)).downcast_mut_unchecked() }
288 }
289 }
290
291 #[bench]
292 fn bench_insertion(b: &mut ::test::Bencher) {
293 b.iter(|| {
294 let mut data = AnyMap::new();
295 for _ in 0..100 {
296 let _ = data.insert(42);
297 }
298 })
299 }
300
301 #[bench]
302 fn bench_get_missing(b: &mut ::test::Bencher) {
303 b.iter(|| {
304 let data = AnyMap::new();
305 for _ in 0..100 {
306 assert_eq!(data.get(), None::<&i32>);
307 }
308 })
309 }
310
311 #[bench]
312 fn bench_get_present(b: &mut ::test::Bencher) {
313 b.iter(|| {
314 let mut data = AnyMap::new();
315 let _ = data.insert(42);
316 // These inner loops are a feeble attempt to drown the other factors.
317 for _ in 0..100 {
318 assert_eq!(data.get(), Some(&42));
319 }
320 })
321 }
322
323 #[test]
324 fn test_entry() {
325 #[derive(Debug, PartialEq)] struct A(i32);
326 #[derive(Debug, PartialEq)] struct B(i32);
327 #[derive(Debug, PartialEq)] struct C(i32);
328 #[derive(Debug, PartialEq)] struct D(i32);
329 #[derive(Debug, PartialEq)] struct E(i32);
330 #[derive(Debug, PartialEq)] struct F(i32);
331 #[derive(Debug, PartialEq)] struct J(i32);
332
333 let mut map: AnyMap = AnyMap::new();
334 assert_eq!(map.insert(A(10)), None);
335 assert_eq!(map.insert(B(20)), None);
336 assert_eq!(map.insert(C(30)), None);
337 assert_eq!(map.insert(D(40)), None);
338 assert_eq!(map.insert(E(50)), None);
339 assert_eq!(map.insert(F(60)), None);
340
341 // Existing key (insert)
342 match map.entry::<A>() {
343 Entry::Vacant(_) => unreachable!(),
344 Entry::Occupied(mut view) => {
345 assert_eq!(view.get(), &A(10));
346 assert_eq!(view.insert(A(100)), A(10));
347 }
348 }
349 assert_eq!(map.get::<A>().unwrap(), &A(100));
350 assert_eq!(map.len(), 6);
351
352
353 // Existing key (update)
354 match map.entry::<B>() {
355 Entry::Vacant(_) => unreachable!(),
356 Entry::Occupied(mut view) => {
357 let v = view.get_mut();
358 let new_v = B(v.0 * 10);
359 *v = new_v;
360 }
361 }
362 assert_eq!(map.get().unwrap(), &B(200));
363 assert_eq!(map.len(), 6);
364
365
366 // Existing key (remove)
367 match map.entry::<C>() {
368 Entry::Vacant(_) => unreachable!(),
369 Entry::Occupied(view) => {
370 assert_eq!(view.remove(), C(30));
371 }
372 }
373 assert_eq!(map.get::<C>(), None);
374 assert_eq!(map.len(), 5);
375
376
377 // Inexistent key (insert)
378 match map.entry::<J>() {
379 Entry::Occupied(_) => unreachable!(),
380 Entry::Vacant(view) => {
381 assert_eq!(*view.insert(J(1000)), J(1000));
382 }
383 }
384 assert_eq!(map.get::<J>().unwrap(), &J(1000));
385 assert_eq!(map.len(), 6);
386 }