3f656e3084d693493cb7f0d86ff9d4e313f0aea2
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #![warn(missing_docs, unused_results)]
6 use std
::marker
::PhantomData
;
9 use any
::{UncheckedAnyExt
, IntoBox
};
10 pub use any
::{Any
, CloneAny
};
12 macro_rules
! impl_common_methods
{
14 field
: $t
:ident
.$field
:ident
;
16 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
18 impl<A
: ?Sized
+ UncheckedAnyExt
> $t
<A
> {
19 /// Create an empty collection.
21 pub fn new() -> $t
<A
> {
27 /// Creates an empty collection with the given initial capacity.
29 pub fn with_capacity($with_capacity_arg
: usize) -> $t
<A
> {
31 $field
: $with_capacity
,
35 /// Returns the number of elements the collection can hold without reallocating.
37 pub fn capacity(&self) -> usize {
38 self.$field
.capacity()
41 /// Reserves capacity for at least `additional` more elements to be inserted
42 /// in the collection. The collection may reserve more space to avoid
43 /// frequent reallocations.
47 /// Panics if the new allocation size overflows `usize`.
49 pub fn reserve(&mut self, additional
: usize) {
50 self.$field
.reserve(additional
)
53 /// Shrinks the capacity of the collection as much as possible. It will drop
54 /// down as much as possible while maintaining the internal rules
55 /// and possibly leaving some space in accordance with the resize policy.
57 pub fn shrink_to_fit(&mut self) {
58 self.$field
.shrink_to_fit()
61 /// Returns the number of items in the collection.
63 pub fn len(&self) -> usize {
67 /// Returns true if there are no items in the collection.
69 pub fn is_empty(&self) -> bool
{
70 self.$field
.is_empty()
73 /// Removes all items from the collection. Keeps the allocated memory for reuse.
75 pub fn clear(&mut self) {
80 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for $t
<A
> {
82 fn default() -> $t
<A
> {
92 /// A collection containing zero or one values for any given type and allowing convenient,
93 /// type-safe access to those values.
95 /// The type parameter `A` allows you to use a different value type; normally you will want it to
96 /// be `anymap::any::Any`, but there are other choices:
98 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
99 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<dyn Any + Send>`) to add those bounds.
102 /// # use anymap::AnyMap;
103 /// let mut data = AnyMap::new();
104 /// assert_eq!(data.get(), None::<&i32>);
105 /// data.insert(42i32);
106 /// assert_eq!(data.get(), Some(&42i32));
107 /// data.remove::<i32>();
108 /// assert_eq!(data.get::<i32>(), None);
110 /// #[derive(Clone, PartialEq, Debug)]
115 /// assert_eq!(data.get::<Foo>(), None);
116 /// data.insert(Foo { str: format!("foo") });
117 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
118 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
119 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
122 /// Values containing non-static references are not permitted.
124 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= dyn Any
> {
128 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
129 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
131 fn clone(&self) -> Map
<A
> {
133 raw
: self.raw
.clone(),
138 /// The most common type of `Map`: just using `Any`.
140 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
141 /// doesn’t seem to be happy to infer that it should go with the default value.
142 /// It’s a bit sad, really. Ah well, I guess this approach will do.
143 pub type AnyMap
= Map
<dyn Any
>;
145 impl_common_methods
! {
147 new() => RawMap
::new();
148 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
151 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
152 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
154 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
155 self.raw
.get(&TypeId
::of
::<T
>())
156 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
159 /// Returns a mutable reference to the value stored in the collection for the type `T`,
162 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
163 self.raw
.get_mut(&TypeId
::of
::<T
>())
164 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
167 /// Sets the value stored in the collection for the type `T`.
168 /// If the collection already had a value of type `T`, that value is returned.
169 /// Otherwise, `None` is returned.
171 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
173 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
174 .map(|any
| *any
.downcast_unchecked
::<T
>())
178 /// Removes the `T` value from the collection,
179 /// returning it if there was one or `None` if there was not.
181 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
182 self.raw
.remove(&TypeId
::of
::<T
>())
183 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
186 /// Returns true if the collection contains a value of type `T`.
188 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
189 self.raw
.contains_key(&TypeId
::of
::<T
>())
192 /// Gets the entry for the given type in the collection for in-place manipulation
194 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
195 match self.raw
.entry(TypeId
::of
::<T
>()) {
196 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
200 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
208 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
210 fn as_ref(&self) -> &RawMap
<A
> {
215 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
217 fn as_mut(&mut self) -> &mut RawMap
<A
> {
222 impl<A
: ?Sized
+ UncheckedAnyExt
> Into
<RawMap
<A
>> for Map
<A
> {
224 fn into(self) -> RawMap
<A
> {
229 /// A view into a single occupied location in an `Map`.
230 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
231 inner
: raw
::OccupiedEntry
<'a
, A
>,
232 type_
: PhantomData
<V
>,
235 /// A view into a single empty location in an `Map`.
236 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
237 inner
: raw
::VacantEntry
<'a
, A
>,
238 type_
: PhantomData
<V
>,
241 /// A view into a single location in an `Map`, which may be vacant or occupied.
242 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
243 /// An occupied Entry
244 Occupied(OccupiedEntry
<'a
, A
, V
>),
246 Vacant(VacantEntry
<'a
, A
, V
>),
249 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
250 /// Ensures a value is in the entry by inserting the default if empty, and returns
251 /// a mutable reference to the value in the entry.
253 pub fn or_insert(self, default: V
) -> &'a
mut V
{
255 Entry
::Occupied(inner
) => inner
.into_mut(),
256 Entry
::Vacant(inner
) => inner
.insert(default),
260 /// Ensures a value is in the entry by inserting the result of the default function if empty,
261 /// and returns a mutable reference to the value in the entry.
263 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
265 Entry
::Occupied(inner
) => inner
.into_mut(),
266 Entry
::Vacant(inner
) => inner
.insert(default()),
271 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
272 /// Gets a reference to the value in the entry
274 pub fn get(&self) -> &V
{
275 unsafe { self.inner
.get().downcast_ref_unchecked() }
278 /// Gets a mutable reference to the value in the entry
280 pub fn get_mut(&mut self) -> &mut V
{
281 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
284 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
285 /// with a lifetime bound to the collection itself
287 pub fn into_mut(self) -> &'a
mut V
{
288 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
291 /// Sets the value of the entry, and returns the entry's old value
293 pub fn insert(&mut self, value
: V
) -> V
{
294 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
297 /// Takes the value out of the entry, and returns it
299 pub fn remove(self) -> V
{
300 unsafe { *self.inner
.remove().downcast_unchecked() }
304 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
305 /// Sets the value of the entry with the VacantEntry's key,
306 /// and returns a mutable reference to it
308 pub fn insert(self, value
: V
) -> &'a
mut V
{
309 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
315 use {Map
, AnyMap
, Entry
};
316 use any
::{Any
, CloneAny
};
318 #[derive(Clone, Debug, PartialEq)] struct A(i32);
319 #[derive(Clone, Debug, PartialEq)] struct B(i32);
320 #[derive(Clone, Debug, PartialEq)] struct C(i32);
321 #[derive(Clone, Debug, PartialEq)] struct D(i32);
322 #[derive(Clone, Debug, PartialEq)] struct E(i32);
323 #[derive(Clone, Debug, PartialEq)] struct F(i32);
324 #[derive(Clone, Debug, PartialEq)] struct J(i32);
326 macro_rules
! test_entry
{
327 ($name
:ident
, $init
:ty
) => {
330 let mut map
= <$init
>::new();
331 assert_eq!(map
.insert(A(10)), None
);
332 assert_eq!(map
.insert(B(20)), None
);
333 assert_eq!(map
.insert(C(30)), None
);
334 assert_eq!(map
.insert(D(40)), None
);
335 assert_eq!(map
.insert(E(50)), None
);
336 assert_eq!(map
.insert(F(60)), None
);
338 // Existing key (insert)
339 match map
.entry
::<A
>() {
340 Entry
::Vacant(_
) => unreachable!(),
341 Entry
::Occupied(mut view
) => {
342 assert_eq!(view
.get(), &A(10));
343 assert_eq!(view
.insert(A(100)), A(10));
346 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
347 assert_eq!(map
.len(), 6);
350 // Existing key (update)
351 match map
.entry
::<B
>() {
352 Entry
::Vacant(_
) => unreachable!(),
353 Entry
::Occupied(mut view
) => {
354 let v
= view
.get_mut();
355 let new_v
= B(v
.0 * 10);
359 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
360 assert_eq!(map
.len(), 6);
363 // Existing key (remove)
364 match map
.entry
::<C
>() {
365 Entry
::Vacant(_
) => unreachable!(),
366 Entry
::Occupied(view
) => {
367 assert_eq!(view
.remove(), C(30));
370 assert_eq!(map
.get
::<C
>(), None
);
371 assert_eq!(map
.len(), 5);
374 // Inexistent key (insert)
375 match map
.entry
::<J
>() {
376 Entry
::Occupied(_
) => unreachable!(),
377 Entry
::Vacant(view
) => {
378 assert_eq!(*view
.insert(J(1000)), J(1000));
381 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
382 assert_eq!(map
.len(), 6);
384 // Entry.or_insert on existing key
385 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
386 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
387 assert_eq!(map
.len(), 6);
389 // Entry.or_insert on nonexisting key
390 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
391 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
392 assert_eq!(map
.len(), 7);
397 test_entry!(test_entry_any
, AnyMap
);
398 test_entry!(test_entry_cloneany
, Map
<dyn CloneAny
>);
402 let map
: AnyMap
= Default
::default();
403 assert_eq!(map
.len(), 0);
408 let mut map
: Map
<dyn CloneAny
> = Map
::new();
409 let _
= map
.insert(A(1));
410 let _
= map
.insert(B(2));
411 let _
= map
.insert(D(3));
412 let _
= map
.insert(E(4));
413 let _
= map
.insert(F(5));
414 let _
= map
.insert(J(6));
415 let map2
= map
.clone();
416 assert_eq!(map2
.len(), 6);
417 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
418 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
419 assert_eq!(map2
.get
::<C
>(), None
);
420 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
421 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
422 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
423 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
427 fn test_varieties() {
428 fn assert_send
<T
: Send
>() { }
429 fn assert_sync
<T
: Sync
>() { }
430 fn assert_clone
<T
: Clone
>() { }
431 fn assert_debug
<T
: ::std
::fmt
::Debug
>() { }
432 assert_send
::<Map
<dyn Any
+ Send
>>();
433 assert_send
::<Map
<dyn Any
+ Send
+ Sync
>>();
434 assert_sync
::<Map
<dyn Any
+ Sync
>>();
435 assert_sync
::<Map
<dyn Any
+ Send
+ Sync
>>();
436 assert_debug
::<Map
<dyn Any
>>();
437 assert_debug
::<Map
<dyn Any
+ Send
>>();
438 assert_debug
::<Map
<dyn Any
+ Sync
>>();
439 assert_debug
::<Map
<dyn Any
+ Send
+ Sync
>>();
440 assert_send
::<Map
<dyn CloneAny
+ Send
>>();
441 assert_send
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
442 assert_sync
::<Map
<dyn CloneAny
+ Sync
>>();
443 assert_sync
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
444 assert_clone
::<Map
<dyn CloneAny
+ Send
>>();
445 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
446 assert_clone
::<Map
<dyn CloneAny
+ Sync
>>();
447 assert_clone
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();
448 assert_debug
::<Map
<dyn CloneAny
>>();
449 assert_debug
::<Map
<dyn CloneAny
+ Send
>>();
450 assert_debug
::<Map
<dyn CloneAny
+ Sync
>>();
451 assert_debug
::<Map
<dyn CloneAny
+ Send
+ Sync
>>();