From a485f664a0a42362062a9dfa011f4eb206c7adf8 Mon Sep 17 00:00:00 2001 From: trivernis Date: Wed, 20 Oct 2021 19:46:37 +0200 Subject: [PATCH] Add EventReceivePayload trait and BytePayload wrapper Signed-off-by: trivernis --- src/events/event.rs | 5 +++-- src/events/payload.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 ++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/events/event.rs b/src/events/event.rs index cbc694bf..fb1e9813 100644 --- a/src/events/event.rs +++ b/src/events/event.rs @@ -1,5 +1,6 @@ use crate::error::Result; use crate::events::generate_event_id; +use crate::events::payload::EventReceivePayload; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncRead, AsyncReadExt}; @@ -45,8 +46,8 @@ impl Event { } /// Decodes the data to the given type - pub fn data(&self) -> Result { - let data = rmp_serde::from_read(&self.data[..])?; + pub fn data(&self) -> Result { + let data = T::from_payload_bytes(&self.data[..])?; Ok(data) } diff --git a/src/events/payload.rs b/src/events/payload.rs index b39f4916..99aa027f 100644 --- a/src/events/payload.rs +++ b/src/events/payload.rs @@ -1,6 +1,10 @@ use crate::prelude::IPCResult; +use serde::de::DeserializeOwned; use serde::Serialize; +use std::io::Read; +/// Trait to convert event data into sending bytes +/// It is implemented for all types that implement Serialize pub trait EventSendPayload { fn to_payload_bytes(self) -> IPCResult>; } @@ -15,3 +19,38 @@ where Ok(bytes) } } + +/// Trait to get the event data from receiving bytes. +/// It is implemented for all types that are DeserializeOwned +pub trait EventReceivePayload: Sized { + fn from_payload_bytes(reader: R) -> IPCResult; +} + +impl EventReceivePayload for T +where + T: DeserializeOwned, +{ + fn from_payload_bytes(reader: R) -> IPCResult { + let type_data = rmp_serde::from_read(reader)?; + Ok(type_data) + } +} + +/// A payload wrapper type for sending bytes directly without +/// serializing them +#[derive(Clone, Debug)] +pub struct BytePayload { + bytes: Vec, +} + +impl BytePayload { + pub fn new(bytes: Vec) -> Self { + Self { bytes } + } +} + +impl EventSendPayload for BytePayload { + fn to_payload_bytes(self) -> IPCResult> { + Ok(self.bytes) + } +} diff --git a/src/lib.rs b/src/lib.rs index 74ce621c..f053f100 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -109,6 +109,7 @@ mod namespaces; pub use events::error_event; pub use events::event; pub use events::event_handler; +pub use events::payload; pub use ipc::builder::IPCBuilder; pub use macros::*; pub use namespaces::builder::NamespaceBuilder; @@ -126,5 +127,6 @@ pub mod prelude { pub use crate::namespace::Namespace; pub use crate::namespaces::builder::NamespaceBuilder; pub use crate::namespaces::provider_trait::*; + pub use crate::payload::*; pub use crate::*; }