easy_sockets/
sendable.rs

1//! Defines messages able to be sent between devices
2use super::Bytes;
3use anyhow::{Context, Result};
4use bincode::{deserialize, serialize};
5pub use serde::{Deserialize, Serialize};
6
7/// Type able to be sent between devices
8pub trait Sendable {
9    fn to_bytes(&self) -> Result<Bytes>;
10    fn from_bytes(bytes: &Bytes) -> Result<Self>
11    where
12        Self: Sized;
13}
14impl<T> Sendable for T
15where
16    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
17{
18    /// Converts object to bytes
19    fn to_bytes(&self) -> Result<Bytes> {
20        serialize(self).context("Failed to serialize object")
21    }
22    /// Creates an object from bytes
23    fn from_bytes(bytes: &Bytes) -> Result<Self> {
24        deserialize(bytes).context("Failed to deserialize object")
25    }
26}