73 lines
1.4 KiB
Rust
Raw Normal View History

2021-06-25 23:53:13 +08:00
use crate::{
errors::{DispatchError, InternalError},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
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
pub struct AFPluginState<T: ?Sized + Send + Sync>(Arc<T>);
2021-06-25 23:53:13 +08:00
impl<T> AFPluginState<T>
where
T: Send + Sync,
{
pub fn new(data: T) -> Self {
AFPluginState(Arc::new(data))
}
2021-06-25 23:53:13 +08:00
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
2021-06-25 23:53:13 +08:00
}
impl<T> Deref for AFPluginState<T>
where
T: ?Sized + Send + Sync,
{
type Target = Arc<T>;
2021-06-25 23:53:13 +08:00
fn deref(&self) -> &Arc<T> {
&self.0
}
2021-06-25 23:53:13 +08:00
}
impl<T> Clone for AFPluginState<T>
where
T: ?Sized + Send + Sync,
{
fn clone(&self) -> AFPluginState<T> {
AFPluginState(self.0.clone())
}
2021-06-25 23:53:13 +08:00
}
impl<T> From<Arc<T>> for AFPluginState<T>
where
T: ?Sized + Send + Sync,
{
fn from(arc: Arc<T>) -> Self {
AFPluginState(arc)
}
2021-06-25 23:53:13 +08:00
}
impl<T> FromAFPluginRequest for AFPluginState<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]
fn from_request(req: &AFPluginEventRequest, _: &mut Payload) -> Self::Future {
if let Some(state) = req.get_state::<AFPluginState<T>>() {
ready(Ok(state.clone()))
} else {
let msg = format!(
"Failed to get the plugin state of type: {}",
type_name::<T>()
);
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
}