Skip to main content

mxr_protocol/
codec.rs

1use crate::types::IpcMessage;
2use bytes::BytesMut;
3use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec};
4
5pub struct IpcCodec {
6    inner: LengthDelimitedCodec,
7}
8
9impl IpcCodec {
10    pub fn new() -> Self {
11        Self {
12            inner: LengthDelimitedCodec::builder()
13                .length_field_length(4)
14                .max_frame_length(16 * 1024 * 1024)
15                .new_codec(),
16        }
17    }
18}
19
20impl Default for IpcCodec {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl Decoder for IpcCodec {
27    type Item = IpcMessage;
28    type Error = std::io::Error;
29
30    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
31        match self.inner.decode(src)? {
32            Some(frame) => {
33                let msg: IpcMessage = serde_json::from_slice(&frame)
34                    .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
35                Ok(Some(msg))
36            }
37            None => Ok(None),
38        }
39    }
40}
41
42impl Encoder<IpcMessage> for IpcCodec {
43    type Error = std::io::Error;
44
45    fn encode(&mut self, item: IpcMessage, dst: &mut BytesMut) -> Result<(), Self::Error> {
46        let json = serde_json::to_vec(&item)
47            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
48        self.inner.encode(json.into(), dst)
49    }
50}