1use serde::Serialize;
5use serde::de::DeserializeOwned;
6use std::io::{self, Read, Write};
7
8pub const MAX_FRAME: usize = 64 << 20;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum Wire {
13 #[default]
14 MsgPack,
15 Json,
16}
17
18impl Wire {
19 pub fn from_env() -> Wire {
21 match std::env::var("MOUSER_MODE_WIRE").as_deref() {
22 Ok("json") => Wire::Json,
23 _ => Wire::MsgPack,
24 }
25 }
26}
27
28fn bad(e: impl std::fmt::Display) -> io::Error {
29 io::Error::new(io::ErrorKind::InvalidData, e.to_string())
30}
31
32pub fn write<T: Serialize>(w: &mut impl Write, wire: Wire, msg: &T) -> io::Result<()> {
35 let body = match wire {
36 Wire::MsgPack => rmp_serde::to_vec(msg).map_err(bad)?,
37 Wire::Json => serde_json::to_vec(msg).map_err(bad)?,
38 };
39 frame(w, body)
40}
41
42pub fn write_named<T: Serialize>(w: &mut impl Write, wire: Wire, msg: &T) -> io::Result<()> {
48 let body = match wire {
49 Wire::MsgPack => rmp_serde::to_vec_named(msg).map_err(bad)?,
50 Wire::Json => serde_json::to_vec(msg).map_err(bad)?,
51 };
52 frame(w, body)
53}
54
55fn frame(w: &mut impl Write, body: Vec<u8>) -> io::Result<()> {
56 if body.len() > MAX_FRAME {
57 return Err(bad(format!("frame of {} bytes is over the {MAX_FRAME} limit", body.len())));
58 }
59 w.write_all(&(body.len() as u32).to_le_bytes())?;
60 w.write_all(&body)?;
61 w.flush()
62}
63
64pub fn read<T: DeserializeOwned>(r: &mut impl Read, wire: Wire, buf: &mut Vec<u8>) -> io::Result<Option<T>> {
66 let mut len = [0u8; 4];
67 match r.read_exact(&mut len) {
68 Ok(()) => {}
69 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
70 Err(e) => return Err(e),
71 }
72 let n = u32::from_le_bytes(len) as usize;
73 if n > MAX_FRAME {
74 return Err(bad(format!("frame of {n} bytes is over the {MAX_FRAME} limit")));
75 }
76 buf.resize(n, 0);
77 r.read_exact(buf)?;
78 Ok(Some(match wire {
79 Wire::MsgPack => rmp_serde::from_slice(buf).map_err(bad)?,
80 Wire::Json => serde_json::from_slice(buf).map_err(bad)?,
81 }))
82}