diff options
| author | HampusM <hampus@hampusmat.com> | 2022-07-28 20:38:33 +0200 | 
|---|---|---|
| committer | HampusM <hampus@hampusmat.com> | 2022-07-31 12:17:51 +0200 | 
| commit | 94b8e52eeefdabab98dfdb5bf4c91f75d778150c (patch) | |
| tree | bf57b9d717778c6be9798e47828c9bed45f28aa4 /src/di_container_binding_map.rs | |
| parent | 545e8efddf217f300b26b930f8345d8573c30ec7 (diff) | |
refactor: tidy up DI container internals
Diffstat (limited to 'src/di_container_binding_map.rs')
| -rw-r--r-- | src/di_container_binding_map.rs | 55 | 
1 files changed, 55 insertions, 0 deletions
| diff --git a/src/di_container_binding_map.rs b/src/di_container_binding_map.rs new file mode 100644 index 0000000..b505321 --- /dev/null +++ b/src/di_container_binding_map.rs @@ -0,0 +1,55 @@ +use std::any::{type_name, TypeId}; + +use ahash::AHashMap; +use error_stack::report; + +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) -> error_stack::Result<&dyn IProvider, DIContainerError> +    where +        Interface: 'static + ?Sized, +    { +        let interface_typeid = TypeId::of::<Interface>(); + +        Ok(self +            .bindings +            .get(&interface_typeid) +            .ok_or_else(|| { +                report!(DIContainerError).attach_printable(format!( +                    "No binding exists for {}", +                    type_name::<Interface>() +                )) +            })? +            .as_ref()) +    } + +    pub fn set<Interface>(&mut self, provider: Box<dyn IProvider>) +    where +        Interface: 'static + ?Sized, +    { +        let interface_typeid = TypeId::of::<Interface>(); + +        self.bindings.insert(interface_typeid, provider); +    } + +    /// Only used by tests in the ``di_container`` module. +    #[cfg(test)] +    pub fn count(&self) -> usize +    { +        self.bindings.len() +    } +} | 
