data.rs 1.3 KB

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