mod context_map;
mod id;
pub use context_map::*;
pub use id::*;
use std::{any::Any, ops::Deref, sync::Arc};
use crate::{abort::AbortStore, memoize::MemoizeCache};
#[derive(Debug, Default)]
pub struct Cx {
id: CxId,
app_context: Arc<ContextMap>,
request_context: ContextMap,
memoize_cache: MemoizeCache,
abort_store: AbortStore,
}
impl Cx {
fn new(app_context: Arc<ContextMap>, request_context: ContextMap) -> Self {
Self {
id: CxId::new(),
app_context,
request_context,
memoize_cache: MemoizeCache::new(),
abort_store: AbortStore::new(),
}
}
#[inline]
pub fn id(&self) -> CxId {
self.id
}
}
#[derive(Debug, Default)]
pub struct CxBuilder {
cx: Cx,
}
impl CxBuilder {
#[must_use]
pub fn new(app_context: Arc<ContextMap>) -> Self {
Self {
cx: Cx::new(app_context, ContextMap::new()),
}
}
pub fn insert<T>(&mut self, value: T) -> Option<T>
where
T: Any + Send + Sync,
{
self.cx.request_context.insert(value)
}
#[must_use]
pub fn contains<T>(&self) -> bool
where
T: Any + Send + Sync,
{
self.cx.request_context.contains::<T>()
}
#[must_use]
pub fn get<T>(&self) -> Option<&T>
where
T: Any + Send + Sync,
{
self.cx.request_context.get::<T>()
}
#[must_use]
pub fn get_mut<T>(&mut self) -> Option<&mut T>
where
T: Any + Send + Sync,
{
self.cx.request_context.get_mut::<T>()
}
#[must_use]
pub fn build(self) -> Cx {
self.cx
}
}
impl Deref for CxBuilder {
type Target = Cx;
fn deref(&self) -> &Cx {
&self.cx
}
}
#[derive(Debug, Default)]
pub struct CxTestBuilder {
app_context: ContextMap,
request_context: ContextMap,
}
impl CxTestBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn app_context<T>(mut self, value: T) -> Self
where
T: Any + Send + Sync,
{
self.app_context.insert(value);
self
}
#[must_use]
pub fn request_context<T>(mut self, value: T) -> Self
where
T: Any + Send + Sync,
{
self.request_context.insert(value);
self
}
#[must_use]
pub fn build(self) -> Cx {
Cx::new(Arc::new(self.app_context), self.request_context)
}
}
#[inline]
#[doc(hidden)]
pub fn memoize_cache(cx: &Cx) -> &MemoizeCache {
&cx.memoize_cache
}
#[inline]
#[doc(hidden)]
pub fn abort_store(cx: &Cx) -> &AbortStore {
&cx.abort_store
}