bcd5c231a4e0d75e156974b833835dd68657a179
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) {
84 /// A collection containing zero or one values for any given type and allowing convenient,
85 /// type-safe access to those values.
87 /// The type parameter `A` allows you to use a different value type; normally you will want it to
88 /// be `anymap::any::Any`, but there are other choices:
90 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
91 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
94 /// # use anymap::AnyMap;
95 /// let mut data = AnyMap::new();
96 /// assert_eq!(data.get(), None::<&i32>);
97 /// data.insert(42i32);
98 /// assert_eq!(data.get(), Some(&42i32));
99 /// data.remove::<i32>();
100 /// assert_eq!(data.get::<i32>(), None);
102 /// #[derive(Clone, PartialEq, Debug)]
107 /// assert_eq!(data.get::<Foo>(), None);
108 /// data.insert(Foo { str: format!("foo") });
109 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
110 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
111 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
114 /// Values containing non-static references are not permitted.
116 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= Any
> {
120 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
121 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
123 fn clone(&self) -> Map
<A
> {
125 raw
: self.raw
.clone(),
130 /// The most common type of `Map`: just using `Any`.
132 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
133 /// doesn’t seem to be happy to infer that it should go with the default value.
134 /// It’s a bit sad, really. Ah well, I guess this approach will do.
135 pub type AnyMap
= Map
<Any
>;
137 impl_common_methods
! {
139 new() => RawMap
::new();
140 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
143 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
144 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
146 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
147 self.raw
.get(&TypeId
::of
::<T
>())
148 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
151 /// Returns a mutable reference to the value stored in the collection for the type `T`,
154 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
155 self.raw
.get_mut(&TypeId
::of
::<T
>())
156 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
159 /// Sets the value stored in the collection for the type `T`.
160 /// If the collection already had a value of type `T`, that value is returned.
161 /// Otherwise, `None` is returned.
163 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
165 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
166 .map(|any
| *any
.downcast_unchecked
::<T
>())
170 /// Removes the `T` value from the collection,
171 /// returning it if there was one or `None` if there was not.
173 pub fn remove
<T
: IntoBox
<A
>>(&mut self) -> Option
<T
> {
174 self.raw
.remove(&TypeId
::of
::<T
>())
175 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
178 /// Returns true if the collection contains a value of type `T`.
180 pub fn contains
<T
: IntoBox
<A
>>(&self) -> bool
{
181 self.raw
.contains_key(&TypeId
::of
::<T
>())
184 /// Gets the entry for the given type in the collection for in-place manipulation
186 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
187 match self.raw
.entry(TypeId
::of
::<T
>()) {
188 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
192 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
200 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
202 fn as_ref(&self) -> &RawMap
<A
> {
207 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
209 fn as_mut(&mut self) -> &mut RawMap
<A
> {
214 impl<A
: ?Sized
+ UncheckedAnyExt
> Into
<RawMap
<A
>> for Map
<A
> {
216 fn into(self) -> RawMap
<A
> {
221 /// A view into a single occupied location in an `Map`.
222 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
223 inner
: raw
::OccupiedEntry
<'a
, A
>,
224 type_
: PhantomData
<V
>,
227 /// A view into a single empty location in an `Map`.
228 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
229 inner
: raw
::VacantEntry
<'a
, A
>,
230 type_
: PhantomData
<V
>,
233 /// A view into a single location in an `Map`, which may be vacant or occupied.
234 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
235 /// An occupied Entry
236 Occupied(OccupiedEntry
<'a
, A
, V
>),
238 Vacant(VacantEntry
<'a
, A
, V
>),
241 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> Entry
<'a
, A
, V
> {
242 /// Ensures a value is in the entry by inserting the default if empty, and returns
243 /// a mutable reference to the value in the entry.
245 pub fn or_insert(self, default: V
) -> &'a
mut V
{
247 Entry
::Occupied(inner
) => inner
.into_mut(),
248 Entry
::Vacant(inner
) => inner
.insert(default),
252 /// Ensures a value is in the entry by inserting the result of the default function if empty,
253 /// and returns a mutable reference to the value in the entry.
255 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
257 Entry
::Occupied(inner
) => inner
.into_mut(),
258 Entry
::Vacant(inner
) => inner
.insert(default()),
263 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
264 /// Gets a reference to the value in the entry
266 pub fn get(&self) -> &V
{
267 unsafe { self.inner
.get().downcast_ref_unchecked() }
270 /// Gets a mutable reference to the value in the entry
272 pub fn get_mut(&mut self) -> &mut V
{
273 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
276 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
277 /// with a lifetime bound to the collection itself
279 pub fn into_mut(self) -> &'a
mut V
{
280 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
283 /// Sets the value of the entry, and returns the entry's old value
285 pub fn insert(&mut self, value
: V
) -> V
{
286 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
289 /// Takes the value out of the entry, and returns it
291 pub fn remove(self) -> V
{
292 unsafe { *self.inner
.remove().downcast_unchecked() }
296 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
297 /// Sets the value of the entry with the VacantEntry's key,
298 /// and returns a mutable reference to it
300 pub fn insert(self, value
: V
) -> &'a
mut V
{
301 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
307 use {Map
, AnyMap
, Entry
};
308 use any
::{Any
, CloneAny
};
310 #[derive(Clone, Debug, PartialEq)] struct A(i32);
311 #[derive(Clone, Debug, PartialEq)] struct B(i32);
312 #[derive(Clone, Debug, PartialEq)] struct C(i32);
313 #[derive(Clone, Debug, PartialEq)] struct D(i32);
314 #[derive(Clone, Debug, PartialEq)] struct E(i32);
315 #[derive(Clone, Debug, PartialEq)] struct F(i32);
316 #[derive(Clone, Debug, PartialEq)] struct J(i32);
318 macro_rules
! test_entry
{
319 ($name
:ident
, $init
:ty
) => {
322 let mut map
= <$init
>::new();
323 assert_eq!(map
.insert(A(10)), None
);
324 assert_eq!(map
.insert(B(20)), None
);
325 assert_eq!(map
.insert(C(30)), None
);
326 assert_eq!(map
.insert(D(40)), None
);
327 assert_eq!(map
.insert(E(50)), None
);
328 assert_eq!(map
.insert(F(60)), None
);
330 // Existing key (insert)
331 match map
.entry
::<A
>() {
332 Entry
::Vacant(_
) => unreachable!(),
333 Entry
::Occupied(mut view
) => {
334 assert_eq!(view
.get(), &A(10));
335 assert_eq!(view
.insert(A(100)), A(10));
338 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
339 assert_eq!(map
.len(), 6);
342 // Existing key (update)
343 match map
.entry
::<B
>() {
344 Entry
::Vacant(_
) => unreachable!(),
345 Entry
::Occupied(mut view
) => {
346 let v
= view
.get_mut();
347 let new_v
= B(v
.0 * 10);
351 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
352 assert_eq!(map
.len(), 6);
355 // Existing key (remove)
356 match map
.entry
::<C
>() {
357 Entry
::Vacant(_
) => unreachable!(),
358 Entry
::Occupied(view
) => {
359 assert_eq!(view
.remove(), C(30));
362 assert_eq!(map
.get
::<C
>(), None
);
363 assert_eq!(map
.len(), 5);
366 // Inexistent key (insert)
367 match map
.entry
::<J
>() {
368 Entry
::Occupied(_
) => unreachable!(),
369 Entry
::Vacant(view
) => {
370 assert_eq!(*view
.insert(J(1000)), J(1000));
373 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
374 assert_eq!(map
.len(), 6);
376 // Entry.or_insert on existing key
377 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
378 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
379 assert_eq!(map
.len(), 6);
381 // Entry.or_insert on nonexisting key
382 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
383 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
384 assert_eq!(map
.len(), 7);
389 test_entry!(test_entry_any
, AnyMap
);
390 test_entry!(test_entry_cloneany
, Map
<CloneAny
>);
394 let mut map
: Map
<CloneAny
> = Map
::new();
395 let _
= map
.insert(A(1));
396 let _
= map
.insert(B(2));
397 let _
= map
.insert(D(3));
398 let _
= map
.insert(E(4));
399 let _
= map
.insert(F(5));
400 let _
= map
.insert(J(6));
401 let map2
= map
.clone();
402 assert_eq!(map2
.len(), 6);
403 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
404 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
405 assert_eq!(map2
.get
::<C
>(), None
);
406 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
407 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
408 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
409 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
413 fn test_varieties() {
414 fn assert_send
<T
: Send
>() { }
415 fn assert_sync
<T
: Sync
>() { }
416 fn assert_clone
<T
: Clone
>() { }
417 fn assert_debug
<T
: ::std
::fmt
::Debug
>() { }
418 assert_send
::<Map
<Any
+ Send
>>();
419 assert_send
::<Map
<Any
+ Send
+ Sync
>>();
420 assert_sync
::<Map
<Any
+ Sync
>>();
421 assert_sync
::<Map
<Any
+ Send
+ Sync
>>();
422 assert_debug
::<Map
<Any
>>();
423 assert_debug
::<Map
<Any
+ Send
>>();
424 assert_debug
::<Map
<Any
+ Sync
>>();
425 assert_debug
::<Map
<Any
+ Send
+ Sync
>>();
426 assert_send
::<Map
<CloneAny
+ Send
>>();
427 assert_send
::<Map
<CloneAny
+ Send
+ Sync
>>();
428 assert_sync
::<Map
<CloneAny
+ Sync
>>();
429 assert_sync
::<Map
<CloneAny
+ Send
+ Sync
>>();
430 assert_clone
::<Map
<CloneAny
+ Send
>>();
431 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
432 assert_clone
::<Map
<CloneAny
+ Sync
>>();
433 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
434 assert_debug
::<Map
<CloneAny
>>();
435 assert_debug
::<Map
<CloneAny
+ Send
>>();
436 assert_debug
::<Map
<CloneAny
+ Sync
>>();
437 assert_debug
::<Map
<CloneAny
+ Send
+ Sync
>>();