use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone, Default)]
pub struct StateMap {
map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl StateMap {
pub fn new() -> Self {
Self::default()
}
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
self.map.insert(TypeId::of::<T>(), Arc::new(value));
}
pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
self.map
.get(&TypeId::of::<T>())
.and_then(|arc| arc.clone().downcast::<T>().ok())
}
}
impl std::fmt::Debug for StateMap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StateMap")
.field("len", &self.map.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stores_and_retrieves_by_type() {
let mut m = StateMap::new();
m.insert(7u32);
m.insert(String::from("hello"));
assert_eq!(*m.get::<u32>().unwrap(), 7);
assert_eq!(m.get::<String>().unwrap().as_str(), "hello");
assert!(m.get::<i64>().is_none());
}
}