60 lines
1.3 KiB
Rust
Raw Normal View History

2021-06-25 23:53:13 +08:00
use crate::{
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>
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>
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>
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>
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>
where
T: ?Sized + Send + Sync + 'static,
{
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,);
ready(Err(InternalError::Other(msg).into()))
2021-07-09 17:47:15 +08:00
}
}
2021-06-25 23:53:13 +08:00
}