70 lines
1.4 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
2022-02-25 22:27:44 +08:00
pub struct AppData<T: ?Sized + Send + Sync>(Arc<T>);
2021-06-25 23:53:13 +08:00
2022-02-25 22:27:44 +08:00
impl<T> AppData<T>
where
T: Send + Sync,
{
2022-01-23 12:14:00 +08:00
pub fn new(data: T) -> Self {
2022-02-25 22:27:44 +08:00
AppData(Arc::new(data))
2022-01-23 12:14:00 +08:00
}
2021-06-25 23:53:13 +08:00
2022-01-23 12:14:00 +08:00
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
2021-06-25 23:53:13 +08:00
}
2022-02-25 22:27:44 +08:00
impl<T> Deref for AppData<T>
where
T: ?Sized + Send + Sync,
{
2021-06-25 23:53:13 +08:00
type Target = Arc<T>;
2022-01-23 12:14:00 +08:00
fn deref(&self) -> &Arc<T> {
&self.0
}
2021-06-25 23:53:13 +08:00
}
2022-02-25 22:27:44 +08:00
impl<T> Clone for AppData<T>
where
T: ?Sized + Send + Sync,
{
2022-02-25 22:27:44 +08:00
fn clone(&self) -> AppData<T> {
AppData(self.0.clone())
2022-01-23 12:14:00 +08:00
}
2021-06-25 23:53:13 +08:00
}
2022-02-25 22:27:44 +08:00
impl<T> From<Arc<T>> for AppData<T>
where
T: ?Sized + Send + Sync,
{
2022-01-23 12:14:00 +08:00
fn from(arc: Arc<T>) -> Self {
2022-02-25 22:27:44 +08:00
AppData(arc)
2022-01-23 12:14:00 +08:00
}
2021-06-25 23:53:13 +08:00
}
2022-02-25 22:27:44 +08:00
impl<T> FromRequest for AppData<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 {
2022-02-25 22:27:44 +08:00
if let Some(data) = req.module_data::<AppData<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
}