d32af5f2aa4327826844727c183a09f47c247fb7
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #![cfg_attr(feature = "nightly", feature(core, std_misc))]
4 #![cfg_attr(test, feature(test))]
5 #![warn(missing_docs, unused_results)]
11 use std
::marker
::PhantomData
;
13 use raw
::{RawAnyMap
, Any
};
14 use unchecked_any
::UncheckedAnyExt
;
16 macro_rules
! impl_common_methods
{
18 field
: $t
:ident
.$field
:ident
;
20 with_capacity($with_capacity_arg
:ident
) => $with_capacity
:expr
;
23 /// Create an empty collection.
31 /// Creates an empty collection with the given initial capacity.
33 pub fn with_capacity($with_capacity_arg
: usize) -> $t
{
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.
93 /// # use anymap::AnyMap;
94 /// let mut data = AnyMap::new();
95 /// assert_eq!(data.get(), None::<&i32>);
96 /// data.insert(42i32);
97 /// assert_eq!(data.get(), Some(&42i32));
98 /// data.remove::<i32>();
99 /// assert_eq!(data.get::<i32>(), None);
101 /// #[derive(Clone, PartialEq, Debug)]
106 /// assert_eq!(data.get::<Foo>(), None);
107 /// data.insert(Foo { str: format!("foo") });
108 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
109 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
110 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
113 /// Values containing non-static references are not permitted.
115 #[cfg_attr(feature = "clone", derive(Clone))]
120 impl_common_methods
! {
122 new() => RawAnyMap
::new();
123 with_capacity(capacity
) => RawAnyMap
::with_capacity(capacity
);
127 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
128 pub fn get
<T
: Any
>(&self) -> Option
<&T
> {
129 self.raw
.get(&TypeId
::of
::<T
>())
130 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
133 /// Returns a mutable reference to the value stored in the collection for the type `T`,
135 pub fn get_mut
<T
: Any
>(&mut self) -> Option
<&mut T
> {
136 self.raw
.get_mut(&TypeId
::of
::<T
>())
137 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
140 /// Sets the value stored in the collection for the type `T`.
141 /// If the collection already had a value of type `T`, that value is returned.
142 /// Otherwise, `None` is returned.
143 pub fn insert
<T
: Any
>(&mut self, value
: T
) -> Option
<T
> {
145 self.raw
.insert(TypeId
::of
::<T
>(), Box
::new(value
))
146 .map(|any
| *any
.downcast_unchecked
::<T
>())
150 /// Removes the `T` value from the collection,
151 /// returning it if there was one or `None` if there was not.
152 pub fn remove
<T
: Any
>(&mut self) -> Option
<T
> {
153 self.raw
.remove(&TypeId
::of
::<T
>())
154 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
157 /// Returns true if the collection contains a value of type `T`.
159 pub fn contains
<T
: Any
>(&self) -> bool
{
160 self.raw
.contains_key(&TypeId
::of
::<T
>())
163 /// Gets the entry for the given type in the collection for in-place manipulation
164 pub fn entry
<T
: Any
>(&mut self) -> Entry
<T
> {
165 match self.raw
.entry(TypeId
::of
::<T
>()) {
166 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
170 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
178 impl AsRef
<RawAnyMap
> for AnyMap
{
179 fn as_ref(&self) -> &RawAnyMap
{
184 impl AsMut
<RawAnyMap
> for AnyMap
{
185 fn as_mut(&mut self) -> &mut RawAnyMap
{
190 impl Into
<RawAnyMap
> for AnyMap
{
191 fn into(self) -> RawAnyMap
{
196 /// A view into a single occupied location in an `AnyMap`.
197 pub struct OccupiedEntry
<'a
, V
: 'a
> {
198 inner
: raw
::OccupiedEntry
<'a
>,
199 type_
: PhantomData
<V
>,
202 /// A view into a single empty location in an `AnyMap`.
203 pub struct VacantEntry
<'a
, V
: 'a
> {
204 inner
: raw
::VacantEntry
<'a
>,
205 type_
: PhantomData
<V
>,
208 /// A view into a single location in an `AnyMap`, which may be vacant or occupied.
209 pub enum Entry
<'a
, V
: 'a
> {
210 /// An occupied Entry
211 Occupied(OccupiedEntry
<'a
, V
>),
213 Vacant(VacantEntry
<'a
, V
>),
216 impl<'a
, V
: Any
+ Clone
> Entry
<'a
, V
> {
217 /// Ensures a value is in the entry by inserting the default if empty, and returns
218 /// a mutable reference to the value in the entry.
219 pub fn or_insert(self, default: V
) -> &'a
mut V
{
221 Entry
::Occupied(inner
) => inner
.into_mut(),
222 Entry
::Vacant(inner
) => inner
.insert(default),
226 /// Ensures a value is in the entry by inserting the result of the default function if empty,
227 /// and returns a mutable reference to the value in the entry.
228 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
230 Entry
::Occupied(inner
) => inner
.into_mut(),
231 Entry
::Vacant(inner
) => inner
.insert(default()),
236 impl<'a
, V
: Any
> OccupiedEntry
<'a
, V
> {
237 /// Gets a reference to the value in the entry
238 pub fn get(&self) -> &V
{
239 unsafe { self.inner
.get().downcast_ref_unchecked() }
242 /// Gets a mutable reference to the value in the entry
243 pub fn get_mut(&mut self) -> &mut V
{
244 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
247 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
248 /// with a lifetime bound to the collection itself
249 pub fn into_mut(self) -> &'a
mut V
{
250 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
253 /// Sets the value of the entry, and returns the entry's old value
254 pub fn insert(&mut self, value
: V
) -> V
{
255 unsafe { *self.inner
.insert(Box
::new(value
)).downcast_unchecked() }
258 /// Takes the value out of the entry, and returns it
259 pub fn remove(self) -> V
{
260 unsafe { *self.inner
.remove().downcast_unchecked() }
264 impl<'a
, V
: Any
> VacantEntry
<'a
, V
> {
265 /// Sets the value of the entry with the VacantEntry's key,
266 /// and returns a mutable reference to it
267 pub fn insert(self, value
: V
) -> &'a
mut V
{
268 unsafe { self.inner
.insert(Box
::new(value
)).downcast_mut_unchecked() }
273 fn bench_insertion(b
: &mut ::test
::Bencher
) {
275 let mut data
= AnyMap
::new();
277 let _
= data
.insert(42);
283 fn bench_get_missing(b
: &mut ::test
::Bencher
) {
285 let data
= AnyMap
::new();
287 assert_eq!(data
.get(), None
::<&i32>);
293 fn bench_get_present(b
: &mut ::test
::Bencher
) {
295 let mut data
= AnyMap
::new();
296 let _
= data
.insert(42);
297 // These inner loops are a feeble attempt to drown the other factors.
299 assert_eq!(data
.get(), Some(&42));
308 #[derive(Clone, Debug, PartialEq)] struct A(i32);
309 #[derive(Clone, Debug, PartialEq)] struct B(i32);
310 #[derive(Clone, Debug, PartialEq)] struct C(i32);
311 #[derive(Clone, Debug, PartialEq)] struct D(i32);
312 #[derive(Clone, Debug, PartialEq)] struct E(i32);
313 #[derive(Clone, Debug, PartialEq)] struct F(i32);
314 #[derive(Clone, Debug, PartialEq)] struct J(i32);
318 let mut map
: AnyMap
= AnyMap
::new();
319 assert_eq!(map
.insert(A(10)), None
);
320 assert_eq!(map
.insert(B(20)), None
);
321 assert_eq!(map
.insert(C(30)), None
);
322 assert_eq!(map
.insert(D(40)), None
);
323 assert_eq!(map
.insert(E(50)), None
);
324 assert_eq!(map
.insert(F(60)), None
);
326 // Existing key (insert)
327 match map
.entry
::<A
>() {
328 Entry
::Vacant(_
) => unreachable!(),
329 Entry
::Occupied(mut view
) => {
330 assert_eq!(view
.get(), &A(10));
331 assert_eq!(view
.insert(A(100)), A(10));
334 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
335 assert_eq!(map
.len(), 6);
338 // Existing key (update)
339 match map
.entry
::<B
>() {
340 Entry
::Vacant(_
) => unreachable!(),
341 Entry
::Occupied(mut view
) => {
342 let v
= view
.get_mut();
343 let new_v
= B(v
.0 * 10);
347 assert_eq!(map
.get
::<B
>().unwrap(), &B(200));
348 assert_eq!(map
.len(), 6);
351 // Existing key (remove)
352 match map
.entry
::<C
>() {
353 Entry
::Vacant(_
) => unreachable!(),
354 Entry
::Occupied(view
) => {
355 assert_eq!(view
.remove(), C(30));
358 assert_eq!(map
.get
::<C
>(), None
);
359 assert_eq!(map
.len(), 5);
362 // Inexistent key (insert)
363 match map
.entry
::<J
>() {
364 Entry
::Occupied(_
) => unreachable!(),
365 Entry
::Vacant(view
) => {
366 assert_eq!(*view
.insert(J(1000)), J(1000));
369 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
370 assert_eq!(map
.len(), 6);
372 // Entry.or_insert on existing key
373 map
.entry
::<B
>().or_insert(B(71)).0 += 1;
374 assert_eq!(map
.get
::<B
>().unwrap(), &B(201));
375 assert_eq!(map
.len(), 6);
377 // Entry.or_insert on nonexisting key
378 map
.entry
::<C
>().or_insert(C(300)).0 += 1;
379 assert_eq!(map
.get
::<C
>().unwrap(), &C(301));
380 assert_eq!(map
.len(), 7);
383 #[cfg(feature = "clone")]
386 let mut map
= AnyMap
::new();
387 let _
= map
.insert(A(1));
388 let _
= map
.insert(B(2));
389 let _
= map
.insert(D(3));
390 let _
= map
.insert(E(4));
391 let _
= map
.insert(F(5));
392 let _
= map
.insert(J(6));
393 let map2
= map
.clone();
394 assert_eq!(map2
.len(), 6);
395 assert_eq!(map2
.get
::<A
>(), Some(&A(1)));
396 assert_eq!(map2
.get
::<B
>(), Some(&B(2)));
397 assert_eq!(map2
.get
::<C
>(), None
);
398 assert_eq!(map2
.get
::<D
>(), Some(&D(3)));
399 assert_eq!(map2
.get
::<E
>(), Some(&E(4)));
400 assert_eq!(map2
.get
::<F
>(), Some(&F(5)));
401 assert_eq!(map2
.get
::<J
>(), Some(&J(6)));
404 #[cfg(feature = "concurrent")]
406 fn test_concurrent() {
407 fn assert_concurrent
<T
: Send
+ Sync
>() { }
408 assert_concurrent
::<AnyMap
>();