use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Default)]
pub struct ContextStorage {
values: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
}
impl ContextStorage {
pub fn new() -> Self {
Self::default()
}
pub fn provide<T: Clone + 'static>(&self, value: T) {
let type_id = TypeId::of::<T>();
self.values.borrow_mut().insert(type_id, Rc::new(value));
}
pub fn get<T: Clone + 'static>(&self) -> Option<T> {
let type_id = TypeId::of::<T>();
self.values
.borrow()
.get(&type_id)
.and_then(|v| v.downcast_ref::<T>())
.cloned()
}
pub fn has<T: 'static>(&self) -> bool {
let type_id = TypeId::of::<T>();
self.values.borrow().contains_key(&type_id)
}
pub fn clear(&self) {
self.values.borrow_mut().clear();
}
}