container.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use std::{
  2. any::{Any, TypeId},
  3. collections::HashMap,
  4. };
  5. #[derive(Default, Debug)]
  6. pub struct ModuleDataMap {
  7. map: HashMap<TypeId, Box<dyn Any + Sync + Send>>,
  8. }
  9. impl ModuleDataMap {
  10. #[inline]
  11. pub fn new() -> ModuleDataMap {
  12. ModuleDataMap {
  13. map: HashMap::default(),
  14. }
  15. }
  16. pub fn insert<T>(&mut self, val: T) -> Option<T>
  17. where
  18. T: 'static + Send + Sync,
  19. {
  20. self.map
  21. .insert(TypeId::of::<T>(), Box::new(val))
  22. .and_then(downcast_owned)
  23. }
  24. pub fn remove<T>(&mut self) -> Option<T>
  25. where
  26. T: 'static + Send + Sync,
  27. {
  28. self.map.remove(&TypeId::of::<T>()).and_then(downcast_owned)
  29. }
  30. pub fn get<T>(&self) -> Option<&T>
  31. where
  32. T: 'static + Send + Sync,
  33. {
  34. self.map.get(&TypeId::of::<T>()).and_then(|boxed| boxed.downcast_ref())
  35. }
  36. pub fn get_mut<T>(&mut self) -> Option<&mut T>
  37. where
  38. T: 'static + Send + Sync,
  39. {
  40. self.map
  41. .get_mut(&TypeId::of::<T>())
  42. .and_then(|boxed| boxed.downcast_mut())
  43. }
  44. pub fn contains<T>(&self) -> bool
  45. where
  46. T: 'static + Send + Sync,
  47. {
  48. self.map.contains_key(&TypeId::of::<T>())
  49. }
  50. pub fn extend(&mut self, other: ModuleDataMap) {
  51. self.map.extend(other.map);
  52. }
  53. }
  54. fn downcast_owned<T: 'static + Send + Sync>(boxed: Box<dyn Any + Send + Sync>) -> Option<T> {
  55. boxed.downcast().ok().map(|boxed| *boxed)
  56. }