1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
use std::any::TypeId;
use ahash::AHashMap;
#[derive(Debug, PartialEq, Eq, Hash)]
struct DIContainerBindingKey
{
type_id: TypeId,
name: Option<&'static str>,
}
pub struct DIContainerBindingMap<Provider>
where
Provider: 'static + ?Sized,
{
bindings: AHashMap<DIContainerBindingKey, Box<Provider>>,
}
impl<Provider> DIContainerBindingMap<Provider>
where
Provider: 'static + ?Sized,
{
pub fn new() -> Self
{
Self {
bindings: AHashMap::new(),
}
}
pub fn get<Interface>(&self, name: Option<&'static str>) -> Option<&Provider>
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
self.bindings
.get(&DIContainerBindingKey {
type_id: interface_typeid,
name,
})
.map(|provider| provider.as_ref())
}
pub fn set<Interface>(&mut self, name: Option<&'static str>, provider: Box<Provider>)
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
self.bindings.insert(
DIContainerBindingKey {
type_id: interface_typeid,
name,
},
provider,
);
}
pub fn remove<Interface>(
&mut self,
name: Option<&'static str>,
) -> Option<Box<Provider>>
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
self.bindings.remove(&DIContainerBindingKey {
type_id: interface_typeid,
name,
})
}
pub fn has<Interface>(&self, name: Option<&'static str>) -> bool
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
self.bindings.contains_key(&DIContainerBindingKey {
type_id: interface_typeid,
name,
})
}
/// Only used by tests in the `di_container` module.
#[cfg(test)]
pub fn count(&self) -> usize
{
self.bindings.len()
}
}
|