1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
3 #![crate_id = "anymap#0.9"]
4 #![crate_type = "rlib"]
5 #![crate_type = "dylib"]
6 #![warn(unnecessary_qualification, non_uppercase_statics, unsafe_block,
7 variant_size_difference
, managed_heap_memory
, unnecessary_typecast
,
8 missing_doc
, unused_result
, deprecated_owned_vector
)]
13 use std
::any
::{Any
, AnyRefExt
, AnyMutRefExt
};
14 use std
::intrinsics
::TypeId
;
15 use std
::collections
::HashMap
;
17 /// A map containing zero or one values for any given type and allowing convenient,
18 /// type-safe access to those values.
21 /// # use anymap::AnyMap;
22 /// let mut data = AnyMap::new();
23 /// assert_eq!(data.find(), None::<&int>);
25 /// assert_eq!(data.find(), Some(&42i));
26 /// data.remove::<int>();
27 /// assert_eq!(data.find::<int>(), None);
29 /// #[deriving(PartialEq, Show)]
34 /// assert_eq!(data.find::<Foo>(), None);
35 /// data.insert(Foo { str: "foo".to_string() });
36 /// assert_eq!(data.find(), Some(&Foo { str: "foo".to_string() }));
37 /// data.find_mut::<Foo>().map(|foo| foo.str.push_char('t'));
38 /// assert_eq!(data.find::<Foo>().unwrap().str.as_slice(), "foot");
41 /// Values containing non-static references are not permitted.
43 data
: HashMap
<TypeId
, Box
<Any
>:'
static>,
47 /// Construct a new `AnyMap`.
48 pub fn new() -> AnyMap
{
56 /// Retrieve the value stored in the map for the type `T`, if it exists.
57 pub fn find
<'a
, T
: '
static>(&'a
self) -> Option
<&'a T
> {
58 self.data
.find(&TypeId
::of
::<T
>()).and_then(|any
| any
.as_ref
::<T
>())
61 /// Retrieve a mutable reference to the value stored in the map for the type `T`, if it exists.
62 pub fn find_mut
<'a
, T
: '
static>(&'a
mut self) -> Option
<&'a
mut T
> {
63 self.data
.find_mut(&TypeId
::of
::<T
>()).and_then(|any
| any
.as_mut
::<T
>())
66 /// Set the value contained in the map for the type `T`.
67 /// This will override any previous value stored.
68 pub fn insert
<T
: '
static>(&mut self, value
: T
) {
69 self.data
.insert(TypeId
::of
::<T
>(), box value
as Box
<Any
>:'
static);
72 /// Remove the value for the type `T` if it existed.
73 pub fn remove
<T
: '
static>(&mut self) {
74 self.data
.remove(&TypeId
::of
::<T
>());
79 fn bench_insertion(b
: &mut ::test
::Bencher
) {
81 let mut data
= AnyMap
::new();
87 fn bench_find_missing(b
: &mut ::test
::Bencher
) {
89 let data
= AnyMap
::new();
90 assert_eq!(data
.find(), None
::<&int
>);
95 fn bench_find_present(b
: &mut ::test
::Bencher
) {
97 let mut data
= AnyMap
::new();
99 assert_eq!(data
.find(), Some(&42i));