diff options
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() + } +} |