use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone, Default)]
pub struct ContextExtensions(HashMap<TypeId, Arc<dyn Any + Send + Sync>>);
impl ContextExtensions {
pub fn insert<T: Any + Send + Sync>(&mut self, value: T) {
_ = self.0.insert(TypeId::of::<T>(), Arc::new(value));
}
#[must_use]
pub fn get<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
Arc::clone(self.0.get(&TypeId::of::<T>())?).downcast().ok()
}
}
impl ContextExtensions {
#[must_use]
pub(crate) fn cloned_or_default<T: Any + Send + Sync + Clone + Default>(&self) -> T {
self.get::<T>()
.map(|value| (*value).clone())
.unwrap_or_default()
}
}
impl std::fmt::Debug for ContextExtensions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContextExtensions").finish_non_exhaustive()
}
}