From 5b0c6a52022e67a2d9cee251b3d08b9cb2b5f6cb Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 9 Oct 2022 12:05:24 +0200 Subject: refactor!: reorganize DI containers BREAKING CHANGE: DIContainer, AsyncDIContainer & the binding structs have been relocated --- src/di_container/binding_map.rs | 91 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 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..eb71ff7 --- /dev/null +++ b/src/di_container/binding_map.rs @@ -0,0 +1,91 @@ +use std::any::TypeId; + +use ahash::AHashMap; + +#[derive(Debug, PartialEq, Eq, Hash)] +struct DIContainerBindingKey +{ + type_id: TypeId, + name: Option<&'static str>, +} + +pub struct DIContainerBindingMap +where + Provider: 'static + ?Sized, +{ + bindings: AHashMap>, +} + +impl DIContainerBindingMap +where + Provider: 'static + ?Sized, +{ + pub fn new() -> Self + { + Self { + bindings: AHashMap::new(), + } + } + + #[allow(clippy::borrowed_box)] + pub fn get(&self, name: Option<&'static str>) -> Option<&Box> + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + self.bindings.get(&DIContainerBindingKey { + type_id: interface_typeid, + name, + }) + } + + pub fn set(&mut self, name: Option<&'static str>, provider: Box) + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + self.bindings.insert( + DIContainerBindingKey { + type_id: interface_typeid, + name, + }, + provider, + ); + } + + pub fn remove( + &mut self, + name: Option<&'static str>, + ) -> Option> + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + self.bindings.remove(&DIContainerBindingKey { + type_id: interface_typeid, + name, + }) + } + + pub fn has(&self, name: Option<&'static str>) -> bool + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + 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() + } +} -- cgit v1.2.3-18-g5258