blob: e64ff171fde88c97146df55f310897eaa9775004 (
plain)
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
|
use std::any::{type_name, TypeId};
use ahash::AHashMap;
use crate::{errors::di_container::DIContainerError, provider::IProvider};
pub struct DIContainerBindingMap
{
bindings: AHashMap<TypeId, Box<dyn IProvider>>,
}
impl DIContainerBindingMap
{
pub fn new() -> Self
{
Self {
bindings: AHashMap::new(),
}
}
pub fn get<Interface>(&self) -> Result<&dyn IProvider, DIContainerError>
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
Ok(self
.bindings
.get(&interface_typeid)
.ok_or_else(|| DIContainerError::BindingNotFound(type_name::<Interface>()))?
.as_ref())
}
pub fn set<Interface>(&mut self, provider: Box<dyn IProvider>) -> Option<()>
where
Interface: 'static + ?Sized,
{
let interface_typeid = TypeId::of::<Interface>();
if self.bindings.contains_key(&interface_typeid) {
return None;
}
self.bindings.insert(interface_typeid, provider);
Some(())
}
/// Only used by tests in the `di_container` module.
#[cfg(test)]
pub fn count(&self) -> usize
{
self.bindings.len()
}
}
|