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.
7 //! This crate has two independent features, each of which provides an implementation providing
8 //! types `Map`, `AnyMap`, `OccupiedEntry`, `VacantEntry`, `Entry` and `RawMap`:
10 #![cfg_attr(feature = "std", doc = " - **std** (default, *enabled* in this build):")]
11 #![cfg_attr(not(feature = "std"), doc = " - **std** (default, *disabled* in this build):")]
12 //! an implementation using `std::collections::hash_map`, placed in the crate root
13 //! (e.g. `anymap::AnyMap`).
15 #![cfg_attr(feature = "hashbrown", doc = " - **hashbrown** (optional; *enabled* in this build):")]
16 #![cfg_attr(not(feature = "hashbrown"), doc = " - **hashbrown** (optional; *disabled* in this build):")]
17 //! an implementation using `alloc` and `hashbrown::hash_map`, placed in a module `hashbrown`
18 //! (e.g. `anymap::hashbrown::AnyMap`).
20 #![warn(missing_docs, unused_results)]
22 #![cfg_attr(not(feature = "std"), no_std)]
24 use core
::convert
::TryInto
;
25 use core
::hash
::Hasher
;
27 #[cfg(not(feature = "std"))]
30 pub use crate::any
::CloneAny
;
34 #[cfg(any(feature = "std", feature = "hashbrown"))]
35 macro_rules
! everything
{
36 ($example_init
:literal
, $
($parent
:ident
)::+ $
(, $entry_generics
:ty
)?
) => {
37 use core
::any
::{Any
, TypeId
};
38 use core
::hash
::BuildHasherDefault
;
39 use core
::marker
::PhantomData
;
41 #[cfg(not(feature = "std"))]
42 use alloc
::boxed
::Box
;
44 use ::$
($parent
)::+::hash_map
::{self, HashMap
};
46 use crate::any
::{Downcast
, IntoBox
};
48 /// Raw access to the underlying `HashMap`.
50 /// This alias is provided for convenience because of the ugly third generic parameter.
51 pub type RawMap
<A
> = HashMap
<TypeId
, Box
<A
>, BuildHasherDefault
<TypeIdHasher
>>;
53 /// A collection containing zero or one values for any given type and allowing convenient,
54 /// type-safe access to those values.
56 /// The type parameter `A` allows you to use a different value type; normally you will want
57 /// it to be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
59 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with
60 /// that, you can only add types that implement `Clone` to the map.
61 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those
64 /// Cumulatively, there are thus six forms of map:
66 /// - <code>[Map]<dyn [core::any::Any]></code>,
67 /// also spelled [`AnyMap`] for convenience.
68 /// - <code>[Map]<dyn [core::any::Any] + Send></code>
69 /// - <code>[Map]<dyn [core::any::Any] + Send + Sync></code>
70 /// - <code>[Map]<dyn [CloneAny]></code>
71 /// - <code>[Map]<dyn [CloneAny] + Send></code>
72 /// - <code>[Map]<dyn [CloneAny] + Send + Sync></code>
76 /// (Here using the [`AnyMap`] convenience alias; the first line could use
77 /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
80 #[doc = $example_init]
81 /// assert_eq!(data.get(), None::<&i32>);
82 /// data.insert(42i32);
83 /// assert_eq!(data.get(), Some(&42i32));
84 /// data.remove::<i32>();
85 /// assert_eq!(data.get::<i32>(), None);
87 /// #[derive(Clone, PartialEq, Debug)]
92 /// assert_eq!(data.get::<Foo>(), None);
93 /// data.insert(Foo { str: format!("foo") });
94 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
95 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
96 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
99 /// Values containing non-static references are not permitted.
101 pub struct Map
<A
: ?Sized
+ Downcast
= dyn Any
> {
105 // #[derive(Clone)] would want A to implement Clone, but in reality only Box<A> can.
106 impl<A
: ?Sized
+ Downcast
> Clone
for Map
<A
> where Box
<A
>: Clone
{
108 fn clone(&self) -> Map
<A
> {
110 raw
: self.raw
.clone(),
115 /// The most common type of `Map`: just using `Any`; <code>[Map]<dyn [Any]></code>.
117 /// Why is this a separate type alias rather than a default value for `Map<A>`?
118 /// `Map::new()` doesn’t seem to be happy to infer that it should go with the default
119 /// value. It’s a bit sad, really. Ah well, I guess this approach will do.
120 pub type AnyMap
= Map
<dyn Any
>;
122 impl<A
: ?Sized
+ Downcast
> Default
for Map
<A
> {
124 fn default() -> Map
<A
> {
129 impl<A
: ?Sized
+ Downcast
> Map
<A
> {
130 /// Create an empty collection.
132 pub fn new() -> Map
<A
> {
134 raw
: RawMap
::with_hasher(Default
::default()),
138 /// Creates an empty collection with the given initial capacity.
140 pub fn with_capacity(capacity
: usize) -> Map
<A
> {
142 raw
: RawMap
::with_capacity_and_hasher(capacity
, Default
::default()),
146 /// Returns the number of elements the collection can hold without reallocating.
148 pub fn capacity(&self) -> usize {
152 /// Reserves capacity for at least `additional` more elements to be inserted
153 /// in the collection. The collection may reserve more space to avoid
154 /// frequent reallocations.
158 /// Panics if the new allocation size overflows `usize`.
160 pub fn reserve(&mut self, additional
: usize) {
161 self.raw
.reserve(additional
)
164 /// Shrinks the capacity of the collection as much as possible. It will drop
165 /// down as much as possible while maintaining the internal rules
166 /// and possibly leaving some space in accordance with the resize policy.
168 pub fn shrink_to_fit(&mut self) {
169 self.raw
.shrink_to_fit()
172 // Additional stable methods (as of 1.60.0-nightly) that could be added:
173 // try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> (1.57.0)
174 // shrink_to(&mut self, min_capacity: usize) (1.56.0)
176 /// Returns the number of items in the collection.
178 pub fn len(&self) -> usize {
182 /// Returns true if there are no items in the collection.
184 pub fn is_empty(&self) -> bool
{
188 /// Removes all items from the collection. Keeps the allocated memory for reuse.
190 pub fn clear(&mut self) {
194 /// Returns a reference to the value stored in the collection for the type `T`,
197 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
198 self.raw
.get(&TypeId
::of
::<T
>())
199 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
202 /// Returns a mutable reference to the value stored in the collection for the type `T`,
205 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
206 self.raw
.get_mut(&TypeId
::of
::<T
>())
207 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
210 /// Sets the value stored in the collection for the type `T`.
211 /// If the collection already had a value of type `T`, that value is returned.
212 /// Otherwise, `None` is returned.
214 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
215 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
216 .map(|any
| unsafe { *any
.downcast_unchecked
::<T
>() })
219 // rustc 1.60.0-nightly has another method try_insert that would be nice when stable.
221 /// Removes the `T` value from the collection,
222 /// returning it if there was one or `None` if there was not.
224 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
225 self.raw
.remove(&TypeId
::of
::<T
>())
226 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
229 /// Returns true if the collection contains a value of type `T`.
231 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
232 self.raw
.contains_key(&TypeId
::of
::<T
>())
235 /// Gets the entry for the given type in the collection for in-place manipulation
237 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
238 match self.raw
.entry(TypeId
::of
::<T
>()) {
239 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
243 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
250 /// Get access to the raw hash map that backs this.
252 /// This will seldom be useful, but it’s conceivable that you could wish to iterate
253 /// over all the items in the collection, and this lets you do that.
255 pub fn as_raw(&self) -> &RawMap
<A
> {
259 /// Get mutable access to the raw hash map that backs this.
261 /// This will seldom be useful, but it’s conceivable that you could wish to iterate
262 /// over all the items in the collection mutably, or drain or something, or *possibly*
263 /// even batch insert, and this lets you do that.
267 /// If you insert any values to the raw map, the key (a `TypeId`) must match the
268 /// value’s type, or *undefined behaviour* will occur when you access those values.
270 /// (*Removing* entries is perfectly safe.)
272 pub unsafe fn as_raw_mut(&mut self) -> &mut RawMap
<A
> {
276 /// Convert this into the raw hash map that backs this.
278 /// This will seldom be useful, but it’s conceivable that you could wish to consume all
279 /// the items in the collection and do *something* with some or all of them, and this
280 /// lets you do that, without the `unsafe` that `.as_raw_mut().drain()` would require.
282 pub fn into_raw(self) -> RawMap
<A
> {
286 /// Construct a map from a collection of raw values.
288 /// You know what? I can’t immediately think of any legitimate use for this, especially
289 /// because of the requirement of the `BuildHasherDefault<TypeIdHasher>` generic in the
292 /// Perhaps this will be most practical as `unsafe { Map::from_raw(iter.collect()) }`,
293 /// `iter` being an iterator over `(TypeId, Box<A>)` pairs. Eh, this method provides
294 /// symmetry with `into_raw`, so I don’t care if literally no one ever uses it. I’m not
295 /// even going to write a test for it, it’s so trivial.
299 /// For all entries in the raw map, the key (a `TypeId`) must match the value’s type,
300 /// or *undefined behaviour* will occur when you access that entry.
302 pub unsafe fn from_raw(raw
: RawMap
<A
>) -> Map
<A
> {
307 impl<A
: ?Sized
+ Downcast
> Extend
<Box
<A
>> for Map
<A
> {
309 fn extend
<T
: IntoIterator
<Item
= Box
<A
>>>(&mut self, iter
: T
) {
311 let _
= self.raw
.insert(Downcast
::type_id(&*item
), item
);
316 /// A view into a single occupied location in an `Map`.
317 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ Downcast
, V
: 'a
> {
318 inner
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<A
>, $
($entry_generics
)?
>,
319 type_
: PhantomData
<V
>,
322 /// A view into a single empty location in an `Map`.
323 pub struct VacantEntry
<'a
, A
: ?Sized
+ Downcast
, V
: 'a
> {
324 inner
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<A
>, $
($entry_generics
)?
>,
325 type_
: PhantomData
<V
>,
328 /// A view into a single location in an `Map`, which may be vacant or occupied.
329 pub enum Entry
<'a
, A
: ?Sized
+ Downcast
, V
: 'a
> {
330 /// An occupied Entry
331 Occupied(OccupiedEntry
<'a
, A
, V
>),
333 Vacant(VacantEntry
<'a
, A
, V
>),
336 impl<'a
, A
: ?Sized
+ Downcast
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
337 /// Ensures a value is in the entry by inserting the default if empty, and returns
338 /// a mutable reference to the value in the entry.
340 pub fn or_insert(self, default: V
) -> &'a
mut V
{
342 Entry
::Occupied(inner
) => inner
.into_mut(),
343 Entry
::Vacant(inner
) => inner
.insert(default),
347 /// Ensures a value is in the entry by inserting the result of the default function if
348 /// empty, and returns a mutable reference to the value in the entry.
350 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
352 Entry
::Occupied(inner
) => inner
.into_mut(),
353 Entry
::Vacant(inner
) => inner
.insert(default()),
357 /// Ensures a value is in the entry by inserting the default value if empty,
358 /// and returns a mutable reference to the value in the entry.
360 pub fn or_default(self) -> &'a
mut V
where V
: Default
{
362 Entry
::Occupied(inner
) => inner
.into_mut(),
363 Entry
::Vacant(inner
) => inner
.insert(Default
::default()),
367 /// Provides in-place mutable access to an occupied entry before any potential inserts
370 pub fn and_modify
<F
: FnOnce(&mut V
)>(self, f
: F
) -> Self {
372 Entry
::Occupied(mut inner
) => {
374 Entry
::Occupied(inner
)
376 Entry
::Vacant(inner
) => Entry
::Vacant(inner
),
380 // Additional stable methods (as of 1.60.0-nightly) that could be added:
381 // insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> (1.59.0)
384 impl<'a
, A
: ?Sized
+ Downcast
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
385 /// Gets a reference to the value in the entry
387 pub fn get(&self) -> &V
{
388 unsafe { self.inner
.get().downcast_ref_unchecked() }
391 /// Gets a mutable reference to the value in the entry
393 pub fn get_mut(&mut self) -> &mut V
{
394 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
397 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
398 /// with a lifetime bound to the collection itself
400 pub fn into_mut(self) -> &'a
mut V
{
401 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
404 /// Sets the value of the entry, and returns the entry's old value
406 pub fn insert(&mut self, value
: V
) -> V
{
407 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
410 /// Takes the value out of the entry, and returns it
412 pub fn remove(self) -> V
{
413 unsafe { *self.inner
.remove().downcast_unchecked() }
417 impl<'a
, A
: ?Sized
+ Downcast
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
418 /// Sets the value of the entry with the VacantEntry's key,
419 /// and returns a mutable reference to it
421 pub fn insert(self, value
: V
) -> &'a
mut V
{
422 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
431 #[derive(Clone, Debug, PartialEq)] struct A(i32);
432 #[derive(Clone, Debug, PartialEq)] struct B(i32);
433 #[derive(Clone, Debug, PartialEq)] struct C(i32);
434 #[derive(Clone, Debug, PartialEq)] struct D(i32);
435 #[derive(Clone, Debug, PartialEq)] struct E(i32);
436 #[derive(Clone, Debug, PartialEq)] struct F(i32);
437 #[derive(Clone, Debug, PartialEq)] struct J(i32);
439 macro_rules
! test_entry
{
440 ($name
:ident
, $init
:ty
) => {
443 let mut map
= <$init
>::new();
444 assert_eq!(map
.insert(A(10)), None
);
445 assert_eq!(map
.insert(B(20)), None
);
446 assert_eq!(map
.insert(C(30)), None
);
447 assert_eq!(map
.insert(D(40)), None
);
448 assert_eq!(map
.insert(E(50)), None
);
449 assert_eq!(map
.insert(F(60)), None
);
451 // Existing key (insert)
452 match map
.entry
::<A
>() {
453 Entry
::Vacant(_
) => unreachable!(),
454 Entry
::Occupied(mut view
) => {
455 assert_eq!(view
.get(), &A(10));
456 assert_eq!(view
.insert(A(100)), A(10));
459 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
460 assert_eq!(map
.len(), 6);
463 // Existing key (update)
464 match map
.entry
::<B
>() {
465 Entry
::Vacant(_
) => unreachable!(),
466 Entry
::Occupied(mut view
) => {
467 let v
= view
.get_mut();
468 let new_v
= B(v
.0 * 10);
472 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
473 assert_eq!(map
.len(), 6);
476 // Existing key (remove)
477 match map
.entry
::<C
>() {
478 Entry
::Vacant(_
) => unreachable!(),
479 Entry
::Occupied(view
) => {
480 assert_eq!(view
.remove(), C(30));
483 assert_eq!(map
.get
::<C
>(), None
);
484 assert_eq!(map
.len(), 5);
487 // Inexistent key (insert)
488 match map
.entry
::<J
>() {
489 Entry
::Occupied(_
) => unreachable!(),
490 Entry
::Vacant(view
) => {
491 assert_eq!(*view
.insert(J(1000)), J(1000));
494 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
495 assert_eq!(map
.len(), 6);
497 // Entry.or_insert on existing key
498 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
499 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
500 assert_eq!(map
.len(), 6);
502 // Entry.or_insert on nonexisting key
503 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
504 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
505 assert_eq!(map
.len(), 7);
510 test_entry!(test_entry_any
, AnyMap
);
511 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
515 let map
: AnyMap
= Default
::default();
516 assert_eq!(map
.len(), 0);
521 let mut map
: Map
<dyn CloneAny
> = Map
::new();
522 let _
= map
.insert(A(1));
523 let _
= map
.insert(B(2));
524 let _
= map
.insert(D(3));
525 let _
= map
.insert(E(4));
526 let _
= map
.insert(F(5));
527 let _
= map
.insert(J(6));
528 let map2
= map
.clone();
529 assert_eq!(map2
.len(), 6);
530 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
531 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
532 assert_eq!(map2
.get
::<C
>(), None
);
533 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
534 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
535 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
536 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
540 fn test_varieties() {
541 fn assert_send
<T
: Send
>() { }
542 fn assert_sync
<T
: Sync
>() { }
543 fn assert_clone
<T
: Clone
>() { }
544 fn assert_debug
<T
: ::core
::fmt
::Debug
>() { }
545 assert_send
::<Map
<dyn Any
+ Send
>>();
546 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
547 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
548 assert_debug
::<Map
<dyn Any
>>();
549 assert_debug
::<Map
<dyn Any
+ Send
>>();
550 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
551 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
552 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
553 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
554 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
555 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
556 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
557 assert_debug
::<Map
<dyn CloneAny
>>();
558 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
559 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
564 let mut map
= AnyMap
::new();
565 // (vec![] for 1.36.0 compatibility; more recently, you should use [] instead.)
566 #[cfg(not(feature = "std"))]
568 map
.extend(vec
![Box
::new(123) as Box
<dyn Any
>, Box
::new(456), Box
::new(true)]);
569 assert_eq!(map
.get(), Some(&456));
570 assert_eq!(map
.get
::<bool
>(), Some(&true));
571 assert!(map
.get
::<Box
<dyn Any
>>().is_none());
577 #[cfg(feature = "std")]
579 "let mut data = anymap::AnyMap::new();",
583 #[cfg(feature = "hashbrown")]
584 /// AnyMap backed by `hashbrown`.
586 /// This depends on the `hashbrown` Cargo feature being enabled.
588 use crate::TypeIdHasher
;
590 use crate::any
::CloneAny
;
593 "let mut data = anymap::hashbrown::AnyMap::new();",
595 BuildHasherDefault
<TypeIdHasher
>
599 /// A hasher designed to eke a little more speed out, given `TypeId`’s known characteristics.
601 /// Specifically, this is a no-op hasher that expects to be fed a u64’s worth of
602 /// randomly-distributed bits. It works well for `TypeId` (eliminating start-up time, so that my
603 /// get_missing benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
604 /// that my insert_and_get_on_260_types benchmark is ~12μs instead of ~21.5μs), but will
605 /// panic in debug mode and always emit zeros in release mode for any other sorts of inputs, so
606 /// yeah, don’t use it! 😀
608 pub struct TypeIdHasher
{
612 impl Hasher
for TypeIdHasher
{
614 fn write(&mut self, bytes
: &[u8]) {
615 // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
616 // that changing, but I don’t want to depend on something that isn’t expressly part of the
617 // contract for safety. But I’m OK with release builds putting everything in one bucket
618 // if it *did* change (and debug builds panicking).
619 debug_assert_eq!(bytes
.len(), 8);
620 let _
= bytes
.try_into()
621 .map(|array
| self.value
= u64::from_ne_bytes(array
));
625 fn finish(&self) -> u64 { self.value
}
629 fn type_id_hasher() {
630 #[cfg(not(feature = "std"))]
632 use core
::hash
::Hash
;
633 use core
::any
::TypeId
;
634 fn verify_hashing_with(type_id
: TypeId
) {
635 let mut hasher
= TypeIdHasher
::default();
636 type_id
.hash(&mut hasher
);
637 // SAFETY: u64 is valid for all bit patterns.
638 assert_eq!(hasher
.finish(), unsafe { core
::mem
::transmute
::<TypeId
, u64>(type_id
) });
640 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
641 verify_hashing_with(TypeId
::of
::<usize>());
642 verify_hashing_with(TypeId
::of
::<()>());
643 verify_hashing_with(TypeId
::of
::<str>());
644 verify_hashing_with(TypeId
::of
::<&str>());
645 verify_hashing_with(TypeId
::of
::<Vec
<u8>>());