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