container.rs 1.3 KB

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