aboutsummaryrefslogtreecommitdiff
path: root/src/di_container/binding_map.rs
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2022-10-09 12:05:24 +0200
committerHampusM <hampus@hampusmat.com>2022-10-09 17:03:01 +0200
commit5b0c6a52022e67a2d9cee251b3d08b9cb2b5f6cb (patch)
treec33f06eaab96ec43e477ea5ecd2af93e9d739097 /src/di_container/binding_map.rs
parent97c789e38bb8e61389a3808d241689e623144344 (diff)
refactor!: reorganize DI containers
BREAKING CHANGE: DIContainer, AsyncDIContainer & the binding structs have been relocated
Diffstat (limited to 'src/di_container/binding_map.rs')
-rw-r--r--src/di_container/binding_map.rs91
1 files changed, 91 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..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<Provider>
+where
+ Provider: 'static + ?Sized,
+{
+ bindings: AHashMap<DIContainerBindingKey, Box<Provider>>,
+}
+
+impl<Provider> DIContainerBindingMap<Provider>
+where
+ Provider: 'static + ?Sized,
+{
+ pub fn new() -> Self
+ {
+ Self {
+ bindings: AHashMap::new(),
+ }
+ }
+
+ #[allow(clippy::borrowed_box)]
+ pub fn get<Interface>(&self, name: Option<&'static str>) -> Option<&Box<Provider>>
+ where
+ Interface: 'static + ?Sized,
+ {
+ let interface_typeid = TypeId::of::<Interface>();
+
+ self.bindings.get(&DIContainerBindingKey {
+ type_id: interface_typeid,
+ name,
+ })
+ }
+
+ pub fn set<Interface>(&mut self, name: Option<&'static str>, provider: Box<Provider>)
+ 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<Provider>>
+ 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()
+ }
+}