1use alloc::string::String;
11use alloc::vec::Vec;
12use core::fmt;
13
14#[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 pub fn as_uint(&self) -> Option<u64> {
48 match self {
49 Value::UInt(v) => Some(*v),
50 _ => None,
51 }
52 }
53
54 pub fn as_int(&self) -> Option<i64> {
56 match self {
57 Value::Int(v) => Some(*v),
58 _ => None,
59 }
60 }
61
62 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 pub fn as_bool(&self) -> Option<bool> {
79 match self {
80 Value::Bool(v) => Some(*v),
81 _ => None,
82 }
83 }
84
85 pub fn as_float(&self) -> Option<f64> {
87 match self {
88 Value::Float(v) => Some(*v),
89 _ => None,
90 }
91 }
92
93 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 pub fn as_bin(&self) -> Option<&[u8]> {
105 match self {
106 Value::Bin(v) => Some(v),
107 _ => None,
108 }
109 }
110
111 pub fn as_str(&self) -> Option<&str> {
113 match self {
114 Value::Str(v) => Some(v),
115 _ => None,
116 }
117 }
118
119 pub fn as_array(&self) -> Option<&[Value]> {
121 match self {
122 Value::Array(v) => Some(v),
123 _ => None,
124 }
125 }
126
127 pub fn as_map(&self) -> Option<&[(Value, Value)]> {
129 match self {
130 Value::Map(v) => Some(v),
131 _ => None,
132 }
133 }
134
135 pub fn is_nil(&self) -> bool {
137 matches!(self, Value::Nil)
138 }
139
140 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
155const MAX_DEPTH: usize = 32;
157
158#[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
180pub 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); } 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
313pub 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
322pub 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 0x00..=0x7f => Ok((Value::UInt(b as u64), 1)),
343
344 0x80..=0x8f => {
346 let len = (b & 0x0f) as usize;
347 unpack_map_entries(data, 1, len, depth)
348 }
349
350 0x90..=0x9f => {
352 let len = (b & 0x0f) as usize;
353 unpack_array_entries(data, 1, len, depth)
354 }
355
356 0xa0..=0xbf => {
358 let len = (b & 0x1f) as usize;
359 unpack_str_bytes(data, 1, len)
360 }
361
362 0xc0 => Ok((Value::Nil, 1)),
364
365 0xc1 => Err(Error::UnsupportedFormat(b)),
367
368 0xc2 => Ok((Value::Bool(false), 1)),
370 0xc3 => Ok((Value::Bool(true), 1)),
371
372 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 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 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 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 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 0xcc => {
414 ensure_len(data, 2)?;
415 Ok((Value::UInt(data[1] as u64), 2))
416 }
417
418 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 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 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 0xd0 => {
443 ensure_len(data, 2)?;
444 Ok((Value::Int(data[1] as i8 as i64), 2))
445 }
446
447 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 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 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 0xd9 => {
472 ensure_len(data, 2)?;
473 let len = data[1] as usize;
474 unpack_str_bytes(data, 2, len)
475 }
476
477 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 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 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 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 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 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 0xe0..=0xff => Ok((Value::Int(b as i8 as i64), 1)),
521
522 _ => Err(Error::UnsupportedFormat(b)),
523 }
524}
525
526pub 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 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 let packed = pack(&Value::Int(42));
683 assert_eq!(packed, vec![42]); }
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); assert_eq!(roundtrip(&v), v);
692
693 let v = Value::Str(String::from("hello"));
694 assert_eq!(roundtrip(&v), v);
695
696 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 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); assert_eq!(roundtrip(&v), v);
747
748 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); 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 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 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 let mut data = Vec::new();
831 data.extend(core::iter::repeat_n(0x91, MAX_DEPTH + 2)); data.push(0x01); assert_eq!(unpack(&data), Err(Error::MaxDepthExceeded));
834 }
835
836 #[test]
837 fn test_depth_within_limit() {
838 let mut data = Vec::new();
840 data.extend(core::iter::repeat_n(0x91, 5)); data.push(0x01); let (val, _) = unpack(&data).unwrap();
843 let mut current = &val;
845 for _ in 0..5 {
846 current = ¤t.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); 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); 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); 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); assert_eq!(roundtrip(&v), v);
886 }
887
888 #[test]
889 fn test_unsupported_format() {
890 assert_eq!(unpack(&[0xc1]), Err(Error::UnsupportedFormat(0xc1)));
892 }
893}