2021-06-25 23:53:13 +08:00
|
|
|
use crate::{
|
2021-07-09 17:47:15 +08:00
|
|
|
error::{InternalError, SystemError},
|
2021-06-27 15:11:41 +08:00
|
|
|
request::{payload::Payload, EventRequest, FromRequest},
|
2021-07-09 17:47:15 +08:00
|
|
|
util::ready::{ready, Ready},
|
2021-06-25 23:53:13 +08:00
|
|
|
};
|
2021-07-09 17:47:15 +08:00
|
|
|
use std::{any::type_name, ops::Deref, sync::Arc};
|
2021-06-25 23:53:13 +08:00
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
pub struct ModuleData<T: ?Sized + Send + Sync>(Arc<T>);
|
2021-06-25 23:53:13 +08:00
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
impl<T> ModuleData<T>
|
|
|
|
where
|
|
|
|
T: Send + Sync,
|
|
|
|
{
|
2021-06-25 23:53:13 +08:00
|
|
|
pub fn new(data: T) -> Self { ModuleData(Arc::new(data)) }
|
|
|
|
|
|
|
|
pub fn get_ref(&self) -> &T { self.0.as_ref() }
|
|
|
|
}
|
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
impl<T> Deref for ModuleData<T>
|
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync,
|
|
|
|
{
|
2021-06-25 23:53:13 +08:00
|
|
|
type Target = Arc<T>;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Arc<T> { &self.0 }
|
|
|
|
}
|
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
impl<T> Clone for ModuleData<T>
|
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync,
|
|
|
|
{
|
2021-06-25 23:53:13 +08:00
|
|
|
fn clone(&self) -> ModuleData<T> { ModuleData(self.0.clone()) }
|
|
|
|
}
|
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
impl<T> From<Arc<T>> for ModuleData<T>
|
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync,
|
|
|
|
{
|
2021-06-25 23:53:13 +08:00
|
|
|
fn from(arc: Arc<T>) -> Self { ModuleData(arc) }
|
|
|
|
}
|
|
|
|
|
2021-07-02 20:45:51 +08:00
|
|
|
impl<T> FromRequest for ModuleData<T>
|
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync + 'static,
|
|
|
|
{
|
2021-06-25 23:53:13 +08:00
|
|
|
type Error = SystemError;
|
|
|
|
type Future = Ready<Result<Self, SystemError>>;
|
|
|
|
|
|
|
|
#[inline]
|
2021-07-09 17:47:15 +08:00
|
|
|
fn from_request(req: &EventRequest, _: &mut Payload) -> Self::Future {
|
|
|
|
if let Some(data) = req.module_data::<ModuleData<T>>() {
|
|
|
|
ready(Ok(data.clone()))
|
|
|
|
} else {
|
|
|
|
let msg = format!("Failed to get the module data(type: {})", type_name::<T>());
|
|
|
|
log::error!("{}", msg,);
|
|
|
|
ready(Err(InternalError::new(msg).into()))
|
|
|
|
}
|
|
|
|
}
|
2021-06-25 23:53:13 +08:00
|
|
|
}
|