Skip to main content

proc_macro_api/transport/
json.rs

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