0fc29419faff02434400c3879125f12c00486e28
[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::convert::TryInto;
11 use core::hash::{Hasher, BuildHasherDefault};
12 use core::marker::PhantomData;
13
14 #[cfg(not(any(feature = "std", feature = "hashbrown")))]
15 compile_error!("anymap: you must enable the 'std' feature or the 'hashbrown' feature");
16
17 #[cfg(not(feature = "std"))]
18 extern crate alloc;
19
20 #[cfg(not(feature = "std"))]
21 use alloc::boxed::Box;
22
23 use any::{Downcast, IntoBox};
24 pub use any::CloneAny;
25
26 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
27 /// A re-export of [`std::collections::hash_map`] for raw access.
28 ///
29 /// If the `hashbrown` feature gets enabled, this will become an export of `hashbrown::hash_map`.
30 ///
31 /// As with [`RawMap`][crate::RawMap], this is exposed for compatibility reasons, since features
32 /// are supposed to be additive. This *is* imperfect, since the two modules are incompatible in a
33 /// few places (e.g. hashbrown’s entry types have an extra generic parameter), but it’s close, and
34 /// much too useful to give up the whole concept.
35 pub use std::collections::hash_map as raw_hash_map;
36
37 #[cfg(feature = "hashbrown")]
38 /// A re-export of [`hashbrown::hash_map`] for raw access.
39 ///
40 /// If the `hashbrown` feature was disabled, this would become an export of
41 /// `std::collections::hash_map`.
42 ///
43 /// As with [`RawMap`][crate::RawMap], this is exposed for compatibility reasons, since features
44 /// are supposed to be additive. This *is* imperfect, since the two modules are incompatible in a
45 /// few places (e.g. hashbrown’s entry types have an extra generic parameter), but it’s close, and
46 /// much too useful to give up the whole concept.
47 pub use hashbrown::hash_map as raw_hash_map;
48
49 use self::raw_hash_map::HashMap;
50
51 mod any;
52
53 /// Raw access to the underlying `HashMap`.
54 ///
55 /// This is a public type alias because the underlying `HashMap` could be
56 /// `std::collections::HashMap` or `hashbrown::HashMap`, depending on the crate features enabled.
57 /// For that reason, you should refer to this type as `anymap::RawMap` rather than
58 /// `std::collections::HashMap` to avoid breakage if something else in your crate tree enables
59 /// hashbrown.
60 ///
61 /// See also [`raw_hash_map`], an export of the corresponding `hash_map` module.
62 pub type RawMap<A> = HashMap<TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>;
63
64 /// A collection containing zero or one values for any given type and allowing convenient,
65 /// type-safe access to those values.
66 ///
67 /// The type parameter `A` allows you to use a different value type; normally you will want it to
68 /// be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
69 ///
70 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with that, you
71 /// can only add types that implement `Clone` to the map.
72 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those auto
73 /// traits.
74 ///
75 /// Cumulatively, there are thus six forms of map:
76 ///
77 /// - <code>[Map]&lt;dyn [core::any::Any]&gt;</code>, also spelled [`AnyMap`] for convenience.
78 /// - <code>[Map]&lt;dyn [core::any::Any] + Send&gt;</code>
79 /// - <code>[Map]&lt;dyn [core::any::Any] + Send + Sync&gt;</code>
80 /// - <code>[Map]&lt;dyn [CloneAny]&gt;</code>
81 /// - <code>[Map]&lt;dyn [CloneAny] + Send&gt;</code>
82 /// - <code>[Map]&lt;dyn [CloneAny] + Send + Sync&gt;</code>
83 ///
84 /// ## Example
85 ///
86 /// (Here using the [`AnyMap`] convenience alias; the first line could use
87 /// <code>[anymap::Map][Map]::&lt;[core::any::Any]&gt;::new()</code> instead if desired.)
88 ///
89 /// ```rust
90 /// let mut data = anymap::AnyMap::new();
91 /// assert_eq!(data.get(), None::<&i32>);
92 /// data.insert(42i32);
93 /// assert_eq!(data.get(), Some(&42i32));
94 /// data.remove::<i32>();
95 /// assert_eq!(data.get::<i32>(), None);
96 ///
97 /// #[derive(Clone, PartialEq, Debug)]
98 /// struct Foo {
99 /// str: String,
100 /// }
101 ///
102 /// assert_eq!(data.get::<Foo>(), None);
103 /// data.insert(Foo { str: format!("foo") });
104 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
105 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
106 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
107 /// ```
108 ///
109 /// Values containing non-static references are not permitted.
110 #[derive(Debug)]
111 pub struct Map<A: ?Sized + Downcast = dyn Any> {
112 raw: RawMap<A>,
113 }
114
115 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
116 impl<A: ?Sized + Downcast> Clone for Map<A> where Box<A>: Clone {
117 #[inline]
118 fn clone(&self) -> Map<A> {
119 Map {
120 raw: self.raw.clone(),
121 }
122 }
123 }
124
125 /// The most common type of `Map`: just using `Any`; <code>[Map]&lt;dyn [Any]&gt;</code>.
126 ///
127 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
128 /// doesn’t seem to be happy to infer that it should go with the default value.
129 /// It’s a bit sad, really. Ah well, I guess this approach will do.
130 pub type AnyMap = Map<dyn Any>;
131
132 impl<A: ?Sized + Downcast> Default for Map<A> {
133 #[inline]
134 fn default() -> Map<A> {
135 Map::new()
136 }
137 }
138
139 impl<A: ?Sized + Downcast> Map<A> {
140 /// Create an empty collection.
141 #[inline]
142 pub fn new() -> Map<A> {
143 Map {
144 raw: RawMap::with_hasher(Default::default()),
145 }
146 }
147
148 /// Creates an empty collection with the given initial capacity.
149 #[inline]
150 pub fn with_capacity(capacity: usize) -> Map<A> {
151 Map {
152 raw: RawMap::with_capacity_and_hasher(capacity, Default::default()),
153 }
154 }
155
156 /// Returns the number of elements the collection can hold without reallocating.
157 #[inline]
158 pub fn capacity(&self) -> usize {
159 self.raw.capacity()
160 }
161
162 /// Reserves capacity for at least `additional` more elements to be inserted
163 /// in the collection. The collection may reserve more space to avoid
164 /// frequent reallocations.
165 ///
166 /// # Panics
167 ///
168 /// Panics if the new allocation size overflows `usize`.
169 #[inline]
170 pub fn reserve(&mut self, additional: usize) {
171 self.raw.reserve(additional)
172 }
173
174 /// Shrinks the capacity of the collection as much as possible. It will drop
175 /// down as much as possible while maintaining the internal rules
176 /// and possibly leaving some space in accordance with the resize policy.
177 #[inline]
178 pub fn shrink_to_fit(&mut self) {
179 self.raw.shrink_to_fit()
180 }
181
182 // Additional stable methods (as of 1.60.0-nightly) that could be added:
183 // try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> (1.57.0)
184 // shrink_to(&mut self, min_capacity: usize) (1.56.0)
185
186 /// Returns the number of items in the collection.
187 #[inline]
188 pub fn len(&self) -> usize {
189 self.raw.len()
190 }
191
192 /// Returns true if there are no items in the collection.
193 #[inline]
194 pub fn is_empty(&self) -> bool {
195 self.raw.is_empty()
196 }
197
198 /// Removes all items from the collection. Keeps the allocated memory for reuse.
199 #[inline]
200 pub fn clear(&mut self) {
201 self.raw.clear()
202 }
203
204 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
205 #[inline]
206 pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
207 self.raw.get(&TypeId::of::<T>())
208 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
209 }
210
211 /// Returns a mutable reference to the value stored in the collection for the type `T`,
212 /// if it exists.
213 #[inline]
214 pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T> {
215 self.raw.get_mut(&TypeId::of::<T>())
216 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
217 }
218
219 /// Sets the value stored in the collection for the type `T`.
220 /// If the collection already had a value of type `T`, that value is returned.
221 /// Otherwise, `None` is returned.
222 #[inline]
223 pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
224 self.raw.insert(TypeId::of::<T>(), value.into_box())
225 .map(|any| unsafe { *any.downcast_unchecked::<T>() })
226 }
227
228 // rustc 1.60.0-nightly has another method try_insert that would be nice to add when stable.
229
230 /// Removes the `T` value from the collection,
231 /// returning it if there was one or `None` if there was not.
232 #[inline]
233 pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
234 self.raw.remove(&TypeId::of::<T>())
235 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
236 }
237
238 /// Returns true if the collection contains a value of type `T`.
239 #[inline]
240 pub fn contains<T: IntoBox<A>>(&self) -> bool {
241 self.raw.contains_key(&TypeId::of::<T>())
242 }
243
244 /// Gets the entry for the given type in the collection for in-place manipulation
245 #[inline]
246 pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<A, T> {
247 match self.raw.entry(TypeId::of::<T>()) {
248 raw_hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
249 inner: e,
250 type_: PhantomData,
251 }),
252 raw_hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
253 inner: e,
254 type_: PhantomData,
255 }),
256 }
257 }
258
259 /// Get access to the raw hash map that backs this.
260 ///
261 /// This will seldom be useful, but it’s conceivable that you could wish to iterate over all
262 /// the items in the collection, and this lets you do that.
263 ///
264 /// To improve compatibility with Cargo features, interact with this map through the names
265 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
266 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
267 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
268 /// hashbrown, your code will break.
269 #[inline]
270 pub fn as_raw(&self) -> &RawMap<A> {
271 &self.raw
272 }
273
274 /// Get mutable access to the raw hash map that backs this.
275 ///
276 /// This will seldom be useful, but it’s conceivable that you could wish to iterate over all
277 /// the items in the collection mutably, or drain or something, or *possibly* even batch
278 /// insert, and this lets you do that.
279 ///
280 /// To improve compatibility with Cargo features, interact with this map through the names
281 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
282 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
283 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
284 /// hashbrown, your code will break.
285 ///
286 /// # Safety
287 ///
288 /// If you insert any values to the raw map, the key (a `TypeId`) must match the value’s type,
289 /// or *undefined behaviour* will occur when you access those values.
290 ///
291 /// (*Removing* entries is perfectly safe.)
292 #[inline]
293 pub unsafe fn as_raw_mut(&mut self) -> &mut RawMap<A> {
294 &mut self.raw
295 }
296
297 /// Convert this into the raw hash map that backs this.
298 ///
299 /// This will seldom be useful, but it’s conceivable that you could wish to consume all the
300 /// items in the collection and do *something* with some or all of them, and this lets you do
301 /// that, without the `unsafe` that `.as_raw_mut().drain()` would require.
302 ///
303 /// To improve compatibility with Cargo features, interact with this map through the names
304 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
305 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
306 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
307 /// hashbrown, your code will break.
308 #[inline]
309 pub fn into_raw(self) -> RawMap<A> {
310 self.raw
311 }
312
313 /// Construct a map from a collection of raw values.
314 ///
315 /// You know what? I can’t immediately think of any legitimate use for this, especially because
316 /// of the requirement of the `BuildHasherDefault<TypeIdHasher>` generic in the map.
317 ///
318 /// Perhaps this will be most practical as `unsafe { Map::from_raw(iter.collect()) }`, iter
319 /// being an iterator over `(TypeId, Box<A>)` pairs. Eh, this method provides symmetry with
320 /// `into_raw`, so I don’t care if literally no one ever uses it. I’m not even going to write a
321 /// test for it, it’s so trivial.
322 ///
323 /// To improve compatibility with Cargo features, interact with this map through the names
324 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
325 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
326 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
327 /// hashbrown, your code will break.
328 ///
329 /// # Safety
330 ///
331 /// For all entries in the raw map, the key (a `TypeId`) must match the value’s type,
332 /// or *undefined behaviour* will occur when you access that entry.
333 #[inline]
334 pub unsafe fn from_raw(raw: RawMap<A>) -> Map<A> {
335 Self { raw }
336 }
337 }
338
339 impl<A: ?Sized + Downcast> Extend<Box<A>> for Map<A> {
340 #[inline]
341 fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T) {
342 for item in iter {
343 let _ = self.raw.insert(Downcast::type_id(&*item), item);
344 }
345 }
346 }
347
348 /// A view into a single occupied location in an `Map`.
349 pub struct OccupiedEntry<'a, A: ?Sized + Downcast, V: 'a> {
350 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
351 inner: raw_hash_map::OccupiedEntry<'a, TypeId, Box<A>>,
352 #[cfg(feature = "hashbrown")]
353 inner: raw_hash_map::OccupiedEntry<'a, TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
354 type_: PhantomData<V>,
355 }
356
357 /// A view into a single empty location in an `Map`.
358 pub struct VacantEntry<'a, A: ?Sized + Downcast, V: 'a> {
359 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
360 inner: raw_hash_map::VacantEntry<'a, TypeId, Box<A>>,
361 #[cfg(feature = "hashbrown")]
362 inner: raw_hash_map::VacantEntry<'a, TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
363 type_: PhantomData<V>,
364 }
365
366 /// A view into a single location in an `Map`, which may be vacant or occupied.
367 pub enum Entry<'a, A: ?Sized + Downcast, V: 'a> {
368 /// An occupied Entry
369 Occupied(OccupiedEntry<'a, A, V>),
370 /// A vacant Entry
371 Vacant(VacantEntry<'a, A, V>),
372 }
373
374 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> Entry<'a, A, V> {
375 /// Ensures a value is in the entry by inserting the default if empty, and returns
376 /// a mutable reference to the value in the entry.
377 #[inline]
378 pub fn or_insert(self, default: V) -> &'a mut V {
379 match self {
380 Entry::Occupied(inner) => inner.into_mut(),
381 Entry::Vacant(inner) => inner.insert(default),
382 }
383 }
384
385 /// Ensures a value is in the entry by inserting the result of the default function if empty,
386 /// and returns a mutable reference to the value in the entry.
387 #[inline]
388 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
389 match self {
390 Entry::Occupied(inner) => inner.into_mut(),
391 Entry::Vacant(inner) => inner.insert(default()),
392 }
393 }
394
395 /// Ensures a value is in the entry by inserting the default value if empty,
396 /// and returns a mutable reference to the value in the entry.
397 #[inline]
398 pub fn or_default(self) -> &'a mut V where V: Default {
399 match self {
400 Entry::Occupied(inner) => inner.into_mut(),
401 Entry::Vacant(inner) => inner.insert(Default::default()),
402 }
403 }
404
405 /// Provides in-place mutable access to an occupied entry before any potential inserts into the
406 /// map.
407 #[inline]
408 // std::collections::hash_map::Entry::and_modify doesn’t have #[must_use], I’ll follow suit.
409 #[allow(clippy::return_self_not_must_use)]
410 pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Self {
411 match self {
412 Entry::Occupied(mut inner) => {
413 f(inner.get_mut());
414 Entry::Occupied(inner)
415 },
416 Entry::Vacant(inner) => Entry::Vacant(inner),
417 }
418 }
419
420 // Additional stable methods (as of 1.60.0-nightly) that could be added:
421 // insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> (1.59.0)
422 }
423
424 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> OccupiedEntry<'a, A, V> {
425 /// Gets a reference to the value in the entry
426 #[inline]
427 pub fn get(&self) -> &V {
428 unsafe { self.inner.get().downcast_ref_unchecked() }
429 }
430
431 /// Gets a mutable reference to the value in the entry
432 #[inline]
433 pub fn get_mut(&mut self) -> &mut V {
434 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
435 }
436
437 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
438 /// with a lifetime bound to the collection itself
439 #[inline]
440 pub fn into_mut(self) -> &'a mut V {
441 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
442 }
443
444 /// Sets the value of the entry, and returns the entry's old value
445 #[inline]
446 pub fn insert(&mut self, value: V) -> V {
447 unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() }
448 }
449
450 /// Takes the value out of the entry, and returns it
451 #[inline]
452 pub fn remove(self) -> V {
453 unsafe { *self.inner.remove().downcast_unchecked() }
454 }
455 }
456
457 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> VacantEntry<'a, A, V> {
458 /// Sets the value of the entry with the VacantEntry's key,
459 /// and returns a mutable reference to it
460 #[inline]
461 pub fn insert(self, value: V) -> &'a mut V {
462 unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() }
463 }
464 }
465
466 /// A hasher designed to eke a little more speed out, given `TypeId`’s known characteristics.
467 ///
468 /// Specifically, this is a no-op hasher that expects to be fed a u64’s worth of
469 /// randomly-distributed bits. It works well for `TypeId` (eliminating start-up time, so that my
470 /// get_missing benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
471 /// that my insert_and_get_on_260_types benchmark is ~12μs instead of ~21.5μs), but will
472 /// panic in debug mode and always emit zeros in release mode for any other sorts of inputs, so
473 /// yeah, don’t use it! 😀
474 #[derive(Default)]
475 pub struct TypeIdHasher {
476 value: u64,
477 }
478
479 impl Hasher for TypeIdHasher {
480 #[inline]
481 fn write(&mut self, bytes: &[u8]) {
482 // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
483 // that changing, but I don’t want to depend on something that isn’t expressly part of the
484 // contract for safety. But I’m OK with release builds putting everything in one bucket
485 // if it *did* change (and debug builds panicking).
486 debug_assert_eq!(bytes.len(), 8);
487 let _ = bytes.try_into()
488 .map(|array| self.value = u64::from_ne_bytes(array));
489 }
490
491 #[inline]
492 fn finish(&self) -> u64 { self.value }
493 }
494
495 #[cfg(test)]
496 mod tests {
497 use super::*;
498
499 #[derive(Clone, Debug, PartialEq)] struct A(i32);
500 #[derive(Clone, Debug, PartialEq)] struct B(i32);
501 #[derive(Clone, Debug, PartialEq)] struct C(i32);
502 #[derive(Clone, Debug, PartialEq)] struct D(i32);
503 #[derive(Clone, Debug, PartialEq)] struct E(i32);
504 #[derive(Clone, Debug, PartialEq)] struct F(i32);
505 #[derive(Clone, Debug, PartialEq)] struct J(i32);
506
507 macro_rules! test_entry {
508 ($name:ident, $init:ty) => {
509 #[test]
510 fn $name() {
511 let mut map = <$init>::new();
512 assert_eq!(map.insert(A(10)), None);
513 assert_eq!(map.insert(B(20)), None);
514 assert_eq!(map.insert(C(30)), None);
515 assert_eq!(map.insert(D(40)), None);
516 assert_eq!(map.insert(E(50)), None);
517 assert_eq!(map.insert(F(60)), None);
518
519 // Existing key (insert)
520 match map.entry::<A>() {
521 Entry::Vacant(_) => unreachable!(),
522 Entry::Occupied(mut view) => {
523 assert_eq!(view.get(), &A(10));
524 assert_eq!(view.insert(A(100)), A(10));
525 }
526 }
527 assert_eq!(map.get::<A>().unwrap(), &A(100));
528 assert_eq!(map.len(), 6);
529
530
531 // Existing key (update)
532 match map.entry::<B>() {
533 Entry::Vacant(_) => unreachable!(),
534 Entry::Occupied(mut view) => {
535 let v = view.get_mut();
536 let new_v = B(v.0 * 10);
537 *v = new_v;
538 }
539 }
540 assert_eq!(map.get::<B>().unwrap(), &B(200));
541 assert_eq!(map.len(), 6);
542
543
544 // Existing key (remove)
545 match map.entry::<C>() {
546 Entry::Vacant(_) => unreachable!(),
547 Entry::Occupied(view) => {
548 assert_eq!(view.remove(), C(30));
549 }
550 }
551 assert_eq!(map.get::<C>(), None);
552 assert_eq!(map.len(), 5);
553
554
555 // Inexistent key (insert)
556 match map.entry::<J>() {
557 Entry::Occupied(_) => unreachable!(),
558 Entry::Vacant(view) => {
559 assert_eq!(*view.insert(J(1000)), J(1000));
560 }
561 }
562 assert_eq!(map.get::<J>().unwrap(), &J(1000));
563 assert_eq!(map.len(), 6);
564
565 // Entry.or_insert on existing key
566 map.entry::<B>().or_insert(B(71)).0 += 1;
567 assert_eq!(map.get::<B>().unwrap(), &B(201));
568 assert_eq!(map.len(), 6);
569
570 // Entry.or_insert on nonexisting key
571 map.entry::<C>().or_insert(C(300)).0 += 1;
572 assert_eq!(map.get::<C>().unwrap(), &C(301));
573 assert_eq!(map.len(), 7);
574 }
575 }
576 }
577
578 test_entry!(test_entry_any, AnyMap);
579 test_entry!(test_entry_cloneany, Map<dyn CloneAny>);
580
581 #[test]
582 fn test_default() {
583 let map: AnyMap = Default::default();
584 assert_eq!(map.len(), 0);
585 }
586
587 #[test]
588 fn test_clone() {
589 let mut map: Map<dyn CloneAny> = Map::new();
590 let _ = map.insert(A(1));
591 let _ = map.insert(B(2));
592 let _ = map.insert(D(3));
593 let _ = map.insert(E(4));
594 let _ = map.insert(F(5));
595 let _ = map.insert(J(6));
596 let map2 = map.clone();
597 assert_eq!(map2.len(), 6);
598 assert_eq!(map2.get::<A>(), Some(&A(1)));
599 assert_eq!(map2.get::<B>(), Some(&B(2)));
600 assert_eq!(map2.get::<C>(), None);
601 assert_eq!(map2.get::<D>(), Some(&D(3)));
602 assert_eq!(map2.get::<E>(), Some(&E(4)));
603 assert_eq!(map2.get::<F>(), Some(&F(5)));
604 assert_eq!(map2.get::<J>(), Some(&J(6)));
605 }
606
607 #[test]
608 fn test_varieties() {
609 fn assert_send<T: Send>() { }
610 fn assert_sync<T: Sync>() { }
611 fn assert_clone<T: Clone>() { }
612 fn assert_debug<T: ::core::fmt::Debug>() { }
613 assert_send::<Map<dyn Any + Send>>();
614 assert_send::<Map<dyn Any + Send + Sync>>();
615 assert_sync::<Map<dyn Any + Send + Sync>>();
616 assert_debug::<Map<dyn Any>>();
617 assert_debug::<Map<dyn Any + Send>>();
618 assert_debug::<Map<dyn Any + Send + Sync>>();
619 assert_send::<Map<dyn CloneAny + Send>>();
620 assert_send::<Map<dyn CloneAny + Send + Sync>>();
621 assert_sync::<Map<dyn CloneAny + Send + Sync>>();
622 assert_clone::<Map<dyn CloneAny + Send>>();
623 assert_clone::<Map<dyn CloneAny + Send + Sync>>();
624 assert_clone::<Map<dyn CloneAny + Send + Sync>>();
625 assert_debug::<Map<dyn CloneAny>>();
626 assert_debug::<Map<dyn CloneAny + Send>>();
627 assert_debug::<Map<dyn CloneAny + Send + Sync>>();
628 }
629
630 #[test]
631 fn type_id_hasher() {
632 #[cfg(not(feature = "std"))]
633 use alloc::vec::Vec;
634 use core::hash::Hash;
635 fn verify_hashing_with(type_id: TypeId) {
636 let mut hasher = TypeIdHasher::default();
637 type_id.hash(&mut hasher);
638 // SAFETY: u64 is valid for all bit patterns.
639 assert_eq!(hasher.finish(), unsafe { core::mem::transmute::<TypeId, u64>(type_id) });
640 }
641 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
642 verify_hashing_with(TypeId::of::<usize>());
643 verify_hashing_with(TypeId::of::<()>());
644 verify_hashing_with(TypeId::of::<str>());
645 verify_hashing_with(TypeId::of::<&str>());
646 verify_hashing_with(TypeId::of::<Vec<u8>>());
647 }
648
649 #[test]
650 fn test_extend() {
651 let mut map = AnyMap::new();
652 map.extend([Box::new(123) as Box<dyn Any>, Box::new(456), Box::new(true)]);
653 assert_eq!(map.get(), Some(&456));
654 assert_eq!(map.get::<bool>(), Some(&true));
655 assert!(map.get::<Box<dyn Any>>().is_none());
656 }
657 }