data.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use crate::{
  2. errors::{DispatchError, InternalError},
  3. request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
  4. util::ready::{ready, Ready},
  5. };
  6. use std::{any::type_name, ops::Deref, sync::Arc};
  7. pub struct AFPluginState<T: ?Sized + Send + Sync>(Arc<T>);
  8. impl<T> AFPluginState<T>
  9. where
  10. T: Send + Sync,
  11. {
  12. pub fn new(data: T) -> Self {
  13. AFPluginState(Arc::new(data))
  14. }
  15. pub fn get_ref(&self) -> &T {
  16. self.0.as_ref()
  17. }
  18. }
  19. impl<T> Deref for AFPluginState<T>
  20. where
  21. T: ?Sized + Send + Sync,
  22. {
  23. type Target = Arc<T>;
  24. fn deref(&self) -> &Arc<T> {
  25. &self.0
  26. }
  27. }
  28. impl<T> Clone for AFPluginState<T>
  29. where
  30. T: ?Sized + Send + Sync,
  31. {
  32. fn clone(&self) -> AFPluginState<T> {
  33. AFPluginState(self.0.clone())
  34. }
  35. }
  36. impl<T> From<Arc<T>> for AFPluginState<T>
  37. where
  38. T: ?Sized + Send + Sync,
  39. {
  40. fn from(arc: Arc<T>) -> Self {
  41. AFPluginState(arc)
  42. }
  43. }
  44. impl<T> FromAFPluginRequest for AFPluginState<T>
  45. where
  46. T: ?Sized + Send + Sync + 'static,
  47. {
  48. type Error = DispatchError;
  49. type Future = Ready<Result<Self, DispatchError>>;
  50. #[inline]
  51. fn from_request(req: &AFPluginEventRequest, _: &mut Payload) -> Self::Future {
  52. if let Some(state) = req.get_state::<AFPluginState<T>>() {
  53. ready(Ok(state.clone()))
  54. } else {
  55. let msg = format!("Failed to get the plugin state of type: {}", type_name::<T>());
  56. log::error!("{}", msg,);
  57. ready(Err(InternalError::Other(msg).into()))
  58. }
  59. }
  60. }