Skip to main content

mouser_mode_api/
codec.rs

1//! Framing: a 4-byte little-endian length, then one message in MessagePack
2//! (default) or JSON (`MOUSER_MODE_WIRE=json`, for authors in any language).
3
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use std::io::{self, Read, Write};
7
8/// Larger frames are refused (an inline 4K RGBA frame is ~33 MB).
9pub 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    /// From `MOUSER_MODE_WIRE` (`json` or `msgpack`).
20    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
32/// Write one message, MessagePack structs as arrays (the plugin side: the
33/// host reads both shapes).
34pub 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
42/// Write one message with MessagePack structs as maps keyed by field name
43/// (what the host sends a plugin). A plugin built before a field was added
44/// skips the unknown key; as an array the extra element made its decoder
45/// fail ("array had incorrect length") and the plugin exit at the
46/// handshake. Plugins built from any mode-api version read both shapes.
47pub 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
64/// Read one message; `Ok(None)` at a clean end of stream. `buf` is reused.
65pub 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}