proc_macro_api/legacy_protocol/
postcard.rs

1//! Postcard encode and decode implementations.
2
3use std::io::{self, BufRead, Write};
4
5use serde::{Serialize, de::DeserializeOwned};
6
7use crate::{codec::Codec, framing::Framing};
8
9pub struct PostcardProtocol;
10
11impl Framing for PostcardProtocol {
12    type Buf = Vec<u8>;
13
14    fn read<'a, R: BufRead>(
15        inp: &mut R,
16        buf: &'a mut Vec<u8>,
17    ) -> io::Result<Option<&'a mut Vec<u8>>> {
18        buf.clear();
19        let n = inp.read_until(0, buf)?;
20        if n == 0 {
21            return Ok(None);
22        }
23        Ok(Some(buf))
24    }
25
26    fn write<W: Write>(out: &mut W, buf: &Vec<u8>) -> io::Result<()> {
27        out.write_all(buf)?;
28        out.flush()
29    }
30}
31
32impl Codec for PostcardProtocol {
33    fn encode<T: Serialize>(msg: &T) -> io::Result<Vec<u8>> {
34        postcard::to_allocvec_cobs(msg).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
35    }
36
37    fn decode<T: DeserializeOwned>(buf: &mut Self::Buf) -> io::Result<T> {
38        postcard::from_bytes_cobs(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
39    }
40}