use std::{ any::{Any, TypeId}, collections::HashMap, }; #[derive(Default)] pub struct DataContainer { map: HashMap>, } impl DataContainer { #[inline] pub fn new() -> DataContainer { DataContainer { map: HashMap::default(), } } pub fn insert(&mut self, val: T) -> Option where T: 'static + Send + Sync, { self.map .insert(TypeId::of::(), Box::new(val)) .and_then(downcast_owned) } pub fn remove(&mut self) -> Option where T: 'static + Send + Sync, { self.map.remove(&TypeId::of::()).and_then(downcast_owned) } pub fn get(&self) -> Option<&T> where T: 'static + Send + Sync, { self.map .get(&TypeId::of::()) .and_then(|boxed| boxed.downcast_ref()) } pub fn get_mut(&mut self) -> Option<&mut T> where T: 'static + Send + Sync, { self.map .get_mut(&TypeId::of::()) .and_then(|boxed| boxed.downcast_mut()) } pub fn contains(&self) -> bool where T: 'static + Send + Sync, { self.map.contains_key(&TypeId::of::()) } pub fn extend(&mut self, other: DataContainer) { self.map.extend(other.map); } } fn downcast_owned(boxed: Box) -> Option { boxed.downcast().ok().map(|boxed| *boxed) } // use std::{ // any::{Any, TypeId}, // collections::HashMap, // sync::RwLock, // }; // // #[derive(Default)] // pub struct DataContainer { // map: RwLock>>, // } // // impl DataContainer { // #[inline] // pub fn new() -> DataContainer { // DataContainer { // map: RwLock::new(HashMap::default()), // } // } // // pub fn insert(&mut self, val: T) -> Option { // self.map // .write() // .unwrap() // .insert(TypeId::of::(), Box::new(val)) // .and_then(downcast_owned) // } // // pub fn remove(&mut self) -> Option { // self.map // .write() // .unwrap() // .remove(&TypeId::of::()) // .and_then(downcast_owned) // } // // pub fn get(&self) -> Option<&T> { // self.map // .read() // .unwrap() // .get(&TypeId::of::()) // .and_then(|boxed| boxed.downcast_ref()) // } // // pub fn get_mut(&mut self) -> Option<&mut T> { // self.map // .write() // .unwrap() // .get_mut(&TypeId::of::()) // .and_then(|boxed| boxed.downcast_mut()) // } // // pub fn contains(&self) -> bool { // self.map.read().unwrap().contains_key(&TypeId::of::()) // } // // pub fn extend(&mut self, other: DataContainer) { // self.map.write().unwrap().extend(other.map); } } // // fn downcast_owned(boxed: Box) -> Option { // boxed.downcast().ok().map(|boxed| *boxed) // }