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
, Any
};
11 macro_rules
! impl_common_methods
{
13 field
: $t
:ident
.$field
:ident
;
15 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
17 impl<A
: ?Sized
+ UncheckedAnyExt
> $t
<A
> {
18 /// Create an empty collection.
20 pub fn new() -> $t
<A
> {
26 /// Creates an empty collection with the given initial capacity.
28 pub fn with_capacity($with_capacity_arg
: usize) -> $t
<A
> {
30 $field
: $with_capacity
,
34 /// Returns the number of elements the collection can hold without reallocating.
36 pub fn capacity(&self) -> usize {
37 self.$field
.capacity()
40 /// Reserves capacity for at least `additional` more elements to be inserted
41 /// in the collection. The collection may reserve more space to avoid
42 /// frequent reallocations.
46 /// Panics if the new allocation size overflows `usize`.
48 pub fn reserve(&mut self, additional
: usize) {
49 self.$field
.reserve(additional
)
52 /// Shrinks the capacity of the collection as much as possible. It will drop
53 /// down as much as possible while maintaining the internal rules
54 /// and possibly leaving some space in accordance with the resize policy.
56 pub fn shrink_to_fit(&mut self) {
57 self.$field
.shrink_to_fit()
60 /// Returns the number of items in the collection.
62 pub fn len(&self) -> usize {
66 /// Returns true if there are no items in the collection.
68 pub fn is_empty(&self) -> bool
{
69 self.$field
.is_empty()
72 /// Removes all items from the collection. Keeps the allocated memory for reuse.
74 pub fn clear(&mut self) {
79 impl<A
: ?Sized
+ UncheckedAnyExt
> Default
for $t
<A
> {
81 fn default() -> $t
<A
> {
91 /// A collection containing zero or one values for any given type and allowing convenient,
92 /// type-safe access to those values.
94 /// The type parameter `A` allows you to use a different value type; normally you will want it to
95 /// be `anymap::any::Any`, but there are other choices:
97 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
98 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
101 /// # use anymap::AnyMap;
102 /// let mut data = AnyMap::new();
103 /// assert_eq!(data.get(), None::<&i32>);
104 /// data.insert(42i32);
105 /// assert_eq!(data.get(), Some(&42i32));
106 /// data.remove::<i32>();
107 /// assert_eq!(data.get::<i32>(), None);
109 /// #[derive(Clone, PartialEq, Debug)]
114 /// assert_eq!(data.get::<Foo>(), None);
115 /// data.insert(Foo { str: format!("foo") });
116 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
117 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
118 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
121 /// Values containing non-static references are not permitted.
123 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= Any
> {
127 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
128 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
130 fn clone(&self) -> Map
<A
> {
132 raw
: self.raw
.clone(),
137 /// The most common type of `Map`: just using `Any`.
139 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
140 /// doesn’t seem to be happy to infer that it should go with the default value.
141 /// It’s a bit sad, really. Ah well, I guess this approach will do.
142 pub type AnyMap
= Map
<Any
>;
144 impl_common_methods
! {
146 new() => RawMap
::new();
147 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
150 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
151 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
153 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
154 self.raw
.get(&TypeId
::of
::<T
>())
155 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
158 /// Returns a mutable reference to the value stored in the collection for the type `T`,
161 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
162 self.raw
.get_mut(&TypeId
::of
::<T
>())
163 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
166 /// Sets the value stored in the collection for the type `T`.
167 /// If the collection already had a value of type `T`, that value is returned.
168 /// Otherwise, `None` is returned.
170 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
172 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
173 .map(|any
| *any
.downcast_unchecked
::<T
>())
177 /// Removes the `T` value from the collection,
178 /// returning it if there was one or `None` if there was not.
180 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
181 self.raw
.remove(&TypeId
::of
::<T
>())
182 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
185 /// Returns true if the collection contains a value of type `T`.
187 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
188 self.raw
.contains_key(&TypeId
::of
::<T
>())
191 /// Gets the entry for the given type in the collection for in-place manipulation
193 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
194 match self.raw
.entry(TypeId
::of
::<T
>()) {
195 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
199 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
207 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
209 fn as_ref(&self) -> &RawMap
<A
> {
214 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
216 fn as_mut(&mut self) -> &mut RawMap
<A
> {
221 impl<A
: ?Sized
+ UncheckedAnyExt
> Into
<RawMap
<A
>> for Map
<A
> {
223 fn into(self) -> RawMap
<A
> {
228 /// A view into a single occupied location in an `Map`.
229 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
230 inner
: raw
::OccupiedEntry
<'a
, A
>,
231 type_
: PhantomData
<V
>,
234 /// A view into a single empty location in an `Map`.
235 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
236 inner
: raw
::VacantEntry
<'a
, A
>,
237 type_
: PhantomData
<V
>,
240 /// A view into a single location in an `Map`, which may be vacant or occupied.
241 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
242 /// An occupied Entry
243 Occupied(OccupiedEntry
<'a
, A
, V
>),
245 Vacant(VacantEntry
<'a
, A
, V
>),
248 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
249 /// Ensures a value is in the entry by inserting the default if empty, and returns
250 /// a mutable reference to the value in the entry.
252 pub fn or_insert(self, default: V
) -> &'a
mut V
{
254 Entry
::Occupied(inner
) => inner
.into_mut(),
255 Entry
::Vacant(inner
) => inner
.insert(default),
259 /// Ensures a value is in the entry by inserting the result of the default function if empty,
260 /// and returns a mutable reference to the value in the entry.
262 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
264 Entry
::Occupied(inner
) => inner
.into_mut(),
265 Entry
::Vacant(inner
) => inner
.insert(default()),
270 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
271 /// Gets a reference to the value in the entry
273 pub fn get(&self) -> &V
{
274 unsafe { self.inner
.get().downcast_ref_unchecked() }
277 /// Gets a mutable reference to the value in the entry
279 pub fn get_mut(&mut self) -> &mut V
{
280 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
283 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
284 /// with a lifetime bound to the collection itself
286 pub fn into_mut(self) -> &'a
mut V
{
287 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
290 /// Sets the value of the entry, and returns the entry's old value
292 pub fn insert(&mut self, value
: V
) -> V
{
293 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
296 /// Takes the value out of the entry, and returns it
298 pub fn remove(self) -> V
{
299 unsafe { *self.inner
.remove().downcast_unchecked() }
303 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
304 /// Sets the value of the entry with the VacantEntry's key,
305 /// and returns a mutable reference to it
307 pub fn insert(self, value
: V
) -> &'a
mut V
{
308 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
314 use {Map
, AnyMap
, Entry
};
315 use any
::{Any
, CloneAny
};
317 #
[derive(Clone
, Debug
, PartialEq
)] struct A(i32);
318 #
[derive(Clone
, Debug
, PartialEq
)] struct B(i32);
319 #
[derive(Clone
, Debug
, PartialEq
)] struct C(i32);
320 #
[derive(Clone
, Debug
, PartialEq
)] struct D(i32);
321 #
[derive(Clone
, Debug
, PartialEq
)] struct E(i32);
322 #
[derive(Clone
, Debug
, PartialEq
)] struct F(i32);
323 #
[derive(Clone
, Debug
, PartialEq
)] struct J(i32);
325 macro_rules
! test_entry
{
326 ($name
:ident
, $init
:ty
) => {
329 let mut map
= <$init
>::new();
330 assert_eq!(map
.insert(A(10)), None
);
331 assert_eq!(map
.insert(B(20)), None
);
332 assert_eq!(map
.insert(C(30)), None
);
333 assert_eq!(map
.insert(D(40)), None
);
334 assert_eq!(map
.insert(E(50)), None
);
335 assert_eq!(map
.insert(F(60)), None
);
337 // Existing key (insert)
338 match map
.entry
::<A
>() {
339 Entry
::Vacant(_
) => unreachable!(),
340 Entry
::Occupied(mut view
) => {
341 assert_eq!(view
.get(), &A(10));
342 assert_eq!(view
.insert(A(100)), A(10));
345 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
346 assert_eq!(map
.len(), 6);
349 // Existing key (update)
350 match map
.entry
::<B
>() {
351 Entry
::Vacant(_
) => unreachable!(),
352 Entry
::Occupied(mut view
) => {
353 let v
= view
.get_mut();
354 let new_v
= B(v
.0 * 10);
358 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
359 assert_eq!(map
.len(), 6);
362 // Existing key (remove)
363 match map
.entry
::<C
>() {
364 Entry
::Vacant(_
) => unreachable!(),
365 Entry
::Occupied(view
) => {
366 assert_eq!(view
.remove(), C(30));
369 assert_eq!(map
.get
::<C
>(), None
);
370 assert_eq!(map
.len(), 5);
373 // Inexistent key (insert)
374 match map
.entry
::<J
>() {
375 Entry
::Occupied(_
) => unreachable!(),
376 Entry
::Vacant(view
) => {
377 assert_eq!(*view
.insert(J(1000)), J(1000));
380 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
381 assert_eq!(map
.len(), 6);
383 // Entry.or_insert on existing key
384 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
385 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
386 assert_eq!(map
.len(), 6);
388 // Entry.or_insert on nonexisting key
389 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
390 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
391 assert_eq!(map
.len(), 7);
396 test_entry!(test_entry_any
, AnyMap
);
397 test_entry!(test_entry_cloneany
, Map
<CloneAny
>);
401 let map
: AnyMap
= Default
::default();
402 assert_eq!(map
.len(), 0);
407 let mut map
: Map
<CloneAny
> = Map
::new();
408 let _
= map
.insert(A(1));
409 let _
= map
.insert(B(2));
410 let _
= map
.insert(D(3));
411 let _
= map
.insert(E(4));
412 let _
= map
.insert(F(5));
413 let _
= map
.insert(J(6));
414 let map2
= map
.clone();
415 assert_eq!(map2
.len(), 6);
416 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
417 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
418 assert_eq!(map2
.get
::<C
>(), None
);
419 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
420 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
421 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
422 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
426 fn test_varieties() {
427 fn assert_send
<T
: Send
>() { }
428 fn assert_sync
<T
: Sync
>() { }
429 fn assert_clone
<T
: Clone
>() { }
430 fn assert_debug
<T
: ::std
::fmt
::Debug
>() { }
431 assert_send
::<Map
<Any
+ Send
>>();
432 assert_send
::<Map
<Any
+ Send
+ Sync
>>();
433 assert_sync
::<Map
<Any
+ Sync
>>();
434 assert_sync
::<Map
<Any
+ Send
+ Sync
>>();
435 assert_debug
::<Map
<Any
>>();
436 assert_debug
::<Map
<Any
+ Send
>>();
437 assert_debug
::<Map
<Any
+ Sync
>>();
438 assert_debug
::<Map
<Any
+ Send
+ Sync
>>();
439 assert_send
::<Map
<CloneAny
+ Send
>>();
440 assert_send
::<Map
<CloneAny
+ Send
+ Sync
>>();
441 assert_sync
::<Map
<CloneAny
+ Sync
>>();
442 assert_sync
::<Map
<CloneAny
+ Send
+ Sync
>>();
443 assert_clone
::<Map
<CloneAny
+ Send
>>();
444 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
445 assert_clone
::<Map
<CloneAny
+ Sync
>>();
446 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
447 assert_debug
::<Map
<CloneAny
>>();
448 assert_debug
::<Map
<CloneAny
+ Send
>>();
449 assert_debug
::<Map
<CloneAny
+ Sync
>>();
450 assert_debug
::<Map
<CloneAny
+ Send
+ Sync
>>();