peerrs_binarypack/
binarypack.rs

1use std::collections::HashMap;
2use std::hash::{Hash, Hasher};
3use std::mem::size_of;
4
5use byteorder::{BigEndian, ByteOrder};
6use num::{NumCast, Unsigned};
7
8use crate::error::{Error, Result};
9
10/// An enum representing possible unpacked structures
11#[derive(Clone, Debug)]
12pub enum Unpacked {
13    Uint8(u8),
14    Uint16(u16),
15    Uint32(u32),
16    Uint64(u64),
17    Int8(i8),
18    Int16(i16),
19    Int32(i32),
20    Int64(i64),
21    Float(f32),
22    Double(f64),
23    Bool(bool),
24    Raw(Vec<u8>),
25    String(String),
26    Null,
27    Undefined,
28    Array(Vec<Unpacked>),
29    Map(HashMap<Unpacked, Unpacked>),
30}
31
32impl PartialEq for Unpacked {
33    fn eq(&self, other: &Self) -> bool {
34        match (self, other) {
35            (Unpacked::Bool(a), Unpacked::Bool(b)) => a == b,
36            (Unpacked::Uint8(a), Unpacked::Uint8(b)) => a == b,
37            (Unpacked::Uint16(a), Unpacked::Uint16(b)) => a == b,
38            (Unpacked::Uint32(a), Unpacked::Uint32(b)) => a == b,
39            (Unpacked::Uint64(a), Unpacked::Uint64(b)) => a == b,
40            (Unpacked::Int8(a), Unpacked::Int8(b)) => a == b,
41            (Unpacked::Int16(a), Unpacked::Int16(b)) => a == b,
42            (Unpacked::Int32(a), Unpacked::Int32(b)) => a == b,
43            (Unpacked::Int64(a), Unpacked::Int64(b)) => a == b,
44            (Unpacked::Float(a), Unpacked::Float(b)) => a == b,
45            (Unpacked::Double(a), Unpacked::Double(b)) => a == b,
46            (Unpacked::Raw(a), Unpacked::Raw(b)) => a == b,
47            (Unpacked::String(a), Unpacked::String(b)) => a == b,
48            (Unpacked::Null, Unpacked::Null) => true,
49            (Unpacked::Array(a), Unpacked::Array(b)) => {
50                if a.len() != b.len() {
51                    return false;
52                }
53
54                for i in 0..a.len() {
55                    if a[i] != b[i] {
56                        return false;
57                    }
58                }
59
60                true
61            }
62            (Unpacked::Map(a), Unpacked::Map(b)) => {
63                if a.len() != b.len() {
64                    return false;
65                }
66
67                for (k, a_v) in a.iter() {
68                    if let Some(b_v) = b.get(k) {
69                        if b_v == a_v {
70                            continue;
71                        }
72                    }
73
74                    return false;
75                }
76
77                return true;
78            }
79            (_, _) => false,
80        }
81    }
82}
83
84impl Eq for Unpacked {}
85
86impl Hash for Unpacked {
87    fn hash<H: Hasher>(&self, state: &mut H) {
88        state.write(format!("{:?}", self).as_bytes());
89        state.finish();
90    }
91}
92
93const MAP_MASK: u8 = 0x80;
94const ARR_MASK: u8 = 0x90;
95const RAW_MASK: u8 = 0xa0;
96const STR_MASK: u8 = 0xb0;
97const INT_MASK: u8 = 0xe0;
98
99const PACKED_NULL: u8 = 0xc0;
100const PACKED_UNDEFINED: u8 = 0xc1;
101const PACKED_FALSE: u8 = 0xc2;
102const PACKED_TRUE: u8 = 0xc3;
103const PACKED_FLOAT: u8 = 0xca;
104const PACKED_DOUBLE: u8 = 0xcb;
105const PACKED_UINT8: u8 = 0xcc;
106const PACKED_UINT16: u8 = 0xcd;
107const PACKED_UINT32: u8 = 0xce;
108const PACKED_UINT64: u8 = 0xcf;
109const PACKED_INT8: u8 = 0xd0;
110const PACKED_INT16: u8 = 0xd1;
111const PACKED_INT32: u8 = 0xd2;
112const PACKED_INT64: u8 = 0xd3;
113const PACKED_STR_U16: u8 = 0xd8;
114const PACKED_STR_U32: u8 = 0xd9;
115const PACKED_RAW_U16: u8 = 0xda;
116const PACKED_RAW_U32: u8 = 0xdb;
117const PACKED_ARR_U16: u8 = 0xdc;
118const PACKED_ARR_U32: u8 = 0xdd;
119const PACKED_MAP_U16: u8 = 0xde;
120const PACKED_MAP_U32: u8 = 0xdf;
121
122/// An object that can unpack the js-binarypack format
123pub struct Unpacker<'a> {
124    data: &'a [u8],
125}
126
127impl<'a> Unpacker<'a> {
128    fn new(data: &[u8]) -> Unpacker {
129        Unpacker { data }
130    }
131
132    fn unpack_unsigned<T: Copy + Unsigned + NumCast>(&mut self) -> Result<T> {
133        let length = size_of::<T>();
134        if self.data.len() < length {
135            return Err(Error::EndOfData);
136        }
137
138        let mut digits = vec![];
139        for i in 0..length {
140            digits.push(T::from(self.data[i]).unwrap());
141        }
142        self.data = &self.data[length..];
143
144        let mut val: T = T::zero();
145        // If the cast of 256 fails, then T must be u8, so we know there's only one digit to
146        // worry about.
147        let shift = T::from(256).unwrap_or(T::zero());
148        for d in digits {
149            val = (val * shift) + d;
150        }
151
152        Ok(val)
153    }
154
155    fn unpack_uint8(&mut self) -> Result<u8> {
156        self.unpack_unsigned()
157    }
158
159    fn unpack_int8(&mut self) -> Result<i8> {
160        self.unpack_unsigned().map(|x: u8| x as i8)
161    }
162
163    fn unpack_uint16(&mut self) -> Result<u16> {
164        self.unpack_unsigned()
165    }
166
167    fn unpack_int16(&mut self) -> Result<i16> {
168        self.unpack_unsigned().map(|x: u16| x as i16)
169    }
170
171    fn unpack_uint32(&mut self) -> Result<u32> {
172        self.unpack_unsigned()
173    }
174
175    fn unpack_int32(&mut self) -> Result<i32> {
176        self.unpack_unsigned().map(|x: u32| x as i32)
177    }
178
179    fn unpack_uint64(&mut self) -> Result<u64> {
180        self.unpack_unsigned()
181    }
182
183    fn unpack_int64(&mut self) -> Result<i64> {
184        self.unpack_unsigned().map(|x: u64| x as i64)
185    }
186
187    fn unpack_raw(&mut self, size: usize) -> Result<Vec<u8>> {
188        let mut raw = vec![];
189        if self.data.len() < size {
190            return Err(Error::EndOfData);
191        }
192
193        for i in 0..size {
194            raw.push(self.data[i]);
195        }
196        self.data = &self.data[size..];
197
198        Ok(raw)
199    }
200
201    fn unpack_string(&mut self, size: usize) -> Result<String> {
202        Ok(String::from_utf8(self.unpack_raw(size)?)?)
203    }
204
205    fn unpack_array(&mut self, size: usize) -> Result<Vec<Unpacked>> {
206        let mut arr = vec![];
207        for _i in 0..size {
208            arr.push(self.unpack()?);
209        }
210
211        Ok(arr)
212    }
213
214    fn unpack_map(&mut self, size: usize) -> Result<HashMap<Unpacked, Unpacked>> {
215        let mut map = HashMap::new();
216        for _i in 0..size {
217            map.insert(self.unpack()?, self.unpack()?);
218        }
219
220        Ok(map)
221    }
222
223    fn unpack_float(&mut self) -> Result<f32> {
224        let i = self.unpack_uint32()?;
225        let mut bytes = [0u8; 4];
226        BigEndian::write_u32(&mut bytes, i);
227        Ok(BigEndian::read_f32(&mut bytes))
228    }
229
230    fn unpack_double(&mut self) -> Result<f64> {
231        let i = self.unpack_uint64()?;
232        let mut bytes = [0u8; 8];
233        BigEndian::write_u64(&mut bytes, i);
234        Ok(BigEndian::read_f64(&mut bytes))
235    }
236
237    fn unpack(&mut self) -> Result<Unpacked> {
238        let type_ = self.unpack_uint8()?;
239        if type_ < MAP_MASK {
240            return Ok(Unpacked::Uint8(type_));
241        } else if (type_ ^ INT_MASK) < 0x20 {
242            return Ok(Unpacked::Int8((type_ ^ INT_MASK) as i8 - 0x20));
243        }
244
245        let size = type_ ^ MAP_MASK;
246        if size <= 0x0f {
247            return Ok(Unpacked::Map(self.unpack_map(size as usize)?));
248        }
249
250        let size = type_ ^ ARR_MASK;
251        if size <= 0x0f {
252            return Ok(Unpacked::Array(self.unpack_array(size as usize)?));
253        }
254
255        let size = type_ ^ RAW_MASK;
256        if size <= 0x0f {
257            return Ok(Unpacked::Raw(self.unpack_raw(size as usize)?));
258        }
259        let size = type_ ^ STR_MASK;
260        if size <= 0x0f {
261            return Ok(Unpacked::String(self.unpack_string(size as usize)?));
262        }
263
264        Ok(match type_ {
265            PACKED_NULL => Unpacked::Null,
266            PACKED_FALSE => Unpacked::Bool(false),
267            PACKED_TRUE => Unpacked::Bool(true),
268            PACKED_FLOAT => Unpacked::Float(self.unpack_float()?),
269            PACKED_DOUBLE => Unpacked::Double(self.unpack_double()?),
270            PACKED_UINT8 => Unpacked::Uint8(self.unpack_uint8()?),
271            PACKED_UINT16 => Unpacked::Uint16(self.unpack_uint16()?),
272            PACKED_UINT32 => Unpacked::Uint32(self.unpack_uint32()?),
273            PACKED_UINT64 => Unpacked::Uint64(self.unpack_uint64()?),
274            PACKED_INT8 => Unpacked::Int8(self.unpack_int8()?),
275            PACKED_INT16 => Unpacked::Int16(self.unpack_int16()?),
276            PACKED_INT32 => Unpacked::Int32(self.unpack_int32()?),
277            PACKED_INT64 => Unpacked::Int64(self.unpack_int64()?),
278            PACKED_STR_U16 => {
279                let size = self.unpack_uint16()? as usize;
280                Unpacked::String(self.unpack_string(size)?)
281            }
282            PACKED_STR_U32 => {
283                let size = self.unpack_uint32()? as usize;
284                Unpacked::String(self.unpack_string(size)?)
285            }
286            PACKED_RAW_U16 => {
287                let size = self.unpack_uint16()? as usize;
288                Unpacked::Raw(self.unpack_raw(size)?)
289            }
290            PACKED_RAW_U32 => {
291                let size = self.unpack_uint32()? as usize;
292                Unpacked::Raw(self.unpack_raw(size)?)
293            }
294            PACKED_ARR_U16 => {
295                let size = self.unpack_uint16()? as usize;
296                Unpacked::Array(self.unpack_array(size)?)
297            }
298            PACKED_ARR_U32 => {
299                let size = self.unpack_uint32()? as usize;
300                Unpacked::Array(self.unpack_array(size)?)
301            }
302            PACKED_MAP_U16 => {
303                let size = self.unpack_uint16()? as usize;
304                Unpacked::Map(self.unpack_map(size)?)
305            }
306            PACKED_MAP_U32 => {
307                let size = self.unpack_uint32()? as usize;
308                Unpacked::Map(self.unpack_map(size)?)
309            }
310
311            _ => Unpacked::Undefined,
312        })
313    }
314}
315
316/// Unpacks data in the js-binarypack format
317pub fn unpack(data: &[u8]) -> Result<Unpacked> {
318    Unpacker::new(data).unpack()
319}
320
321impl Unpacked {
322    fn _pack_len(packed: &mut Vec<u8>, size: usize, u16_type: u8, u32_type: u8) {
323        if size <= (u16::max_value() as usize) {
324            packed.push(u16_type);
325
326            let mut size_bytes = [0u8; 2];
327            BigEndian::write_u16(&mut size_bytes, size as u16);
328            for b in size_bytes.iter() {
329                packed.push(*b);
330            }
331        } else {
332            packed.push(u32_type);
333
334            let mut size_bytes = [0u8; 4];
335            BigEndian::write_u32(&mut size_bytes, size as u32);
336            for b in size_bytes.iter() {
337                packed.push(*b);
338            }
339        }
340    }
341
342    fn _pack(&self, packed: &mut Vec<u8>) {
343        match self {
344            Unpacked::Uint8(a) => {
345                if *a < MAP_MASK {
346                    packed.push(*a);
347                } else {
348                    packed.push(PACKED_UINT8);
349                    packed.push(*a);
350                }
351            }
352            Unpacked::Uint16(a) => {
353                packed.push(PACKED_UINT16);
354                let mut bytes = [0u8; 2];
355                BigEndian::write_u16(&mut bytes, *a);
356                for b in bytes.iter() {
357                    packed.push(*b);
358                }
359            }
360            Unpacked::Uint32(a) => {
361                packed.push(PACKED_UINT32);
362                let mut bytes = [0u8; 4];
363                BigEndian::write_u32(&mut bytes, *a);
364                for b in bytes.iter() {
365                    packed.push(*b);
366                }
367            }
368            Unpacked::Uint64(a) => {
369                packed.push(PACKED_UINT64);
370                let mut bytes = [0u8; 8];
371                BigEndian::write_u64(&mut bytes, *a);
372                for b in bytes.iter() {
373                    packed.push(*b);
374                }
375            }
376            Unpacked::Int8(a) => {
377                if *a < 0 && *a > -0x20 {
378                    packed.push(((a + 0x20) as u8) ^ INT_MASK)
379                } else {
380                    packed.push(PACKED_INT8);
381                    packed.push(*a as u8);
382                }
383            }
384            Unpacked::Int16(a) => {
385                packed.push(PACKED_INT16);
386                let mut bytes = [0u8; 2];
387                BigEndian::write_u16(&mut bytes, *a as u16);
388                for b in bytes.iter() {
389                    packed.push(*b);
390                }
391            }
392            Unpacked::Int32(a) => {
393                packed.push(PACKED_INT32);
394                let mut bytes = [0u8; 4];
395                BigEndian::write_u32(&mut bytes, *a as u32);
396                for b in bytes.iter() {
397                    packed.push(*b);
398                }
399            }
400            Unpacked::Int64(a) => {
401                packed.push(PACKED_INT64);
402                let mut bytes = [0u8; 8];
403                BigEndian::write_u64(&mut bytes, *a as u64);
404                for b in bytes.iter() {
405                    packed.push(*b);
406                }
407            }
408            Unpacked::Float(f) => {
409                let mut bytes = [0u8; 4];
410                BigEndian::write_f32(&mut bytes, *f);
411
412                packed.push(PACKED_FLOAT);
413                for b in bytes.iter() {
414                    packed.push(*b);
415                }
416            }
417            Unpacked::Double(f) => {
418                let mut bytes = [0u8; 8];
419                BigEndian::write_f64(&mut bytes, *f);
420
421                packed.push(PACKED_DOUBLE);
422                for b in bytes.iter() {
423                    packed.push(*b);
424                }
425            }
426            Unpacked::Bool(b) => {
427                match b {
428                    true => packed.push(PACKED_TRUE),
429                    false => packed.push(PACKED_FALSE),
430                };
431            }
432            Unpacked::Raw(bytes) => {
433                Unpacked::_pack_len(packed, bytes.len(), PACKED_RAW_U16, PACKED_RAW_U32);
434                for b in bytes.iter() {
435                    packed.push(*b);
436                }
437            }
438            Unpacked::String(s) => {
439                let bytes = s.bytes();
440                Unpacked::_pack_len(packed, bytes.len(), PACKED_STR_U16, PACKED_STR_U32);
441                for b in bytes {
442                    packed.push(b);
443                }
444            }
445            Unpacked::Null => {
446                packed.push(PACKED_NULL);
447            }
448            Unpacked::Undefined => packed.push(PACKED_UNDEFINED),
449            Unpacked::Array(v) => {
450                Unpacked::_pack_len(packed, v.len(), PACKED_ARR_U16, PACKED_ARR_U32);
451                for element in v {
452                    element._pack(packed);
453                }
454            }
455            Unpacked::Map(m) => {
456                Unpacked::_pack_len(packed, m.len(), PACKED_MAP_U16, PACKED_MAP_U32);
457                for (key, value) in m {
458                    key._pack(packed);
459                    value._pack(packed);
460                }
461            }
462        }
463    }
464
465    /// Pack a value into the js-binarypack format
466    pub fn pack(&self) -> Vec<u8> {
467        let mut packed = vec![];
468        self._pack(&mut packed);
469        packed
470    }
471}
472
473#[cfg(test)]
474mod test {
475    use super::*;
476
477    impl Unpacked {
478        fn is_undefined(&self) -> bool {
479            match self {
480                Unpacked::Undefined => true,
481                _ => false,
482            }
483        }
484    }
485
486    #[test]
487    fn test_unpack_uint8() {
488        let a = [1, 2, 3, 4, 5, 6, 7, 8];
489        assert_eq!(Unpacker::new(&a).unpack_uint8().unwrap(), 1);
490        assert_eq!(Unpacker::new(&a).unpack().expect("!"), Unpacked::Uint8(1));
491    }
492
493    #[test]
494    fn test_unpack_int8() {
495        let a = [1, 2, 3, 4, 5, 6, 7, 8];
496        assert_eq!(Unpacker::new(&a).unpack_int8().unwrap(), 1);
497        let a = [255];
498        assert_eq!(Unpacker::new(&a).unpack_int8().unwrap(), -1);
499    }
500
501    #[test]
502    fn test_unpack_uint16() {
503        let a = [1, 2, 3, 4, 5, 6, 7, 8];
504        assert_eq!(Unpacker::new(&a).unpack_uint16().unwrap(), 258);
505    }
506
507    #[test]
508    fn test_unpack_uint32() {
509        let a = [1, 2, 3, 4, 5, 6, 7, 8];
510        assert_eq!(Unpacker::new(&a).unpack_uint32().unwrap(), 16909060);
511    }
512
513    #[test]
514    fn test_unpack_uint64() {
515        let a = [1, 2, 3, 4, 5, 6, 7, 8];
516        assert_eq!(
517            Unpacker::new(&a).unpack_uint64().unwrap(),
518            72623859790382856
519        );
520    }
521
522    #[test]
523    fn test_unpack_raw() {
524        let a = [1, 2, 3, 4, 5, 6, 7, 8];
525        assert_eq!(Unpacker::new(&a).unpack_raw(3).unwrap(), vec!(1, 2, 3));
526    }
527
528    #[test]
529    fn test_unpack_string() {
530        let a = [
531            0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21,
532        ];
533        assert_eq!(
534            Unpacker::new(&a).unpack_string(a.len()).unwrap(),
535            "hello world!"
536        );
537    }
538
539    #[test]
540    fn test_unpack_array() {
541        let a = [1, 2, 3, 4, 5];
542        assert_eq!(
543            Unpacker::new(&a).unpack_array(a.len()).unwrap(),
544            vec!(
545                Unpacked::Uint8(1),
546                Unpacked::Uint8(2),
547                Unpacked::Uint8(3),
548                Unpacked::Uint8(4),
549                Unpacked::Uint8(5)
550            )
551        );
552    }
553
554    #[test]
555    fn test_unpack_map() {
556        let a = [1, 2, 3, 4];
557        let mut expected = HashMap::new();
558        expected.insert(Unpacked::Uint8(1), Unpacked::Uint8(2));
559        expected.insert(Unpacked::Uint8(3), Unpacked::Uint8(4));
560        assert_eq!(Unpacker::new(&a).unpack_map(a.len() / 2).unwrap(), expected);
561    }
562
563    #[test]
564    fn test_unpack_float() {
565        // 0b00111110001000000000000000000000 = 0.15625
566        // source: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
567        let a = [0b00111110, 0b00100000, 0b00000000, 0b00000000];
568        assert_eq!(Unpacker::new(&a).unpack_float().unwrap(), 0.15625);
569    }
570
571    #[test]
572    fn test_unpack_double() {
573        // src: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
574        let a = [
575            0b00111111, 0b11010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101,
576            0b01010101,
577        ];
578        assert_eq!(
579            Unpacker::new(&a).unpack_double().unwrap(),
580            0.3333333333333333
581        );
582    }
583
584    #[test]
585    fn test_unpack() {
586        let packed = [1];
587        assert_eq!(Unpacker::new(&packed).unpack().unwrap(), Unpacked::Uint8(1));
588
589        let packed = [1 ^ 0xe0];
590        assert_eq!(
591            Unpacker::new(&packed).unpack().unwrap(),
592            Unpacked::Int8(-31)
593        );
594
595        let packed = [2 ^ 0xa0, 1, 2];
596        assert_eq!(
597            Unpacker::new(&packed).unpack().unwrap(),
598            Unpacked::Raw(vec!(1, 2))
599        );
600
601        let packed = [2 ^ 0xb0, 65, 66];
602        assert_eq!(
603            Unpacker::new(&packed).unpack().unwrap(),
604            Unpacked::String("AB".to_string())
605        );
606
607        let packed = [2 ^ 0x90, 2 ^ 0xb0, 65, 66, 1];
608        let v = vec![Unpacked::String("AB".to_string()), Unpacked::Uint8(1)];
609        assert_eq!(Unpacker::new(&packed).unpack().unwrap(), Unpacked::Array(v));
610
611        let packed = [2 ^ 0x80, 1 ^ 0xb0, 65, 1, 1 ^ 0xb0, 66, 2];
612        let mut m = HashMap::new();
613        m.insert(Unpacked::String("A".to_string()), Unpacked::Uint8(1));
614        m.insert(Unpacked::String("B".to_string()), Unpacked::Uint8(2));
615        assert_eq!(Unpacker::new(&packed).unpack().unwrap(), Unpacked::Map(m));
616
617        let packed = [0xc0];
618        assert_eq!(Unpacker::new(&packed).unpack().unwrap(), Unpacked::Null);
619
620        let packed = [0xc2];
621        assert_eq!(
622            Unpacker::new(&packed).unpack().unwrap(),
623            Unpacked::Bool(false)
624        );
625
626        let packed = [0xc3];
627        assert_eq!(
628            Unpacker::new(&packed).unpack().unwrap(),
629            Unpacked::Bool(true)
630        );
631
632        let packed = [0xca, 0b00111110, 0b00100000, 0b00000000, 0b00000000];
633        assert_eq!(
634            Unpacker::new(&packed).unpack().unwrap(),
635            Unpacked::Float(0.15625)
636        );
637
638        let packed = [
639            0xcb, 0b00111111, 0b11010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101,
640            0b01010101, 0b01010101,
641        ];
642        assert_eq!(
643            Unpacker::new(&packed).unpack().unwrap(),
644            Unpacked::Double(0.3333333333333333)
645        );
646
647        let packed = [0xcc, 255];
648        assert_eq!(
649            Unpacker::new(&packed).unpack().unwrap(),
650            Unpacked::Uint8(255)
651        );
652
653        let packed = [0xcd, 255, 255];
654        assert_eq!(
655            Unpacker::new(&packed).unpack().unwrap(),
656            Unpacked::Uint16(u16::max_value())
657        );
658
659        let packed = [0xce, 255, 255, 255, 255];
660        assert_eq!(
661            Unpacker::new(&packed).unpack().unwrap(),
662            Unpacked::Uint32(u32::max_value())
663        );
664
665        let packed = [0xcf, 255, 255, 255, 255, 255, 255, 255, 255];
666        assert_eq!(
667            Unpacker::new(&packed).unpack().unwrap(),
668            Unpacked::Uint64(u64::max_value())
669        );
670
671        let packed = [0xd0, 255];
672        assert_eq!(Unpacker::new(&packed).unpack().unwrap(), Unpacked::Int8(-1));
673
674        let packed = [0xd1, 255, 255];
675        assert_eq!(
676            Unpacker::new(&packed).unpack().unwrap(),
677            Unpacked::Int16(-1)
678        );
679
680        let packed = [0xd2, 255, 255, 255, 255];
681        assert_eq!(
682            Unpacker::new(&packed).unpack().unwrap(),
683            Unpacked::Int32(-1)
684        );
685
686        let packed = [0xd3, 255, 255, 255, 255, 255, 255, 255, 255];
687        assert_eq!(
688            Unpacker::new(&packed).unpack().unwrap(),
689            Unpacked::Int64(-1)
690        );
691
692        let packed = [0xd8, 0, 1, 65];
693        assert_eq!(
694            Unpacker::new(&packed).unpack().unwrap(),
695            Unpacked::String("A".to_string())
696        );
697
698        let packed = [0xc1];
699        assert!(Unpacker::new(&packed).unpack().unwrap().is_undefined());
700    }
701
702    #[test]
703    fn pack_uint8() {
704        assert_eq!(Unpacked::Uint8(0x79).pack(), vec!(0x79));
705        assert_eq!(Unpacked::Uint8(0x80).pack(), vec!(0xcc, 0x80));
706
707        for i in 0..u8::max_value() {
708            let expected = Unpacked::Uint8(i);
709            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
710        }
711    }
712
713    #[test]
714    fn pack_uint16() {
715        assert_eq!(Unpacked::Uint16(258).pack(), vec!(0xcd, 0x1, 0x2));
716
717        for i in 0..u16::max_value() {
718            let expected = Unpacked::Uint16(i);
719            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
720        }
721    }
722
723    #[test]
724    fn pack_uint32() {
725        assert_eq!(
726            Unpacked::Uint32(16909060).pack(),
727            vec!(0xce, 0x1, 0x2, 0x3, 0x4)
728        );
729
730        let expected = Unpacked::Uint32(16909060);
731        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
732    }
733
734    #[test]
735    fn pack_uint64() {
736        assert_eq!(
737            Unpacked::Uint64(72623859790382856).pack(),
738            vec!(0xcf, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8)
739        );
740
741        let expected = Unpacked::Uint64(72623859790382856);
742        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
743    }
744
745    #[test]
746    fn pack_int8() {
747        assert_eq!(Unpacked::Int8(-31).pack(), vec!(0xe1));
748        assert_eq!(Unpacked::Int8(-100).pack(), vec!(0xd0, 0x9c));
749
750        for i in 0..u8::max_value() {
751            let expected = Unpacked::Int8(i as i8);
752            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
753        }
754    }
755
756    #[test]
757    fn pack_int16() {
758        for i in 0..u16::max_value() {
759            let expected = Unpacked::Int16(i as i16);
760            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
761        }
762    }
763
764    #[test]
765    fn pack_int32() {
766        for i in 0..u16::max_value() {
767            let expected = Unpacked::Int32(-(i as i32));
768            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
769        }
770    }
771
772    #[test]
773    fn pack_int64() {
774        for i in 0..u16::max_value() {
775            let expected = Unpacked::Int64(-(i as i64));
776            assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
777        }
778    }
779
780    #[test]
781    fn pack_float() {
782        assert_eq!(
783            Unpacked::Float(0.15625).pack(),
784            vec!(0xca, 0b00111110, 0b00100000, 0b00000000, 0b00000000)
785        );
786
787        let expected = Unpacked::Float(0.15625);
788        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
789    }
790
791    #[test]
792    fn pack_double() {
793        assert_eq!(
794            Unpacked::Double(0.3333333333333333).pack(),
795            vec!(
796                0xcb, 0b00111111, 0b11010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101,
797                0b01010101, 0b01010101
798            )
799        );
800
801        let expected = Unpacked::Double(0.3333333333333333);
802        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
803    }
804
805    #[test]
806    fn pack_bool() {
807        let expected = Unpacked::Bool(true);
808        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
809
810        let expected = Unpacked::Bool(false);
811        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
812    }
813
814    #[test]
815    fn pack_raw() {
816        let mut raw_vec = vec![];
817        for _ in 0..u16::max_value() {
818            raw_vec.push(0);
819        }
820        let expected = Unpacked::Raw(raw_vec);
821        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
822
823        let mut raw_vec = vec![];
824        for _ in 0..u16::max_value() {
825            raw_vec.push(0);
826        }
827        raw_vec.push(0);
828        let expected = Unpacked::Raw(raw_vec);
829        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
830    }
831
832    #[test]
833    fn pack_str() {
834        let mut s = String::from("");
835        for _ in 0..u16::max_value() {
836            s.push('a');
837        }
838        let expected = Unpacked::String(s);
839        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
840
841        let mut s = String::from("");
842        for _ in 0..u16::max_value() {
843            s.push('a');
844        }
845        s.push('a');
846        let expected = Unpacked::String(s);
847        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
848    }
849
850    #[test]
851    fn pack_arr() {
852        let mut v = vec![];
853        for _ in 0..u16::max_value() {
854            v.push(Unpacked::Null);
855        }
856        let expected = Unpacked::Array(v);
857        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
858
859        let mut v = vec![];
860        for _ in 0..u16::max_value() {
861            v.push(Unpacked::Null);
862        }
863        v.push(Unpacked::Null);
864        let expected = Unpacked::Array(v);
865        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
866    }
867
868    #[test]
869    fn pack_map() {
870        let mut m = HashMap::new();
871        for i in 0..u16::max_value() {
872            m.insert(Unpacked::Uint32(i as u32), Unpacked::Null);
873        }
874        let expected = Unpacked::Map(m);
875        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
876
877        let mut m = HashMap::new();
878        for i in 0..u16::max_value() {
879            m.insert(Unpacked::Uint32(i as u32), Unpacked::Null);
880        }
881        m.insert(Unpacked::Uint32(u16::max_value as u32 + 1), Unpacked::Null);
882        let expected = Unpacked::Map(m);
883        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
884    }
885
886    #[test]
887    fn pack_null() {
888        let expected = Unpacked::Null;
889        assert_eq!(Unpacker::new(&expected.pack()).unpack().unwrap(), expected);
890    }
891
892    #[test]
893    fn pack_undefined() {
894        let expected = Unpacked::Undefined;
895        assert!(Unpacker::new(&expected.pack())
896            .unpack()
897            .unwrap()
898            .is_undefined());
899    }
900}