Skip to main content

rns_core/
msgpack.rs

1//! Minimal msgpack encoder/decoder for Resource advertisements and HMU packets.
2//!
3//! Supports the subset needed by Reticulum's Resource protocol:
4//! - Nil, Bool, positive/negative fixint, uint8-64, int8-32
5//! - fixstr, str8
6//! - bin8, bin16, bin32
7//! - fixarray, array16
8//! - fixmap, map16
9
10use alloc::string::String;
11use alloc::vec::Vec;
12use core::fmt;
13
14/// A msgpack value.
15#[derive(Debug, Clone)]
16pub enum Value {
17    Nil,
18    Bool(bool),
19    UInt(u64),
20    Int(i64),
21    Float(f64),
22    Bin(Vec<u8>),
23    Str(String),
24    Array(Vec<Value>),
25    Map(Vec<(Value, Value)>),
26}
27
28impl PartialEq for Value {
29    fn eq(&self, other: &Self) -> bool {
30        match (self, other) {
31            (Value::Nil, Value::Nil) => true,
32            (Value::Bool(a), Value::Bool(b)) => a == b,
33            (Value::UInt(a), Value::UInt(b)) => a == b,
34            (Value::Int(a), Value::Int(b)) => a == b,
35            (Value::Float(a), Value::Float(b)) => a.to_bits() == b.to_bits(),
36            (Value::Bin(a), Value::Bin(b)) => a == b,
37            (Value::Str(a), Value::Str(b)) => a == b,
38            (Value::Array(a), Value::Array(b)) => a == b,
39            (Value::Map(a), Value::Map(b)) => a == b,
40            _ => false,
41        }
42    }
43}
44
45impl Value {
46    /// Get as u64 if this is a UInt.
47    pub fn as_uint(&self) -> Option<u64> {
48        match self {
49            Value::UInt(v) => Some(*v),
50            _ => None,
51        }
52    }
53
54    /// Get as i64 if this is an Int.
55    pub fn as_int(&self) -> Option<i64> {
56        match self {
57            Value::Int(v) => Some(*v),
58            _ => None,
59        }
60    }
61
62    /// Get as integer (works for both UInt and Int).
63    pub fn as_integer(&self) -> Option<i64> {
64        match self {
65            Value::UInt(v) => {
66                if *v <= i64::MAX as u64 {
67                    Some(*v as i64)
68                } else {
69                    None
70                }
71            }
72            Value::Int(v) => Some(*v),
73            _ => None,
74        }
75    }
76
77    /// Get as bool.
78    pub fn as_bool(&self) -> Option<bool> {
79        match self {
80            Value::Bool(v) => Some(*v),
81            _ => None,
82        }
83    }
84
85    /// Get as f64 if Float.
86    pub fn as_float(&self) -> Option<f64> {
87        match self {
88            Value::Float(v) => Some(*v),
89            _ => None,
90        }
91    }
92
93    /// Get as f64, accepting Float, UInt, or Int.
94    pub fn as_number(&self) -> Option<f64> {
95        match self {
96            Value::Float(v) => Some(*v),
97            Value::UInt(v) => Some(*v as f64),
98            Value::Int(v) => Some(*v as f64),
99            _ => None,
100        }
101    }
102
103    /// Get as byte slice if Bin.
104    pub fn as_bin(&self) -> Option<&[u8]> {
105        match self {
106            Value::Bin(v) => Some(v),
107            _ => None,
108        }
109    }
110
111    /// Get as string slice if Str.
112    pub fn as_str(&self) -> Option<&str> {
113        match self {
114            Value::Str(v) => Some(v),
115            _ => None,
116        }
117    }
118
119    /// Get as array slice.
120    pub fn as_array(&self) -> Option<&[Value]> {
121        match self {
122            Value::Array(v) => Some(v),
123            _ => None,
124        }
125    }
126
127    /// Get as map slice.
128    pub fn as_map(&self) -> Option<&[(Value, Value)]> {
129        match self {
130            Value::Map(v) => Some(v),
131            _ => None,
132        }
133    }
134
135    /// Check if nil.
136    pub fn is_nil(&self) -> bool {
137        matches!(self, Value::Nil)
138    }
139
140    /// Look up a string key in a map.
141    pub fn map_get(&self, key: &str) -> Option<&Value> {
142        self.as_map().and_then(|entries| {
143            entries.iter().find_map(|(k, v)| {
144                if let Value::Str(s) = k {
145                    if s == key {
146                        return Some(v);
147                    }
148                }
149                None
150            })
151        })
152    }
153}
154
155/// Maximum nesting depth for msgpack decoding.
156const MAX_DEPTH: usize = 32;
157
158/// Msgpack error.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum Error {
161    UnexpectedEof,
162    UnsupportedFormat(u8),
163    InvalidUtf8,
164    TrailingData,
165    MaxDepthExceeded,
166}
167
168impl fmt::Display for Error {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        match self {
171            Error::UnexpectedEof => write!(f, "Unexpected end of msgpack data"),
172            Error::UnsupportedFormat(b) => write!(f, "Unsupported msgpack format: 0x{:02x}", b),
173            Error::InvalidUtf8 => write!(f, "Invalid UTF-8 in msgpack string"),
174            Error::TrailingData => write!(f, "Trailing data after msgpack value"),
175            Error::MaxDepthExceeded => write!(f, "Maximum nesting depth exceeded"),
176        }
177    }
178}
179
180// ============================================================================
181// Encoder
182// ============================================================================
183
184/// Encode a Value to msgpack bytes.
185pub fn pack(value: &Value) -> Vec<u8> {
186    let mut buf = Vec::new();
187    pack_into(value, &mut buf);
188    buf
189}
190
191fn pack_into(value: &Value, buf: &mut Vec<u8>) {
192    match value {
193        Value::Nil => buf.push(0xc0),
194        Value::Bool(true) => buf.push(0xc3),
195        Value::Bool(false) => buf.push(0xc2),
196        Value::UInt(v) => pack_uint(*v, buf),
197        Value::Int(v) => pack_int(*v, buf),
198        Value::Float(v) => {
199            buf.push(0xcb);
200            buf.extend_from_slice(&v.to_bits().to_be_bytes());
201        }
202        Value::Bin(data) => pack_bin(data, buf),
203        Value::Str(s) => pack_str(s, buf),
204        Value::Array(items) => pack_array(items, buf),
205        Value::Map(entries) => pack_map(entries, buf),
206    }
207}
208
209fn pack_uint(v: u64, buf: &mut Vec<u8>) {
210    if v <= 127 {
211        buf.push(v as u8);
212    } else if v <= 0xFF {
213        buf.push(0xcc);
214        buf.push(v as u8);
215    } else if v <= 0xFFFF {
216        buf.push(0xcd);
217        buf.extend_from_slice(&(v as u16).to_be_bytes());
218    } else if v <= 0xFFFF_FFFF {
219        buf.push(0xce);
220        buf.extend_from_slice(&(v as u32).to_be_bytes());
221    } else {
222        buf.push(0xcf);
223        buf.extend_from_slice(&v.to_be_bytes());
224    }
225}
226
227fn pack_int(v: i64, buf: &mut Vec<u8>) {
228    if v >= 0 {
229        pack_uint(v as u64, buf);
230    } else if v >= -32 {
231        buf.push(v as u8); // negative fixint: 0xe0..0xff
232    } else if v >= -128 {
233        buf.push(0xd0);
234        buf.push(v as i8 as u8);
235    } else if v >= -32768 {
236        buf.push(0xd1);
237        buf.extend_from_slice(&(v as i16).to_be_bytes());
238    } else if v >= -2_147_483_648 {
239        buf.push(0xd2);
240        buf.extend_from_slice(&(v as i32).to_be_bytes());
241    } else {
242        buf.push(0xd3);
243        buf.extend_from_slice(&v.to_be_bytes());
244    }
245}
246
247fn pack_bin(data: &[u8], buf: &mut Vec<u8>) {
248    let len = data.len();
249    if len <= 0xFF {
250        buf.push(0xc4);
251        buf.push(len as u8);
252    } else if len <= 0xFFFF {
253        buf.push(0xc5);
254        buf.extend_from_slice(&(len as u16).to_be_bytes());
255    } else {
256        buf.push(0xc6);
257        buf.extend_from_slice(&(len as u32).to_be_bytes());
258    }
259    buf.extend_from_slice(data);
260}
261
262fn pack_str(s: &str, buf: &mut Vec<u8>) {
263    let bytes = s.as_bytes();
264    let len = bytes.len();
265    if len <= 31 {
266        buf.push(0xa0 | len as u8);
267    } else if len <= 0xFF {
268        buf.push(0xd9);
269        buf.push(len as u8);
270    } else if len <= 0xFFFF {
271        buf.push(0xda);
272        buf.extend_from_slice(&(len as u16).to_be_bytes());
273    } else {
274        buf.push(0xdb);
275        buf.extend_from_slice(&(len as u32).to_be_bytes());
276    }
277    buf.extend_from_slice(bytes);
278}
279
280fn pack_array(items: &[Value], buf: &mut Vec<u8>) {
281    let len = items.len();
282    if len <= 15 {
283        buf.push(0x90 | len as u8);
284    } else if len <= 0xFFFF {
285        buf.push(0xdc);
286        buf.extend_from_slice(&(len as u16).to_be_bytes());
287    } else {
288        buf.push(0xdd);
289        buf.extend_from_slice(&(len as u32).to_be_bytes());
290    }
291    for item in items {
292        pack_into(item, buf);
293    }
294}
295
296fn pack_map(entries: &[(Value, Value)], buf: &mut Vec<u8>) {
297    let len = entries.len();
298    if len <= 15 {
299        buf.push(0x80 | len as u8);
300    } else if len <= 0xFFFF {
301        buf.push(0xde);
302        buf.extend_from_slice(&(len as u16).to_be_bytes());
303    } else {
304        buf.push(0xdf);
305        buf.extend_from_slice(&(len as u32).to_be_bytes());
306    }
307    for (k, v) in entries {
308        pack_into(k, buf);
309        pack_into(v, buf);
310    }
311}
312
313/// Convenience: pack a map from string keys.
314pub fn pack_str_map(entries: &[(&str, Value)]) -> Vec<u8> {
315    let map: Vec<(Value, Value)> = entries
316        .iter()
317        .map(|(k, v)| (Value::Str(String::from(*k)), v.clone()))
318        .collect();
319    pack(&Value::Map(map))
320}
321
322// ============================================================================
323// Decoder
324// ============================================================================
325
326/// Decode a single msgpack value from the start of `data`.
327/// Returns (value, bytes_consumed).
328pub fn unpack(data: &[u8]) -> Result<(Value, usize), Error> {
329    unpack_depth(data, 0)
330}
331
332fn unpack_depth(data: &[u8], depth: usize) -> Result<(Value, usize), Error> {
333    if data.is_empty() {
334        return Err(Error::UnexpectedEof);
335    }
336    if depth > MAX_DEPTH {
337        return Err(Error::MaxDepthExceeded);
338    }
339    let b = data[0];
340    match b {
341        // positive fixint: 0x00..0x7f
342        0x00..=0x7f => Ok((Value::UInt(b as u64), 1)),
343
344        // fixmap: 0x80..0x8f
345        0x80..=0x8f => {
346            let len = (b & 0x0f) as usize;
347            unpack_map_entries(data, 1, len, depth)
348        }
349
350        // fixarray: 0x90..0x9f
351        0x90..=0x9f => {
352            let len = (b & 0x0f) as usize;
353            unpack_array_entries(data, 1, len, depth)
354        }
355
356        // fixstr: 0xa0..0xbf
357        0xa0..=0xbf => {
358            let len = (b & 0x1f) as usize;
359            unpack_str_bytes(data, 1, len)
360        }
361
362        // nil
363        0xc0 => Ok((Value::Nil, 1)),
364
365        // (unused)
366        0xc1 => Err(Error::UnsupportedFormat(b)),
367
368        // bool
369        0xc2 => Ok((Value::Bool(false), 1)),
370        0xc3 => Ok((Value::Bool(true), 1)),
371
372        // float32
373        0xca => {
374            ensure_len(data, 5)?;
375            let bits = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
376            Ok((Value::Float(f32::from_bits(bits) as f64), 5))
377        }
378
379        // float64
380        0xcb => {
381            ensure_len(data, 9)?;
382            let bits = u64::from_be_bytes([
383                data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
384            ]);
385            Ok((Value::Float(f64::from_bits(bits)), 9))
386        }
387
388        // bin8
389        0xc4 => {
390            ensure_len(data, 2)?;
391            let len = data[1] as usize;
392            ensure_len(data, 2 + len)?;
393            Ok((Value::Bin(data[2..2 + len].to_vec()), 2 + len))
394        }
395
396        // bin16
397        0xc5 => {
398            ensure_len(data, 3)?;
399            let len = u16::from_be_bytes([data[1], data[2]]) as usize;
400            ensure_len(data, 3 + len)?;
401            Ok((Value::Bin(data[3..3 + len].to_vec()), 3 + len))
402        }
403
404        // bin32
405        0xc6 => {
406            ensure_len(data, 5)?;
407            let len = u32::from_be_bytes([data[1], data[2], data[3], data[4]]) as usize;
408            ensure_len(data, 5 + len)?;
409            Ok((Value::Bin(data[5..5 + len].to_vec()), 5 + len))
410        }
411
412        // uint8
413        0xcc => {
414            ensure_len(data, 2)?;
415            Ok((Value::UInt(data[1] as u64), 2))
416        }
417
418        // uint16
419        0xcd => {
420            ensure_len(data, 3)?;
421            let v = u16::from_be_bytes([data[1], data[2]]);
422            Ok((Value::UInt(v as u64), 3))
423        }
424
425        // uint32
426        0xce => {
427            ensure_len(data, 5)?;
428            let v = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
429            Ok((Value::UInt(v as u64), 5))
430        }
431
432        // uint64
433        0xcf => {
434            ensure_len(data, 9)?;
435            let v = u64::from_be_bytes([
436                data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
437            ]);
438            Ok((Value::UInt(v), 9))
439        }
440
441        // int8
442        0xd0 => {
443            ensure_len(data, 2)?;
444            Ok((Value::Int(data[1] as i8 as i64), 2))
445        }
446
447        // int16
448        0xd1 => {
449            ensure_len(data, 3)?;
450            let v = i16::from_be_bytes([data[1], data[2]]);
451            Ok((Value::Int(v as i64), 3))
452        }
453
454        // int32
455        0xd2 => {
456            ensure_len(data, 5)?;
457            let v = i32::from_be_bytes([data[1], data[2], data[3], data[4]]);
458            Ok((Value::Int(v as i64), 5))
459        }
460
461        // int64
462        0xd3 => {
463            ensure_len(data, 9)?;
464            let v = i64::from_be_bytes([
465                data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
466            ]);
467            Ok((Value::Int(v), 9))
468        }
469
470        // str8
471        0xd9 => {
472            ensure_len(data, 2)?;
473            let len = data[1] as usize;
474            unpack_str_bytes(data, 2, len)
475        }
476
477        // str16
478        0xda => {
479            ensure_len(data, 3)?;
480            let len = u16::from_be_bytes([data[1], data[2]]) as usize;
481            unpack_str_bytes(data, 3, len)
482        }
483
484        // str32
485        0xdb => {
486            ensure_len(data, 5)?;
487            let len = u32::from_be_bytes([data[1], data[2], data[3], data[4]]) as usize;
488            unpack_str_bytes(data, 5, len)
489        }
490
491        // array16
492        0xdc => {
493            ensure_len(data, 3)?;
494            let len = u16::from_be_bytes([data[1], data[2]]) as usize;
495            unpack_array_entries(data, 3, len, depth)
496        }
497
498        // array32
499        0xdd => {
500            ensure_len(data, 5)?;
501            let len = u32::from_be_bytes([data[1], data[2], data[3], data[4]]) as usize;
502            unpack_array_entries(data, 5, len, depth)
503        }
504
505        // map16
506        0xde => {
507            ensure_len(data, 3)?;
508            let len = u16::from_be_bytes([data[1], data[2]]) as usize;
509            unpack_map_entries(data, 3, len, depth)
510        }
511
512        // map32
513        0xdf => {
514            ensure_len(data, 5)?;
515            let len = u32::from_be_bytes([data[1], data[2], data[3], data[4]]) as usize;
516            unpack_map_entries(data, 5, len, depth)
517        }
518
519        // negative fixint: 0xe0..0xff
520        0xe0..=0xff => Ok((Value::Int(b as i8 as i64), 1)),
521
522        _ => Err(Error::UnsupportedFormat(b)),
523    }
524}
525
526/// Decode a complete msgpack value, ensuring no trailing data.
527pub fn unpack_exact(data: &[u8]) -> Result<Value, Error> {
528    let (value, consumed) = unpack(data)?;
529    if consumed != data.len() {
530        return Err(Error::TrailingData);
531    }
532    Ok(value)
533}
534
535fn ensure_len(data: &[u8], needed: usize) -> Result<(), Error> {
536    if data.len() < needed {
537        Err(Error::UnexpectedEof)
538    } else {
539        Ok(())
540    }
541}
542
543fn unpack_str_bytes(data: &[u8], offset: usize, len: usize) -> Result<(Value, usize), Error> {
544    ensure_len(data, offset + len)?;
545    let bytes = &data[offset..offset + len];
546    let s = core::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8)?;
547    Ok((Value::Str(String::from(s)), offset + len))
548}
549
550fn unpack_array_entries(
551    data: &[u8],
552    start: usize,
553    count: usize,
554    depth: usize,
555) -> Result<(Value, usize), Error> {
556    let mut offset = start;
557    let mut items = Vec::with_capacity(count);
558    for _ in 0..count {
559        let (v, consumed) = unpack_depth(&data[offset..], depth + 1)?;
560        items.push(v);
561        offset += consumed;
562    }
563    Ok((Value::Array(items), offset))
564}
565
566fn unpack_map_entries(
567    data: &[u8],
568    start: usize,
569    count: usize,
570    depth: usize,
571) -> Result<(Value, usize), Error> {
572    let mut offset = start;
573    let mut entries = Vec::with_capacity(count);
574    for _ in 0..count {
575        let (k, kc) = unpack_depth(&data[offset..], depth + 1)?;
576        offset += kc;
577        let (v, vc) = unpack_depth(&data[offset..], depth + 1)?;
578        offset += vc;
579        entries.push((k, v));
580    }
581    Ok((Value::Map(entries), offset))
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    fn roundtrip(v: &Value) -> Value {
589        let packed = pack(v);
590        let (unpacked, consumed) = unpack(&packed).unwrap();
591        assert_eq!(consumed, packed.len(), "all bytes consumed");
592        unpacked
593    }
594
595    #[test]
596    fn test_nil() {
597        let packed = pack(&Value::Nil);
598        assert_eq!(packed, vec![0xc0]);
599        assert_eq!(roundtrip(&Value::Nil), Value::Nil);
600    }
601
602    #[test]
603    fn test_bool() {
604        assert_eq!(pack(&Value::Bool(true)), vec![0xc3]);
605        assert_eq!(pack(&Value::Bool(false)), vec![0xc2]);
606        assert_eq!(roundtrip(&Value::Bool(true)), Value::Bool(true));
607        assert_eq!(roundtrip(&Value::Bool(false)), Value::Bool(false));
608    }
609
610    #[test]
611    fn test_positive_fixint() {
612        assert_eq!(pack(&Value::UInt(0)), vec![0x00]);
613        assert_eq!(pack(&Value::UInt(127)), vec![0x7f]);
614        assert_eq!(roundtrip(&Value::UInt(0)), Value::UInt(0));
615        assert_eq!(roundtrip(&Value::UInt(42)), Value::UInt(42));
616        assert_eq!(roundtrip(&Value::UInt(127)), Value::UInt(127));
617    }
618
619    #[test]
620    fn test_uint8() {
621        assert_eq!(pack(&Value::UInt(128)), vec![0xcc, 0x80]);
622        assert_eq!(pack(&Value::UInt(255)), vec![0xcc, 0xff]);
623        assert_eq!(roundtrip(&Value::UInt(128)), Value::UInt(128));
624        assert_eq!(roundtrip(&Value::UInt(255)), Value::UInt(255));
625    }
626
627    #[test]
628    fn test_uint16() {
629        assert_eq!(pack(&Value::UInt(256)), vec![0xcd, 0x01, 0x00]);
630        assert_eq!(roundtrip(&Value::UInt(256)), Value::UInt(256));
631        assert_eq!(roundtrip(&Value::UInt(0xFFFF)), Value::UInt(0xFFFF));
632    }
633
634    #[test]
635    fn test_uint32() {
636        assert_eq!(
637            pack(&Value::UInt(0x10000)),
638            vec![0xce, 0x00, 0x01, 0x00, 0x00]
639        );
640        assert_eq!(roundtrip(&Value::UInt(0x10000)), Value::UInt(0x10000));
641        assert_eq!(roundtrip(&Value::UInt(0xFFFFFFFF)), Value::UInt(0xFFFFFFFF));
642    }
643
644    #[test]
645    fn test_uint64() {
646        let big = 0x1_0000_0000u64;
647        assert_eq!(roundtrip(&Value::UInt(big)), Value::UInt(big));
648        let huge = u64::MAX;
649        assert_eq!(roundtrip(&Value::UInt(huge)), Value::UInt(huge));
650    }
651
652    #[test]
653    fn test_negative_fixint() {
654        // -1 = 0xff, -32 = 0xe0
655        assert_eq!(pack(&Value::Int(-1)), vec![0xff]);
656        assert_eq!(pack(&Value::Int(-32)), vec![0xe0]);
657        assert_eq!(roundtrip(&Value::Int(-1)), Value::Int(-1));
658        assert_eq!(roundtrip(&Value::Int(-32)), Value::Int(-32));
659    }
660
661    #[test]
662    fn test_int8() {
663        assert_eq!(pack(&Value::Int(-33)), vec![0xd0, 0xdf]);
664        assert_eq!(roundtrip(&Value::Int(-33)), Value::Int(-33));
665        assert_eq!(roundtrip(&Value::Int(-128)), Value::Int(-128));
666    }
667
668    #[test]
669    fn test_int16() {
670        assert_eq!(roundtrip(&Value::Int(-129)), Value::Int(-129));
671        assert_eq!(roundtrip(&Value::Int(-32768)), Value::Int(-32768));
672    }
673
674    #[test]
675    fn test_int32() {
676        assert_eq!(roundtrip(&Value::Int(-32769)), Value::Int(-32769));
677    }
678
679    #[test]
680    fn test_positive_int_packed_as_uint() {
681        // Positive values always encode as uint format
682        let packed = pack(&Value::Int(42));
683        assert_eq!(packed, vec![42]); // positive fixint
684    }
685
686    #[test]
687    fn test_fixstr() {
688        let v = Value::Str(String::from("t"));
689        let packed = pack(&v);
690        assert_eq!(packed[0], 0xa1); // fixstr len=1
691        assert_eq!(roundtrip(&v), v);
692
693        let v = Value::Str(String::from("hello"));
694        assert_eq!(roundtrip(&v), v);
695
696        // Empty string
697        let v = Value::Str(String::new());
698        assert_eq!(pack(&v), vec![0xa0]);
699        assert_eq!(roundtrip(&v), v);
700    }
701
702    #[test]
703    fn test_str8() {
704        let s: String = "a".repeat(32);
705        let v = Value::Str(s);
706        let packed = pack(&v);
707        assert_eq!(packed[0], 0xd9);
708        assert_eq!(packed[1], 32);
709        assert_eq!(roundtrip(&v), v);
710    }
711
712    #[test]
713    fn test_bin8() {
714        let v = Value::Bin(vec![1, 2, 3]);
715        let packed = pack(&v);
716        assert_eq!(packed[0], 0xc4);
717        assert_eq!(packed[1], 3);
718        assert_eq!(roundtrip(&v), v);
719    }
720
721    #[test]
722    fn test_bin16() {
723        let data = vec![0xAB; 300];
724        let v = Value::Bin(data);
725        let packed = pack(&v);
726        assert_eq!(packed[0], 0xc5);
727        assert_eq!(roundtrip(&v), v);
728    }
729
730    #[test]
731    fn test_bin32() {
732        // bin32 threshold is > 65535 bytes, skip actual large allocation but
733        // test the format byte by manually checking a 0-length edge
734        let data = vec![0xCD; 70000];
735        let v = Value::Bin(data);
736        let packed = pack(&v);
737        assert_eq!(packed[0], 0xc6);
738        assert_eq!(roundtrip(&v), v);
739    }
740
741    #[test]
742    fn test_fixarray() {
743        let v = Value::Array(vec![Value::UInt(1), Value::UInt(2), Value::UInt(3)]);
744        let packed = pack(&v);
745        assert_eq!(packed[0], 0x93); // fixarray len=3
746        assert_eq!(roundtrip(&v), v);
747
748        // Empty array
749        let v = Value::Array(vec![]);
750        assert_eq!(pack(&v), vec![0x90]);
751        assert_eq!(roundtrip(&v), v);
752    }
753
754    #[test]
755    fn test_fixmap() {
756        let v = Value::Map(vec![
757            (Value::Str(String::from("a")), Value::UInt(1)),
758            (Value::Str(String::from("b")), Value::UInt(2)),
759        ]);
760        let packed = pack(&v);
761        assert_eq!(packed[0], 0x82); // fixmap len=2
762        assert_eq!(roundtrip(&v), v);
763    }
764
765    #[test]
766    fn test_nested_structure() {
767        let v = Value::Map(vec![
768            (Value::Str(String::from("t")), Value::UInt(1000)),
769            (Value::Str(String::from("m")), Value::Bin(vec![0xAA; 10])),
770            (Value::Str(String::from("q")), Value::Nil),
771        ]);
772        assert_eq!(roundtrip(&v), v);
773    }
774
775    #[test]
776    fn test_pack_str_map() {
777        let packed = pack_str_map(&[("x", Value::UInt(42)), ("y", Value::Bool(true))]);
778        let (v, _) = unpack(&packed).unwrap();
779        assert_eq!(v.map_get("x").unwrap().as_uint(), Some(42));
780        assert_eq!(v.map_get("y").unwrap().as_bool(), Some(true));
781    }
782
783    #[test]
784    fn test_map_get_missing_key() {
785        let v = Value::Map(vec![(Value::Str(String::from("a")), Value::UInt(1))]);
786        assert!(v.map_get("b").is_none());
787    }
788
789    #[test]
790    fn test_hmu_array_format() {
791        // HMU format: [segment_int, hashmap_bytes]
792        let v = Value::Array(vec![
793            Value::UInt(2),
794            Value::Bin(vec![0x11, 0x22, 0x33, 0x44, 0xAA, 0xBB, 0xCC, 0xDD]),
795        ]);
796        assert_eq!(roundtrip(&v), v);
797    }
798
799    #[test]
800    fn test_decode_error_eof() {
801        assert_eq!(unpack(&[]), Err(Error::UnexpectedEof));
802        // bin8 with length but no data
803        assert_eq!(unpack(&[0xc4, 0x05]), Err(Error::UnexpectedEof));
804    }
805
806    #[test]
807    fn test_unpack_exact_trailing() {
808        let packed = pack(&Value::UInt(42));
809        let mut with_extra = packed.clone();
810        with_extra.push(0x00);
811        assert!(unpack_exact(&with_extra).is_err());
812        assert!(unpack_exact(&packed).is_ok());
813    }
814
815    #[test]
816    fn test_value_accessors() {
817        assert_eq!(Value::UInt(42).as_uint(), Some(42));
818        assert_eq!(Value::UInt(42).as_int(), None);
819        assert_eq!(Value::UInt(42).as_integer(), Some(42));
820        assert_eq!(Value::Int(-5).as_integer(), Some(-5));
821        assert_eq!(Value::Bool(true).as_bool(), Some(true));
822        assert_eq!(Value::Bin(vec![1]).as_bin(), Some(&[1u8][..]));
823        assert_eq!(Value::Str(String::from("x")).as_str(), Some("x"));
824        assert!(Value::Nil.is_nil());
825    }
826
827    #[test]
828    fn test_max_depth_exceeded() {
829        // Build deeply nested arrays: [[[[...]]]] beyond MAX_DEPTH
830        let mut data = Vec::new();
831        data.extend(core::iter::repeat_n(0x91, MAX_DEPTH + 2)); // fixarray of length 1
832        data.push(0x01); // innermost value: uint 1
833        assert_eq!(unpack(&data), Err(Error::MaxDepthExceeded));
834    }
835
836    #[test]
837    fn test_depth_within_limit() {
838        // Build nested arrays within limit (depth 5)
839        let mut data = Vec::new();
840        data.extend(core::iter::repeat_n(0x91, 5)); // fixarray of length 1
841        data.push(0x01); // innermost value
842        let (val, _) = unpack(&data).unwrap();
843        // Should be Array([Array([Array([Array([Array([UInt(1)])])])])])
844        let mut current = &val;
845        for _ in 0..5 {
846            current = &current.as_array().unwrap()[0];
847        }
848        assert_eq!(current.as_uint(), Some(1));
849    }
850
851    #[test]
852    fn test_int64_roundtrip() {
853        let v = Value::Int(i64::MIN);
854        assert_eq!(roundtrip(&v), v);
855        let v = Value::Int(-2_147_483_649); // beyond i32 range
856        assert_eq!(roundtrip(&v), v);
857    }
858
859    #[test]
860    fn test_str16_roundtrip() {
861        let s: String = "x".repeat(256);
862        let v = Value::Str(s);
863        let packed = pack(&v);
864        assert_eq!(packed[0], 0xda); // str16
865        assert_eq!(roundtrip(&v), v);
866    }
867
868    #[test]
869    fn test_array16_roundtrip() {
870        let items: Vec<Value> = (0..16).map(Value::UInt).collect();
871        let v = Value::Array(items);
872        let packed = pack(&v);
873        assert_eq!(packed[0], 0xdc); // array16
874        assert_eq!(roundtrip(&v), v);
875    }
876
877    #[test]
878    fn test_map16_roundtrip() {
879        let entries: Vec<(Value, Value)> = (0..16)
880            .map(|i| (Value::UInt(i), Value::Bool(i % 2 == 0)))
881            .collect();
882        let v = Value::Map(entries);
883        let packed = pack(&v);
884        assert_eq!(packed[0], 0xde); // map16
885        assert_eq!(roundtrip(&v), v);
886    }
887
888    #[test]
889    fn test_unsupported_format() {
890        // 0xc1 is unused/never valid
891        assert_eq!(unpack(&[0xc1]), Err(Error::UnsupportedFormat(0xc1)));
892    }
893}