64a0f6bebc69af1643679525ac9efa4bc4dc50a2
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #
![cfg_attr(feature
= "unstable", feature(hashmap_hasher
, raw
))]
4 #
![cfg_attr(all(feature
= "unstable", test
), feature(test
))]
5 #
![warn(missing_docs
, unused_results
)]
7 #
[cfg(all(feature
= "unstable", test
))]
11 use std
::marker
::PhantomData
;
14 use any
::{UncheckedAnyExt
, IntoBox
, Any
};
16 macro_rules
! impl_common_methods
{
18 field
: $t
:ident
.$field
:ident
;
20 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
22 impl<A
: ?Sized
+ UncheckedAnyExt
> $t
<A
> {
23 /// Create an empty collection.
25 pub fn new() -> $t
<A
> {
31 /// Creates an empty collection with the given initial capacity.
33 pub fn with_capacity($with_capacity_arg
: usize) -> $t
<A
> {
35 $field
: $with_capacity
,
39 /// Returns the number of elements the collection can hold without reallocating.
41 pub fn capacity(&self) -> usize {
42 self.$field
.capacity()
45 /// Reserves capacity for at least `additional` more elements to be inserted
46 /// in the collection. The collection may reserve more space to avoid
47 /// frequent reallocations.
51 /// Panics if the new allocation size overflows `usize`.
53 pub fn reserve(&mut self, additional
: usize) {
54 self.$field
.reserve(additional
)
57 /// Shrinks the capacity of the collection as much as possible. It will drop
58 /// down as much as possible while maintaining the internal rules
59 /// and possibly leaving some space in accordance with the resize policy.
61 pub fn shrink_to_fit(&mut self) {
62 self.$field
.shrink_to_fit()
65 /// Returns the number of items in the collection.
67 pub fn len(&self) -> usize {
71 /// Returns true if there are no items in the collection.
73 pub fn is_empty(&self) -> bool
{
74 self.$field
.is_empty()
77 /// Removes all items from the collection. Keeps the allocated memory for reuse.
79 pub fn clear(&mut self) {
89 /// A collection containing zero or one values for any given type and allowing convenient,
90 /// type-safe access to those values.
92 /// The type parameter `A` allows you to use a different value type; normally you will want it to
93 /// be `anymap::any::Any`, but there are other choices:
95 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
96 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
99 /// # use anymap::AnyMap;
100 /// let mut data = AnyMap::new();
101 /// assert_eq!(data.get(), None::<&i32>);
102 /// data.insert(42i32);
103 /// assert_eq!(data.get(), Some(&42i32));
104 /// data.remove::<i32>();
105 /// assert_eq!(data.get::<i32>(), None);
107 /// #[derive(Clone, PartialEq, Debug)]
112 /// assert_eq!(data.get::<Foo>(), None);
113 /// data.insert(Foo { str: format!("foo") });
114 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
115 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
116 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
119 /// Values containing non-static references are not permitted.
121 pub struct Map
<A
: ?Sized
+ UncheckedAnyExt
= Any
> {
125 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
126 impl<A
: ?Sized
+ UncheckedAnyExt
> Clone
for Map
<A
> where Box
<A
>: Clone
{
127 fn clone(&self) -> Map
<A
> {
129 raw
: self.raw
.clone(),
134 /// The most common type of `Map`: just using `Any`.
136 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
137 /// doesn’t seem to be happy to infer that it should go with the default value.
138 /// It’s a bit sad, really. Ah well, I guess this approach will do.
139 pub type AnyMap
= Map
<Any
>;
141 impl_common_methods
! {
143 new() => RawMap
::new();
144 with_capacity(capacity
) => RawMap
::with_capacity(capacity
);
147 impl<A
: ?Sized
+ UncheckedAnyExt
> Map
<A
> {
148 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
149 pub fn get
<T
: IntoBox
<A
>>(&self) -> Option
<&T
> {
150 self.raw
.get(&TypeId
::of
::<T
>())
151 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
154 /// Returns a mutable reference to the value stored in the collection for the type `T`,
156 pub fn get_mut
<T
: IntoBox
<A
>>(&mut self) -> Option
<&mut T
> {
157 self.raw
.get_mut(&TypeId
::of
::<T
>())
158 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
161 /// Sets the value stored in the collection for the type `T`.
162 /// If the collection already had a value of type `T`, that value is returned.
163 /// Otherwise, `None` is returned.
164 pub fn insert
<T
: IntoBox
<A
>>(&mut self, value
: T
) -> Option
<T
> {
166 self.raw
.insert(TypeId
::of
::<T
>(), value
.into_box())
167 .map(|any
| *any
.downcast_unchecked
::<T
>())
171 /// Removes the `T` value from the collection,
172 /// 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
185 pub fn entry
<T
: IntoBox
<A
>>(&mut self) -> Entry
<A
, T
> {
186 match self.raw
.entry(TypeId
::of
::<T
>()) {
187 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
191 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
199 impl<A
: ?Sized
+ UncheckedAnyExt
> AsRef
<RawMap
<A
>> for Map
<A
> {
200 fn as_ref(&self) -> &RawMap
<A
> {
205 impl<A
: ?Sized
+ UncheckedAnyExt
> AsMut
<RawMap
<A
>> for Map
<A
> {
206 fn as_mut(&mut self) -> &mut RawMap
<A
> {
211 impl<A
: ?Sized
+ UncheckedAnyExt
> Into
<RawMap
<A
>> for Map
<A
> {
212 fn into(self) -> RawMap
<A
> {
217 /// A view into a single occupied location in an `Map`.
218 pub struct OccupiedEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
219 inner
: raw
::OccupiedEntry
<'a
, A
>,
220 type_
: PhantomData
<V
>,
223 /// A view into a single empty location in an `Map`.
224 pub struct VacantEntry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
225 inner
: raw
::VacantEntry
<'a
, A
>,
226 type_
: PhantomData
<V
>,
229 /// A view into a single location in an `Map`, which may be vacant or occupied.
230 pub enum Entry
<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: 'a
> {
231 /// An occupied Entry
232 Occupied(OccupiedEntry
<'a
, A
, V
>),
234 Vacant(VacantEntry
<'a
, A
, V
>),
237 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
> + Clone
> Entry
<'a
, A
, V
> {
238 /// Ensures a value is in the entry by inserting the default if empty, and returns
239 /// a mutable reference to the value in the entry.
240 pub fn or_insert(self, default: V
) -> &'a
mut V
{
242 Entry
::Occupied(inner
) => inner
.into_mut(),
243 Entry
::Vacant(inner
) => inner
.insert(default),
247 /// Ensures a value is in the entry by inserting the result of the default function if empty,
248 /// and returns a mutable reference to the value in the entry.
249 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
251 Entry
::Occupied(inner
) => inner
.into_mut(),
252 Entry
::Vacant(inner
) => inner
.insert(default()),
257 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> OccupiedEntry
<'a
, A
, V
> {
258 /// Gets a reference to the value in the entry
259 pub fn get(&self) -> &V
{
260 unsafe { self.inner
.get().downcast_ref_unchecked() }
263 /// Gets a mutable reference to the value in the entry
264 pub fn get_mut(&mut self) -> &mut V
{
265 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
268 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
269 /// with a lifetime bound to the collection itself
270 pub fn into_mut(self) -> &'a
mut V
{
271 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
274 /// Sets the value of the entry, and returns the entry's old value
275 pub fn insert(&mut self, value
: V
) -> V
{
276 unsafe { *self.inner
.insert(value
.into_box()).downcast_unchecked() }
279 /// Takes the value out of the entry, and returns it
280 pub fn remove(self) -> V
{
281 unsafe { *self.inner
.remove().downcast_unchecked() }
285 impl<'a
, A
: ?Sized
+ UncheckedAnyExt
, V
: IntoBox
<A
>> VacantEntry
<'a
, A
, V
> {
286 /// Sets the value of the entry with the VacantEntry's key,
287 /// and returns a mutable reference to it
288 pub fn insert(self, value
: V
) -> &'a
mut V
{
289 unsafe { self.inner
.insert(value
.into_box()).downcast_mut_unchecked() }
293 #
[cfg(feature
= "unstable")]
295 fn bench_insertion(b
: &mut ::test
::Bencher
) {
297 let mut data
= AnyMap
::new();
299 let _
= data
.insert(42);
304 #
[cfg(feature
= "unstable")]
306 fn bench_get_missing(b
: &mut ::test
::Bencher
) {
308 let data
= AnyMap
::new();
310 assert_eq!(data
.get(), None
::<&i32>);
315 #
[cfg(feature
= "unstable")]
317 fn bench_get_present(b
: &mut ::test
::Bencher
) {
319 let mut data
= AnyMap
::new();
320 let _
= data
.insert(42);
321 // These inner loops are a feeble attempt to drown the other factors.
323 assert_eq!(data
.get(), Some(&42));
330 use {Map
, AnyMap
, Entry
};
331 use any
::{Any
, CloneAny
};
333 #
[derive(Clone
, Debug
, PartialEq
)] struct A(i32);
334 #
[derive(Clone
, Debug
, PartialEq
)] struct B(i32);
335 #
[derive(Clone
, Debug
, PartialEq
)] struct C(i32);
336 #
[derive(Clone
, Debug
, PartialEq
)] struct D(i32);
337 #
[derive(Clone
, Debug
, PartialEq
)] struct E(i32);
338 #
[derive(Clone
, Debug
, PartialEq
)] struct F(i32);
339 #
[derive(Clone
, Debug
, PartialEq
)] struct J(i32);
343 let mut map
: AnyMap
= AnyMap
::new();
344 assert_eq!(map
.insert(A(10)), None
);
345 assert_eq!(map
.insert(B(20)), None
);
346 assert_eq!(map
.insert(C(30)), None
);
347 assert_eq!(map
.insert(D(40)), None
);
348 assert_eq!(map
.insert(E(50)), None
);
349 assert_eq!(map
.insert(F(60)), None
);
351 // Existing key (insert)
352 match map
.entry
::<A
>() {
353 Entry
::Vacant(_
) => unreachable!(),
354 Entry
::Occupied(mut view
) => {
355 assert_eq!(view
.get(), &A(10));
356 assert_eq!(view
.insert(A(100)), A(10));
359 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
360 assert_eq!(map
.len(), 6);
363 // Existing key (update)
364 match map
.entry
::<B
>() {
365 Entry
::Vacant(_
) => unreachable!(),
366 Entry
::Occupied(mut view
) => {
367 let v
= view
.get_mut();
368 let new_v
= B(v
.0 * 10);
372 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
373 assert_eq!(map
.len(), 6);
376 // Existing key (remove)
377 match map
.entry
::<C
>() {
378 Entry
::Vacant(_
) => unreachable!(),
379 Entry
::Occupied(view
) => {
380 assert_eq!(view
.remove(), C(30));
383 assert_eq!(map
.get
::<C
>(), None
);
384 assert_eq!(map
.len(), 5);
387 // Inexistent key (insert)
388 match map
.entry
::<J
>() {
389 Entry
::Occupied(_
) => unreachable!(),
390 Entry
::Vacant(view
) => {
391 assert_eq!(*view
.insert(J(1000)), J(1000));
394 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
395 assert_eq!(map
.len(), 6);
397 // Entry.or_insert on existing key
398 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
399 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
400 assert_eq!(map
.len(), 6);
402 // Entry.or_insert on nonexisting key
403 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
404 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
405 assert_eq!(map
.len(), 7);
410 let mut map
: Map
<CloneAny
> = Map
::new();
411 let _
= map
.insert(A(1));
412 let _
= map
.insert(B(2));
413 let _
= map
.insert(D(3));
414 let _
= map
.insert(E(4));
415 let _
= map
.insert(F(5));
416 let _
= map
.insert(J(6));
417 let map2
= map
.clone();
418 assert_eq!(map2
.len(), 6);
419 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
420 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
421 assert_eq!(map2
.get
::<C
>(), None
);
422 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
423 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
424 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
425 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
429 fn test_varieties() {
430 fn assert_send
<T
: Send
>() { }
431 fn assert_sync
<T
: Sync
>() { }
432 fn assert_clone
<T
: Clone
>() { }
433 fn assert_debug
<T
: ::std
::fmt
::Debug
>() { }
434 assert_send
::<Map
<Any
+ Send
>>();
435 assert_send
::<Map
<Any
+ Send
+ Sync
>>();
436 assert_sync
::<Map
<Any
+ Sync
>>();
437 assert_sync
::<Map
<Any
+ Send
+ Sync
>>();
438 assert_debug
::<Map
<Any
>>();
439 assert_debug
::<Map
<Any
+ Send
>>();
440 assert_debug
::<Map
<Any
+ Sync
>>();
441 assert_debug
::<Map
<Any
+ Send
+ Sync
>>();
442 assert_send
::<Map
<CloneAny
+ Send
>>();
443 assert_send
::<Map
<CloneAny
+ Send
+ Sync
>>();
444 assert_sync
::<Map
<CloneAny
+ Sync
>>();
445 assert_sync
::<Map
<CloneAny
+ Send
+ Sync
>>();
446 assert_clone
::<Map
<CloneAny
+ Send
>>();
447 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
448 assert_clone
::<Map
<CloneAny
+ Sync
>>();
449 assert_clone
::<Map
<CloneAny
+ Send
+ Sync
>>();
450 assert_debug
::<Map
<CloneAny
>>();
451 assert_debug
::<Map
<CloneAny
+ Send
>>();
452 assert_debug
::<Map
<CloneAny
+ Sync
>>();
453 assert_debug
::<Map
<CloneAny
+ Send
+ Sync
>>();