use crate::scoped::Scoped;
use crate::{Container, Inject, Shared, Singleton};
use std::fmt::{Debug, Formatter};
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum ProviderKind {
Scoped,
Singleton,
}
#[derive(Clone)]
pub enum Provider<'a> {
Scoped(Scoped),
Singleton(Shared<'a>),
}
impl<'a> Provider<'a> {
pub fn is_scoped(&self) -> bool {
matches!(self, Provider::Scoped(_))
}
pub fn is_singleton(&self) -> bool {
matches!(self, Provider::Singleton(_))
}
pub fn kind(&self) -> ProviderKind {
match self {
Provider::Scoped(_) => ProviderKind::Scoped,
Provider::Singleton(_) => ProviderKind::Singleton,
}
}
#[inline]
pub fn get_scoped<T>(&self) -> Option<T>
where
T: Send + Sync + 'static,
{
match self {
Provider::Scoped(scoped @ Scoped::Factory(_)) => scoped.call_factory(),
_ => None,
}
}
#[inline]
pub fn get_inject<T>(&self, container: &Container) -> Option<T>
where
T: Inject + 'static,
{
match self {
Provider::Scoped(scoped) => match scoped {
Scoped::Factory(_) => None,
Scoped::Construct(_) => scoped.call_construct(container),
},
_ => None,
}
}
#[inline]
pub fn get_singleton<T>(&self) -> Option<Singleton<T>>
where
T: Send + Sync + 'static,
{
match self {
Provider::Singleton(x) => x.get(),
_ => None,
}
}
#[inline]
#[cfg(feature = "lazy")]
pub fn get_singleton_with<T>(&self, container: &Container) -> Option<Singleton<T>>
where
T: Send + Sync + 'static,
{
match self {
Provider::Singleton(x) => x.get_with(container),
_ => None,
}
}
}
impl Debug for Provider<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Provider::Scoped(scoped) => write!(f, "Provider::Scoped({:?})", scoped),
Provider::Singleton(_) => write!(f, "Provider::Singleton(..))"),
}
}
}