d4f227a293da168d6b4ffa0119ffc1c8aa7946f5
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 // Additional stable methods (as of 1.60.0-nightly) that could be added:
75 // try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> (1.57.0)
76 // shrink_to(&mut self, min_capacity: usize) (1.56.0)
78 /// Returns the number of items in the collection.
80 pub fn len(&self) -> usize {
84 /// Returns true if there are no items in the collection.
86 pub fn is_empty(&self) -> bool
{
87 self.$field
.is_empty()
90 /// Removes all items from the collection. Keeps the allocated memory for reuse.
92 pub fn clear(&mut self) {
97 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for $t
<A
> {
99 fn default() -> $t
<A
> {
109 /// A collection containing zero or one values for any given type and allowing convenient,
110 /// type-safe access to those values.
112 /// The type parameter `A` allows you to use a different value type; normally you will want it to
113 /// be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
115 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with that, you
116 /// can only add types that implement `Clone` to the map.
117 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those auto
120 /// Cumulatively, there are thus six forms of map:
122 /// - <code>[Map]<dyn [core::any::Any]></code>, also spelled [`AnyMap`] for convenience.
123 /// - <code>[Map]<dyn [core::any::Any] + Send></code>
124 /// - <code>[Map]<dyn [core::any::Any] + Send + Sync></code>
125 /// - <code>[Map]<dyn [CloneAny]></code>
126 /// - <code>[Map]<dyn [CloneAny] + Send></code>
127 /// - <code>[Map]<dyn [CloneAny] + Send + Sync></code>
131 /// (Here using the [`AnyMap`] convenience alias; the first line could use
132 /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
135 /// let mut data = anymap::AnyMap::new();
136 /// assert_eq!(data.get(), None::<&i32>);
137 /// data.insert(42i32);
138 /// assert_eq!(data.get(), Some(&42i32));
139 /// data.remove::<i32>();
140 /// assert_eq!(data.get::<i32>(), None);
142 /// #[derive(Clone, PartialEq, Debug)]
147 /// assert_eq!(data.get::<Foo>(), None);
148 /// data.insert(Foo { str: format!("foo") });
149 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
150 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
151 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
154 /// Values containing non-static references are not permitted.
156 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
160 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
161 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
163 fn clone(&self) -> Map
<A
> {
165 raw
: self.raw
.clone(),
170 /// The most common type of `Map`: just using `Any`; <code>[Map]<dyn [Any]></code>.
172 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
173 /// doesn’t seem to be happy to infer that it should go with the default value.
174 /// It’s a bit sad, really. Ah well, I guess this approach will do.
175 pub type AnyMap
= Map
<dyn Any
>;
177 impl_common_methods
! {
179 new() => RawMap
::new();
180 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
183 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
184 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
186 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
187 self.raw
.get(&TypeId
::of
::<T
>())
188 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
191 /// Returns a mutable reference to the value stored in the collection for the type `T`,
194 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
195 self.raw
.get_mut(&TypeId
::of
::<T
>())
196 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
199 /// Sets the value stored in the collection for the type `T`.
200 /// If the collection already had a value of type `T`, that value is returned.
201 /// Otherwise, `None` is returned.
203 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
205 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
206 .map(|any
| *any
.downcast_unchecked
::<T
>())
210 // rustc 1.60.0-nightly has another method try_insert that would be nice to add when stable.
212 /// Removes the `T` value from the collection,
213 /// returning it if there was one or `None` if there was not.
215 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
216 self.raw
.remove(&TypeId
::of
::<T
>())
217 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
220 /// Returns true if the collection contains a value of type `T`.
222 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
223 self.raw
.contains_key(&TypeId
::of
::<T
>())
226 /// Gets the entry for the given type in the collection for in-place manipulation
228 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
229 match self.raw
.entry(TypeId
::of
::<T
>()) {
230 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
234 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
242 impl<A
: ?Sized
+ UncheckedAnyExt
> Extend
<Box
<A
>> for Map
<A
> {
244 fn extend
<T
: IntoIterator
<Item
= Box
<A
>>>(&mut self, iter
: T
) {
246 let _
= unsafe { self.raw
.insert(item
.type_id(), item
) };
251 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
253 fn as_ref(&self) -> &RawMap
<A
> {
258 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
260 fn as_mut(&mut self) -> &mut RawMap
<A
> {
265 impl<A
: ?Sized
+ UncheckedAnyExt
> From
<Map
<A
>> for RawMap
<A
> {
267 fn from(map
: Map
<A
>) -> RawMap
<A
> {
272 /// A view into a single occupied location in an `Map`.
273 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
274 inner
: raw
::OccupiedEntry
<'a
, A
>,
275 type_
: PhantomData
<V
>,
278 /// A view into a single empty location in an `Map`.
279 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
280 inner
: raw
::VacantEntry
<'a
, A
>,
281 type_
: PhantomData
<V
>,
284 /// A view into a single location in an `Map`, which may be vacant or occupied.
285 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
286 /// An occupied Entry
287 Occupied(OccupiedEntry
<'a
, A
, V
>),
289 Vacant(VacantEntry
<'a
, A
, V
>),
292 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
293 /// Ensures a value is in the entry by inserting the default if empty, and returns
294 /// a mutable reference to the value in the entry.
296 pub fn or_insert(self, default: V
) -> &'a
mut V
{
298 Entry
::Occupied(inner
) => inner
.into_mut(),
299 Entry
::Vacant(inner
) => inner
.insert(default),
303 /// Ensures a value is in the entry by inserting the result of the default function if empty,
304 /// and returns a mutable reference to the value in the entry.
306 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
308 Entry
::Occupied(inner
) => inner
.into_mut(),
309 Entry
::Vacant(inner
) => inner
.insert(default()),
314 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
315 /// Gets a reference to the value in the entry
317 pub fn get(&self) -> &V
{
318 unsafe { self.inner
.get().downcast_ref_unchecked() }
321 /// Gets a mutable reference to the value in the entry
323 pub fn get_mut(&mut self) -> &mut V
{
324 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
327 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
328 /// with a lifetime bound to the collection itself
330 pub fn into_mut(self) -> &'a
mut V
{
331 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
334 /// Sets the value of the entry, and returns the entry's old value
336 pub fn insert(&mut self, value
: V
) -> V
{
337 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
340 /// Takes the value out of the entry, and returns it
342 pub fn remove(self) -> V
{
343 unsafe { *self.inner
.remove().downcast_unchecked() }
347 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
348 /// Sets the value of the entry with the VacantEntry's key,
349 /// and returns a mutable reference to it
351 pub fn insert(self, value
: V
) -> &'a
mut V
{
352 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
360 #[derive(Clone, Debug, PartialEq)] struct A(i32);
361 #[derive(Clone, Debug, PartialEq)] struct B(i32);
362 #[derive(Clone, Debug, PartialEq)] struct C(i32);
363 #[derive(Clone, Debug, PartialEq)] struct D(i32);
364 #[derive(Clone, Debug, PartialEq)] struct E(i32);
365 #[derive(Clone, Debug, PartialEq)] struct F(i32);
366 #[derive(Clone, Debug, PartialEq)] struct J(i32);
368 macro_rules
! test_entry
{
369 ($name
:ident
, $init
:ty
) => {
372 let mut map
= <$init
>::new();
373 assert_eq!(map
.insert(A(10)), None
);
374 assert_eq!(map
.insert(B(20)), None
);
375 assert_eq!(map
.insert(C(30)), None
);
376 assert_eq!(map
.insert(D(40)), None
);
377 assert_eq!(map
.insert(E(50)), None
);
378 assert_eq!(map
.insert(F(60)), None
);
380 // Existing key (insert)
381 match map
.entry
::<A
>() {
382 Entry
::Vacant(_
) => unreachable!(),
383 Entry
::Occupied(mut view
) => {
384 assert_eq!(view
.get(), &A(10));
385 assert_eq!(view
.insert(A(100)), A(10));
388 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
389 assert_eq!(map
.len(), 6);
392 // Existing key (update)
393 match map
.entry
::<B
>() {
394 Entry
::Vacant(_
) => unreachable!(),
395 Entry
::Occupied(mut view
) => {
396 let v
= view
.get_mut();
397 let new_v
= B(v
.0 * 10);
401 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
402 assert_eq!(map
.len(), 6);
405 // Existing key (remove)
406 match map
.entry
::<C
>() {
407 Entry
::Vacant(_
) => unreachable!(),
408 Entry
::Occupied(view
) => {
409 assert_eq!(view
.remove(), C(30));
412 assert_eq!(map
.get
::<C
>(), None
);
413 assert_eq!(map
.len(), 5);
416 // Inexistent key (insert)
417 match map
.entry
::<J
>() {
418 Entry
::Occupied(_
) => unreachable!(),
419 Entry
::Vacant(view
) => {
420 assert_eq!(*view
.insert(J(1000)), J(1000));
423 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
424 assert_eq!(map
.len(), 6);
426 // Entry.or_insert on existing key
427 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
428 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
429 assert_eq!(map
.len(), 6);
431 // Entry.or_insert on nonexisting key
432 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
433 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
434 assert_eq!(map
.len(), 7);
439 test_entry!(test_entry_any
, AnyMap
);
440 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
444 let map
: AnyMap
= Default
::default();
445 assert_eq!(map
.len(), 0);
450 let mut map
: Map
<dyn CloneAny
> = Map
::new();
451 let _
= map
.insert(A(1));
452 let _
= map
.insert(B(2));
453 let _
= map
.insert(D(3));
454 let _
= map
.insert(E(4));
455 let _
= map
.insert(F(5));
456 let _
= map
.insert(J(6));
457 let map2
= map
.clone();
458 assert_eq!(map2
.len(), 6);
459 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
460 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
461 assert_eq!(map2
.get
::<C
>(), None
);
462 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
463 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
464 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
465 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
469 fn test_varieties() {
470 fn assert_send
<T
: Send
>() { }
471 fn assert_sync
<T
: Sync
>() { }
472 fn assert_clone
<T
: Clone
>() { }
473 fn assert_debug
<T
: ::core
::fmt
::Debug
>() { }
474 assert_send
::<Map
<dyn Any
+ Send
>>();
475 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
476 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
477 assert_debug
::<Map
<dyn Any
>>();
478 assert_debug
::<Map
<dyn Any
+ Send
>>();
479 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
480 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
481 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
482 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
483 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
484 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
485 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
486 assert_debug
::<Map
<dyn CloneAny
>>();
487 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
488 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();