aboutsummaryrefslogtreecommitdiff
path: root/src/ptr.rs
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2022-08-25 20:21:49 +0200
committerHampusM <hampus@hampusmat.com>2022-08-27 14:28:23 +0200
commit1c46b68581213ca8ae6200daa32f626b5389b4b0 (patch)
tree8da649471db7893a2347a2df383324b84ac226f0 /src/ptr.rs
parent8e862c7998d0b59c71d20cbcbbc57031f734b6fa (diff)
refactor!: make DI container have single get function
BREAKING CHANGE: The DI container get_singleton & get_factory functions have been replaced by the get function now returning a enum
Diffstat (limited to 'src/ptr.rs')
-rw-r--r--src/ptr.rs58
1 files changed, 56 insertions, 2 deletions
diff --git a/src/ptr.rs b/src/ptr.rs
index 082edf2..08c3788 100644
--- a/src/ptr.rs
+++ b/src/ptr.rs
@@ -3,11 +3,65 @@
//! Smart pointer type aliases.
use std::rc::Rc;
-/// A smart pointer unique to the holder.
+use paste::paste;
+
+use crate::errors::ptr::SomePtrError;
+
+/// A smart pointer for a interface in the transient scope.
pub type TransientPtr<Interface> = Box<Interface>;
-/// A smart pointer to a shared resource.
+/// A smart pointer to a interface in the singleton scope.
pub type SingletonPtr<Interface> = Rc<Interface>;
/// A smart pointer to a factory.
pub type FactoryPtr<FactoryInterface> = Rc<FactoryInterface>;
+
+/// Some smart pointer.
+#[derive(strum_macros::IntoStaticStr)]
+pub enum SomePtr<Interface>
+where
+ Interface: 'static + ?Sized,
+{
+ /// A smart pointer to a interface in the transient scope.
+ Transient(TransientPtr<Interface>),
+
+ /// A smart pointer to a interface in the singleton scope.
+ Singleton(SingletonPtr<Interface>),
+
+ /// A smart pointer to a factory.
+ Factory(FactoryPtr<Interface>),
+}
+
+macro_rules! create_as_variant_fn {
+ ($variant: ident) => {
+ paste! {
+ #[doc =
+ "Returns as " [<$variant:lower>] ".\n"
+ "\n"
+ "# Errors\n"
+ "Will return Err if it's not a " [<$variant:lower>] "."
+ ]
+ pub fn [<$variant:lower>](self) -> Result<[<$variant Ptr>]<Interface>, SomePtrError>
+ {
+ if let SomePtr::$variant(ptr) = self {
+ return Ok(ptr);
+ }
+
+
+ Err(SomePtrError::WrongPtrType {
+ expected: stringify!($variant),
+ found: self.into()
+ })
+ }
+ }
+ };
+}
+
+impl<Interface> SomePtr<Interface>
+where
+ Interface: 'static + ?Sized,
+{
+ create_as_variant_fn!(Transient);
+ create_as_variant_fn!(Singleton);
+ create_as_variant_fn!(Factory);
+}