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