From 1c46b68581213ca8ae6200daa32f626b5389b4b0 Mon Sep 17 00:00:00 2001 From: HampusM Date: Thu, 25 Aug 2022 20:21:49 +0200 Subject: 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 --- src/ptr.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) (limited to 'src/ptr.rs') 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 = Box; -/// A smart pointer to a shared resource. +/// A smart pointer to a interface in the singleton scope. pub type SingletonPtr = Rc; /// A smart pointer to a factory. pub type FactoryPtr = Rc; + +/// Some smart pointer. +#[derive(strum_macros::IntoStaticStr)] +pub enum SomePtr +where + Interface: 'static + ?Sized, +{ + /// A smart pointer to a interface in the transient scope. + Transient(TransientPtr), + + /// A smart pointer to a interface in the singleton scope. + Singleton(SingletonPtr), + + /// A smart pointer to a factory. + Factory(FactoryPtr), +} + +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>], SomePtrError> + { + if let SomePtr::$variant(ptr) = self { + return Ok(ptr); + } + + + Err(SomePtrError::WrongPtrType { + expected: stringify!($variant), + found: self.into() + }) + } + } + }; +} + +impl SomePtr +where + Interface: 'static + ?Sized, +{ + create_as_variant_fn!(Transient); + create_as_variant_fn!(Singleton); + create_as_variant_fn!(Factory); +} -- cgit v1.2.3-18-g5258