1pub mod marker {
12 pub const INT: u8 = 0x01;
14 pub const BOOL_TRUE: u8 = 0x02;
15 pub const BOOL_FALSE: u8 = 0x03;
16 pub const DOUBLE: u8 = 0x04;
18 pub const STRING: u8 = 0x05;
20 pub const INT64: u8 = 0x06;
22 pub const ARRAY: u8 = 0x07;
24 pub const BINARY: u8 = 0x08;
26 pub const UNDEFINED: u8 = 0x09;
27}
28
29#[derive(Debug, Clone, PartialEq)]
31pub enum Value {
32 Bool(bool),
33 Int(i64),
36 Int64(i64),
38 Double(f64),
40 String(String),
43 Array(Vec<Value>),
45 Binary(Vec<u8>),
47 Undefined,
49 Unknown {
51 type_id: u8,
52 data: Vec<u8>,
53 },
54}
55
56impl Value {
57 pub fn as_bool(&self) -> Option<bool> {
59 match self {
60 Value::Bool(b) => Some(*b),
61 _ => None,
62 }
63 }
64
65 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 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 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 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
137fn 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
156pub 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 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
179pub 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
195pub 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; Some(s)
202}
203
204pub 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 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 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 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
273pub 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 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 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 let mut buf = Vec::new();
356 Value::Bool(true).write_to_stream(&mut buf);
357 assert_eq!(buf, [0x01, 0x01, 0x02]); buf.clear();
360 Value::Bool(false).write_to_stream(&mut buf);
361 assert_eq!(buf, [0x01, 0x01, 0x03]); buf.clear();
364 Value::Int(75).write_to_stream(&mut buf);
365 assert_eq!(buf, [0x01, 0x05, 0x01, 0x4b, 0x00, 0x00, 0x00]); 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]); 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] );
377 }
378
379 #[test]
380 fn reads_empty_frame_as_void() {
381 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 let mut pos = 0;
391 assert_eq!(read_compressed_int(&[0x05, 1, 2, 3, 4, 5], &mut pos), None);
392 }
393}