1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #![feature(core, std_misc, hash)]
4 #![cfg_attr(test, feature(test))]
5 #![warn(unused_qualifications, non_upper_case_globals,
6 variant_size_differences
, unused_typecasts
,
7 missing_docs
, unused_results
)]
12 use std
::any
::{Any
, TypeId
};
14 use std
::collections
::HashMap
;
15 use std
::collections
::hash_map
;
16 use std
::hash
::{Hasher
, Writer
};
17 use std
::collections
::hash_state
::HashState
;
18 use std
::mem
::transmute
;
19 use std
::raw
::TraitObject
;
27 impl HashState
for TypeIdState
{
28 type Hasher
= TypeIdHasher
;
30 fn hasher(&self) -> TypeIdHasher
{
31 TypeIdHasher
{ value
: 0 }
35 impl Writer
for TypeIdHasher
{
37 fn write(&mut self, bytes
: &[u8]) {
38 // This expects to receive one and exactly one 64-bit value
39 debug_assert!(bytes
.len() == 8);
41 std
::ptr
::copy_nonoverlapping_memory(&mut self.value
,
48 impl Hasher
for TypeIdHasher
{
51 fn reset(&mut self) { }
53 fn finish(&self) -> u64 { self.value
}
56 /// An extension of `AnyRefExt` allowing unchecked downcasting of trait objects to `&T`.
57 trait UncheckedAnyRefExt
<'a
> {
58 /// Returns a reference to the boxed value, assuming that it is of type `T`. This should only be
59 /// called if you are ABSOLUTELY CERTAIN of `T` as you will get really wacky output if it’s not.
60 unsafe fn downcast_ref_unchecked
<T
: '
static>(self) -> &'a T
;
63 impl<'a
> UncheckedAnyRefExt
<'a
> for &'a Any
{
65 unsafe fn downcast_ref_unchecked
<T
: '
static>(self) -> &'a T
{
66 // Get the raw representation of the trait object
67 let to
: TraitObject
= transmute(self);
69 // Extract the data pointer
74 /// An extension of `AnyMutRefExt` allowing unchecked downcasting of trait objects to `&mut T`.
75 trait UncheckedAnyMutRefExt
<'a
> {
76 /// Returns a reference to the boxed value, assuming that it is of type `T`. This should only be
77 /// called if you are ABSOLUTELY CERTAIN of `T` as you will get really wacky output if it’s not.
78 unsafe fn downcast_mut_unchecked
<T
: '
static>(self) -> &'a
mut T
;
81 impl<'a
> UncheckedAnyMutRefExt
<'a
> for &'a
mut Any
{
83 unsafe fn downcast_mut_unchecked
<T
: '
static>(self) -> &'a
mut T
{
84 // Get the raw representation of the trait object
85 let to
: TraitObject
= transmute(self);
87 // Extract the data pointer
92 /// An extension of `BoxAny` allowing unchecked downcasting of trait objects to `Box<T>`.
93 trait UncheckedBoxAny
{
94 /// Returns the boxed value, assuming that it is of type `T`. This should only be called if you
95 /// are ABSOLUTELY CERTAIN of `T` as you will get really wacky output if it’s not.
96 unsafe fn downcast_unchecked
<T
: '
static>(self) -> Box
<T
>;
99 impl UncheckedBoxAny
for Box
<Any
+ '
static> {
101 unsafe fn downcast_unchecked
<T
: '
static>(self) -> Box
<T
> {
102 // Get the raw representation of the trait object
103 let to
: TraitObject
= *transmute
::<&Box
<Any
>, &TraitObject
>(&self);
105 // Prevent destructor on self being run
108 // Extract the data pointer
113 /// A collection containing zero or one values for any given type and allowing convenient,
114 /// type-safe access to those values.
117 /// # use anymap::AnyMap;
118 /// let mut data = AnyMap::new();
119 /// assert_eq!(data.get(), None::<&i32>);
120 /// data.insert(42i32);
121 /// assert_eq!(data.get(), Some(&42i32));
122 /// data.remove::<i32>();
123 /// assert_eq!(data.get::<i32>(), None);
125 /// #[derive(PartialEq, Debug)]
130 /// assert_eq!(data.get::<Foo>(), None);
131 /// data.insert(Foo { str: format!("foo") });
132 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
133 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
134 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
137 /// Values containing non-static references are not permitted.
140 data
: HashMap
<TypeId
, Box
<Any
+ '
static>, TypeIdState
>,
144 /// Construct a new `AnyMap`.
147 pub fn new() -> AnyMap
{
149 data
: HashMap
::with_hash_state(TypeIdState
),
153 /// Creates an empty AnyMap with the given initial capacity.
156 pub fn with_capcity(capacity
: usize) -> AnyMap
{
158 data
: HashMap
::with_capacity_and_hash_state(capacity
, TypeIdState
),
162 /// Returns the number of elements the collection can hold without reallocating.
165 pub fn capacity(&self) -> usize {
169 /// Reserves capacity for at least `additional` more elements to be inserted
170 /// in the `AnyMap`. The collection may reserve more space to avoid
171 /// frequent reallocations.
175 /// Panics if the new allocation size overflows `usize`.
178 pub fn reserve(&mut self, additional
: usize) {
179 self.data
.reserve(additional
)
182 /// Shrinks the capacity of the collection as much as possible. It will drop
183 /// down as much as possible while maintaining the internal rules
184 /// and possibly leaving some space in accordance with the resize policy.
187 pub fn shrink_to_fit(&mut self) {
188 self.data
.shrink_to_fit()
191 /// An iterator visiting all items in the collection in arbitrary order.
192 /// Iterator element type is `&Any`.
194 /// This is probably not a great deal of use.
197 pub fn iter(&self) -> Iter
{
199 inner
: self.data
.iter(),
203 /// An iterator visiting all items in the collection in arbitrary order.
204 /// Iterator element type is `&mut Any`.
206 /// This is probably not a great deal of use.
209 pub fn iter_mut(&mut self) -> IterMut
{
211 inner
: self.data
.iter_mut(),
215 /// An iterator visiting all items in the collection in arbitrary order.
216 /// Creates a consuming iterator, that is, one that moves each item
217 /// out of the map in arbitrary order. The map cannot be used after
220 /// Iterator element type is `Box<Any>`.
223 pub fn into_iter(self) -> IntoIter
{
225 inner
: self.data
.into_iter(),
229 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
231 pub fn get
<T
: Any
+ '
static>(&self) -> Option
<&T
> {
232 self.data
.get(&TypeId
::of
::<T
>())
233 .map(|any
| unsafe { any
.downcast_ref_unchecked
::<T
>() })
236 /// Returns a mutable reference to the value stored in the collection for the type `T`,
239 pub fn get_mut
<T
: Any
+ '
static>(&mut self) -> Option
<&mut T
> {
240 self.data
.get_mut(&TypeId
::of
::<T
>())
241 .map(|any
| unsafe { any
.downcast_mut_unchecked
::<T
>() })
244 /// Sets the value stored in the collection for the type `T`.
245 /// If the collection already had a value of type `T`, that value is returned.
246 /// Otherwise, `None` is returned.
248 pub fn insert
<T
: Any
+ '
static>(&mut self, value
: T
) -> Option
<T
> {
249 self.data
.insert(TypeId
::of
::<T
>(), Box
::new(value
) as Box
<Any
>)
250 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
253 /// Removes the `T` value from the collection,
254 /// returning it if there was one or `None` if there was not.
256 pub fn remove
<T
: Any
+ '
static>(&mut self) -> Option
<T
> {
257 self.data
.remove(&TypeId
::of
::<T
>())
258 .map(|any
| *unsafe { any
.downcast_unchecked
::<T
>() })
261 /// Returns true if the collection contains a value of type `T`.
263 pub fn contains
<T
: Any
+ '
static>(&self) -> bool
{
264 self.data
.contains_key(&TypeId
::of
::<T
>())
267 /// Gets the entry for the given type in the collection for in-place manipulation
269 pub fn entry
<T
: Any
+ '
static>(&mut self) -> Entry
<T
> {
270 match self.data
.entry(TypeId
::of
::<T
>()) {
271 hash_map
::Entry
::Occupied(e
) => Entry
::Occupied(OccupiedEntry
{ entry
: e
}),
272 hash_map
::Entry
::Vacant(e
) => Entry
::Vacant(VacantEntry
{ entry
: e
}),
276 /// Returns the number of items in the collection.
279 pub fn len(&self) -> usize {
283 /// Returns true if there are no items in the collection.
286 pub fn is_empty(&self) -> bool
{
290 /// Clears the map, returning all items as an iterator.
292 /// Iterator element type is `Box<Any>`.
294 /// Keeps the allocated memory for reuse.
296 #[unstable = "matches collection reform specification, waiting for dust to settle"]
297 pub fn drain(&mut self) -> Drain
{
299 inner
: self.data
.drain(),
303 /// Removes all items from the collection. Keeps the allocated memory for reuse.
306 pub fn clear(&mut self) {
311 /// A view into a single occupied location in an AnyMap
313 pub struct OccupiedEntry
<'a
, V
: 'a
> {
314 entry
: hash_map
::OccupiedEntry
<'a
, TypeId
, Box
<Any
+ '
static>>,
317 /// A view into a single empty location in an AnyMap
319 pub struct VacantEntry
<'a
, V
: 'a
> {
320 entry
: hash_map
::VacantEntry
<'a
, TypeId
, Box
<Any
+ '
static>>,
323 /// A view into a single location in an AnyMap, which may be vacant or occupied
325 pub enum Entry
<'a
, V
: 'a
> {
326 /// An occupied Entry
327 Occupied(OccupiedEntry
<'a
, V
>),
329 Vacant(VacantEntry
<'a
, V
>),
332 impl<'a
, V
: '
static + Clone
> Entry
<'a
, V
> {
333 #[unstable = "matches collection reform v2 specification, waiting for dust to settle"]
334 /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
335 pub fn get(self) -> Result
<&'a
mut V
, VacantEntry
<'a
, V
>> {
337 Entry
::Occupied(entry
) => Ok(entry
.into_mut()),
338 Entry
::Vacant(entry
) => Err(entry
),
343 impl<'a
, V
: '
static> OccupiedEntry
<'a
, V
> {
345 /// Gets a reference to the value in the entry
346 pub fn get(&self) -> &V
{
347 unsafe { self.entry
.get().downcast_ref_unchecked() }
351 /// Gets a mutable reference to the value in the entry
352 pub fn get_mut(&mut self) -> &mut V
{
353 unsafe { self.entry
.get_mut().downcast_mut_unchecked() }
357 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
358 /// with a lifetime bound to the collection itself
359 pub fn into_mut(self) -> &'a
mut V
{
360 unsafe { self.entry
.into_mut().downcast_mut_unchecked() }
364 /// Sets the value of the entry, and returns the entry's old value
365 pub fn insert(&mut self, value
: V
) -> V
{
366 unsafe { *self.entry
.insert(Box
::new(value
) as Box
<Any
+ '
static>).downcast_unchecked() }
370 /// Takes the value out of the entry, and returns it
371 pub fn remove(self) -> V
{
372 unsafe { *self.entry
.remove().downcast_unchecked() }
376 impl<'a
, V
: '
static> VacantEntry
<'a
, V
> {
378 /// Sets the value of the entry with the VacantEntry's key,
379 /// and returns a mutable reference to it
380 pub fn insert(self, value
: V
) -> &'a
mut V
{
381 unsafe { self.entry
.insert(Box
::new(value
) as Box
<Any
+ '
static>).downcast_mut_unchecked() }
385 /// `AnyMap` iterator.
388 pub struct Iter
<'a
> {
389 inner
: hash_map
::Iter
<'a
, TypeId
, Box
<Any
+ '
static>>,
392 /// `AnyMap` mutable references iterator.
394 pub struct IterMut
<'a
> {
395 inner
: hash_map
::IterMut
<'a
, TypeId
, Box
<Any
+ '
static>>,
398 /// `AnyMap` draining iterator.
399 #[unstable = "matches collection reform specification, waiting for dust to settle"]
400 pub struct Drain
<'a
> {
401 inner
: hash_map
::Drain
<'a
, TypeId
, Box
<Any
+ '
static>>,
404 /// `AnyMap` move iterator.
406 pub struct IntoIter
{
407 inner
: hash_map
::IntoIter
<TypeId
, Box
<Any
+ '
static>>,
411 impl<'a
> Iterator
for Iter
<'a
> {
415 fn next(&mut self) -> Option
<&'a Any
> {
416 self.inner
.next().map(|item
| &**item
.1)
420 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner
.size_hint() }
424 impl<'a
> Iterator
for IterMut
<'a
> {
425 type Item
= &'a
mut Any
;
428 fn next(&mut self) -> Option
<&'a
mut Any
> {
429 self.inner
.next().map(|item
| &mut **item
.1)
433 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner
.size_hint() }
437 impl<'a
> Iterator
for Drain
<'a
> {
438 type Item
= Box
<Any
+ '
static>;
441 fn next(&mut self) -> Option
<Box
<Any
+ '
static>> {
442 self.inner
.next().map(|item
| item
.1)
446 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner
.size_hint() }
450 impl Iterator
for IntoIter
{
451 type Item
= Box
<Any
+ '
static>;
454 fn next(&mut self) -> Option
<Box
<Any
+ '
static>> {
455 self.inner
.next().map(|item
| item
.1)
459 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner
.size_hint() }
463 fn bench_insertion(b
: &mut ::test
::Bencher
) {
465 let mut data
= AnyMap
::new();
466 for _
in range(0, 100) {
467 let _
= data
.insert(42i32);
473 fn bench_get_missing(b
: &mut ::test
::Bencher
) {
475 let data
= AnyMap
::new();
476 for _
in range(0, 100) {
477 assert_eq!(data
.get(), None
::<&i32>);
483 fn bench_get_present(b
: &mut ::test
::Bencher
) {
485 let mut data
= AnyMap
::new();
486 let _
= data
.insert(42i32);
487 // These inner loops are a feeble attempt to drown the other factors.
488 for _
in range(0, 100) {
489 assert_eq!(data
.get(), Some(&42i32));
496 #[derive(Debug, PartialEq)] struct A(i32);
497 #[derive(Debug, PartialEq)] struct B(i32);
498 #[derive(Debug, PartialEq)] struct C(i32);
499 #[derive(Debug, PartialEq)] struct D(i32);
500 #[derive(Debug, PartialEq)] struct E(i32);
501 #[derive(Debug, PartialEq)] struct F(i32);
502 #[derive(Debug, PartialEq)] struct J(i32);
504 let mut map
: AnyMap
= AnyMap
::new();
505 assert_eq!(map
.insert(A(10)), None
);
506 assert_eq!(map
.insert(B(20)), None
);
507 assert_eq!(map
.insert(C(30)), None
);
508 assert_eq!(map
.insert(D(40)), None
);
509 assert_eq!(map
.insert(E(50)), None
);
510 assert_eq!(map
.insert(F(60)), None
);
512 // Existing key (insert)
513 match map
.entry
::<A
>() {
514 Entry
::Vacant(_
) => unreachable!(),
515 Entry
::Occupied(mut view
) => {
516 assert_eq!(view
.get(), &A(10));
517 assert_eq!(view
.insert(A(100)), A(10));
520 assert_eq!(map
.get
::<A
>().unwrap(), &A(100));
521 assert_eq!(map
.len(), 6);
524 // Existing key (update)
525 match map
.entry
::<B
>() {
526 Entry
::Vacant(_
) => unreachable!(),
527 Entry
::Occupied(mut view
) => {
528 let v
= view
.get_mut();
529 let new_v
= B(v
.0 * 10);
533 assert_eq!(map
.get().unwrap(), &B(200));
534 assert_eq!(map
.len(), 6);
537 // Existing key (remove)
538 match map
.entry
::<C
>() {
539 Entry
::Vacant(_
) => unreachable!(),
540 Entry
::Occupied(view
) => {
541 assert_eq!(view
.remove(), C(30));
544 assert_eq!(map
.get
::<C
>(), None
);
545 assert_eq!(map
.len(), 5);
548 // Inexistent key (insert)
549 match map
.entry
::<J
>() {
550 Entry
::Occupied(_
) => unreachable!(),
551 Entry
::Vacant(view
) => {
552 assert_eq!(*view
.insert(J(1000)), J(1000));
555 assert_eq!(map
.get
::<J
>().unwrap(), &J(1000));
556 assert_eq!(map
.len(), 6);