79a45615b60169f5d877b521831ac61b05e80b76
1 //! This crate provides a safe and convenient store for one value of each type.
3 //! Your starting point is [`Map`]. It has an example.
5 #![warn(missing_docs, unused_results)]
7 #![cfg_attr(not(feature = "std"), no_std)]
9 use core
::any
::{Any
, TypeId
};
10 use core
::convert
::TryInto
;
11 use core
::hash
::{Hasher
, BuildHasherDefault
};
12 use core
::marker
::PhantomData
;
14 #[cfg(not(any(feature = "std", feature = "hashbrown")))]
15 compile_error!("anymap: you must enable the 'std' feature or the 'hashbrown' feature");
17 #[cfg(not(feature = "std"))]
20 #[cfg(not(feature = "std"))]
21 use alloc
::boxed
::Box
;
23 use any
::{UncheckedAnyExt
, IntoBox
};
24 pub use any
::CloneAny
;
26 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
27 /// A re-export of [`std::collections::hash_map`] for raw access.
29 /// If the `hashbrown` feature gets enabled, this will become an export of `hashbrown::hash_map`.
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
;
37 #[cfg(feature = "hashbrown")]
38 /// A re-export of [`hashbrown::hash_map`] for raw access.
40 /// If the `hashbrown` feature was disabled, this would become an export of
41 /// `std::collections::hash_map`.
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
;
49 use self::raw_hash_map
::HashMap
;
53 /// Raw access to the underlying `HashMap`.
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
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
>>;
64 /// A collection containing zero or one values for any given type and allowing convenient,
65 /// type-safe access to those values.
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:
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
75 /// Cumulatively, there are thus six forms of map:
77 /// - <code>[Map]<dyn [core::any::Any]></code>, also spelled [`AnyMap`] for convenience.
78 /// - <code>[Map]<dyn [core::any::Any] + Send></code>
79 /// - <code>[Map]<dyn [core::any::Any] + Send + Sync></code>
80 /// - <code>[Map]<dyn [CloneAny]></code>
81 /// - <code>[Map]<dyn [CloneAny] + Send></code>
82 /// - <code>[Map]<dyn [CloneAny] + Send + Sync></code>
86 /// (Here using the [`AnyMap`] convenience alias; the first line could use
87 /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
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);
97 /// #[derive(Clone, PartialEq, Debug)]
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");
109 /// Values containing non-static references are not permitted.
111 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
115 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
116 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
118 fn clone(&self) -> Map
<A
> {
120 raw
: self.raw
.clone(),
125 /// The most common type of `Map`: just using `Any`; <code>[Map]<dyn [Any]></code>.
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
>;
132 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for Map
<A
> {
134 fn default() -> Map
<A
> {
139 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
140 /// Create an empty collection.
142 pub fn new() -> Map
<A
> {
144 raw
: RawMap
::with_hasher(Default
::default()),
148 /// Creates an empty collection with the given initial capacity.
150 pub fn with_capacity(capacity
: usize) -> Map
<A
> {
152 raw
: RawMap
::with_capacity_and_hasher(capacity
, Default
::default()),
156 /// Returns the number of elements the collection can hold without reallocating.
158 pub fn capacity(&self) -> usize {
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.
168 /// Panics if the new allocation size overflows `usize`.
170 pub fn reserve(&mut self, additional
: usize) {
171 self.raw
.reserve(additional
)
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.
178 pub fn shrink_to_fit(&mut self) {
179 self.raw
.shrink_to_fit()
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)
186 /// Returns the number of items in the collection.
188 pub fn len(&self) -> usize {
192 /// Returns true if there are no items in the collection.
194 pub fn is_empty(&self) -> bool
{
198 /// Removes all items from the collection. Keeps the allocated memory for reuse.
200 pub fn clear(&mut self) {
204 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
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
>() })
211 /// Returns a mutable reference to the value stored in the collection for the type `T`,
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
>() })
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.
223 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
225 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
226 .map(|any
| *any
.downcast_unchecked
::<T
>())
230 // rustc 1.60.0-nightly has another method try_insert that would be nice to add when stable.
232 /// Removes the `T` value from the collection,
233 /// returning it if there was one or `None` if there was not.
235 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
236 self.raw
.remove(&TypeId
::of
::<T
>())
237 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
240 /// Returns true if the collection contains a value of type `T`.
242 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
243 self.raw
.contains_key(&TypeId
::of
::<T
>())
246 /// Gets the entry for the given type in the collection for in-place manipulation
248 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
249 match self.raw
.entry(TypeId
::of
::<T
>()) {
250 raw_hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
254 raw_hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
261 /// Get access to the raw hash map that backs this.
263 /// This will seldom be useful, but it’s conceivable that you could wish to iterate over all
264 /// the items in the collection, and this lets you do that.
266 /// To improve compatibility with Cargo features, interact with this map through the names
267 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
268 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
269 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
270 /// hashbrown, your code will break.
272 pub fn as_raw(&self) -> &RawMap
<A
> {
276 /// Get mutable access to the raw hash map that backs this.
278 /// This will seldom be useful, but it’s conceivable that you could wish to iterate over all
279 /// the items in the collection mutably, or drain or something, or *possibly* even batch
280 /// insert, and this lets you do that.
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.
290 /// If you insert any values to the raw map, the key (a `TypeId`) must match the value’s type,
291 /// or *undefined behaviour* will occur when you access those values.
293 /// (*Removing* entries is perfectly safe.)
295 pub unsafe fn as_raw_mut(&mut self) -> &mut RawMap
<A
> {
299 /// Convert this into the raw hash map that backs this.
301 /// This will seldom be useful, but it’s conceivable that you could wish to consume all the
302 /// items in the collection and do *something* with some or all of them, and this lets you do
303 /// that, without the `unsafe` that `.as_raw_mut().drain()` would require.
305 /// To improve compatibility with Cargo features, interact with this map through the names
306 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
307 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
308 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
309 /// hashbrown, your code will break.
311 pub fn into_raw(self) -> RawMap
<A
> {
315 /// Construct a map from a collection of raw values.
317 /// You know what? I can’t immediately think of any legitimate use for this, especially because
318 /// of the requirement of the `BuildHasherDefault<TypeIdHasher>` generic in the map.
320 /// Perhaps this will be most practical as `unsafe { Map::from_raw(iter.collect()) }`, iter
321 /// being an iterator over `(TypeId, Box<A>)` pairs. Eh, this method provides symmetry with
322 /// `into_raw`, so I don’t care if literally no one ever uses it. I’m not even going to write a
323 /// test for it, it’s so trivial.
325 /// To improve compatibility with Cargo features, interact with this map through the names
326 /// [`anymap::RawMap`][RawMap] and [`anymap::raw_hash_map`][raw_hash_map], rather than through
327 /// `std::collections::{HashMap, hash_map}` or `hashbrown::{HashMap, hash_map}`, for anything
328 /// beyond self methods. Otherwise, if you use std and another crate in the tree enables
329 /// hashbrown, your code will break.
333 /// For all entries in the raw map, the key (a `TypeId`) must match the value’s type,
334 /// or *undefined behaviour* will occur when you access that entry.
336 pub unsafe fn from_raw(raw
: RawMap
<A
>) -> Map
<A
> {
341 impl<A
: ?Sized
+ UncheckedAnyExt
> Extend
<Box
<A
>> for Map
<A
> {
343 fn extend
<T
: IntoIterator
<Item
= Box
<A
>>>(&mut self, iter
: T
) {
345 let _
= self.raw
.insert(item
.type_id(), item
);
350 /// A view into a single occupied location in an `Map`.
351 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
352 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
353 inner
: raw_hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>>,
354 #[cfg(feature = "hashbrown")]
355 inner
: raw_hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>,
356 type_
: PhantomData
<V
>,
359 /// A view into a single empty location in an `Map`.
360 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
361 #[cfg(all(feature = "std", not(feature = "hashbrown")))]
362 inner
: raw_hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>>,
363 #[cfg(feature = "hashbrown")]
364 inner
: raw_hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>,
365 type_
: PhantomData
<V
>,
368 /// A view into a single location in an `Map`, which may be vacant or occupied.
369 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
370 /// An occupied Entry
371 Occupied(OccupiedEntry
<'a
, A
, V
>),
373 Vacant(VacantEntry
<'a
, A
, V
>),
376 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
377 /// Ensures a value is in the entry by inserting the default if empty, and returns
378 /// a mutable reference to the value in the entry.
380 pub fn or_insert(self, default: V
) -> &'a
mut V
{
382 Entry
::Occupied(inner
) => inner
.into_mut(),
383 Entry
::Vacant(inner
) => inner
.insert(default),
387 /// Ensures a value is in the entry by inserting the result of the default function if empty,
388 /// and returns a mutable reference to the value in the entry.
390 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
392 Entry
::Occupied(inner
) => inner
.into_mut(),
393 Entry
::Vacant(inner
) => inner
.insert(default()),
397 /// Ensures a value is in the entry by inserting the default value if empty,
398 /// and returns a mutable reference to the value in the entry.
400 pub fn or_default(self) -> &'a
mut V
where V
: Default
{
402 Entry
::Occupied(inner
) => inner
.into_mut(),
403 Entry
::Vacant(inner
) => inner
.insert(Default
::default()),
407 /// Provides in-place mutable access to an occupied entry before any potential inserts into the
410 // std::collections::hash_map::Entry::and_modify doesn’t have #[must_use], I’ll follow suit.
411 #[allow(clippy::return_self_not_must_use)]
412 pub fn and_modify
<F
: FnOnce(&mut V
)>(self, f
: F
) -> Self {
414 Entry
::Occupied(mut inner
) => {
416 Entry
::Occupied(inner
)
418 Entry
::Vacant(inner
) => Entry
::Vacant(inner
),
422 // Additional stable methods (as of 1.60.0-nightly) that could be added:
423 // insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> (1.59.0)
426 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
427 /// Gets a reference to the value in the entry
429 pub fn get(&self) -> &V
{
430 unsafe { self.inner
.get().downcast_ref_unchecked() }
433 /// Gets a mutable reference to the value in the entry
435 pub fn get_mut(&mut self) -> &mut V
{
436 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
439 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
440 /// with a lifetime bound to the collection itself
442 pub fn into_mut(self) -> &'a
mut V
{
443 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
446 /// Sets the value of the entry, and returns the entry's old value
448 pub fn insert(&mut self, value
: V
) -> V
{
449 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
452 /// Takes the value out of the entry, and returns it
454 pub fn remove(self) -> V
{
455 unsafe { *self.inner
.remove().downcast_unchecked() }
459 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
460 /// Sets the value of the entry with the VacantEntry's key,
461 /// and returns a mutable reference to it
463 pub fn insert(self, value
: V
) -> &'a
mut V
{
464 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
468 /// A hasher designed to eke a little more speed out, given `TypeId`’s known characteristics.
470 /// Specifically, this is a no-op hasher that expects to be fed a u64’s worth of
471 /// randomly-distributed bits. It works well for `TypeId` (eliminating start-up time, so that my
472 /// get_missing benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
473 /// that my insert_and_get_on_260_types benchmark is ~12μs instead of ~21.5μs), but will
474 /// panic in debug mode and always emit zeros in release mode for any other sorts of inputs, so
475 /// yeah, don’t use it! 😀
477 pub struct TypeIdHasher
{
481 impl Hasher
for TypeIdHasher
{
483 fn write(&mut self, bytes
: &[u8]) {
484 // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
485 // that changing, but I don’t want to depend on something that isn’t expressly part of the
486 // contract for safety. But I’m OK with release builds putting everything in one bucket
487 // if it *did* change (and debug builds panicking).
488 debug_assert_eq!(bytes
.len(), 8);
489 let _
= bytes
.try_into()
490 .map(|array
| self.value
= u64::from_ne_bytes(array
));
494 fn finish(&self) -> u64 { self.value
}
501 #[derive(Clone, Debug, PartialEq)] struct A(i32);
502 #[derive(Clone, Debug, PartialEq)] struct B(i32);
503 #[derive(Clone, Debug, PartialEq)] struct C(i32);
504 #[derive(Clone, Debug, PartialEq)] struct D(i32);
505 #[derive(Clone, Debug, PartialEq)] struct E(i32);
506 #[derive(Clone, Debug, PartialEq)] struct F(i32);
507 #[derive(Clone, Debug, PartialEq)] struct J(i32);
509 macro_rules
! test_entry
{
510 ($name
:ident
, $init
:ty
) => {
513 let mut map
= <$init
>::new();
514 assert_eq!(map
.insert(A(10)), None
);
515 assert_eq!(map
.insert(B(20)), None
);
516 assert_eq!(map
.insert(C(30)), None
);
517 assert_eq!(map
.insert(D(40)), None
);
518 assert_eq!(map
.insert(E(50)), None
);
519 assert_eq!(map
.insert(F(60)), None
);
521 // Existing key (insert)
522 match map
.entry
::<A
>() {
523 Entry
::Vacant(_
) => unreachable!(),
524 Entry
::Occupied(mut view
) => {
525 assert_eq!(view
.get(), &A(10));
526 assert_eq!(view
.insert(A(100)), A(10));
529 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
530 assert_eq!(map
.len(), 6);
533 // Existing key (update)
534 match map
.entry
::<B
>() {
535 Entry
::Vacant(_
) => unreachable!(),
536 Entry
::Occupied(mut view
) => {
537 let v
= view
.get_mut();
538 let new_v
= B(v
.0 * 10);
542 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
543 assert_eq!(map
.len(), 6);
546 // Existing key (remove)
547 match map
.entry
::<C
>() {
548 Entry
::Vacant(_
) => unreachable!(),
549 Entry
::Occupied(view
) => {
550 assert_eq!(view
.remove(), C(30));
553 assert_eq!(map
.get
::<C
>(), None
);
554 assert_eq!(map
.len(), 5);
557 // Inexistent key (insert)
558 match map
.entry
::<J
>() {
559 Entry
::Occupied(_
) => unreachable!(),
560 Entry
::Vacant(view
) => {
561 assert_eq!(*view
.insert(J(1000)), J(1000));
564 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
565 assert_eq!(map
.len(), 6);
567 // Entry.or_insert on existing key
568 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
569 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
570 assert_eq!(map
.len(), 6);
572 // Entry.or_insert on nonexisting key
573 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
574 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
575 assert_eq!(map
.len(), 7);
580 test_entry!(test_entry_any
, AnyMap
);
581 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
585 let map
: AnyMap
= Default
::default();
586 assert_eq!(map
.len(), 0);
591 let mut map
: Map
<dyn CloneAny
> = Map
::new();
592 let _
= map
.insert(A(1));
593 let _
= map
.insert(B(2));
594 let _
= map
.insert(D(3));
595 let _
= map
.insert(E(4));
596 let _
= map
.insert(F(5));
597 let _
= map
.insert(J(6));
598 let map2
= map
.clone();
599 assert_eq!(map2
.len(), 6);
600 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
601 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
602 assert_eq!(map2
.get
::<C
>(), None
);
603 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
604 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
605 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
606 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
610 fn test_varieties() {
611 fn assert_send
<T
: Send
>() { }
612 fn assert_sync
<T
: Sync
>() { }
613 fn assert_clone
<T
: Clone
>() { }
614 fn assert_debug
<T
: ::core
::fmt
::Debug
>() { }
615 assert_send
::<Map
<dyn Any
+ Send
>>();
616 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
617 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
618 assert_debug
::<Map
<dyn Any
>>();
619 assert_debug
::<Map
<dyn Any
+ Send
>>();
620 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
621 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
622 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
623 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
624 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
625 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
626 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
627 assert_debug
::<Map
<dyn CloneAny
>>();
628 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
629 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
633 fn type_id_hasher() {
634 #[cfg(not(feature = "std"))]
636 use core
::hash
::Hash
;
637 fn verify_hashing_with(type_id
: TypeId
) {
638 let mut hasher
= TypeIdHasher
::default();
639 type_id
.hash(&mut hasher
);
640 // SAFETY: u64 is valid for all bit patterns.
641 assert_eq!(hasher
.finish(), unsafe { core
::mem
::transmute
::<TypeId
, u64>(type_id
) });
643 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
644 verify_hashing_with(TypeId
::of
::<usize>());
645 verify_hashing_with(TypeId
::of
::<()>());
646 verify_hashing_with(TypeId
::of
::<str>());
647 verify_hashing_with(TypeId
::of
::<&str>());
648 verify_hashing_with(TypeId
::of
::<Vec
<u8>>());