use async_trait::async_trait;
use super::*;
use std::any::TypeId;
pub trait Protocol: Send + 'static {
fn into_boxed_payload(self) -> BoxPayload;
fn try_from_boxed_payload(payload: BoxPayload) -> Result<Self, BoxPayload>
where
Self: Sized;
fn accepts_msg(msg_id: &TypeId) -> bool
where
Self: Sized;
}
pub trait FromPayload<M: Message>: Protocol {
fn from_payload(payload: M::Payload) -> Self
where
Self: Sized;
fn try_into_payload(self) -> Result<M::Payload, Self>
where
Self: Sized;
}
impl Protocol for () {
fn into_boxed_payload(self) -> BoxPayload {
BoxPayload::new::<()>(())
}
fn try_from_boxed_payload(payload: BoxPayload) -> Result<Self, BoxPayload> {
payload.downcast::<()>()
}
fn accepts_msg(msg_id: &std::any::TypeId) -> bool {
*msg_id == TypeId::of::<()>()
}
}
#[async_trait]
impl<H: Handler> HandledBy<H> for ()
where
H: HandleMessage<()>,
{
async fn handle_with(
self,
handler: &mut H,
state: &mut <H as Handler>::State,
) -> HandlerResult<H> {
handler.handle_msg(state, self).await
}
}
impl FromPayload<()> for () {
fn from_payload(payload: ()) -> Self
where
Self: Sized,
{
payload
}
fn try_into_payload(self) -> Result<(), Self>
where
Self: Sized,
{
Ok(self)
}
}