use crate::{ error::{InternalError, SystemError}, request::{payload::Payload, EventRequest, FromRequest}, util::ready::{ready, Ready}, }; use std::{any::type_name, ops::Deref, sync::Arc}; pub struct ModuleData(Arc); impl ModuleData where T: Send + Sync, { pub fn new(data: T) -> Self { ModuleData(Arc::new(data)) } pub fn get_ref(&self) -> &T { self.0.as_ref() } } impl Deref for ModuleData where T: ?Sized + Send + Sync, { type Target = Arc; fn deref(&self) -> &Arc { &self.0 } } impl Clone for ModuleData where T: ?Sized + Send + Sync, { fn clone(&self) -> ModuleData { ModuleData(self.0.clone()) } } impl From> for ModuleData where T: ?Sized + Send + Sync, { fn from(arc: Arc) -> Self { ModuleData(arc) } } impl FromRequest for ModuleData where T: ?Sized + Send + Sync + 'static, { type Error = SystemError; type Future = Ready>; #[inline] fn from_request(req: &EventRequest, _: &mut Payload) -> Self::Future { if let Some(data) = req.module_data::>() { ready(Ok(data.clone())) } else { let msg = format!("Failed to get the module data(type: {})", type_name::()); log::error!("{}", msg,); ready(Err(InternalError::new(msg).into())) } } }