Skip to main content

php_std/
serialize.rs

1//! `serialize`, `unserialize` and `var_export`, in PHP 8.5's formats.
2//!
3//! | PHP | Rust |
4//! |---|---|
5//! | `serialize($value)` | [`serialize`] ([`Value`]) |
6//! | `unserialize($data, ['max_depth' => $n])` | [`unserialize`], [`Options`] |
7//! | `var_export($value, true)` | [`var_export`] |
8//! | warnings `unserialize()` emits | [`Unserialized::warnings`], [`Error::Failed`] |
9//!
10//! Values are scalars, arrays and `stdClass` objects. Floats use
11//! `serialize_precision = -1` (`d:0.1;`, `d:1.0E+25;`, `d:INF;`). An
12//! [`Value::Ext`] object is written as its [`Extension::to_array`] (PHP code
13//! serializes `getArrayCopy()`, not the object).
14//!
15//! `unserialize` reads every format PHP writes for those values (`N`, `b`,
16//! `i`, `d`, `s`, `S`, `a`, `O`/`C` of `stdClass`, and the `r`/`R`
17//! back-references), with PHP's error offsets, warnings and depth limit.
18//! Back-references resolve to the value at that slot when they are read,
19//! which is what PHP produces for data `serialize` writes; [`Value`] has no
20//! references or object identity, so they become copies. Objects of other
21//! classes, enums (`E:`), and back-references to a container that is still
22//! being read (recursive structures) cannot be represented and fail with
23//! [`Error::Unsupported`].
24
25use std::cell::RefCell;
26use std::collections::HashMap;
27use std::fmt;
28
29use indexmap::IndexMap;
30
31use crate::json::push_int;
32use crate::number;
33use crate::types::{Array, ArrayKey, Builder, Extension, KeyRef, Str, Value};
34
35// ---------------------------------------------------------------------------
36// serialize (ext/standard/var.c)
37// ---------------------------------------------------------------------------
38
39/// `serialize($value)`: PHP's byte string.
40pub fn serialize<X: Extension>(value: &Value<X>) -> Vec<u8> {
41    let mut out = Vec::with_capacity(128);
42    serialize_into(&mut out, value);
43    out
44}
45
46/// `serialize($value)`, appended to `out`.
47pub fn serialize_into<X: Extension>(out: &mut Vec<u8>, value: &Value<X>) {
48    match value {
49        Value::Null => out.extend_from_slice(b"N;"),
50        Value::Bool(b) => out.extend_from_slice(if *b { b"b:1;" } else { b"b:0;" }),
51        Value::Int(i) => {
52            out.extend_from_slice(b"i:");
53            push_int(out, *i);
54            out.push(b';');
55        }
56        Value::Float(f) => {
57            out.extend_from_slice(b"d:");
58            number::gcvt_into(out, *f, -1, b'E');
59            out.push(b';');
60        }
61        Value::Str(s) => serialize_string(out, s),
62        Value::Array(a) => {
63            out.extend_from_slice(b"a:");
64            nested(out, a);
65        }
66        Value::Object(a) => {
67            out.extend_from_slice(b"O:8:\"stdClass\":");
68            nested(out, a);
69        }
70        Value::Ext(x) => {
71            out.extend_from_slice(b"a:");
72            nested(out, &x.to_array());
73        }
74    }
75}
76
77fn serialize_string(out: &mut Vec<u8>, s: &[u8]) {
78    out.extend_from_slice(b"s:");
79    push_int(out, s.len() as i64);
80    out.extend_from_slice(b":\"");
81    out.extend_from_slice(s);
82    out.extend_from_slice(b"\";");
83}
84
85/// `php_var_serialize_nested_data`.
86fn nested<X: Extension>(out: &mut Vec<u8>, entries: &Array<X>) {
87    push_int(out, entries.len() as i64);
88    out.extend_from_slice(b":{");
89    for (key, value) in entries.iter() {
90        match key {
91            KeyRef::Int(i) => {
92                out.extend_from_slice(b"i:");
93                push_int(out, i);
94                out.push(b';');
95            }
96            KeyRef::Str(s) => serialize_string(out, s),
97        }
98        serialize_into(out, value);
99    }
100    out.push(b'}');
101}
102
103// ---------------------------------------------------------------------------
104// var_export (ext/standard/var.c)
105// ---------------------------------------------------------------------------
106
107/// `var_export($value, true)`: PHP source code for the value, as bytes
108/// (string contents are copied verbatim).
109pub fn var_export<X: Extension>(value: &Value<X>) -> Vec<u8> {
110    let mut out = Vec::new();
111    export(&mut out, value, 1);
112    out
113}
114
115/// `buffer_append_spaces`: `%*c` with a space, so never fewer than one.
116fn spaces(out: &mut Vec<u8>, n: usize) {
117    out.resize(out.len() + n.max(1), b' ');
118}
119
120/// A single-quoted PHP string literal: `'` and `\` escaped, NUL bytes as
121/// `' . "\0" . '` when `nul` is set.
122fn quoted(out: &mut Vec<u8>, s: &[u8], nul: bool) {
123    out.push(b'\'');
124    for &c in s {
125        match c {
126            b'\'' | b'\\' => out.extend_from_slice(&[b'\\', c]),
127            0 if nul => out.extend_from_slice(b"' . \"\\0\" . '"),
128            _ => out.push(c),
129        }
130    }
131    out.push(b'\'');
132}
133
134/// `php_var_export_ex`.
135fn export<X: Extension>(out: &mut Vec<u8>, value: &Value<X>, level: usize) {
136    match value {
137        Value::Null => out.extend_from_slice(b"NULL"),
138        Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
139        Value::Int(i64::MIN) => out.extend_from_slice(b"-9223372036854775807-1"),
140        Value::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
141        Value::Float(f) => {
142            let f = *f;
143            let s = number::gcvt(f, -1, 'E');
144            out.extend_from_slice(s.as_bytes());
145            if f.is_finite() && !s.contains('.') {
146                out.extend_from_slice(b".0");
147            }
148        }
149        Value::Str(s) => quoted(out, s, true),
150        Value::Ext(x) => export(out, &Value::Array(x.to_array()), level),
151        Value::Array(entries) => {
152            if level > 1 {
153                out.push(b'\n');
154                spaces(out, level - 1);
155            }
156            out.extend_from_slice(b"array (\n");
157            for (key, v) in entries.iter() {
158                spaces(out, level + 1);
159                match key {
160                    KeyRef::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
161                    KeyRef::Str(k) => quoted(out, k, true),
162                }
163                out.extend_from_slice(b" => ");
164                export(out, v, level + 2);
165                out.extend_from_slice(b",\n");
166            }
167            if level > 1 {
168                spaces(out, level - 1);
169            }
170            out.push(b')');
171        }
172        Value::Object(entries) => {
173            if level > 1 {
174                out.push(b'\n');
175                spaces(out, level - 1);
176            }
177            out.extend_from_slice(b"(object) array(\n");
178            for (key, v) in entries.iter() {
179                spaces(out, level + 2);
180                match key {
181                    KeyRef::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
182                    KeyRef::Str(k) => quoted(out, unmangle(k), false),
183                }
184                out.extend_from_slice(b" => ");
185                export(out, v, level + 2);
186                out.extend_from_slice(b",\n");
187            }
188            if level > 1 {
189                spaces(out, level - 1);
190            }
191            out.push(b')');
192        }
193    }
194}
195
196/// `zend_unmangle_property_name_ex`: the name after `"\0Class\0"` (or
197/// `"\0*\0"`); the whole name when it is not mangled.
198fn unmangle(name: &[u8]) -> &[u8] {
199    if name.len() < 2 || name[0] != 0 {
200        return name;
201    }
202    match name[1..].iter().position(|&c| c == 0) {
203        Some(i) => &name[i + 2..],
204        // A malformed mangled name: PHP keeps it whole.
205        None => name,
206    }
207}
208
209// ---------------------------------------------------------------------------
210// unserialize (ext/standard/var_unserializer.re)
211// ---------------------------------------------------------------------------
212
213/// `unserialize()` options.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct Options {
216    /// `max_depth`: arrays and objects nested deeper fail. `0` is unlimited;
217    /// the default is the `unserialize_max_depth` ini default, 4096.
218    pub max_depth: i64,
219}
220
221impl Default for Options {
222    /// The defaults: `max_depth` 4096.
223    fn default() -> Self {
224        Options { max_depth: 4096 }
225    }
226}
227
228/// A successful `unserialize()`: the value and the warnings PHP emitted
229/// (for example `unserialize(): Extra data starting at offset 4 of 5 bytes`).
230#[derive(Debug, Clone, PartialEq)]
231pub struct Unserialized {
232    /// The unserialized value.
233    pub value: Value,
234    /// The warnings PHP emitted, in order.
235    pub warnings: Vec<String>,
236}
237
238/// Why `unserialize()` failed.
239#[derive(Debug, Clone, PartialEq)]
240pub enum Error {
241    /// PHP returns `false` after emitting `warnings` (the last one is
242    /// `unserialize(): Error at offset X of Y bytes`, except for empty input,
243    /// which fails silently). `offset` is X.
244    Failed {
245        /// The byte offset PHP reports, if any.
246        offset: Option<usize>,
247        /// The warnings PHP emitted, in order.
248        warnings: Vec<String>,
249    },
250    /// An invalid option: PHP throws `ValueError` with this message.
251    Value(String),
252    /// Data PHP reads into something [`Value`] cannot hold: objects of other
253    /// classes (or `__PHP_Incomplete_Class`), enums, or a back-reference to
254    /// a container still being read (a recursive structure).
255    Unsupported(&'static str),
256}
257
258impl Error {
259    /// The PHP class of a thrown error (`ValueError`); `unserialize` reports
260    /// the other failures as warnings and `false`.
261    pub fn php_class(&self) -> &'static str {
262        match self {
263            Error::Value(_) => "ValueError",
264            Error::Failed { .. } | Error::Unsupported(_) => "Error",
265        }
266    }
267}
268
269impl fmt::Display for Error {
270    /// Writes the last warning, or the error message.
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        match self {
273            Error::Failed { warnings, .. } => {
274                f.write_str(warnings.last().map(String::as_str).unwrap_or("unserialize() failed"))
275            }
276            Error::Value(message) => f.write_str(message),
277            Error::Unsupported(what) => write!(f, "unserialize(): unsupported data: {what}"),
278        }
279    }
280}
281
282impl std::error::Error for Error {}
283
284/// `unserialize($data, $options)`.
285pub fn unserialize(data: &[u8], options: &Options) -> Result<Unserialized, Error> {
286    if data.is_empty() {
287        return Err(Error::Failed { offset: None, warnings: Vec::new() });
288    }
289    if options.max_depth < 0 {
290        return Err(Error::Value("unserialize(): Option \"max_depth\" must be greater than or equal to 0".into()));
291    }
292    let fresh = || Unserializer {
293        buf: data,
294        max_depth: options.max_depth,
295        cur_depth: 0,
296        slots: Vec::new(),
297        cells: Vec::new(),
298        warnings: Vec::new(),
299        opened: None,
300        unsupported: None,
301        built: RefCell::new(HashMap::new()),
302    };
303    // Data without back-references (what `serialize` writes for these
304    // values) is built directly; anything else, including every failure,
305    // is read again into locations, which back-references point at.
306    let mut u = fresh();
307    let mut p = 0;
308    if let Some(value) = u.direct(&mut p) {
309        if p < data.len() {
310            u.warn(format!("unserialize(): Extra data starting at offset {p} of {} bytes", data.len()));
311        }
312        if let Some(what) = u.unsupported {
313            return Err(Error::Unsupported(what));
314        }
315        return Ok(Unserialized { value, warnings: u.warnings });
316    }
317    let mut u = fresh();
318    // The root location.
319    u.cells.push(Cell::Null);
320    let mut p = 0;
321    match u.run(&mut p) {
322        Ok(true) => {}
323        Ok(false) => {
324            u.warn(format!("unserialize(): Error at offset {p} of {} bytes", data.len()));
325            return Err(Error::Failed { offset: Some(p), warnings: u.warnings });
326        }
327        Err(e) => return Err(e),
328    }
329    if p < data.len() {
330        u.warn(format!("unserialize(): Extra data starting at offset {p} of {} bytes", data.len()));
331    }
332    if let Some(what) = u.unsupported {
333        return Err(Error::Unsupported(what));
334    }
335    let value = u.materialize(0)?;
336    Ok(Unserialized { value, warnings: u.warnings })
337}
338
339/// A location values are read into (PHP's `zval *` slots): back-references
340/// point at locations, and a duplicate key reuses its location.
341type CellId = usize;
342
343enum Cell {
344    Null,
345    Value(Value),
346    Array {
347        entries: IndexMap<ArrayKey, CellId>,
348        done: bool,
349    },
350    Object {
351        props: IndexMap<Str, CellId>,
352        done: bool,
353    },
354    /// A back-reference that makes the value recursive (PHP shares the
355    /// referenced container): reading goes on, the result is unsupported.
356    Recursive(CellId),
357}
358
359struct Unserializer<'a> {
360    buf: &'a [u8],
361    max_depth: i64,
362    cur_depth: i64,
363    /// `var_hash`: the location of every value read so far, in order.
364    slots: Vec<CellId>,
365    cells: Vec<Cell>,
366    warnings: Vec<String>,
367    /// Set by [`Unserializer::value`] when it opened an array or object:
368    /// its element count and whether it is an object.
369    opened: Option<(i64, bool)>,
370    /// Why the value, once read, cannot be returned (an object of another class).
371    unsupported: Option<&'static str>,
372    /// The value each finished container materialized to, so that every back-reference
373    /// to it costs one clone (constant time: arrays are copy-on-write) rather than a
374    /// rebuild. A finished container never changes again, except when a duplicate key
375    /// reuses its location, which [`Unserializer::reset`] forgets here.
376    built: RefCell<HashMap<CellId, Value>>,
377}
378
379/// `HT_MAX_SIZE` on 64-bit platforms.
380const HT_MAX_SIZE: i64 = 0x4000_0000;
381
382/// What a key read produced (`php_var_unserialize_internal` without `var_hash`).
383enum KeyValue {
384    Int(i64),
385    Str(Str),
386    /// A value that cannot be a key (`N;`, `b:..;`, `d:..;`).
387    Other,
388}
389
390type Step = Result<bool, Error>;
391
392/// What [`Unserializer::read`] found at the cursor.
393enum Read {
394    /// A complete value.
395    Value(Value),
396    /// `R:` or `r:`, not read yet (the cursor has not moved).
397    Reference,
398    /// An array (or object) of this many elements, opened.
399    Open { elements: i64, object: bool },
400}
401
402impl Unserializer<'_> {
403    fn warn(&mut self, message: String) {
404        self.warnings.push(message);
405    }
406
407    /// The byte at `i`, or the NUL terminator after the data.
408    fn at(&self, i: usize) -> u8 {
409        self.buf.get(i).copied().unwrap_or(0)
410    }
411
412    fn digits_end(&self, mut i: usize) -> usize {
413        while self.at(i).is_ascii_digit() {
414            i += 1;
415        }
416        i
417    }
418
419    /// `parse_uiv`: `size_t` arithmetic, wrapping like C.
420    fn parse_uiv(&self, mut i: usize) -> u64 {
421        let mut result: u64 = 0;
422        while self.at(i).is_ascii_digit() {
423            result = result.wrapping_mul(10).wrapping_add(u64::from(self.at(i) - b'0'));
424            i += 1;
425        }
426        result
427    }
428
429    /// `parse_iv2`: an optional sign, leading zeros, digits; out of range
430    /// clamps with a warning. Returns the value and where the digits end.
431    fn parse_iv2(&mut self, mut i: usize) -> (i64, usize) {
432        let mut neg = false;
433        if self.at(i) == b'-' {
434            neg = true;
435            i += 1;
436        } else if self.at(i) == b'+' {
437            i += 1;
438        }
439        while self.at(i) == b'0' {
440            i += 1;
441        }
442        let start = i;
443        let mut result: u64 = 0;
444        while self.at(i).is_ascii_digit() {
445            result = result.wrapping_mul(10).wrapping_add(u64::from(self.at(i) - b'0'));
446            i += 1;
447        }
448        if i - start > 19 || result > i64::MAX as u64 + u64::from(neg) {
449            self.warn("unserialize(): Numerical result out of range".into());
450            return (if neg { i64::MIN } else { i64::MAX }, i);
451        }
452        (if neg { (result as i64).wrapping_neg() } else { result as i64 }, i)
453    }
454
455    /// Matches `uiv ";"` (or another terminator) at `i`: the end, after the terminator.
456    fn uiv_then(&self, i: usize, term: u8) -> Option<usize> {
457        let end = self.digits_end(i);
458        (end > i && self.at(end) == term).then_some(end + 1)
459    }
460
461    /// `iv = [+-]? [0-9]+` at `i`: where it ends.
462    fn iv(&self, mut i: usize) -> Option<usize> {
463        if matches!(self.at(i), b'+' | b'-') {
464            i += 1;
465        }
466        let end = self.digits_end(i);
467        (end > i).then_some(end)
468    }
469
470    /// `(iv | nv | nvexp)` at `i`: where the longest match ends.
471    fn number(&self, i: usize) -> Option<usize> {
472        let mut j = i;
473        if matches!(self.at(j), b'+' | b'-') {
474            j += 1;
475        }
476        let int_end = self.digits_end(j);
477        let mut end = None;
478        if int_end > j {
479            end = Some(int_end);
480        }
481        if self.at(int_end) == b'.' {
482            let frac_end = self.digits_end(int_end + 1);
483            // nv: digits* "." digits+ | digits+ "." digits*
484            if frac_end > int_end + 1 || int_end > j {
485                end = Some(frac_end);
486            }
487        }
488        let mantissa_end = end?;
489        if matches!(self.at(mantissa_end), b'e' | b'E')
490            && let Some(exp_end) = self.iv(mantissa_end + 1)
491        {
492            return Some(exp_end);
493        }
494        Some(mantissa_end)
495    }
496
497    fn set(&mut self, cell: CellId, value: Value) {
498        self.reset(cell, Cell::Value(value));
499    }
500
501    /// Replaces what a location holds, and forgets what it materialized to.
502    fn reset(&mut self, cell: CellId, to: Cell) {
503        self.built.get_mut().remove(&cell);
504        self.cells[cell] = to;
505    }
506
507    /// `php_var_unserialize_internal` with `var_hash`: reads a value into `cell`.
508    fn value(&mut self, p: &mut usize, cell: CellId) -> Step {
509        let start = *p;
510        if start >= self.buf.len() {
511            return Ok(false);
512        }
513        let c0 = self.at(start);
514        if c0 != b'R' {
515            self.slots.push(cell);
516        }
517        match self.read(p)? {
518            None => Ok(false),
519            Some(Read::Value(v)) => {
520                self.set(cell, v);
521                Ok(true)
522            }
523            Some(Read::Open { object, elements }) => {
524                let open = if object {
525                    Cell::Object { props: IndexMap::new(), done: false }
526                } else {
527                    Cell::Array { entries: IndexMap::new(), done: false }
528                };
529                self.reset(cell, open);
530                self.opened = Some((elements, object));
531                Ok(true)
532            }
533            Some(Read::Reference) => {
534                let Some(end) = self.uiv_then(start + 2, b';') else { return Ok(false) };
535                *p = end;
536                let id = self.parse_uiv(start + 2).wrapping_sub(1);
537                let Some(&target) = usize::try_from(id).ok().and_then(|id| self.slots.get(id)) else {
538                    return Ok(false);
539                };
540                if target == cell {
541                    return Ok(false);
542                }
543                if c0 == b'r' && !self.is_object(target) {
544                    return Ok(false);
545                }
546                match self.materialize(target) {
547                    Ok(snapshot) => self.set(cell, snapshot),
548                    Err(Error::Unsupported(what)) => {
549                        self.unsupported.get_or_insert(what);
550                        self.reset(cell, Cell::Recursive(target));
551                    }
552                    Err(e) => return Err(e),
553                }
554                Ok(true)
555            }
556        }
557    }
558
559    /// `php_var_unserialize_internal` at the cursor, without `var_hash`:
560    /// the value, a back-reference to resolve, or an opened container;
561    /// `None` after setting `p` where PHP reports the error.
562    fn read(&mut self, p: &mut usize) -> Result<Option<Read>, Error> {
563        let start = *p;
564        if start >= self.buf.len() {
565            return Ok(None);
566        }
567        let c0 = self.at(start);
568        let c1 = self.at(start + 1);
569        let value = match (c0, c1) {
570            (b'R' | b'r', b':') => return Ok(Some(Read::Reference)),
571            (b'N', b';') => {
572                *p = start + 2;
573                Value::Null
574            }
575            (b'b', b':') if matches!(self.at(start + 2), b'0' | b'1') && self.at(start + 3) == b';' => {
576                *p = start + 4;
577                Value::Bool(self.at(start + 2) == b'1')
578            }
579            (b'i', b':') => {
580                let Some(end) = self.iv(start + 2).filter(|&e| self.at(e) == b';') else { return Ok(None) };
581                *p = end + 1;
582                Value::Int(self.parse_iv2(start + 2).0)
583            }
584            (b'd', b':') => {
585                let rest = &self.buf[(start + 2).min(self.buf.len())..];
586                for (text, value) in [(&b"NAN;"[..], f64::NAN), (b"INF;", f64::INFINITY), (b"-INF;", f64::NEG_INFINITY)]
587                {
588                    if rest.starts_with(text) {
589                        *p = start + 2 + text.len();
590                        return Ok(Some(Read::Value(Value::Float(value))));
591                    }
592                }
593                let Some(end) = self.number(start + 2).filter(|&e| self.at(e) == b';') else { return Ok(None) };
594                *p = end + 1;
595                let text = std::str::from_utf8(&self.buf[start + 2..end]).unwrap_or("0");
596                Value::Float(strtod(text))
597            }
598            (b's' | b'S', b':') => match self.string(p, start)? {
599                Some(s) => Value::Str(s),
600                None => return Ok(None),
601            },
602            (b'a', b':') => {
603                let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'{').map(|e| e + 1) else {
604                    return Ok(None);
605                };
606                let (elements, _) = self.parse_iv2(start + 2);
607                *p = cursor;
608                if !(0..HT_MAX_SIZE).contains(&elements) || fake_count(elements, self.buf.len() - cursor) {
609                    return Ok(None);
610                }
611                if elements == 0 {
612                    // No nested data, so no depth check.
613                    if !self.finish(p) {
614                        return Ok(None);
615                    }
616                    Value::Array(Array::new())
617                } else {
618                    return Ok(Some(Read::Open { elements, object: false }));
619                }
620            }
621            (b'O' | b'C', b':') => return self.object(p, start),
622            (b'E', b':') => {
623                self.enumeration(p, start)?;
624                return Ok(None);
625            }
626            (b'}', _) => {
627                self.warn("unserialize(): Unexpected end of serialized data".into());
628                return Ok(None);
629            }
630            _ => return Ok(None),
631        };
632        Ok(Some(Read::Value(value)))
633    }
634
635    /// `"s:" uiv ":" ["]` and `"S:" uiv ":" ["]` at `start`: the string, or
636    /// `None` after setting `p` where PHP reports the error.
637    fn string(&mut self, p: &mut usize, start: usize) -> Result<Option<Str>, Error> {
638        let escaped = self.at(start) == b'S';
639        let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
640            return Ok(None);
641        };
642        let len = self.parse_uiv(start + 2);
643        let maxlen = (self.buf.len() - cursor) as u64;
644        if maxlen < len {
645            *p = start + 2;
646            return Ok(None);
647        }
648        let len = len as usize;
649        let (s, mut cursor) = if escaped {
650            // `unserialize_str`: `\xx` hex escapes; the cursor is local, so a
651            // failure here reports the value's start.
652            let mut out = Vec::with_capacity(len);
653            let mut i = cursor;
654            for _ in 0..len {
655                if i >= self.buf.len() {
656                    return Ok(None);
657                }
658                if self.at(i) != b'\\' {
659                    out.push(self.at(i));
660                } else {
661                    let mut ch: u8 = 0;
662                    for _ in 0..2 {
663                        i += 1;
664                        let Some(d) = char::from(self.at(i)).to_digit(16) else { return Ok(None) };
665                        ch = (ch << 4).wrapping_add(d as u8);
666                    }
667                    out.push(ch);
668                }
669                i += 1;
670            }
671            (Str::from(out), i)
672        } else {
673            (Str::copy_from(&self.buf[cursor..cursor + len]), cursor + len)
674        };
675        if self.at(cursor) != b'"' {
676            *p = cursor;
677            return Ok(None);
678        }
679        if self.at(cursor + 1) != b';' {
680            *p = cursor + 1;
681            return Ok(None);
682        }
683        cursor += 2;
684        *p = cursor;
685        if escaped {
686            self.warn("unserialize(): Unserializing the 'S' format is deprecated".into());
687        }
688        Ok(Some(s))
689    }
690
691    /// `"E:" uiv ":" ["]`: an enum case. No PHP class exists on this side,
692    /// so this is PHP's behaviour for an enum class that is not defined.
693    fn enumeration(&mut self, p: &mut usize, start: usize) -> Step {
694        let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
695            return Ok(false);
696        };
697        let len = self.parse_uiv(start + 2);
698        let maxlen = (self.buf.len() - cursor) as u64;
699        if maxlen < len || len == 0 {
700            *p = start + 2;
701            return Ok(false);
702        }
703        let end = cursor + len as usize;
704        if self.at(end) != b'"' {
705            *p = end;
706            return Ok(false);
707        }
708        if self.at(end + 1) != b';' {
709            *p = end + 1;
710            return Ok(false);
711        }
712        let name = &self.buf[cursor..end];
713        let Some(colon) = name.iter().position(|&c| c == b':') else {
714            let message =
715                format!("unserialize(): Invalid enum name '{}' (missing colon)", String::from_utf8_lossy(name));
716            self.warn(message);
717            return Ok(false);
718        };
719        let class = &name[..colon];
720        if !valid_class_name(class) {
721            return Ok(false);
722        }
723        let message = format!("unserialize(): Class '{}' not found", String::from_utf8_lossy(class));
724        self.warn(message);
725        Ok(false)
726    }
727
728    /// `object ":" uiv ":" ["]`: `O:` and `C:` of `stdClass`.
729    fn object(&mut self, p: &mut usize, start: usize) -> Result<Option<Read>, Error> {
730        let custom = self.at(start) == b'C';
731        let Some(mut cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'"').map(|e| e + 1) else {
732            return Ok(None);
733        };
734        let len = self.parse_uiv(start + 2);
735        let maxlen = (self.buf.len() - cursor) as u64;
736        if maxlen < len || len == 0 {
737            *p = start + 2;
738            return Ok(None);
739        }
740        let name = &self.buf[cursor..cursor + len as usize];
741        cursor += len as usize;
742        if self.at(cursor) != b'"' {
743            *p = cursor;
744            return Ok(None);
745        }
746        if self.at(cursor + 1) != b':' {
747            *p = cursor + 1;
748            return Ok(None);
749        }
750        if name[0] == 0 || name[0] == b'\\' {
751            return Ok(None);
752        }
753        let incomplete = !name.eq_ignore_ascii_case(b"stdClass");
754        if incomplete {
755            if !valid_class_name(name) {
756                return Ok(None);
757            }
758            // No PHP class exists here: PHP reads such an object as
759            // __PHP_Incomplete_Class, parsing on exactly like stdClass. Read
760            // on, so failures match, and refuse the value if it is complete.
761            self.unsupported.get_or_insert("object of a class other than stdClass");
762        }
763        *p = cursor;
764        if custom {
765            // `object_custom`: stdClass has no unserializer.
766            let (datalen, q) = self.parse_iv2(*p + 2);
767            *p = q;
768            if self.buf.len().saturating_sub(*p) < 2 || self.at(*p) != b':' {
769                return Ok(None);
770            }
771            if self.at(*p + 1) != b'{' {
772                *p += 1;
773                return Ok(None);
774            }
775            *p += 2;
776            let present = (self.buf.len() - *p) as i64;
777            if datalen < 0 || present <= datalen {
778                self.warn(format!("Insufficient data for unserializing - {datalen} required, {present} present"));
779                return Ok(None);
780            }
781            if self.at(*p + datalen as usize) != b'}' {
782                *p += datalen as usize;
783                return Ok(None);
784            }
785            let class = if incomplete { "__PHP_Incomplete_Class" } else { "stdClass" };
786            self.warn(format!("Class {class} has no unserializer"));
787            *p += datalen as usize + 1;
788            return Ok(Some(Read::Value(Value::Object(Array::new()))));
789        }
790        if *p + 2 >= self.buf.len() {
791            self.warn("Bad unserialize data".into());
792            return Ok(None);
793        }
794        let (elements, q) = self.parse_iv2(*p + 2);
795        *p = q;
796        if elements < 0 || fake_count(elements, self.buf.len() - cursor) {
797            return Ok(None);
798        }
799        if self.at(*p) != b':' {
800            return Ok(None);
801        }
802        if self.at(*p + 1) != b'{' {
803            *p += 1;
804            return Ok(None);
805        }
806        *p += 2;
807        if elements >= HT_MAX_SIZE {
808            return Ok(None);
809        }
810        Ok(Some(Read::Open { elements, object: true }))
811    }
812
813    /// `finish_nested_data`.
814    fn finish(&self, p: &mut usize) -> bool {
815        if *p >= self.buf.len() || self.at(*p) != b'}' {
816            return false;
817        }
818        *p += 1;
819        true
820    }
821
822    /// `php_var_unserialize_internal` without `var_hash`: an array key or property name.
823    fn key(&mut self, p: &mut usize) -> Result<Option<KeyValue>, Error> {
824        let start = *p;
825        if start >= self.buf.len() {
826            return Ok(None);
827        }
828        let (c0, c1) = (self.at(start), self.at(start + 1));
829        Ok(match (c0, c1) {
830            (b'R' | b'r', b':') => {
831                // The rule matches (and moves the cursor) before refusing a key.
832                if let Some(end) = self.uiv_then(start + 2, b';') {
833                    *p = end;
834                }
835                None
836            }
837            (b'N', b';') => {
838                *p = start + 2;
839                Some(KeyValue::Other)
840            }
841            (b'b', b':') if matches!(self.at(start + 2), b'0' | b'1') && self.at(start + 3) == b';' => {
842                *p = start + 4;
843                Some(KeyValue::Other)
844            }
845            (b'i', b':') => match self.iv(start + 2).filter(|&e| self.at(e) == b';') {
846                Some(end) => {
847                    *p = end + 1;
848                    Some(KeyValue::Int(self.parse_iv2(start + 2).0))
849                }
850                None => None,
851            },
852            (b'd', b':') => {
853                let rest = &self.buf[(start + 2).min(self.buf.len())..];
854                if let Some(text) = [&b"NAN;"[..], b"INF;", b"-INF;"].into_iter().find(|t| rest.starts_with(t)) {
855                    *p = start + 2 + text.len();
856                    Some(KeyValue::Other)
857                } else if let Some(end) = self.number(start + 2).filter(|&e| self.at(e) == b';') {
858                    *p = end + 1;
859                    Some(KeyValue::Other)
860                } else {
861                    None
862                }
863            }
864            (b's' | b'S', b':') => self.string(p, start)?.map(KeyValue::Str),
865            (b'a', b':') => {
866                if let Some(cursor) = self.uiv_then(start + 2, b':').filter(|&e| self.at(e) == b'{') {
867                    self.parse_iv2(start + 2);
868                    *p = cursor + 1;
869                }
870                None
871            }
872            (b'}', _) => {
873                self.warn("unserialize(): Unexpected end of serialized data".into());
874                None
875            }
876            _ => None,
877        })
878    }
879
880    /// Reads the whole value into the root location: `php_var_unserialize_internal`
881    /// with `process_nested_array_data` / `process_nested_object_data` and
882    /// `finish_nested_data`, without recursion.
883    fn run(&mut self, p: &mut usize) -> Step {
884        struct Frame {
885            cell: CellId,
886            remaining: i64,
887            object: bool,
888            started: bool,
889        }
890        let mut frames: Vec<Frame> = Vec::new();
891        let mut target = 0;
892        loop {
893            if !self.value(p, target)? {
894                return Ok(false);
895            }
896            if let Some((elements, object)) = self.opened.take() {
897                if self.max_depth > 0 && self.cur_depth >= self.max_depth {
898                    self.warn(format!(
899                        "unserialize(): Maximum depth of {} exceeded. The depth limit can be changed using the max_depth unserialize() option or the unserialize_max_depth ini setting",
900                        self.max_depth
901                    ));
902                    return Ok(false);
903                }
904                self.cur_depth += 1;
905                frames.push(Frame { cell: target, remaining: elements, object, started: false });
906            }
907            // The value is complete (or a container opened): find the next one.
908            loop {
909                let Some(frame) = frames.last_mut() else { return Ok(true) };
910                if frame.started && frame.remaining > 0 && !matches!(self.at(p.wrapping_sub(1)), b';' | b'}') {
911                    *p -= 1;
912                    return Ok(false);
913                }
914                frame.started = true;
915                if frame.remaining > 0 {
916                    frame.remaining -= 1;
917                    let (cell, object) = (frame.cell, frame.object);
918                    let Some(key) = self.key(p)? else { return Ok(false) };
919                    target = match (key, object) {
920                        (KeyValue::Other, _) => return Ok(false),
921                        (KeyValue::Int(i), false) => self.child(cell, ArrayKey::Int(i)),
922                        (KeyValue::Str(s), false) => self.child(cell, ArrayKey::normalize(s)),
923                        (KeyValue::Int(i), true) => self.prop(cell, Str::from(i.to_string())),
924                        (KeyValue::Str(s), true) => self.prop(cell, s),
925                    };
926                    break;
927                }
928                let Some(frame) = frames.pop() else { return Ok(true) };
929                self.cur_depth -= 1;
930                match &mut self.cells[frame.cell] {
931                    Cell::Array { done, .. } | Cell::Object { done, .. } => *done = true,
932                    _ => {}
933                }
934                if !self.finish(p) {
935                    return Ok(false);
936                }
937            }
938        }
939    }
940
941    /// Reads the whole value, building it directly: [`Unserializer::run`]
942    /// without locations, for what `serialize` writes (`N`, `b`, `i`, `d`,
943    /// `s`, `a`, and `O` of `stdClass`). `None` for anything else (a
944    /// back-reference, another class, `S`, data that warns) and on failure:
945    /// then `run` reads it again and reports what PHP reports.
946    fn direct(&mut self, p: &mut usize) -> Option<Value> {
947        let buf = self.buf;
948        let mut pos = *p;
949        let mut open = match *buf.get(pos)? {
950            b'a' | b'O' => match self.container(&mut pos)? {
951                Ok(open) => open,
952                Err(empty) => {
953                    *p = pos;
954                    return Some(empty);
955                }
956            },
957            _ => {
958                let value = self.scalar(&mut pos)?;
959                *p = pos;
960                return Some(value);
961            }
962        };
963        // The containers `open` is nested in, each with the key it goes to.
964        let mut parents: Vec<(Open, ArrayKey)> = Vec::new();
965        loop {
966            if open.remaining == 0 {
967                if buf.get(pos) != Some(&b'}') {
968                    return None;
969                }
970                pos += 1;
971                self.cur_depth -= 1;
972                let array = open.array.finish();
973                let value = if open.object { Value::Object(array) } else { Value::Array(array) };
974                let Some((parent, key)) = parents.pop() else {
975                    *p = pos;
976                    return Some(value);
977                };
978                open = parent;
979                open.array.set(key, value);
980                continue;
981            }
982            open.remaining -= 1;
983            // Every value read here ends with `;` or `}`, which a key may follow.
984            let (key, end) = key(buf, pos, open.object)?;
985            pos = end;
986            match *buf.get(pos)? {
987                b'a' | b'O' => match self.container(&mut pos)? {
988                    Ok(nested) => parents.push((std::mem::replace(&mut open, nested), key)),
989                    Err(empty) => open.array.set(key, empty),
990                },
991                _ => {
992                    let value = self.scalar(&mut pos)?;
993                    open.array.set(key, value);
994                }
995            }
996        }
997    }
998
999    /// A scalar at the cursor for [`Unserializer::direct`].
1000    #[inline]
1001    fn scalar(&mut self, pos: &mut usize) -> Option<Value> {
1002        if self.buf.get(*pos) == Some(&b'd') {
1003            // Rare: `read` has the float grammar.
1004            return match self.read(pos).ok()?? {
1005                Read::Value(v) => Some(v),
1006                _ => None,
1007            };
1008        }
1009        let (value, end) = scalar(self.buf, *pos)?;
1010        *pos = end;
1011        Some(value)
1012    }
1013
1014    /// An `a:` or `O:` (of `stdClass`) at the cursor for
1015    /// [`Unserializer::direct`]: the container opened, within the depth
1016    /// limit, or the empty array `a:0:{}`.
1017    fn container(&mut self, pos: &mut usize) -> Option<Result<Open, Value>> {
1018        let buf = self.buf;
1019        let i = *pos;
1020        if buf.get(i + 1) != Some(&b':') {
1021            return None;
1022        }
1023        let object = buf[i] == b'O';
1024        let (elements, brace, cursor) = if object {
1025            let (len, quote) = uiv(buf, i + 2, b':')?;
1026            if buf.get(quote) != Some(&b'"') {
1027                return None;
1028            }
1029            let cursor = quote + 1 + len;
1030            let name = buf.get(quote + 1..cursor)?;
1031            // Other classes (and an empty name) are left to `run`.
1032            if !name.eq_ignore_ascii_case(b"stdClass") || buf.get(cursor..cursor + 2) != Some(b"\":") {
1033                return None;
1034            }
1035            let (elements, brace) = uiv(buf, cursor + 2, b':')?;
1036            // PHP counts the bytes after the name.
1037            (elements, brace, cursor)
1038        } else {
1039            let (elements, brace) = uiv(buf, i + 2, b':')?;
1040            (elements, brace, brace + 1)
1041        };
1042        if buf.get(brace) != Some(&b'{')
1043            || elements as i64 >= HT_MAX_SIZE
1044            || fake_count(elements as i64, buf.len() - cursor)
1045        {
1046            return None;
1047        }
1048        *pos = brace + 1;
1049        if elements == 0 && !object {
1050            // No nested data, so no depth check.
1051            if buf.get(*pos) != Some(&b'}') {
1052                return None;
1053            }
1054            *pos += 1;
1055            return Some(Err(Value::Array(Array::new())));
1056        }
1057        if self.max_depth > 0 && self.cur_depth >= self.max_depth {
1058            return None;
1059        }
1060        self.cur_depth += 1;
1061        // Each entry takes at least 6 bytes (`i:0;N;`): no more room than that.
1062        let array = Builder::new(elements.min((buf.len() - *pos) / 6));
1063        Some(Ok(Open { array, remaining: elements, object }))
1064    }
1065
1066    /// The location of `key` in the array at `cell` (reused when the key repeats).
1067    fn child(&mut self, cell: CellId, key: ArrayKey) -> CellId {
1068        let next = self.cells.len();
1069        let Cell::Array { entries, .. } = &mut self.cells[cell] else { unreachable!() };
1070        let id = *entries.entry(key).or_insert(next);
1071        if id == next {
1072            self.cells.push(Cell::Null);
1073        } else {
1074            self.reset(id, Cell::Null);
1075        }
1076        id
1077    }
1078
1079    fn prop(&mut self, cell: CellId, name: Str) -> CellId {
1080        let next = self.cells.len();
1081        let Cell::Object { props, .. } = &mut self.cells[cell] else { unreachable!() };
1082        let id = *props.entry(name).or_insert(next);
1083        if id == next {
1084            self.cells.push(Cell::Null);
1085        } else {
1086            self.reset(id, Cell::Null);
1087        }
1088        id
1089    }
1090
1091    /// Whether the value at a location is an object (`ZVAL_DEREF` + `IS_OBJECT`).
1092    fn is_object(&self, mut cell: CellId) -> bool {
1093        loop {
1094            match &self.cells[cell] {
1095                Cell::Recursive(target) => cell = *target,
1096                Cell::Object { .. } | Cell::Value(Value::Object(_)) => return true,
1097                _ => return false,
1098            }
1099        }
1100    }
1101
1102    /// The value at a location now (without recursion).
1103    fn materialize(&self, root: CellId) -> Result<Value, Error> {
1104        enum Slot<'c> {
1105            Key(&'c ArrayKey),
1106            Prop(&'c Str),
1107        }
1108        enum Partial {
1109            Array(Array),
1110            Object(Array),
1111        }
1112        struct Frame<'c> {
1113            cell: CellId,
1114            partial: Partial,
1115            children: Vec<(Slot<'c>, CellId)>,
1116            next: usize,
1117        }
1118        let mut stack: Vec<Frame<'_>> = Vec::new();
1119        let mut visit = Some(root);
1120        let mut done: Option<Value> = None;
1121        loop {
1122            if let Some(cell) = visit.take() {
1123                if let Some(value) = self.built.borrow().get(&cell) {
1124                    done = Some(value.clone());
1125                } else {
1126                    match &self.cells[cell] {
1127                        Cell::Null => done = Some(Value::Null),
1128                        Cell::Value(v) => done = Some(v.clone()),
1129                        Cell::Array { done: false, .. } | Cell::Object { done: false, .. } | Cell::Recursive(_) => {
1130                            return Err(Error::Unsupported("reference to a container that is still being read"));
1131                        }
1132                        Cell::Array { entries, .. } => stack.push(Frame {
1133                            cell,
1134                            partial: Partial::Array(Array::with_capacity(entries.len())),
1135                            children: entries.iter().map(|(k, &c)| (Slot::Key(k), c)).collect(),
1136                            next: 0,
1137                        }),
1138                        Cell::Object { props, .. } => stack.push(Frame {
1139                            cell,
1140                            partial: Partial::Object(Array::new()),
1141                            children: props.iter().map(|(k, &c)| (Slot::Prop(k), c)).collect(),
1142                            next: 0,
1143                        }),
1144                    }
1145                }
1146            }
1147            let Some(frame) = stack.last_mut() else { return Ok(done.unwrap_or_default()) };
1148            if let Some(value) = done.take() {
1149                match (&mut frame.partial, &frame.children[frame.next - 1].0) {
1150                    (Partial::Array(a), Slot::Key(k)) => {
1151                        a.set((*k).clone(), value);
1152                    }
1153                    (Partial::Object(o), Slot::Prop(name)) => {
1154                        o.set(ArrayKey::Str((*name).clone()), value);
1155                    }
1156                    _ => unreachable!(),
1157                }
1158            }
1159            if frame.next < frame.children.len() {
1160                visit = Some(frame.children[frame.next].1);
1161                frame.next += 1;
1162            } else if let Some(frame) = stack.pop() {
1163                let value = match frame.partial {
1164                    Partial::Array(a) => Value::Array(a),
1165                    Partial::Object(o) => Value::Object(o),
1166                };
1167                // Only finished containers get here: an open one is refused above.
1168                self.built.borrow_mut().insert(frame.cell, value.clone());
1169                done = Some(value);
1170            }
1171        }
1172    }
1173}
1174
1175/// A container [`Unserializer::direct`] is reading.
1176struct Open {
1177    array: Builder,
1178    /// Entries still to read.
1179    remaining: usize,
1180    object: bool,
1181}
1182
1183/// `uiv` at `i` followed by `term`: the number and where the terminator
1184/// ends. At most 18 digits, so it cannot wrap (longer ones are left to
1185/// [`Unserializer::run`]).
1186#[inline]
1187fn uiv(buf: &[u8], mut i: usize, term: u8) -> Option<(usize, usize)> {
1188    let start = i;
1189    let mut n = 0usize;
1190    while let Some(&c) = buf.get(i)
1191        && c.is_ascii_digit()
1192    {
1193        n = n * 10 + usize::from(c - b'0');
1194        i += 1;
1195        if i - start > 18 {
1196            return None;
1197        }
1198    }
1199    (i > start && buf.get(i) == Some(&term)).then_some((n, i + 1))
1200}
1201
1202/// `iv ";"` at `i` (`[+-]? [0-9]+`): the integer and where it ends. At most
1203/// 18 significant digits, so it cannot be out of range (larger ones warn,
1204/// which [`Unserializer::run`] reports).
1205#[inline]
1206fn int(buf: &[u8], mut i: usize) -> Option<(i64, usize)> {
1207    let negative = buf.get(i) == Some(&b'-');
1208    if matches!(buf.get(i), Some(b'-' | b'+')) {
1209        i += 1;
1210    }
1211    let start = i;
1212    while buf.get(i) == Some(&b'0') {
1213        i += 1;
1214    }
1215    let digits = i;
1216    let mut n = 0i64;
1217    while let Some(&c) = buf.get(i)
1218        && c.is_ascii_digit()
1219    {
1220        if i - digits == 18 {
1221            return None;
1222        }
1223        n = n * 10 + i64::from(c - b'0');
1224        i += 1;
1225    }
1226    (i > start && buf.get(i) == Some(&b';')).then_some((if negative { -n } else { n }, i + 1))
1227}
1228
1229/// The bytes of `uiv ":" ["] ... ["] ";"` at `i` (after `s:`), and where it ends.
1230#[inline]
1231fn bytes(buf: &[u8], i: usize) -> Option<(&[u8], usize)> {
1232    let (len, quote) = uiv(buf, i, b':')?;
1233    if buf.get(quote) != Some(&b'"') {
1234        return None;
1235    }
1236    let end = quote + 1 + len;
1237    let s = buf.get(quote + 1..end)?;
1238    (buf.get(end..end + 2) == Some(b"\";")).then_some((s, end + 2))
1239}
1240
1241/// `N;`, `b:0;`, `b:1;`, `i:..;` or `s:..;` at `i`: the value and where it ends.
1242#[inline]
1243fn scalar(buf: &[u8], i: usize) -> Option<(Value, usize)> {
1244    let tag = buf.get(i..i + 2)?;
1245    Some(match tag {
1246        b"N;" => (Value::Null, i + 2),
1247        b"s:" => {
1248            let (s, end) = bytes(buf, i + 2)?;
1249            (Value::Str(Str::copy_from(s)), end)
1250        }
1251        b"i:" => {
1252            let (n, end) = int(buf, i + 2)?;
1253            (Value::Int(n), end)
1254        }
1255        b"b:" => match buf.get(i + 2..i + 4)? {
1256            b"0;" => (Value::Bool(false), i + 4),
1257            b"1;" => (Value::Bool(true), i + 4),
1258            _ => return None,
1259        },
1260        _ => return None,
1261    })
1262}
1263
1264/// An array key (`i:` or `s:`, normalised) or property name at `i`, and where it ends.
1265#[inline]
1266fn key(buf: &[u8], i: usize, object: bool) -> Option<(ArrayKey, usize)> {
1267    match buf.get(i..i + 2)? {
1268        b"s:" => {
1269            let (s, end) = bytes(buf, i + 2)?;
1270            Some((if object { ArrayKey::Str(Str::copy_from(s)) } else { ArrayKey::from_bytes(s) }, end))
1271        }
1272        b"i:" => {
1273            let (n, end) = int(buf, i + 2)?;
1274            Some((if object { ArrayKey::Str(Str::from(n.to_string())) } else { ArrayKey::Int(n) }, end))
1275        }
1276        _ => None,
1277    }
1278}
1279
1280/// `zend_is_valid_class_name`: `0-9 a-z A-Z _ \` and bytes from 0x80.
1281fn valid_class_name(name: &[u8]) -> bool {
1282    name.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_' || c == b'\\' || c >= 0x80)
1283}
1284
1285/// `IS_FAKE_ELEM_COUNT`: each element takes at least two bytes.
1286fn fake_count(elements: i64, remaining: usize) -> bool {
1287    elements > (remaining / 2) as i64
1288}
1289
1290/// `zend_strtod` of a matched `iv | nv | nvexp`: Rust's parser accepts the
1291/// same forms (`+1`, `5.`, `.5e1`) and rounds the same way.
1292fn strtod(text: &str) -> f64 {
1293    text.parse().unwrap_or(0.0)
1294}
1295
1296#[cfg(test)]
1297mod tests {
1298    use super::*;
1299    use serde_json::json;
1300
1301    type V = Value<crate::types::Never>;
1302
1303    fn u(s: &str) -> Result<Unserialized, Error> {
1304        unserialize(s.as_bytes(), &Options::default())
1305    }
1306
1307    #[test]
1308    fn serializes_like_php() {
1309        let v = json!([1.0, 0.1, 1e25, -0.0, "a", {"x": true, "5": null}, {}]);
1310        assert_eq!(
1311            String::from_utf8(serialize(&V::from_json(&v))).unwrap(),
1312            r#"a:7:{i:0;d:1;i:1;d:0.1;i:2;d:1.0E+25;i:3;d:-0;i:4;s:1:"a";i:5;a:2:{s:1:"x";b:1;i:5;N;}i:6;O:8:"stdClass":0:{}}"#
1313        );
1314    }
1315
1316    #[test]
1317    fn exports_like_php() {
1318        let v = json!({"a": [1, {}], "k'": "x\u{0}y"});
1319        assert_eq!(
1320            String::from_utf8(var_export(&V::from_json(&v))).unwrap(),
1321            "array (\n  'a' => \n  array (\n    0 => 1,\n    1 => \n    (object) array(\n    ),\n  ),\n  'k\\'' => 'x' . \"\\0\" . 'y',\n)"
1322        );
1323        assert_eq!(String::from_utf8(var_export(&V::from_json(&json!(1.0)))).unwrap(), "1.0");
1324        assert_eq!(String::from_utf8(var_export(&V::from_json(&json!(i64::MIN)))).unwrap(), "-9223372036854775807-1");
1325    }
1326
1327    #[test]
1328    fn unserializes_like_php() {
1329        assert_eq!(u("i:+0005;").unwrap().value, Value::Int(5));
1330        assert_eq!(u("d:5.;").unwrap().value, Value::Float(5.0));
1331        assert_eq!(u("d:.5e1;").unwrap().value, Value::Float(5.0));
1332        let r = u("a:3:{i:0;i:1;i:0;i:2;i:1;R:2;}").unwrap().value;
1333        assert_eq!(r.to_json(), json!([2, 2]));
1334        assert_eq!(
1335            u("i:5;x").unwrap().warnings,
1336            vec!["unserialize(): Extra data starting at offset 4 of 5 bytes".to_string()]
1337        );
1338        for (s, offset) in [
1339            ("i:5", 0),
1340            ("s:3:\"ab\";", 8),
1341            ("s:2:\"abc\";", 7),
1342            ("a:1:{i:0;i:1;", 13),
1343            ("a:1:{d:1;i:1;}", 9),
1344            ("a:2:{i:0;i:5;i:1;r:2;}", 21),
1345            ("R:1;", 4),
1346        ] {
1347            match u(s) {
1348                Err(Error::Failed { offset: o, .. }) => assert_eq!(o, Some(offset), "{s}"),
1349                other => panic!("{s}: {other:?}"),
1350            }
1351        }
1352        assert!(matches!(u("a:1:{i:0;R:1;}"), Err(Error::Unsupported(_))));
1353    }
1354
1355    #[test]
1356    fn back_references_read_the_container_once() {
1357        // One container of 20,000 entries referenced 20,000 times: rebuilt on every
1358        // reference, this is 400 million element copies; reused, it is 20,000 clones.
1359        let n = 20_000;
1360        let mut s = format!("a:{}:{{i:0;a:{n}:{{", n + 1);
1361        for i in 0..n {
1362            s.push_str(&format!("i:{i};i:{i};"));
1363        }
1364        s.push('}');
1365        for i in 1..=n {
1366            s.push_str(&format!("i:{i};R:2;"));
1367        }
1368        s.push('}');
1369
1370        let started = std::time::Instant::now();
1371        let Value::Array(outer) = u(&s).unwrap().value else { panic!() };
1372        assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed());
1373        assert_eq!(outer.len(), n + 1);
1374        let Some(Value::Array(last)) = outer.get(&ArrayKey::Int(n as i64)) else { panic!() };
1375        assert_eq!(last.len(), n);
1376    }
1377
1378    #[test]
1379    fn back_references_follow_a_location_a_duplicate_key_reused() {
1380        // The first R:2 reads [1]; the duplicate key 0 then puts [9] in that location,
1381        // which the second R:2 reads.
1382        let r = u("a:4:{i:0;a:1:{i:0;i:1;}i:1;R:2;i:0;a:1:{i:0;i:9;}i:2;R:2;}").unwrap().value;
1383        assert_eq!(r.to_json(), json!([[9], [1], [9]]));
1384
1385        let r = u(
1386            r#"a:3:{i:0;O:8:"stdClass":3:{s:1:"p";a:1:{i:0;i:1;}s:1:"q";R:3;s:1:"p";a:1:{i:0;i:9;}}i:1;R:3;i:2;R:2;}"#,
1387        )
1388        .unwrap()
1389        .value;
1390        assert_eq!(r.to_json(), json!([{"p": [9], "q": [1]}, [9], {"p": [9], "q": [1]}]));
1391
1392        let r = u(r#"a:2:{i:0;O:8:"stdClass":2:{s:1:"p";a:1:{i:0;i:1;}s:1:"q";R:3;}i:1;R:2;}"#).unwrap().value;
1393        assert_eq!(r.to_json(), json!([{"p": [1], "q": [1]}, {"p": [1], "q": [1]}]));
1394    }
1395}