cdcc6fffb847134f0d4e0d506abe142655b51612
[anymap] / src / lib.rs
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
2
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)]
9
10 #[cfg(test)]
11 extern crate test;
12
13 use std::any::{Any, AnyRefExt, AnyMutRefExt};
14 use std::intrinsics::TypeId;
15 use std::collections::HashMap;
16
17 /// A map containing zero or one values for any given type and allowing convenient,
18 /// type-safe access to those values.
19 ///
20 /// ```rust
21 /// # use anymap::AnyMap;
22 /// let mut data = AnyMap::new();
23 /// assert_eq!(data.find(), None::<&int>);
24 /// data.insert(42i);
25 /// assert_eq!(data.find(), Some(&42i));
26 /// data.remove::<int>();
27 /// assert_eq!(data.find::<int>(), None);
28 ///
29 /// #[deriving(PartialEq, Show)]
30 /// struct Foo {
31 /// str: String,
32 /// }
33 ///
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");
39 /// ```
40 ///
41 /// Values containing non-static references are not permitted.
42 pub struct AnyMap {
43 data: HashMap<TypeId, Box<Any>:'static>,
44 }
45
46 impl AnyMap {
47 /// Construct a new `AnyMap`.
48 pub fn new() -> AnyMap {
49 AnyMap {
50 data: HashMap::new(),
51 }
52 }
53 }
54
55 impl 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>())
59 }
60
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>())
64 }
65
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);
70 }
71
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>());
75 }
76 }
77
78 #[bench]
79 fn bench_insertion(b: &mut ::test::Bencher) {
80 b.iter(|| {
81 let mut data = AnyMap::new();
82 data.insert(42i);
83 })
84 }
85
86 #[bench]
87 fn bench_find_missing(b: &mut ::test::Bencher) {
88 b.iter(|| {
89 let data = AnyMap::new();
90 assert_eq!(data.find(), None::<&int>);
91 })
92 }
93
94 #[bench]
95 fn bench_find_present(b: &mut ::test::Bencher) {
96 b.iter(|| {
97 let mut data = AnyMap::new();
98 data.insert(42i);
99 assert_eq!(data.find(), Some(&42i));
100 })
101 }