82 lines
2.0 KiB
Rust
Raw Normal View History

2021-06-24 23:37:45 +08:00
use crate::{
byte_trait::AFPluginFromBytes,
data::AFPluginData,
errors::DispatchError,
request::{AFPluginEventRequest, Payload},
response::AFPluginResponder,
2021-06-24 23:37:45 +08:00
};
use derivative::*;
use std::{convert::TryFrom, fmt, fmt::Formatter};
2021-06-24 16:32:36 +08:00
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "use_serde", derive(serde_repr::Serialize_repr))]
#[repr(u8)]
2021-06-24 16:32:36 +08:00
pub enum StatusCode {
Ok = 0,
Err = 1,
2021-06-24 16:32:36 +08:00
}
2021-06-27 15:11:41 +08:00
// serde user guide: https://serde.rs/field-attrs.html
#[derive(Debug, Clone, Derivative)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize))]
2022-12-01 10:59:22 +08:00
pub struct AFPluginEventResponse {
#[derivative(Debug = "ignore")]
pub payload: Payload,
pub status_code: StatusCode,
2021-06-24 16:32:36 +08:00
}
2022-12-01 10:59:22 +08:00
impl AFPluginEventResponse {
pub fn new(status_code: StatusCode) -> Self {
AFPluginEventResponse {
payload: Payload::None,
status_code,
2021-06-24 16:32:36 +08:00
}
}
pub fn parse<T, E>(self) -> Result<Result<T, E>, DispatchError>
where
T: AFPluginFromBytes,
E: AFPluginFromBytes,
{
match self.status_code {
StatusCode::Ok => {
let data = <AFPluginData<T>>::try_from(self.payload)?;
Ok(Ok(data.into_inner()))
},
StatusCode::Err => {
let err = <AFPluginData<E>>::try_from(self.payload)?;
Ok(Err(err.into_inner()))
},
}
}
2021-06-24 16:32:36 +08:00
}
2022-12-01 10:59:22 +08:00
impl std::fmt::Display for AFPluginEventResponse {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("Status_Code: {:?}", self.status_code))?;
match &self.payload {
Payload::Bytes(b) => f.write_fmt(format_args!("Data: {} bytes", b.len()))?,
Payload::None => f.write_fmt(format_args!("Data: Empty"))?,
2021-06-26 23:52:03 +08:00
}
Ok(())
}
2021-06-26 23:52:03 +08:00
}
2022-12-01 10:59:22 +08:00
impl AFPluginResponder for AFPluginEventResponse {
#[inline]
fn respond_to(self, _: &AFPluginEventRequest) -> AFPluginEventResponse {
self
}
2021-06-27 15:11:41 +08:00
}
pub type DataResult<T, E> = std::result::Result<AFPluginData<T>, E>;
2021-07-06 14:14:47 +08:00
pub fn data_result_ok<T, E>(data: T) -> Result<AFPluginData<T>, E>
where
E: Into<DispatchError>,
{
Ok(AFPluginData(data))
}