acc0265a0936107ee6fc411549c5799e1bc44af8
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #![feature(core, std_misc, convert)]
4 #![cfg_attr(test, feature(test))]
5 #![warn(missing_docs, unused_results)]
10 use std
::any
::{Any
, TypeId
};
11 use std
::marker
::PhantomData
;
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(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.
119 impl_common_methods
! {
121 new() => RawAnyMap
::new();
122 with_capacity(capacity
) => RawAnyMap
::with_capacity(capacity
);
126 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
127 pub fn get
<T
: Any
>(&self) -> Option
<&T
> {
128 self.raw
.get(&TypeId
::of
::<T
>())
129 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
132 /// Returns a mutable reference to the value stored in the collection for the type `T`,
134 pub fn get_mut
<T
: Any
>(&mut self) -> Option
<&mut T
> {
135 self.raw
.get_mut(&TypeId
::of
::<T
>())
136 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
139 /// Sets the value stored in the collection for the type `T`.
140 /// If the collection already had a value of type `T`, that value is returned.
141 /// Otherwise, `None` is returned.
142 pub fn insert
<T
: Any
>(&mut self, value
: T
) -> Option
<T
> {
144 self.raw
.insert(TypeId
::of
::<T
>(), Box
::new(value
))
145 .map(|any
| *any
.downcast_unchecked
::<T
>())
149 /// Removes the `T` value from the collection,
150 /// returning it if there was one or `None` if there was not.
151 pub fn remove
<T
: Any
>(&mut self) -> Option
<T
> {
152 self.raw
.remove(&TypeId
::of
::<T
>())
153 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
156 /// Returns true if the collection contains a value of type `T`.
158 pub fn contains
<T
: Any
>(&self) -> bool
{
159 self.raw
.contains_key(&TypeId
::of
::<T
>())
162 /// Gets the entry for the given type in the collection for in-place manipulation
163 pub fn entry
<T
: Any
>(&mut self) -> Entry
<T
> {
164 match self.raw
.entry(TypeId
::of
::<T
>()) {
165 raw
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{
169 raw
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{
177 impl AsRef
<RawAnyMap
> for AnyMap
{
178 fn as_ref(&self) -> &RawAnyMap
{
183 impl AsMut
<RawAnyMap
> for AnyMap
{
184 fn as_mut(&mut self) -> &mut RawAnyMap
{
189 impl Into
<RawAnyMap
> for AnyMap
{
190 fn into(self) -> RawAnyMap
{
195 /// A view into a single occupied location in an `AnyMap`.
196 pub struct OccupiedEntry
<'a
, V
: 'a
> {
197 inner
: raw
::OccupiedEntry
<'a
>,
198 type_
: PhantomData
<V
>,
201 /// A view into a single empty location in an `AnyMap`.
202 pub struct VacantEntry
<'a
, V
: 'a
> {
203 inner
: raw
::VacantEntry
<'a
>,
204 type_
: PhantomData
<V
>,
207 /// A view into a single location in an `AnyMap`, which may be vacant or occupied.
208 pub enum Entry
<'a
, V
: 'a
> {
209 /// An occupied Entry
210 Occupied(OccupiedEntry
<'a
, V
>),
212 Vacant(VacantEntry
<'a
, V
>),
215 impl<'a
, V
: Any
+ Clone
> Entry
<'a
, V
> {
216 /// Ensures a value is in the entry by inserting the default if empty, and returns
217 /// a mutable reference to the value in the entry.
218 pub fn or_insert(self, default: V
) -> &'a
mut V
{
220 Entry
::Occupied(inner
) => inner
.into_mut(),
221 Entry
::Vacant(inner
) => inner
.insert(default),
225 /// Ensures a value is in the entry by inserting the result of the default function if empty,
226 /// and returns a mutable reference to the value in the entry.
227 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
229 Entry
::Occupied(inner
) => inner
.into_mut(),
230 Entry
::Vacant(inner
) => inner
.insert(default()),
235 impl<'a
, V
: Any
> OccupiedEntry
<'a
, V
> {
236 /// Gets a reference to the value in the entry
237 pub fn get(&self) -> &V
{
238 unsafe { self.inner
.get().downcast_ref_unchecked() }
241 /// Gets a mutable reference to the value in the entry
242 pub fn get_mut(&mut self) -> &mut V
{
243 unsafe { self.inner
.get_mut().downcast_mut_unchecked() }
246 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
247 /// with a lifetime bound to the collection itself
248 pub fn into_mut(self) -> &'a
mut V
{
249 unsafe { self.inner
.into_mut().downcast_mut_unchecked() }
252 /// Sets the value of the entry, and returns the entry's old value
253 pub fn insert(&mut self, value
: V
) -> V
{
254 unsafe { *self.inner
.insert(Box
::new(value
)).downcast_unchecked() }
257 /// Takes the value out of the entry, and returns it
258 pub fn remove(self) -> V
{
259 unsafe { *self.inner
.remove().downcast_unchecked() }
263 impl<'a
, V
: Any
> VacantEntry
<'a
, V
> {
264 /// Sets the value of the entry with the VacantEntry's key,
265 /// and returns a mutable reference to it
266 pub fn insert(self, value
: V
) -> &'a
mut V
{
267 unsafe { self.inner
.insert(Box
::new(value
)).downcast_mut_unchecked() }
272 fn bench_insertion(b
: &mut ::test
::Bencher
) {
274 let mut data
= AnyMap
::new();
276 let _
= data
.insert(42);
282 fn bench_get_missing(b
: &mut ::test
::Bencher
) {
284 let data
= AnyMap
::new();
286 assert_eq!(data
.get(), None
::<&i32>);
292 fn bench_get_present(b
: &mut ::test
::Bencher
) {
294 let mut data
= AnyMap
::new();
295 let _
= data
.insert(42);
296 // These inner loops are a feeble attempt to drown the other factors.
298 assert_eq!(data
.get(), Some(&42));
305 #[derive(Debug, PartialEq)] struct A(i32);
306 #[derive(Debug, PartialEq)] struct B(i32);
307 #[derive(Debug, PartialEq)] struct C(i32);
308 #[derive(Debug, PartialEq)] struct D(i32);
309 #[derive(Debug, PartialEq)] struct E(i32);
310 #[derive(Debug, PartialEq)] struct F(i32);
311 #[derive(Debug, PartialEq)] struct J(i32);
313 let mut map
: AnyMap
= AnyMap
::new();
314 assert_eq!(map
.insert(A(10)), None
);
315 assert_eq!(map
.insert(B(20)), None
);
316 assert_eq!(map
.insert(C(30)), None
);
317 assert_eq!(map
.insert(D(40)), None
);
318 assert_eq!(map
.insert(E(50)), None
);
319 assert_eq!(map
.insert(F(60)), None
);
321 // Existing key (insert)
322 match map
.entry
::<A
>() {
323 Entry
::Vacant(_
) => unreachable!(),
324 Entry
::Occupied(mut view
) => {
325 assert_eq!(view
.get(), &A(10));
326 assert_eq!(view
.insert(A(100)), A(10));
329 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
330 assert_eq!(map
.len(), 6);
333 // Existing key (update)
334 match map
.entry
::<B
>() {
335 Entry
::Vacant(_
) => unreachable!(),
336 Entry
::Occupied(mut view
) => {
337 let v
= view
.get_mut();
338 let new_v
= B(v
.0 * 10);
342 assert_eq!(map
.get().unwrap(), &B(200));
343 assert_eq!(map
.len(), 6);
346 // Existing key (remove)
347 match map
.entry
::<C
>() {
348 Entry
::Vacant(_
) => unreachable!(),
349 Entry
::Occupied(view
) => {
350 assert_eq!(view
.remove(), C(30));
353 assert_eq!(map
.get
::<C
>(), None
);
354 assert_eq!(map
.len(), 5);
357 // Inexistent key (insert)
358 match map
.entry
::<J
>() {
359 Entry
::Occupied(_
) => unreachable!(),
360 Entry
::Vacant(view
) => {
361 assert_eq!(*view
.insert(J(1000)), J(1000));
364 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
365 assert_eq!(map
.len(), 6);