Skip to content

Commit fb1a332

Browse files
committed
Merge pull request #3 from reem/typemap
Replace HashMap<&'static str, Box<Any>> with TypeMap.
2 parents 6cdba87 + 4a13439 commit fb1a332

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/lib.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ extern crate semver;
33
use std::collections::HashMap;
44
use std::io::net::ip::IpAddr;
55
use std::hash::Hash;
6-
use std::any::Any;
76
use std::fmt::Show;
87

8+
pub use self::typemap::TypeMap;
9+
mod typemap;
10+
911
#[deriving(PartialEq, Show, Clone)]
1012
pub enum Scheme {
1113
Http,
@@ -38,7 +40,7 @@ pub enum Method {
3840
}
3941

4042
/// A Dictionary for extensions provided by the server or middleware
41-
pub type Extensions = HashMap<&'static str, Box<Any>>;
43+
pub type Extensions = TypeMap;
4244

4345
pub trait Request {
4446
/// The version of HTTP being used

src/typemap.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use std::any::{Any, AnyMutRefExt, AnyRefExt};
2+
use std::intrinsics::TypeId;
3+
use std::collections::HashMap;
4+
5+
pub struct TypeMap {
6+
data: HashMap<TypeId, Box<Any>>
7+
}
8+
9+
impl TypeMap {
10+
pub fn find<T: 'static>(&self) -> Option<&T> {
11+
self.data.find(&TypeId::of::<T>()).and_then(|a| a.downcast_ref())
12+
}
13+
14+
pub fn find_mut<T: 'static>(&mut self) -> Option<&mut T> {
15+
self.data.find_mut(&TypeId::of::<T>()).and_then(|a| a.downcast_mut())
16+
}
17+
18+
pub fn insert<T: 'static>(&mut self, val: T) -> bool {
19+
self.data.insert(TypeId::of::<T>(), box val as Box<Any>)
20+
}
21+
22+
pub fn remove<T: 'static>(&mut self) -> bool {
23+
self.data.remove(&TypeId::of::<T>())
24+
}
25+
26+
pub fn contains<T: 'static>(&mut self) -> bool {
27+
self.data.contains_key(&TypeId::of::<T>())
28+
}
29+
}
30+

0 commit comments

Comments
 (0)