proc_macro_api/legacy_protocol/
json.rs

1//! Protocol functions for json.
2use std::io::{self, BufRead, Write};
3
4use serde::{Serialize, de::DeserializeOwned};
5
6use crate::{codec::Codec, framing::Framing};
7
8pub struct JsonProtocol;
9
10impl Framing for JsonProtocol {
11    type Buf = String;
12
13    fn read<'a, R: BufRead>(
14        inp: &mut R,
15        buf: &'a mut String,
16    ) -> io::Result<Option<&'a mut String>> {
17        loop {
18            buf.clear();
19
20            inp.read_line(buf)?;
21            buf.pop(); // Remove trailing '\n'
22
23            if buf.is_empty() {
24                return Ok(None);
25            }
26
27            // Some ill behaved macro try to use stdout for debugging
28            // We ignore it here
29            if !buf.starts_with('{') {
30                tracing::error!("proc-macro tried to print : {}", buf);
31                continue;
32            }
33
34            return Ok(Some(buf));
35        }
36    }
37
38    fn write<W: Write>(out: &mut W, buf: &String) -> io::Result<()> {
39        tracing::debug!("> {}", buf);
40        out.write_all(buf.as_bytes())?;
41        out.write_all(b"\n")?;
42        out.flush()
43    }
44}
45
46impl Codec for JsonProtocol {
47    fn encode<T: Serialize>(msg: &T) -> io::Result<String> {
48        Ok(serde_json::to_string(msg)?)
49    }
50
51    fn decode<T: DeserializeOwned>(buf: &mut String) -> io::Result<T> {
52        let mut deserializer = serde_json::Deserializer::from_str(buf);
53        // Note that some proc-macro generate very deep syntax tree
54        // We have to disable the current limit of serde here
55        deserializer.disable_recursion_limit();
56        Ok(T::deserialize(&mut deserializer)?)
57    }
58}