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