Skip to main content

rodecaster_protocol/
juce_var.rs

1//! JUCE `var` binary value encoding and decoding.
2//!
3//! Values exchanged with RØDECaster devices are serialized using the JUCE
4//! `var::writeToStream` format. Each value consists of a compressed integer
5//! length, a marker byte indicating the variant type, and the raw payload.
6//!
7//! This module provides the [`Value`] enum to represent these types in Rust
8//! alongside functions to read and write them on binary streams.
9
10/// `juce::var` `VariantStreamMarkers`: the byte after a value's length frame.
11pub mod marker {
12    /// 32-bit int. JUCE always writes a fixed 4-byte `writeInt`.
13    pub const INT: u8 = 0x01;
14    pub const BOOL_TRUE: u8 = 0x02;
15    pub const BOOL_FALSE: u8 = 0x03;
16    /// Double, 8 bytes IEEE 754.
17    pub const DOUBLE: u8 = 0x04;
18    /// String, UTF-8 with a trailing NUL inside the frame.
19    pub const STRING: u8 = 0x05;
20    /// 64-bit int, 8 bytes.
21    pub const INT64: u8 = 0x06;
22    /// Array: a compressed-int element count, then that many values.
23    pub const ARRAY: u8 = 0x07;
24    /// Binary blob / `MemoryBlock`: the rest of the frame, raw.
25    pub const BINARY: u8 = 0x08;
26    pub const UNDEFINED: u8 = 0x09;
27}
28
29/// A decoded `juce::var`. One type shared by every reader and writer.
30#[derive(Debug, Clone, PartialEq)]
31pub enum Value {
32    Bool(bool),
33    /// 32-bit int (marker [`marker::INT`]); JUCE writes a fixed 4 bytes. Stored
34    /// widened to `i64` so it can share an accessor with [`Value::Int64`].
35    Int(i64),
36    /// 64-bit int (marker [`marker::INT64`]).
37    Int64(i64),
38    /// Double (marker [`marker::DOUBLE`]), 8 bytes IEEE 754.
39    Double(f64),
40    /// String (marker [`marker::STRING`]). The trailing NUL is stripped on read
41    /// and re-added on write.
42    String(String),
43    /// Array of values (marker [`marker::ARRAY`]).
44    Array(Vec<Value>),
45    /// Binary blob (marker [`marker::BINARY`]).
46    Binary(Vec<u8>),
47    /// Void var (marker [`marker::UNDEFINED`], or an empty length frame).
48    Undefined,
49    /// Unparsed marker; raw payload preserved so the cursor stays aligned.
50    Unknown {
51        type_id: u8,
52        data: Vec<u8>,
53    },
54}
55
56impl Value {
57    /// Extract a bool, if this var is one.
58    pub fn as_bool(&self) -> Option<bool> {
59        match self {
60            Value::Bool(b) => Some(*b),
61            _ => None,
62        }
63    }
64
65    /// Extract an integer, widening `Int`/`Int64` to `i64`.
66    pub fn as_int(&self) -> Option<i64> {
67        match self {
68            Value::Int(i) | Value::Int64(i) => Some(*i),
69            _ => None,
70        }
71    }
72
73    /// Encode as `juce::var::writeToStream`: `writeCompressedInt(1 + payload)`,
74    /// the marker byte, then the payload.
75    pub fn write_to_stream(&self, out: &mut Vec<u8>) {
76        match self {
77            Value::Bool(b) => {
78                write_compressed_int(out, 1);
79                out.push(if *b {
80                    marker::BOOL_TRUE
81                } else {
82                    marker::BOOL_FALSE
83                });
84            }
85            Value::Int(i) => {
86                write_compressed_int(out, 5);
87                out.push(marker::INT);
88                out.extend_from_slice(&(*i as i32).to_le_bytes());
89            }
90            Value::Int64(i) => {
91                write_compressed_int(out, 9);
92                out.push(marker::INT64);
93                out.extend_from_slice(&i.to_le_bytes());
94            }
95            Value::Double(d) => {
96                write_compressed_int(out, 9);
97                out.push(marker::DOUBLE);
98                out.extend_from_slice(&d.to_bits().to_le_bytes());
99            }
100            Value::String(s) => {
101                let bytes = s.as_bytes();
102                // Payload is UTF-8 plus a trailing NUL; the frame counts both.
103                write_compressed_int(out, 1 + bytes.len() as i64 + 1);
104                out.push(marker::STRING);
105                out.extend_from_slice(bytes);
106                out.push(0);
107            }
108            Value::Binary(data) => {
109                write_compressed_int(out, 1 + data.len() as i64);
110                out.push(marker::BINARY);
111                out.extend_from_slice(data);
112            }
113            Value::Array(values) => {
114                // Serialize the body first so the length frame can count it.
115                let mut body = Vec::new();
116                write_compressed_int(&mut body, values.len() as i64);
117                for v in values {
118                    v.write_to_stream(&mut body);
119                }
120                write_compressed_int(out, 1 + body.len() as i64);
121                out.push(marker::ARRAY);
122                out.extend_from_slice(&body);
123            }
124            Value::Undefined => {
125                write_compressed_int(out, 1);
126                out.push(marker::UNDEFINED);
127            }
128            Value::Unknown { type_id, data } => {
129                write_compressed_int(out, 1 + data.len() as i64);
130                out.push(*type_id);
131                out.extend_from_slice(data);
132            }
133        }
134    }
135}
136
137// Free-function codec over `(data, &mut pos)` so any cursor can delegate.
138
139fn take_u8(data: &[u8], pos: &mut usize) -> Option<u8> {
140    let b = *data.get(*pos)?;
141    *pos += 1;
142    Some(b)
143}
144
145fn take_bytes<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Option<&'a [u8]> {
146    let end = pos.checked_add(n)?;
147    if end <= data.len() {
148        let slice = &data[*pos..end];
149        *pos = end;
150        Some(slice)
151    } else {
152        None
153    }
154}
155
156/// Read a JUCE `writeCompressedInt`: one size byte (low 7 bits = value byte
157/// count, capped at 4; high bit = sign) then that many little-endian bytes.
158pub fn read_compressed_int(data: &[u8], pos: &mut usize) -> Option<i64> {
159    let size_byte = take_u8(data, pos)?;
160    let num_bytes = (size_byte & 0x7f) as usize;
161    if num_bytes == 0 {
162        return Some(0);
163    }
164    if num_bytes > 4 {
165        // JUCE treats this as corrupt data and bails.
166        return None;
167    }
168    let bytes = take_bytes(data, pos, num_bytes)?;
169    let mut value: i64 = 0;
170    for (i, &b) in bytes.iter().enumerate() {
171        value |= (b as i64) << (i * 8);
172    }
173    if size_byte & 0x80 != 0 {
174        value = -value;
175    }
176    Some(value)
177}
178
179/// Write a JUCE `writeCompressedInt` (the inverse of [`read_compressed_int`]).
180pub fn write_compressed_int(out: &mut Vec<u8>, value: i64) {
181    let negative = value < 0;
182    let mut magnitude = value.unsigned_abs();
183    let mut bytes = [0u8; 4];
184    let mut num_bytes = 0usize;
185    while magnitude != 0 && num_bytes < 4 {
186        bytes[num_bytes] = (magnitude & 0xff) as u8;
187        magnitude >>= 8;
188        num_bytes += 1;
189    }
190    let size_byte = num_bytes as u8 | if negative { 0x80 } else { 0 };
191    out.push(size_byte);
192    out.extend_from_slice(&bytes[..num_bytes]);
193}
194
195/// Read a NUL-terminated UTF-8 string (`juce::OutputStream::writeString`).
196pub fn read_cstring<'a>(data: &'a [u8], pos: &mut usize) -> Option<&'a str> {
197    let start = *pos;
198    let rel = data.get(start..)?.iter().position(|&b| b == 0)?;
199    let s = std::str::from_utf8(&data[start..start + rel]).ok()?;
200    *pos = start + rel + 1; // skip the NUL
201    Some(s)
202}
203
204/// Read a single `juce::var` (`var::readFromStream`).
205///
206/// A `writeCompressedInt` length frame (`1 + payload_len`), then the marker
207/// byte, then the payload. A zero-length frame is a void var.
208pub fn read_value(data: &[u8], pos: &mut usize) -> Option<Value> {
209    let data_len = read_compressed_int(data, pos)?;
210    if data_len <= 0 {
211        // numBytes == 0 -> JUCE returns a void var.
212        return Some(Value::Undefined);
213    }
214
215    let type_byte = take_u8(data, pos)?;
216    let value_len = (data_len - 1) as usize;
217
218    match type_byte {
219        marker::INT => {
220            // JUCE writes a fixed 4-byte `writeInt`.
221            let b = take_bytes(data, pos, 4)?;
222            Some(Value::Int(
223                i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as i64
224            ))
225        }
226        marker::BOOL_TRUE => Some(Value::Bool(true)),
227        marker::BOOL_FALSE => Some(Value::Bool(false)),
228        marker::DOUBLE => {
229            let b = take_bytes(data, pos, 8)?;
230            Some(Value::Double(f64::from_le_bytes([
231                b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
232            ])))
233        }
234        marker::STRING => {
235            let b = take_bytes(data, pos, value_len)?;
236            let s = std::str::from_utf8(b)
237                .ok()?
238                .trim_end_matches('\0')
239                .to_string();
240            Some(Value::String(s))
241        }
242        marker::INT64 => {
243            let b = take_bytes(data, pos, 8)?;
244            Some(Value::Int64(i64::from_le_bytes([
245                b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
246            ])))
247        }
248        marker::ARRAY => {
249            let count = usize::try_from(read_compressed_int(data, pos)?).ok()?;
250            // Cap the pre-allocation: a value is at least 1 byte on the wire.
251            let remaining = data.len().saturating_sub(*pos);
252            let mut values = Vec::with_capacity(count.min(remaining));
253            for _ in 0..count {
254                values.push(read_value(data, pos)?);
255            }
256            Some(Value::Array(values))
257        }
258        marker::BINARY => {
259            let b = take_bytes(data, pos, value_len)?;
260            Some(Value::Binary(b.to_vec()))
261        }
262        marker::UNDEFINED => Some(Value::Undefined),
263        _ => {
264            let b = take_bytes(data, pos, value_len)?;
265            Some(Value::Unknown {
266                type_id: type_byte,
267                data: b.to_vec(),
268            })
269        }
270    }
271}
272
273/// A position-tracking reader over a byte slice: the shared cursor for the
274/// `juce::var` decode (the full ValueTree walk in [`crate::valuetree`]).
275pub struct Reader<'a> {
276    data: &'a [u8],
277    pos: usize,
278}
279
280impl<'a> Reader<'a> {
281    pub fn new(data: &'a [u8]) -> Self {
282        Self { data, pos: 0 }
283    }
284
285    /// Bytes left from the current position.
286    pub fn remaining(&self) -> usize {
287        self.data.len().saturating_sub(self.pos)
288    }
289
290    pub fn read_u8(&mut self) -> Option<u8> {
291        take_u8(self.data, &mut self.pos)
292    }
293
294    pub fn read_compressed_int(&mut self) -> Option<i64> {
295        read_compressed_int(self.data, &mut self.pos)
296    }
297
298    pub fn read_cstring(&mut self) -> Option<&'a str> {
299        read_cstring(self.data, &mut self.pos)
300    }
301
302    pub fn read_value(&mut self) -> Option<Value> {
303        read_value(self.data, &mut self.pos)
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    /// Encode a value, decode it back, and assert it survives unchanged and the
312    /// frame is fully consumed.
313    fn assert_round_trip(value: Value) {
314        let mut buf = Vec::new();
315        value.write_to_stream(&mut buf);
316        let mut pos = 0;
317        let decoded = read_value(&buf, &mut pos).expect("decodes");
318        assert_eq!(decoded, value, "round-trip value mismatch");
319        assert_eq!(pos, buf.len(), "frame not fully consumed for {value:?}");
320    }
321
322    #[test]
323    fn round_trips_every_variant() {
324        assert_round_trip(Value::Bool(true));
325        assert_round_trip(Value::Bool(false));
326        assert_round_trip(Value::Int(75));
327        assert_round_trip(Value::Int(-1));
328        assert_round_trip(Value::Int(i32::MIN as i64));
329        assert_round_trip(Value::Int64(1 << 40));
330        assert_round_trip(Value::Double(0.5));
331        assert_round_trip(Value::Double(1.0));
332        assert_round_trip(Value::String("0.472441|0.472441".to_string()));
333        assert_round_trip(Value::String(String::new()));
334        assert_round_trip(Value::Binary(vec![0x01, 0x01, 0x02, 0x01, 0x01, 0x02]));
335        assert_round_trip(Value::Array(vec![Value::Int(1), Value::Int(2)]));
336        assert_round_trip(Value::Undefined);
337    }
338
339    #[test]
340    fn compressed_int_round_trips() {
341        for v in [0i64, 1, 5, 7, 9, 300, -5, 0xFFFF, 0x0100_0000] {
342            let mut buf = Vec::new();
343            write_compressed_int(&mut buf, v);
344            let mut pos = 0;
345            assert_eq!(read_compressed_int(&buf, &mut pos), Some(v), "for {v}");
346            assert_eq!(pos, buf.len());
347        }
348    }
349
350    #[test]
351    fn write_matches_known_juce_frames() {
352        // These are the exact byte vectors the hand-rolled encoders emitted
353        // before this module existed: lock them so the codec stays compatible
354        // with the device's parser.
355        let mut buf = Vec::new();
356        Value::Bool(true).write_to_stream(&mut buf);
357        assert_eq!(buf, [0x01, 0x01, 0x02]); // var bool true
358
359        buf.clear();
360        Value::Bool(false).write_to_stream(&mut buf);
361        assert_eq!(buf, [0x01, 0x01, 0x03]); // var bool false
362
363        buf.clear();
364        Value::Int(75).write_to_stream(&mut buf);
365        assert_eq!(buf, [0x01, 0x05, 0x01, 0x4b, 0x00, 0x00, 0x00]); // var int
366
367        buf.clear();
368        Value::Int(0xFFFF_FFFFu32 as i64).write_to_stream(&mut buf);
369        assert_eq!(buf, [0x01, 0x05, 0x01, 0xff, 0xff, 0xff, 0xff]); // source_id = -1
370
371        buf.clear();
372        Value::Binary(vec![0x01, 0x01, 0x02, 0x01, 0x01, 0x02]).write_to_stream(&mut buf);
373        assert_eq!(
374            buf,
375            [0x01, 0x07, 0x08, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02] // mix link/unlink request
376        );
377    }
378
379    #[test]
380    fn reads_empty_frame_as_void() {
381        // A zero-length frame (compressedInt(0)) decodes to a void var.
382        let mut pos = 0;
383        assert_eq!(read_value(&[0x00], &mut pos), Some(Value::Undefined));
384        assert_eq!(pos, 1);
385    }
386
387    #[test]
388    fn rejects_oversized_compressed_int() {
389        // More than 4 value bytes is corrupt per JUCE.
390        let mut pos = 0;
391        assert_eq!(read_compressed_int(&[0x05, 1, 2, 3, 4, 5], &mut pos), None);
392    }
393}