70 lines
1.5 KiB
Rust
Raw Normal View History

2021-06-25 23:53:13 +08:00
use crate::{
errors::{DispatchError, InternalError},
request::{payload::Payload, AFPluginEventRequest, FromAFPluginRequest},
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
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,
{
2022-01-23 12:14:00 +08:00
pub fn new(data: T) -> Self {
AFPluginState(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
}
impl<T> Deref for AFPluginState<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
}
impl<T> Clone for AFPluginState<T>
where
T: ?Sized + Send + Sync,
{
fn clone(&self) -> AFPluginState<T> {
AFPluginState(self.0.clone())
2022-01-23 12:14:00 +08:00
}
2021-06-25 23:53:13 +08:00
}
impl<T> From<Arc<T>> for AFPluginState<T>
where
T: ?Sized + Send + Sync,
{
2022-01-23 12:14:00 +08:00
fn from(arc: Arc<T>) -> Self {
AFPluginState(arc)
2022-01-23 12:14:00 +08:00
}
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()))
2021-07-09 17:47:15 +08:00
} else {
let msg = format!("Failed to get the plugin state 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
}