Skip to main content

php_std/
igbinary.rs

1//! `igbinary_serialize` and `igbinary_unserialize`, byte-identical to the
2//! igbinary extension (3.2, format version 2, `igbinary.compact_strings=On`)
3//! of the PHP image. Appwrite's cache and queue payloads use it.
4//!
5//! | PHP | Rust |
6//! |---|---|
7//! | `igbinary_serialize($v)` | [`serialize`] |
8//! | `igbinary_unserialize($s)` | [`unserialize`] (strings share the input buffer) |
9//! | its warnings (`igbinary_unserialize_*: ...`) | [`Error::Invalid`] |
10//!
11//! The format: a 4-byte version header (`00 00 00 02`), then one value.
12//! Integers take the smallest of 1, 2, 4 or 8 bytes with the sign in the
13//! type; floats are IEEE 754 big-endian; every non-empty string (values,
14//! keys, class names) is written once and referenced by its index after
15//! that; arrays and objects are a count and key/value pairs; containers
16//! get a reference id in pre-order for back-references.
17//!
18//! Identity: PHP writes a back-reference when the same array or object
19//! instance appears twice, which a [`Value`] (no identity) cannot know. The
20//! engine shares one immutable empty array (`[]` literals, `json_decode`,
21//! `unserialize`, `igbinary_unserialize`), so [`serialize`] writes every
22//! empty array after the first as a back-reference to it, as PHP does for
23//! such data. Back-references PHP wrote for other shared instances or PHP
24//! references read as copies, and are written in full again.
25//! Objects of other classes (`__PHP_Incomplete_Class` in PHP), recursive
26//! structures and nesting deeper than [`MAX_DEPTH`] are [`Error::Unsupported`].
27
28use std::collections::HashMap;
29use std::fmt;
30
31use bytes::Bytes;
32
33use crate::types::{Array, ArrayKey, Extension, KeyRef, Str, Value};
34
35const NULL: u8 = 0x00;
36const REF8: u8 = 0x01;
37const REF16: u8 = 0x02;
38const REF32: u8 = 0x03;
39const FALSE: u8 = 0x04;
40const TRUE: u8 = 0x05;
41const LONG8P: u8 = 0x06;
42const LONG8N: u8 = 0x07;
43const LONG16P: u8 = 0x08;
44const LONG16N: u8 = 0x09;
45const LONG32P: u8 = 0x0a;
46const LONG32N: u8 = 0x0b;
47const DOUBLE: u8 = 0x0c;
48const STRING_EMPTY: u8 = 0x0d;
49const STRING_ID8: u8 = 0x0e;
50const STRING_ID16: u8 = 0x0f;
51const STRING_ID32: u8 = 0x10;
52const STRING8: u8 = 0x11;
53const STRING16: u8 = 0x12;
54const STRING32: u8 = 0x13;
55const ARRAY8: u8 = 0x14;
56const ARRAY16: u8 = 0x15;
57const ARRAY32: u8 = 0x16;
58const OBJECT8: u8 = 0x17;
59const OBJECT16: u8 = 0x18;
60const OBJECT32: u8 = 0x19;
61const OBJECT_ID8: u8 = 0x1a;
62const OBJECT_ID16: u8 = 0x1b;
63const OBJECT_ID32: u8 = 0x1c;
64const LONG64P: u8 = 0x20;
65const LONG64N: u8 = 0x21;
66const OBJREF8: u8 = 0x22;
67const OBJREF16: u8 = 0x23;
68const OBJREF32: u8 = 0x24;
69const REF: u8 = 0x25;
70const STRING64: u8 = 0x26;
71
72/// Nesting deeper than this is refused when reading (PHP recurses without a
73/// limit and exhausts its stack eventually).
74pub const MAX_DEPTH: usize = 4096;
75
76// ---------------------------------------------------------------------------
77// igbinary_serialize
78// ---------------------------------------------------------------------------
79
80/// `igbinary_serialize($value)`.
81pub fn serialize<X: Extension>(value: &Value<X>) -> Vec<u8> {
82    let mut s = Serializer {
83        out: Vec::with_capacity(512),
84        strings: HashMap::with_capacity_and_hasher(32, Default::default()),
85        references: 0,
86        empty_array: None,
87    };
88    s.out.extend_from_slice(&[0, 0, 0, 2]);
89    s.value(value, Borrowed);
90    s.out
91}
92
93/// A string of the table: borrowed from the value being serialized, or
94/// owned when it comes from a temporary (an extension's array form).
95/// Hashes and compares as its bytes, so the table is queried with `&[u8]`.
96enum Entry<'v> {
97    Borrowed(&'v [u8]),
98    Owned(Str),
99}
100
101impl Entry<'_> {
102    fn bytes(&self) -> &[u8] {
103        match self {
104            Entry::Borrowed(b) => b,
105            Entry::Owned(s) => s.as_bytes(),
106        }
107    }
108}
109
110impl PartialEq for Entry<'_> {
111    fn eq(&self, other: &Self) -> bool {
112        self.bytes() == other.bytes()
113    }
114}
115
116impl Eq for Entry<'_> {}
117
118impl std::hash::Hash for Entry<'_> {
119    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
120        self.bytes().hash(state);
121    }
122}
123
124impl std::borrow::Borrow<[u8]> for Entry<'_> {
125    fn borrow(&self) -> &[u8] {
126        self.bytes()
127    }
128}
129
130/// How a string of a value of lifetime `'x` enters a table of lifetime `'v`.
131trait Keep<'x, 'v>: Copy {
132    fn keep(self, s: &'x [u8]) -> Entry<'v>;
133}
134
135/// The value outlives the table: strings are borrowed.
136#[derive(Clone, Copy)]
137struct Borrowed;
138
139impl<'x: 'v, 'v> Keep<'x, 'v> for Borrowed {
140    fn keep(self, s: &'x [u8]) -> Entry<'v> {
141        Entry::Borrowed(s)
142    }
143}
144
145/// A temporary: strings are copied.
146#[derive(Clone, Copy)]
147struct Owned;
148
149impl<'v> Keep<'_, 'v> for Owned {
150    fn keep(self, s: &[u8]) -> Entry<'v> {
151        Entry::Owned(Str::copy_from(s))
152    }
153}
154
155struct Serializer<'v> {
156    out: Vec<u8>,
157    /// The string table: each non-empty string's index.
158    strings: HashMap<Entry<'v>, u32, foldhash::fast::RandomState>,
159    /// Reference ids handed out (arrays and objects, in pre-order).
160    references: u32,
161    /// The id of the shared empty array, once written.
162    empty_array: Option<u32>,
163}
164
165impl<'v> Serializer<'v> {
166    fn sized(&mut self, n: u64, t8: u8, t16: u8, t32: u8) {
167        if n <= 0xff {
168            self.out.extend_from_slice(&[t8, n as u8]);
169        } else if n <= 0xffff {
170            self.out.push(t16);
171            self.out.extend_from_slice(&(n as u16).to_be_bytes());
172        } else {
173            self.out.push(t32);
174            self.out.extend_from_slice(&(n as u32).to_be_bytes());
175        }
176    }
177
178    fn long(&mut self, i: i64) {
179        let (m, p) = (i.unsigned_abs(), i >= 0);
180        if m <= 0xffff_ffff {
181            if p { self.sized(m, LONG8P, LONG16P, LONG32P) } else { self.sized(m, LONG8N, LONG16N, LONG32N) }
182        } else {
183            self.out.push(if p { LONG64P } else { LONG64N });
184            self.out.extend_from_slice(&m.to_be_bytes());
185        }
186    }
187
188    /// `igbinary_serialize_string`: the empty string, an index into the
189    /// table, or the bytes (which join the table).
190    fn string<'x, K: Keep<'x, 'v>>(&mut self, s: &'x [u8], keep: K) {
191        if s.is_empty() {
192            self.out.push(STRING_EMPTY);
193            return;
194        }
195        // One hash per string, found or added.
196        let next = self.strings.len() as u32;
197        match self.strings.entry(keep.keep(s)) {
198            std::collections::hash_map::Entry::Occupied(e) => {
199                let id = *e.get();
200                self.sized(u64::from(id), STRING_ID8, STRING_ID16, STRING_ID32);
201            }
202            std::collections::hash_map::Entry::Vacant(e) => {
203                e.insert(next);
204                self.chararray(s, STRING8, STRING16, STRING32);
205            }
206        }
207    }
208
209    fn chararray(&mut self, s: &[u8], t8: u8, t16: u8, t32: u8) {
210        self.sized(s.len() as u64, t8, t16, t32);
211        self.out.extend_from_slice(s);
212    }
213
214    fn value<'x, X: Extension, K: Keep<'x, 'v>>(&mut self, value: &'x Value<X>, keep: K) {
215        match value {
216            Value::Null => self.out.push(NULL),
217            Value::Bool(b) => self.out.push(if *b { TRUE } else { FALSE }),
218            Value::Int(i) => self.long(*i),
219            Value::Float(f) => {
220                self.out.push(DOUBLE);
221                self.out.extend_from_slice(&f.to_bits().to_be_bytes());
222            }
223            Value::Str(s) => self.string(s.as_bytes(), keep),
224            Value::Array(a) => self.array(a, keep),
225            Value::Ext(x) => self.array(&x.to_array(), Owned),
226            Value::Object(props) => {
227                self.references += 1;
228                const STD_CLASS: &[u8] = b"stdClass";
229                match self.strings.get(STD_CLASS) {
230                    Some(&id) => self.sized(u64::from(id), OBJECT_ID8, OBJECT_ID16, OBJECT_ID32),
231                    None => {
232                        let id = self.strings.len() as u32;
233                        self.strings.insert(Entry::Borrowed(STD_CLASS), id);
234                        self.chararray(STD_CLASS, OBJECT8, OBJECT16, OBJECT32);
235                    }
236                }
237                self.entries(props, keep);
238            }
239        }
240    }
241
242    fn array<'x, X: Extension, K: Keep<'x, 'v>>(&mut self, a: &'x Array<X>, keep: K) {
243        if a.is_empty() {
244            if let Some(id) = self.empty_array {
245                self.sized(u64::from(id), REF8, REF16, REF32);
246                return;
247            }
248            self.empty_array = Some(self.references);
249        }
250        self.references += 1;
251        self.entries(a, keep);
252    }
253
254    fn entries<'x, X: Extension, K: Keep<'x, 'v>>(&mut self, a: &'x Array<X>, keep: K) {
255        self.sized(a.len() as u64, ARRAY8, ARRAY16, ARRAY32);
256        for (k, v) in a.iter() {
257            match k {
258                KeyRef::Int(i) => self.long(i),
259                KeyRef::Str(s) => self.string(s, keep),
260            }
261            self.value(v, keep);
262        }
263    }
264}
265
266// ---------------------------------------------------------------------------
267// igbinary_unserialize
268// ---------------------------------------------------------------------------
269
270/// Why `igbinary_unserialize()` failed.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub enum Error {
273    /// Empty input: PHP returns `false` without a warning.
274    Empty,
275    /// PHP returns `null` after this warning.
276    Invalid(String),
277    /// Data PHP reads into something [`Value`] cannot hold: objects of other
278    /// classes, recursive structures, or nesting deeper than [`MAX_DEPTH`].
279    Unsupported(&'static str),
280}
281
282impl Error {
283    /// The PHP class of the failure (`igbinary_unserialize` warns, it never throws).
284    pub fn php_class(&self) -> &'static str {
285        "Error"
286    }
287}
288
289impl fmt::Display for Error {
290    /// Writes the warning PHP emits.
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        match self {
293            Error::Empty => f.write_str("igbinary_unserialize(): empty input"),
294            Error::Invalid(warning) => f.write_str(warning),
295            Error::Unsupported(what) => write!(f, "igbinary_unserialize(): unsupported data: {what}"),
296        }
297    }
298}
299
300impl std::error::Error for Error {}
301
302/// `igbinary_unserialize($data)`. Strings longer than an inline string
303/// share `input`'s buffer.
304pub fn unserialize(input: &Bytes) -> Result<Value, Error> {
305    if input.is_empty() {
306        return Err(Error::Empty);
307    }
308    header(input)?;
309    Unserializer::new(input).run()
310}
311
312/// `igbinary_unserialize_header`.
313fn header(b: &[u8]) -> Result<(), Error> {
314    if b.len() < 5 {
315        return Err(Error::Invalid(format!(
316            "igbinary_unserialize_header: expected at least 5 bytes of data, got {} byte(s)",
317            b.len()
318        )));
319    }
320    let version = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
321    if version == 1 || version == 2 {
322        return Ok(());
323    }
324    // C `isprint` in the C locale.
325    if b[..4].iter().any(|&c| !(0x20..0x7f).contains(&c)) {
326        let hint = if version != 0 && version & 0xff00_0000 == version { " (wrong endianness?)" } else { "" };
327        return Err(Error::Invalid(format!(
328            "igbinary_unserialize_header: unsupported version: {version}, should be 1 or 2{hint}"
329        )));
330    }
331    let mut shown = String::new();
332    for &c in &b[..4] {
333        if c == b'"' || c == b'\\' {
334            shown.push('\\');
335        }
336        shown.push(char::from(c));
337    }
338    Err(Error::Invalid(format!(
339        "igbinary_unserialize_header: unsupported version: \"{shown}\"..., should begin with a binary version header of \"\\x00\\x00\\x00\\x01\" or \"\\x00\\x00\\x00\\x02\""
340    )))
341}
342
343/// A slot of the reference table.
344#[derive(Clone)]
345enum Slot {
346    /// A container still being read.
347    Open,
348    /// A container read: where it starts (its type byte), and the strings
349    /// and slots before it, so a back-reference reads it again from there
350    /// (rare, so cheaper than keeping a copy of every container).
351    At { pos: usize, strings: usize, slot: usize },
352    /// A scalar that follows a `REF` marker.
353    Value(Value),
354}
355
356struct Unserializer<'a> {
357    input: &'a Bytes,
358    pos: usize,
359    /// The string table: where each string is in the input.
360    strings: Vec<(usize, usize)>,
361    references: Vec<Slot>,
362    /// The pairs of the arrays being read, innermost last.
363    entries: Vec<(ArrayKey, Value)>,
364    depth: usize,
365}
366
367fn invalid<T>(message: impl Into<String>) -> Result<T, Error> {
368    Err(Error::Invalid(message.into()))
369}
370
371impl<'a> Unserializer<'a> {
372    fn new(input: &'a Bytes) -> Self {
373        Unserializer {
374            input,
375            pos: 4,
376            // Room for what typical data holds, without growing.
377            strings: Vec::with_capacity((input.len() / 8).min(256)),
378            references: Vec::with_capacity((input.len() / 64).min(16)),
379            entries: Vec::with_capacity((input.len() / 8).min(64)),
380            depth: 0,
381        }
382    }
383
384    fn run(&mut self) -> Result<Value, Error> {
385        let value = self.value(false)?;
386        if self.pos < self.input.len() {
387            return invalid("igbinary_unserialize: received more data to unserialize than expected");
388        }
389        Ok(value)
390    }
391
392    fn remaining(&self) -> usize {
393        self.input.len() - self.pos
394    }
395
396    /// An unsigned big-endian number of `n` bytes, or `end-of-data` from `func`.
397    fn uint(&mut self, n: usize, func: &str) -> Result<u64, Error> {
398        if self.remaining() < n {
399            return invalid(format!("{func}: end-of-data"));
400        }
401        if n == 1 {
402            self.pos += 1;
403            return Ok(u64::from(self.input[self.pos - 1]));
404        }
405        let mut v = 0u64;
406        for &b in &self.input[self.pos..self.pos + n] {
407            v = v << 8 | u64::from(b);
408        }
409        self.pos += n;
410        Ok(v)
411    }
412
413    fn size_of(t: u8, t8: u8, t16: u8) -> usize {
414        if t == t8 {
415            1
416        } else if t == t16 {
417            2
418        } else {
419            4
420        }
421    }
422
423    fn long(&mut self, t: u8) -> Result<i64, Error> {
424        let n = match t {
425            LONG8P | LONG8N => 1,
426            LONG16P | LONG16N => 2,
427            LONG32P | LONG32N => 4,
428            _ => 8,
429        };
430        let m = self.uint(n, "igbinary_unserialize_long")?;
431        Ok(if matches!(t, LONG8P | LONG16P | LONG32P | LONG64P) { m as i64 } else { (m as i64).wrapping_neg() })
432    }
433
434    /// `igbinary_unserialize_chararray`: a new string, added to the table.
435    fn chararray(&mut self, t: u8) -> Result<Str, Error> {
436        let n = match t {
437            STRING8 | OBJECT8 => 1,
438            STRING16 | OBJECT16 => 2,
439            STRING32 | OBJECT32 => 4,
440            _ => 8,
441        };
442        let len = self.uint(n, "igbinary_unserialize_chararray")?;
443        if (self.remaining() as u64) < len {
444            return invalid("igbinary_unserialize_chararray: end-of-data");
445        }
446        let (start, end) = (self.pos, self.pos + len as usize);
447        self.pos = end;
448        self.strings.push((start, end));
449        Ok(Str::share(self.input, start..end))
450    }
451
452    /// `igbinary_unserialize_string`: a string from the table.
453    fn string_id(&mut self, n: usize) -> Result<Str, Error> {
454        let id = self.uint(n, "igbinary_unserialize_string")? as usize;
455        match self.strings.get(id) {
456            Some(&(start, end)) => Ok(Str::share(self.input, start..end)),
457            None => invalid("igbinary_unserialize_string: string index is out-of-bounds"),
458        }
459    }
460
461    /// A string of any of the string types, or `None` if `t` is not one.
462    fn any_string(&mut self, t: u8) -> Result<Option<Str>, Error> {
463        Ok(Some(match t {
464            STRING_EMPTY => Str::EMPTY,
465            STRING8 | STRING16 | STRING32 | STRING64 => self.chararray(t)?,
466            STRING_ID8 | STRING_ID16 | STRING_ID32 => self.string_id(Self::size_of(t, STRING_ID8, STRING_ID16))?,
467            _ => return Ok(None),
468        }))
469    }
470
471    fn byte(&mut self, func: &str) -> Result<u8, Error> {
472        match self.input.get(self.pos) {
473            Some(&b) => {
474                self.pos += 1;
475                Ok(b)
476            }
477            None => invalid(format!("{func}: end-of-data")),
478        }
479    }
480
481    /// Opens a reference slot for a container (or a referenced scalar).
482    fn open(&mut self) -> usize {
483        self.references.push(Slot::Open);
484        self.references.len() - 1
485    }
486
487    /// Closes a scalar's slot, keeping its value for back-references.
488    fn close(&mut self, id: usize, value: &Value) {
489        self.references[id] = Slot::Value(value.clone());
490    }
491
492    /// Closes a container's slot: `start` is where it began (its type byte)
493    /// and the size of the string table there.
494    fn close_at(&mut self, id: usize, (pos, strings): (usize, usize)) {
495        self.references[id] = Slot::At { pos, strings, slot: id };
496    }
497
498    /// `igbinary_unserialize_ref`: a copy of the value at a reference id.
499    fn back_reference(&mut self, n: usize) -> Result<Value, Error> {
500        let id = self.uint(n, "igbinary_unserialize_ref")? as usize;
501        match self.references.get(id) {
502            None => invalid(format!("igbinary_unserialize_ref: invalid reference {id} >= {}", self.references.len())),
503            Some(Slot::Open) => Err(Error::Unsupported("a reference to a container that is still being read")),
504            Some(Slot::Value(v)) => Ok(v.clone()),
505            Some(&Slot::At { pos, strings, slot }) => {
506                // Read again with the tables as they stood: the same value.
507                let mut again = Unserializer {
508                    input: self.input,
509                    pos,
510                    strings: self.strings[..strings].to_vec(),
511                    references: self.references[..slot].to_vec(),
512                    entries: Vec::new(),
513                    depth: self.depth,
514                };
515                again.value(false)
516            }
517        }
518    }
519
520    /// `igbinary_unserialize_zval`. `referenced`: the value follows a `REF`
521    /// marker, so a scalar gets a reference slot.
522    fn value(&mut self, referenced: bool) -> Result<Value, Error> {
523        let start = (self.pos, self.strings.len());
524        let t = self.byte("igbinary_unserialize_zval")?;
525        let scalar = |u: &mut Self, v: Value| {
526            if referenced {
527                let id = u.open();
528                u.close(id, &v);
529            }
530            Ok(v)
531        };
532        match t {
533            NULL => scalar(self, Value::Null),
534            FALSE => scalar(self, Value::Bool(false)),
535            TRUE => scalar(self, Value::Bool(true)),
536            LONG8P | LONG8N | LONG16P | LONG16N | LONG32P | LONG32N | LONG64P | LONG64N => {
537                let i = self.long(t)?;
538                scalar(self, Value::Int(i))
539            }
540            DOUBLE => {
541                let bits = self.uint(8, "igbinary_unserialize_double")?;
542                scalar(self, Value::Float(f64::from_bits(bits)))
543            }
544            STRING_EMPTY | STRING8 | STRING16 | STRING32 | STRING64 | STRING_ID8 | STRING_ID16 | STRING_ID32 => {
545                let s = self.any_string(t)?.unwrap_or_default();
546                scalar(self, Value::Str(s))
547            }
548            REF8 | REF16 | REF32 => self.back_reference(Self::size_of(t, REF8, REF16)),
549            OBJREF8 | OBJREF16 | OBJREF32 => self.back_reference(Self::size_of(t, OBJREF8, OBJREF16)),
550            REF => self.value(true),
551            ARRAY8 | ARRAY16 | ARRAY32 => {
552                let id = self.open();
553                let a = self.entries(t, false)?;
554                self.close_at(id, start);
555                Ok(Value::Array(a))
556            }
557            OBJECT8 | OBJECT16 | OBJECT32 | OBJECT_ID8 | OBJECT_ID16 | OBJECT_ID32 => {
558                let class = match t {
559                    OBJECT8 | OBJECT16 | OBJECT32 => self.chararray(t)?,
560                    _ => self.string_id(Self::size_of(t, OBJECT_ID8, OBJECT_ID16))?,
561                };
562                let id = self.open();
563                let inner = self.byte("igbinary_unserialize_object")?;
564                if !matches!(inner, ARRAY8 | ARRAY16 | ARRAY32) {
565                    return invalid(format!(
566                        "igbinary_unserialize_object: unknown object inner type '{inner:02x}', position {}",
567                        self.pos
568                    ));
569                }
570                let props = self.entries(inner, true)?;
571                if !class.eq_ignore_ascii_case(b"stdClass") {
572                    return Err(Error::Unsupported("an object of a class other than stdClass"));
573                }
574                self.close_at(id, start);
575                Ok(Value::Object(props))
576            }
577            _ => invalid(format!("igbinary_unserialize_zval: unknown type '{t:02x}', position {}", self.pos)),
578        }
579    }
580
581    /// `igbinary_unserialize_array` after its type byte: count, then pairs.
582    /// Object properties keep integer keys as strings.
583    fn entries(&mut self, t: u8, object: bool) -> Result<Array, Error> {
584        let n = self.uint(Self::size_of(t, ARRAY8, ARRAY16), "igbinary_unserialize_array")? as usize;
585        if self.remaining() < n {
586            return invalid(format!(
587                "igbinary_unserialize_array: data size {} smaller that requested array length {n}.",
588                self.remaining()
589            ));
590        }
591        self.depth += 1;
592        if self.depth > MAX_DEPTH {
593            return Err(Error::Unsupported("nesting deeper than igbinary::MAX_DEPTH"));
594        }
595        let start = self.entries.len();
596        for _ in 0..n {
597            let kt = self.byte("igbinary_unserialize_array")?;
598            let key = match kt {
599                NULL => continue,
600                LONG8P | LONG8N | LONG16P | LONG16N | LONG32P | LONG32N | LONG64P | LONG64N => {
601                    let i = self.long(kt)?;
602                    if object { ArrayKey::Str(Str::from(i.to_string())) } else { ArrayKey::Int(i) }
603                }
604                _ => match self.any_string(kt)? {
605                    Some(s) => ArrayKey::Str(s),
606                    None => {
607                        return invalid(format!(
608                            "igbinary_unserialize_array: unknown key type '{kt:02x}', position {}",
609                            self.pos
610                        ));
611                    }
612                },
613            };
614            let v = self.value(false)?;
615            self.entries.push((key, v));
616        }
617        self.depth -= 1;
618        // Each pair assigned in order (a repeated key keeps its place).
619        Ok(self.entries.drain(start..).collect())
620    }
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626    use crate::types::Never;
627    use serde_json::json;
628
629    fn hex(b: &[u8]) -> String {
630        b.iter().map(|b| format!("{b:02x}")).collect()
631    }
632
633    #[test]
634    fn back_references_read_the_container_again() {
635        // [['s' => <30 bytes>, 'e' => []], <ref 1>, <ref 2: the empty array>]
636        let mut b = vec![0, 0, 0, 2, 0x14, 3, 0x06, 0, 0x14, 2, 0x11, 1, b's', 0x11, 30];
637        b.extend_from_slice(b"abcdefghijklmnopqrstuvwxyz0123");
638        b.extend_from_slice(&[0x11, 1, b'e', 0x14, 0, 0x06, 1, 0x01, 1, 0x06, 2, 0x01, 2]);
639        let inner = json!({"s": "abcdefghijklmnopqrstuvwxyz0123", "e": []});
640        assert_eq!(unserialize(&Bytes::from(b)).unwrap().to_json(), json!([inner, inner, []]));
641        // A reference to a container still being read.
642        let b = Bytes::from_static(&[0, 0, 0, 2, 0x14, 1, 0x06, 0, 0x01, 0]);
643        assert!(matches!(unserialize(&b), Err(Error::Unsupported(_))));
644    }
645
646    fn ser(j: serde_json::Value) -> String {
647        hex(&serialize(&Value::<Never>::from_json(&j)))
648    }
649
650    #[test]
651    fn serializes_like_the_extension() {
652        assert_eq!(ser(json!(null)), "0000000200");
653        assert_eq!(ser(json!(-257)), "00000002090101");
654        assert_eq!(ser(json!(4294967296i64)), "00000002200000000100000000");
655        assert_eq!(hex(&serialize(&Value::<Never>::Int(i64::MIN))), "00000002218000000000000000");
656        assert_eq!(ser(json!(1.5)), "000000020c3ff8000000000000");
657        assert_eq!(
658            ser(json!({"a": 1, "b": "a", "c": "abc", "abc": "b"})),
659            "00000002140411016106011101620e0011016311036162630e030e01"
660        );
661        assert_eq!(
662            ser(json!([[], [], {"a": []}, {}])),
663            "000000021404060014000601010106021401110161010106031708737464436c6173731400"
664        );
665        assert_eq!(ser(json!({"": 1, "x": ""})), "0000000214020d06011101780d");
666    }
667
668    #[test]
669    fn round_trips_and_reads_back_references() {
670        let b = Bytes::from(serialize(&Value::<Never>::from_json(&json!([{"k": [1, 2]}, [], [], "k", {}]))));
671        assert_eq!(serialize(&unserialize(&b).unwrap()), b.as_ref());
672        // [$a, $a] with $a = [1, 2]: the second is a back-reference.
673        let shared = Bytes::from_static(
674            b"\x00\x00\x00\x02\x14\x02\x06\x00\x14\x02\x06\x00\x06\x01\x06\x01\x06\x02\x06\x01\x01\x01",
675        );
676        assert_eq!(unserialize(&shared).unwrap().to_json(), json!([[1, 2], [1, 2]]));
677        let reference = Bytes::from_static(b"\x00\x00\x00\x02\x14\x02\x06\x00\x25\x06\x01\x06\x01\x25\x01\x01");
678        assert_eq!(unserialize(&reference).unwrap().to_json(), json!([1, 1]));
679    }
680
681    #[test]
682    fn errors_like_the_extension() {
683        let err = |b: &'static [u8]| match unserialize(&Bytes::from_static(b)) {
684            Err(Error::Invalid(m)) => m,
685            other => panic!("{other:?}"),
686        };
687        assert_eq!(unserialize(&Bytes::new()), Err(Error::Empty));
688        assert_eq!(
689            err(b"\x00\x00\x00\x02"),
690            "igbinary_unserialize_header: expected at least 5 bytes of data, got 4 byte(s)"
691        );
692        assert_eq!(
693            err(b"\x00\x00\x00\x03\x00"),
694            "igbinary_unserialize_header: unsupported version: 3, should be 1 or 2"
695        );
696        assert_eq!(err(b"\x00\x00\x00\x02\xff"), "igbinary_unserialize_zval: unknown type 'ff', position 5");
697        assert_eq!(
698            err(b"\x00\x00\x00\x02\x14\x05\x06\x00"),
699            "igbinary_unserialize_array: data size 2 smaller that requested array length 5."
700        );
701        assert_eq!(err(b"\x00\x00\x00\x02\x01\x00"), "igbinary_unserialize_ref: invalid reference 0 >= 0");
702        assert!(matches!(
703            unserialize(&Bytes::from_static(b"\x00\x00\x00\x02\x14\x01\x06\x00\x01\x00")),
704            Err(Error::Unsupported(_))
705        ));
706    }
707}