use std::{
any::{Any, TypeId},
collections::HashMap,
ops::Deref,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Default)]
pub struct Context {
items: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}
impl Context {
pub fn get<T: 'static>(&self) -> Option<&T> {
self.items
.get(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_ref())
}
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
self.items
.insert(TypeId::of::<T>(), Box::new(value))
.and_then(|boxed| <Box<dyn Any + 'static>>::downcast(boxed).ok().map(|boxed| *boxed))
}
}
#[derive(Clone)]
pub struct Ref<T: Clone>(pub T);
impl<T: Clone> Ref<T> {
pub(super) fn new(object: T) -> Self {
Self(object)
}
}
impl<T: Clone> Deref for Ref<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}