use log::trace;
use std::any::type_name;
use std::any::Any;
use std::any::TypeId;
use std::collections::BTreeMap;
#[derive(Default, Debug)]
pub struct State {
data: BTreeMap<TypeId, Box<dyn Any>>,
}
impl State {
pub fn put<T: 'static>(&mut self, t: T) {
let type_id = TypeId::of::<T>();
trace!(" inserting record to state for type_id `{:?}`", type_id);
self.data.insert(type_id, Box::new(t));
}
pub fn has<T: 'static>(&self) -> bool {
let type_id = TypeId::of::<T>();
self.data.get(&type_id).is_some()
}
pub fn try_borrow<T: 'static>(&self) -> Option<&T> {
let type_id = TypeId::of::<T>();
trace!(" borrowing state data for type_id `{:?}`", type_id);
self.data.get(&type_id).and_then(|b| b.downcast_ref())
}
pub fn borrow<T: 'static>(&self) -> &T {
self.try_borrow().unwrap_or_else(|| missing::<T>())
}
pub fn try_borrow_mut<T: 'static>(&mut self) -> Option<&mut T> {
let type_id = TypeId::of::<T>();
trace!(" mutably borrowing state data for type_id `{:?}`", type_id);
self.data.get_mut(&type_id).and_then(|b| b.downcast_mut())
}
pub fn borrow_mut<T: 'static>(&mut self) -> &mut T {
self.try_borrow_mut().unwrap_or_else(|| missing::<T>())
}
pub fn try_take<T: 'static>(&mut self) -> Option<T> {
let type_id = TypeId::of::<T>();
trace!(
" taking ownership from state data for type_id `{:?}`",
type_id
);
self.data
.remove(&type_id)
.and_then(|b| b.downcast().ok())
.map(|b| *b)
}
pub fn take<T: 'static>(&mut self) -> T {
self.try_take().unwrap_or_else(|| missing::<T>())
}
}
fn missing<T: 'static>() -> ! {
panic!(
"required type {} is not present in State container",
type_name::<T>()
);
}