2021-06-25 23:53:13 +08:00
|
|
|
use crate::{
|
2021-07-10 16:27:20 +08:00
|
|
|
errors::{DispatchError, InternalError},
|
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-23 14:54:31 +08:00
|
|
|
pub struct Unit<T: ?Sized + Send + Sync>(Arc<T>);
|
2021-06-25 23:53:13 +08:00
|
|
|
|
2021-07-23 14:54:31 +08:00
|
|
|
impl<T> Unit<T>
|
2021-07-02 20:45:51 +08:00
|
|
|
where
|
|
|
|
T: Send + Sync,
|
|
|
|
{
|
2021-07-23 14:54:31 +08:00
|
|
|
pub fn new(data: T) -> Self { Unit(Arc::new(data)) }
|
2021-06-25 23:53:13 +08:00
|
|
|
|
|
|
|
pub fn get_ref(&self) -> &T { self.0.as_ref() }
|
|
|
|
}
|
|
|
|
|
2021-07-23 14:54:31 +08:00
|
|
|
impl<T> Deref for Unit<T>
|
2021-07-02 20:45:51 +08:00
|
|
|
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-23 14:54:31 +08:00
|
|
|
impl<T> Clone for Unit<T>
|
2021-07-02 20:45:51 +08:00
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync,
|
|
|
|
{
|
2021-07-23 14:54:31 +08:00
|
|
|
fn clone(&self) -> Unit<T> { Unit(self.0.clone()) }
|
2021-06-25 23:53:13 +08:00
|
|
|
}
|
|
|
|
|
2021-07-23 14:54:31 +08:00
|
|
|
impl<T> From<Arc<T>> for Unit<T>
|
2021-07-02 20:45:51 +08:00
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync,
|
|
|
|
{
|
2021-07-23 14:54:31 +08:00
|
|
|
fn from(arc: Arc<T>) -> Self { Unit(arc) }
|
2021-06-25 23:53:13 +08:00
|
|
|
}
|
|
|
|
|
2021-07-23 14:54:31 +08:00
|
|
|
impl<T> FromRequest for Unit<T>
|
2021-07-02 20:45:51 +08:00
|
|
|
where
|
|
|
|
T: ?Sized + Send + Sync + 'static,
|
|
|
|
{
|
2021-07-10 16:27:20 +08:00
|
|
|
type Error = DispatchError;
|
|
|
|
type Future = Ready<Result<Self, DispatchError>>;
|
2021-06-25 23:53:13 +08:00
|
|
|
|
|
|
|
#[inline]
|
2021-07-09 17:47:15 +08:00
|
|
|
fn from_request(req: &EventRequest, _: &mut Payload) -> Self::Future {
|
2021-07-23 14:54:31 +08:00
|
|
|
if let Some(data) = req.module_data::<Unit<T>>() {
|
2021-07-09 17:47:15 +08:00
|
|
|
ready(Ok(data.clone()))
|
|
|
|
} else {
|
2021-09-13 15:51:13 +08:00
|
|
|
let msg = format!("Failed to get the module data of type: {}", type_name::<T>());
|
2021-07-09 17:47:15 +08:00
|
|
|
log::error!("{}", msg,);
|
2021-08-21 12:11:33 +08:00
|
|
|
ready(Err(InternalError::Other(msg).into()))
|
2021-07-09 17:47:15 +08:00
|
|
|
}
|
|
|
|
}
|
2021-06-25 23:53:13 +08:00
|
|
|
}
|