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 use core
::any
::{Any
, TypeId
};
8 use core
::marker
::PhantomData
;
11 use any
::{UncheckedAnyExt
, IntoBox
};
12 pub use any
::CloneAny
;
14 macro_rules
! impl_common_methods
{
16 field
: $t
:ident
.$field
:ident
;
18 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
20 impl<A
: ?Sized
+ UncheckedAnyExt
> $t
<A
> {
21 /// Create an empty collection.
23 pub fn new() -> $t
<A
> {
29 /// Creates an empty collection with the given initial capacity.
31 pub fn with_capacity($with_capacity_arg
: usize) -> $t
<A
> {
33 $field
: $with_capacity
,
37 /// Returns the number of elements the collection can hold without reallocating.
39 pub fn capacity(&self) -> usize {
40 self.$field
.capacity()
43 /// Reserves capacity for at least `additional` more elements to be inserted
44 /// in the collection. The collection may reserve more space to avoid
45 /// frequent reallocations.
49 /// Panics if the new allocation size overflows `usize`.
51 pub fn reserve(&mut self, additional
: usize) {
52 self.$field
.reserve(additional
)
55 /// Shrinks the capacity of the collection as much as possible. It will drop
56 /// down as much as possible while maintaining the internal rules
57 /// and possibly leaving some space in accordance with the resize policy.
59 pub fn shrink_to_fit(&mut self) {
60 self.$field
.shrink_to_fit()
63 /// Returns the number of items in the collection.
65 pub fn len(&self) -> usize {
69 /// Returns true if there are no items in the collection.
71 pub fn is_empty(&self) -> bool
{
72 self.$field
.is_empty()
75 /// Removes all items from the collection. Keeps the allocated memory for reuse.
77 pub fn clear(&mut self) {
82 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for $t
<A
> {
84 fn default() -> $t
<A
> {
94 /// A collection containing zero or one values for any given type and allowing convenient,
95 /// type-safe access to those values.
97 /// The type parameter `A` allows you to use a different value type; normally you will want it to
98 /// be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
100 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with that, you
101 /// can only add types that implement `Clone` to the map.
102 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those auto
105 /// Cumulatively, there are thus six forms of map:
107 /// - <code>[Map]<dyn [core::any::Any]></code>, also spelled [`AnyMap`] for convenience.
108 /// - <code>[Map]<dyn [core::any::Any] + Send></code>
109 /// - <code>[Map]<dyn [core::any::Any] + Send + Sync></code>
110 /// - <code>[Map]<dyn [CloneAny]></code>
111 /// - <code>[Map]<dyn [CloneAny] + Send></code>
112 /// - <code>[Map]<dyn [CloneAny] + Send + Sync></code>
116 /// (Here using the [`AnyMap`] convenience alias; the first line could use
117 /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
120 /// let mut data = anymap::AnyMap::new();
121 /// assert_eq!(data.get(), None::<&i32>);
122 /// data.insert(42i32);
123 /// assert_eq!(data.get(), Some(&42i32));
124 /// data.remove::<i32>();
125 /// assert_eq!(data.get::<i32>(), None);
127 /// #[derive(Clone, PartialEq, Debug)]
132 /// assert_eq!(data.get::<Foo>(), None);
133 /// data.insert(Foo { str: format!("foo") });
134 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
135 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
136 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
139 /// Values containing non-static references are not permitted.
141 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
145 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
146 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
148 fn clone(&self) -> Map
<A
> {
150 raw
: self.raw
.clone(),
155 /// The most common type of `Map`: just using `Any`; <code>[Map]<dyn [Any]></code>.
157 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
158 /// doesn’t seem to be happy to infer that it should go with the default value.
159 /// It’s a bit sad, really. Ah well, I guess this approach will do.
160 pub type AnyMap
= Map
<dyn Any
>;
162 impl_common_methods
! {
164 new() => RawMap
::new();
165 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
168 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
169 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
171 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
172 self.raw
.get(&TypeId
::of
::<T
>())
173 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
176 /// Returns a mutable reference to the value stored in the collection for the type `T`,
179 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
180 self.raw
.get_mut(&TypeId
::of
::<T
>())
181 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
184 /// Sets the value stored in the collection for the type `T`.
185 /// If the collection already had a value of type `T`, that value is returned.
186 /// Otherwise, `None` is returned.
188 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
190 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
191 .map(|any
| *any
.downcast_unchecked
::<T
>())
195 /// Removes the `T` value from the collection,
196 /// returning it if there was one or `None` if there was not.
198 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
199 self.raw
.remove(&TypeId
::of
::<T
>())
200 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
203 /// Returns true if the collection contains a value of type `T`.
205 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
206 self.raw
.contains_key(&TypeId
::of
::<T
>())
209 /// Gets the entry for the given type in the collection for in-place manipulation
211 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
212 match self.raw
.entry(TypeId
::of
::<T
>()) {
213 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
217 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
225 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
227 fn as_ref(&self) -> &RawMap
<A
> {
232 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
234 fn as_mut(&mut self) -> &mut RawMap
<A
> {
239 impl<A
: ?Sized
+ UncheckedAnyExt
> From
<Map
<A
>> for RawMap
<A
> {
241 fn from(map
: Map
<A
>) -> RawMap
<A
> {
246 /// A view into a single occupied location in an `Map`.
247 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
248 inner
: raw
::OccupiedEntry
<'a
, A
>,
249 type_
: PhantomData
<V
>,
252 /// A view into a single empty location in an `Map`.
253 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
254 inner
: raw
::VacantEntry
<'a
, A
>,
255 type_
: PhantomData
<V
>,
258 /// A view into a single location in an `Map`, which may be vacant or occupied.
259 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
260 /// An occupied Entry
261 Occupied(OccupiedEntry
<'a
, A
, V
>),
263 Vacant(VacantEntry
<'a
, A
, V
>),
266 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
267 /// Ensures a value is in the entry by inserting the default if empty, and returns
268 /// a mutable reference to the value in the entry.
270 pub fn or_insert(self, default: V
) -> &'a
mut V
{
272 Entry
::Occupied(inner
) => inner
.into_mut(),
273 Entry
::Vacant(inner
) => inner
.insert(default),
277 /// Ensures a value is in the entry by inserting the result of the default function if empty,
278 /// and returns a mutable reference to the value in the entry.
280 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
282 Entry
::Occupied(inner
) => inner
.into_mut(),
283 Entry
::Vacant(inner
) => inner
.insert(default()),
288 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
289 /// Gets a reference to the value in the entry
291 pub fn get(&self) -> &V
{
292 unsafe { self.inner
.get().downcast_ref_unchecked() }
295 /// Gets a mutable reference to the value in the entry
297 pub fn get_mut(&mut self) -> &mut V
{
298 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
301 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
302 /// with a lifetime bound to the collection itself
304 pub fn into_mut(self) -> &'a
mut V
{
305 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
308 /// Sets the value of the entry, and returns the entry's old value
310 pub fn insert(&mut self, value
: V
) -> V
{
311 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
314 /// Takes the value out of the entry, and returns it
316 pub fn remove(self) -> V
{
317 unsafe { *self.inner
.remove().downcast_unchecked() }
321 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
322 /// Sets the value of the entry with the VacantEntry's key,
323 /// and returns a mutable reference to it
325 pub fn insert(self, value
: V
) -> &'a
mut V
{
326 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
334 #[derive(Clone, Debug, PartialEq)] struct A(i32);
335 #[derive(Clone, Debug, PartialEq)] struct B(i32);
336 #[derive(Clone, Debug, PartialEq)] struct C(i32);
337 #[derive(Clone, Debug, PartialEq)] struct D(i32);
338 #[derive(Clone, Debug, PartialEq)] struct E(i32);
339 #[derive(Clone, Debug, PartialEq)] struct F(i32);
340 #[derive(Clone, Debug, PartialEq)] struct J(i32);
342 macro_rules
! test_entry
{
343 ($name
:ident
, $init
:ty
) => {
346 let mut map
= <$init
>::new();
347 assert_eq!(map
.insert(A(10)), None
);
348 assert_eq!(map
.insert(B(20)), None
);
349 assert_eq!(map
.insert(C(30)), None
);
350 assert_eq!(map
.insert(D(40)), None
);
351 assert_eq!(map
.insert(E(50)), None
);
352 assert_eq!(map
.insert(F(60)), None
);
354 // Existing key (insert)
355 match map
.entry
::<A
>() {
356 Entry
::Vacant(_
) => unreachable!(),
357 Entry
::Occupied(mut view
) => {
358 assert_eq!(view
.get(), &A(10));
359 assert_eq!(view
.insert(A(100)), A(10));
362 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
363 assert_eq!(map
.len(), 6);
366 // Existing key (update)
367 match map
.entry
::<B
>() {
368 Entry
::Vacant(_
) => unreachable!(),
369 Entry
::Occupied(mut view
) => {
370 let v
= view
.get_mut();
371 let new_v
= B(v
.0 * 10);
375 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
376 assert_eq!(map
.len(), 6);
379 // Existing key (remove)
380 match map
.entry
::<C
>() {
381 Entry
::Vacant(_
) => unreachable!(),
382 Entry
::Occupied(view
) => {
383 assert_eq!(view
.remove(), C(30));
386 assert_eq!(map
.get
::<C
>(), None
);
387 assert_eq!(map
.len(), 5);
390 // Inexistent key (insert)
391 match map
.entry
::<J
>() {
392 Entry
::Occupied(_
) => unreachable!(),
393 Entry
::Vacant(view
) => {
394 assert_eq!(*view
.insert(J(1000)), J(1000));
397 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
398 assert_eq!(map
.len(), 6);
400 // Entry.or_insert on existing key
401 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
402 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
403 assert_eq!(map
.len(), 6);
405 // Entry.or_insert on nonexisting key
406 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
407 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
408 assert_eq!(map
.len(), 7);
413 test_entry!(test_entry_any
, AnyMap
);
414 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
418 let map
: AnyMap
= Default
::default();
419 assert_eq!(map
.len(), 0);
424 let mut map
: Map
<dyn CloneAny
> = Map
::new();
425 let _
= map
.insert(A(1));
426 let _
= map
.insert(B(2));
427 let _
= map
.insert(D(3));
428 let _
= map
.insert(E(4));
429 let _
= map
.insert(F(5));
430 let _
= map
.insert(J(6));
431 let map2
= map
.clone();
432 assert_eq!(map2
.len(), 6);
433 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
434 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
435 assert_eq!(map2
.get
::<C
>(), None
);
436 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
437 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
438 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
439 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
443 fn test_varieties() {
444 fn assert_send
<T
: Send
>() { }
445 fn assert_sync
<T
: Sync
>() { }
446 fn assert_clone
<T
: Clone
>() { }
447 fn assert_debug
<T
: ::core
::fmt
::Debug
>() { }
448 assert_send
::<Map
<dyn Any
+ Send
>>();
449 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
450 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
451 assert_debug
::<Map
<dyn Any
>>();
452 assert_debug
::<Map
<dyn Any
+ Send
>>();
453 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
454 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
455 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
456 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
457 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
458 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
459 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
460 assert_debug
::<Map
<dyn CloneAny
>>();
461 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
462 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();