From 94b8e52eeefdabab98dfdb5bf4c91f75d778150c Mon Sep 17 00:00:00 2001 From: HampusM Date: Thu, 28 Jul 2022 20:38:33 +0200 Subject: refactor: tidy up DI container internals --- src/di_container_binding_map.rs | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/di_container_binding_map.rs (limited to 'src/di_container_binding_map.rs') 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>, +} + +impl DIContainerBindingMap +{ + pub fn new() -> Self + { + Self { + bindings: AHashMap::new(), + } + } + + pub fn get(&self) -> error_stack::Result<&dyn IProvider, DIContainerError> + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + Ok(self + .bindings + .get(&interface_typeid) + .ok_or_else(|| { + report!(DIContainerError).attach_printable(format!( + "No binding exists for {}", + type_name::() + )) + })? + .as_ref()) + } + + pub fn set(&mut self, provider: Box) + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + 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() + } +} -- cgit v1.2.3-18-g5258