//! Arbitrary object store use std::any::{ TypeId, Any, }; use std::collections::HashMap; /// Arbitrarily typed singleton store. /// /// Stores one object per type. #[derive(Debug)] pub struct SingletonStore { objects: HashMap>, } #[inline] fn unbox_to(b: Box) -> Option { b.downcast().map(|ok| *ok).ok() } impl SingletonStore { pub fn has(&self) -> bool { self.objects.contains_key(&TypeId::of::()) } pub fn remove(&mut self) -> Option { self.objects.remove(&TypeId::of::()) .and_then(|x| x.downcast().ok()) .map(|x| *x) } pub fn insert(&mut self, value: T) -> Option { self.objects.insert(TypeId::of::(), Box::new(value)) .and_then(unbox_to) } pub fn get_mut(&mut self) -> Option<&mut T> { self.objects.get_mut(&TypeId::of::()) .and_then(|x| x.downcast_mut()) } pub fn get(&self) -> Option<&T> { self.objects.get(&TypeId::of::()) .and_then(|x| x.downcast_ref()) } pub fn new() -> Self { Self { objects: HashMap::new(), } } }