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