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