6366c70b5a3781fda251734893cf2585d7f196bc
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
::marker
::PhantomData
;
12 #[cfg(not(any(feature = "std", feature = "hashbrown")))]
13 compile_error!("anymap: you must enable the 'std' feature or the 'hashbrown' feature");
15 #[cfg(not(feature = "std"))]
18 #[cfg(not(feature = "std"))]
19 use alloc
::boxed
::Box
;
22 use any
::{UncheckedAnyExt
, IntoBox
};
23 pub use any
::CloneAny
;
25 macro_rules
! impl_common_methods
{
27 field
: $t
:ident
.$field
:ident
;
29 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
31 impl<A
: ?Sized
+ UncheckedAnyExt
> $t
<A
> {
32 /// Create an empty collection.
34 pub fn new() -> $t
<A
> {
40 /// Creates an empty collection with the given initial capacity.
42 pub fn with_capacity($with_capacity_arg
: usize) -> $t
<A
> {
44 $field
: $with_capacity
,
48 /// Returns the number of elements the collection can hold without reallocating.
50 pub fn capacity(&self) -> usize {
51 self.$field
.capacity()
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.
60 /// Panics if the new allocation size overflows `usize`.
62 pub fn reserve(&mut self, additional
: usize) {
63 self.$field
.reserve(additional
)
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.
70 pub fn shrink_to_fit(&mut self) {
71 self.$field
.shrink_to_fit()
74 /// Returns the number of items in the collection.
76 pub fn len(&self) -> usize {
80 /// Returns true if there are no items in the collection.
82 pub fn is_empty(&self) -> bool
{
83 self.$field
.is_empty()
86 /// Removes all items from the collection. Keeps the allocated memory for reuse.
88 pub fn clear(&mut self) {
93 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for $t
<A
> {
95 fn default() -> $t
<A
> {
105 /// A collection containing zero or one values for any given type and allowing convenient,
106 /// type-safe access to those values.
108 /// The type parameter `A` allows you to use a different value type; normally you will want it to
109 /// be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
111 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with that, you
112 /// can only add types that implement `Clone` to the map.
113 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those auto
116 /// Cumulatively, there are thus six forms of map:
118 /// - <code>[Map]<dyn [core::any::Any]></code>, also spelled [`AnyMap`] for convenience.
119 /// - <code>[Map]<dyn [core::any::Any] + Send></code>
120 /// - <code>[Map]<dyn [core::any::Any] + Send + Sync></code>
121 /// - <code>[Map]<dyn [CloneAny]></code>
122 /// - <code>[Map]<dyn [CloneAny] + Send></code>
123 /// - <code>[Map]<dyn [CloneAny] + Send + Sync></code>
127 /// (Here using the [`AnyMap`] convenience alias; the first line could use
128 /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
131 /// let mut data = anymap::AnyMap::new();
132 /// assert_eq!(data.get(), None::<&i32>);
133 /// data.insert(42i32);
134 /// assert_eq!(data.get(), Some(&42i32));
135 /// data.remove::<i32>();
136 /// assert_eq!(data.get::<i32>(), None);
138 /// #[derive(Clone, PartialEq, Debug)]
143 /// assert_eq!(data.get::<Foo>(), None);
144 /// data.insert(Foo { str: format!("foo") });
145 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
146 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
147 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
150 /// Values containing non-static references are not permitted.
152 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
156 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
157 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
159 fn clone(&self) -> Map
<A
> {
161 raw
: self.raw
.clone(),
166 /// The most common type of `Map`: just using `Any`; <code>[Map]<dyn [Any]></code>.
168 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
169 /// doesn’t seem to be happy to infer that it should go with the default value.
170 /// It’s a bit sad, really. Ah well, I guess this approach will do.
171 pub type AnyMap
= Map
<dyn Any
>;
173 impl_common_methods
! {
175 new() => RawMap
::new();
176 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
179 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
180 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
182 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
183 self.raw
.get(&TypeId
::of
::<T
>())
184 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
187 /// Returns a mutable reference to the value stored in the collection for the type `T`,
190 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
191 self.raw
.get_mut(&TypeId
::of
::<T
>())
192 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
195 /// Sets the value stored in the collection for the type `T`.
196 /// If the collection already had a value of type `T`, that value is returned.
197 /// Otherwise, `None` is returned.
199 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
201 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
202 .map(|any
| *any
.downcast_unchecked
::<T
>())
206 /// Removes the `T` value from the collection,
207 /// returning it if there was one or `None` if there was not.
209 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
210 self.raw
.remove(&TypeId
::of
::<T
>())
211 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
214 /// Returns true if the collection contains a value of type `T`.
216 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
217 self.raw
.contains_key(&TypeId
::of
::<T
>())
220 /// Gets the entry for the given type in the collection for in-place manipulation
222 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
223 match self.raw
.entry(TypeId
::of
::<T
>()) {
224 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
228 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
236 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
238 fn as_ref(&self) -> &RawMap
<A
> {
243 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
245 fn as_mut(&mut self) -> &mut RawMap
<A
> {
250 impl<A
: ?Sized
+ UncheckedAnyExt
> From
<Map
<A
>> for RawMap
<A
> {
252 fn from(map
: Map
<A
>) -> RawMap
<A
> {
257 /// A view into a single occupied location in an `Map`.
258 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
259 inner
: raw
::OccupiedEntry
<'a
, A
>,
260 type_
: PhantomData
<V
>,
263 /// A view into a single empty location in an `Map`.
264 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
265 inner
: raw
::VacantEntry
<'a
, A
>,
266 type_
: PhantomData
<V
>,
269 /// A view into a single location in an `Map`, which may be vacant or occupied.
270 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
271 /// An occupied Entry
272 Occupied(OccupiedEntry
<'a
, A
, V
>),
274 Vacant(VacantEntry
<'a
, A
, V
>),
277 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
278 /// Ensures a value is in the entry by inserting the default if empty, and returns
279 /// a mutable reference to the value in the entry.
281 pub fn or_insert(self, default: V
) -> &'a
mut V
{
283 Entry
::Occupied(inner
) => inner
.into_mut(),
284 Entry
::Vacant(inner
) => inner
.insert(default),
288 /// Ensures a value is in the entry by inserting the result of the default function if empty,
289 /// and returns a mutable reference to the value in the entry.
291 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
293 Entry
::Occupied(inner
) => inner
.into_mut(),
294 Entry
::Vacant(inner
) => inner
.insert(default()),
299 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
300 /// Gets a reference to the value in the entry
302 pub fn get(&self) -> &V
{
303 unsafe { self.inner
.get().downcast_ref_unchecked() }
306 /// Gets a mutable reference to the value in the entry
308 pub fn get_mut(&mut self) -> &mut V
{
309 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
312 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
313 /// with a lifetime bound to the collection itself
315 pub fn into_mut(self) -> &'a
mut V
{
316 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
319 /// Sets the value of the entry, and returns the entry's old value
321 pub fn insert(&mut self, value
: V
) -> V
{
322 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
325 /// Takes the value out of the entry, and returns it
327 pub fn remove(self) -> V
{
328 unsafe { *self.inner
.remove().downcast_unchecked() }
332 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
333 /// Sets the value of the entry with the VacantEntry's key,
334 /// and returns a mutable reference to it
336 pub fn insert(self, value
: V
) -> &'a
mut V
{
337 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
345 #[derive(Clone, Debug, PartialEq)] struct A(i32);
346 #[derive(Clone, Debug, PartialEq)] struct B(i32);
347 #[derive(Clone, Debug, PartialEq)] struct C(i32);
348 #[derive(Clone, Debug, PartialEq)] struct D(i32);
349 #[derive(Clone, Debug, PartialEq)] struct E(i32);
350 #[derive(Clone, Debug, PartialEq)] struct F(i32);
351 #[derive(Clone, Debug, PartialEq)] struct J(i32);
353 macro_rules
! test_entry
{
354 ($name
:ident
, $init
:ty
) => {
357 let mut map
= <$init
>::new();
358 assert_eq!(map
.insert(A(10)), None
);
359 assert_eq!(map
.insert(B(20)), None
);
360 assert_eq!(map
.insert(C(30)), None
);
361 assert_eq!(map
.insert(D(40)), None
);
362 assert_eq!(map
.insert(E(50)), None
);
363 assert_eq!(map
.insert(F(60)), None
);
365 // Existing key (insert)
366 match map
.entry
::<A
>() {
367 Entry
::Vacant(_
) => unreachable!(),
368 Entry
::Occupied(mut view
) => {
369 assert_eq!(view
.get(), &A(10));
370 assert_eq!(view
.insert(A(100)), A(10));
373 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
374 assert_eq!(map
.len(), 6);
377 // Existing key (update)
378 match map
.entry
::<B
>() {
379 Entry
::Vacant(_
) => unreachable!(),
380 Entry
::Occupied(mut view
) => {
381 let v
= view
.get_mut();
382 let new_v
= B(v
.0 * 10);
386 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
387 assert_eq!(map
.len(), 6);
390 // Existing key (remove)
391 match map
.entry
::<C
>() {
392 Entry
::Vacant(_
) => unreachable!(),
393 Entry
::Occupied(view
) => {
394 assert_eq!(view
.remove(), C(30));
397 assert_eq!(map
.get
::<C
>(), None
);
398 assert_eq!(map
.len(), 5);
401 // Inexistent key (insert)
402 match map
.entry
::<J
>() {
403 Entry
::Occupied(_
) => unreachable!(),
404 Entry
::Vacant(view
) => {
405 assert_eq!(*view
.insert(J(1000)), J(1000));
408 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
409 assert_eq!(map
.len(), 6);
411 // Entry.or_insert on existing key
412 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
413 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
414 assert_eq!(map
.len(), 6);
416 // Entry.or_insert on nonexisting key
417 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
418 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
419 assert_eq!(map
.len(), 7);
424 test_entry!(test_entry_any
, AnyMap
);
425 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
429 let map
: AnyMap
= Default
::default();
430 assert_eq!(map
.len(), 0);
435 let mut map
: Map
<dyn CloneAny
> = Map
::new();
436 let _
= map
.insert(A(1));
437 let _
= map
.insert(B(2));
438 let _
= map
.insert(D(3));
439 let _
= map
.insert(E(4));
440 let _
= map
.insert(F(5));
441 let _
= map
.insert(J(6));
442 let map2
= map
.clone();
443 assert_eq!(map2
.len(), 6);
444 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
445 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
446 assert_eq!(map2
.get
::<C
>(), None
);
447 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
448 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
449 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
450 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
454 fn test_varieties() {
455 fn assert_send
<T
: Send
>() { }
456 fn assert_sync
<T
: Sync
>() { }
457 fn assert_clone
<T
: Clone
>() { }
458 fn assert_debug
<T
: ::core
::fmt
::Debug
>() { }
459 assert_send
::<Map
<dyn Any
+ Send
>>();
460 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
461 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
462 assert_debug
::<Map
<dyn Any
>>();
463 assert_debug
::<Map
<dyn Any
+ Send
>>();
464 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
465 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
466 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
467 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
468 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
469 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
470 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
471 assert_debug
::<Map
<dyn CloneAny
>>();
472 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
473 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();