aboutsummaryrefslogtreecommitdiff
path: root/src/di_container_binding_map.rs
blob: d4b46f2296e8714019a69527352e9263cd149c6a (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
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
93
94
95
96
97
98
99
100
101
use std::any::{type_name, TypeId};

use ahash::AHashMap;

use crate::{errors::di_container::DIContainerError, provider::IProvider};

#[derive(Debug, PartialEq, Eq, Hash)]
struct DIContainerBindingKey
{
    type_id: TypeId,
    name: Option<&'static str>,
}

pub struct DIContainerBindingMap
{
    bindings: AHashMap<DIContainerBindingKey, Box<dyn IProvider>>,
}

impl DIContainerBindingMap
{
    pub fn new() -> Self
    {
        Self {
            bindings: AHashMap::new(),
        }
    }

    pub fn get<Interface>(
        &self,
        name: Option<&'static str>,
    ) -> Result<&dyn IProvider, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        let interface_typeid = TypeId::of::<Interface>();

        Ok(self
            .bindings
            .get(&DIContainerBindingKey {
                type_id: interface_typeid,
                name,
            })
            .ok_or_else(|| DIContainerError::BindingNotFound {
                interface: type_name::<Interface>(),
                name,
            })?
            .as_ref())
    }

    pub fn set<Interface>(
        &mut self,
        name: Option<&'static str>,
        provider: Box<dyn IProvider>,
    ) 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<dyn IProvider>>
    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()
    }
}