rmp_ipc/events/
payload.rs1use crate::prelude::IPCResult;
2use byteorder::{BigEndian, ReadBytesExt};
3use serde::de::DeserializeOwned;
4use serde::Serialize;
5use std::io::Read;
6
7pub trait EventSendPayload {
10 fn to_payload_bytes(self) -> IPCResult<Vec<u8>>;
11}
12
13impl<T> EventSendPayload for T
14where
15 T: Serialize,
16{
17 fn to_payload_bytes(self) -> IPCResult<Vec<u8>> {
18 let bytes = rmp_serde::to_vec(&self)?;
19
20 Ok(bytes)
21 }
22}
23
24pub trait EventReceivePayload: Sized {
27 fn from_payload_bytes<R: Read>(reader: R) -> IPCResult<Self>;
28}
29
30impl<T> EventReceivePayload for T
31where
32 T: DeserializeOwned,
33{
34 fn from_payload_bytes<R: Read>(reader: R) -> IPCResult<Self> {
35 let type_data = rmp_serde::from_read(reader)?;
36 Ok(type_data)
37 }
38}
39
40#[derive(Clone, Debug)]
43pub struct BytePayload {
44 bytes: Vec<u8>,
45}
46
47impl BytePayload {
48 pub fn new(bytes: Vec<u8>) -> Self {
49 Self { bytes }
50 }
51
52 pub fn into_inner(self) -> Vec<u8> {
54 self.bytes
55 }
56}
57
58impl EventSendPayload for BytePayload {
59 fn to_payload_bytes(self) -> IPCResult<Vec<u8>> {
60 Ok(self.bytes)
61 }
62}
63
64impl EventReceivePayload for BytePayload {
65 fn from_payload_bytes<R: Read>(mut reader: R) -> IPCResult<Self> {
66 let mut buf = Vec::new();
67 reader.read_to_end(&mut buf)?;
68
69 Ok(Self::new(buf))
70 }
71}
72
73pub struct TandemPayload<P1, P2> {
78 load1: P1,
79 load2: P2,
80}
81
82impl<P1, P2> TandemPayload<P1, P2> {
83 pub fn new(load1: P1, load2: P2) -> Self {
84 Self { load1, load2 }
85 }
86
87 pub fn into_inner(self) -> (P1, P2) {
89 (self.load1, self.load2)
90 }
91}
92
93impl<P1, P2> EventSendPayload for TandemPayload<P1, P2>
94where
95 P1: EventSendPayload,
96 P2: EventSendPayload,
97{
98 fn to_payload_bytes(self) -> IPCResult<Vec<u8>> {
99 let mut p1_bytes = self.load1.to_payload_bytes()?;
100 let mut p2_bytes = self.load2.to_payload_bytes()?;
101
102 let mut p1_length_bytes = (p1_bytes.len() as u32).to_be_bytes().to_vec();
103 let mut p2_length_bytes = (p2_bytes.len() as u32).to_be_bytes().to_vec();
104
105 let mut bytes = Vec::new();
106 bytes.append(&mut p1_length_bytes);
107 bytes.append(&mut p1_bytes);
108 bytes.append(&mut p2_length_bytes);
109 bytes.append(&mut p2_bytes);
110
111 Ok(bytes)
112 }
113}
114
115impl<P1, P2> EventReceivePayload for TandemPayload<P1, P2>
116where
117 P1: EventReceivePayload,
118 P2: EventReceivePayload,
119{
120 fn from_payload_bytes<R: Read>(mut reader: R) -> IPCResult<Self> {
121 let p1_length = reader.read_u32::<BigEndian>()?;
122 let mut load1_bytes = vec![0u8; p1_length as usize];
123 reader.read_exact(&mut load1_bytes)?;
124
125 let p2_length = reader.read_u32::<BigEndian>()?;
126 let mut load2_bytes = vec![0u8; p2_length as usize];
127 reader.read_exact(&mut load2_bytes)?;
128
129 Ok(Self {
130 load1: P1::from_payload_bytes(load1_bytes.as_slice())?,
131 load2: P2::from_payload_bytes(load2_bytes.as_slice())?,
132 })
133 }
134}