Skip to main content

php_std/
json.rs

1//! `json_encode`, `json_decode`, `json_validate`, `json_last_error` and
2//! `json_last_error_msg`, as PHP 8.5's `ext/json` implements them.
3//!
4//! | PHP | Rust |
5//! |---|---|
6//! | `json_encode($v, $flags, $depth)` | [`encode`] ([`Value`]) |
7//! | `json_decode($s, $assoc, $depth, $flags)` | [`decode`] ([`Value`]), [`decode_value`] (`serde_json::Value`, `$assoc = true`) |
8//! | `json_validate($s, $depth, $flags)` | [`validate`] |
9//! | `json_last_error()`, `json_last_error_msg()` | [`ErrorCode::code`], [`ErrorCode::message`] of the returned error |
10//! | `JSON_*` constants | [`Flags`] |
11//! | `JsonException` / `ValueError` | [`Error`] ([`Error::php_class`]) |
12//!
13//! There is no global "last error": each call returns its error. PHP's
14//! `json_last_error()` after a call without `JSON_THROW_ON_ERROR` is the
15//! code of the returned error (`0` on success).
16//!
17//! Faithful details: floats print with `serialize_precision = -1`
18//! ([`crate::number::serialize`]); strings are validated as UTF-8 exactly
19//! like PHP (`php_next_utf8_char` when encoding, the scanner's byte ranges
20//! when decoding, so `JSON_INVALID_UTF8_SUBSTITUTE` replaces the same byte
21//! runs); errors follow PHP's precedence (the first error in input order when
22//! decoding, the last one recorded when encoding); the decoder reports the
23//! same error as PHP's bison parser when nesting exhausts its 10000-entry
24//! stack, and never recurses.
25//!
26//! Objects other than `stdClass` are [`Value::Ext`]: they encode as an
27//! object of their [`Extension::to_array`] (what `json_encode` does for an
28//! `ArrayObject`, such as `Utopia\Database\Document`). Not modelled:
29//! `JsonSerializable`, enums, recursion (a [`Value`] cannot contain itself)
30//! and the engine's stack-size limit when encoding values nested thousands
31//! of levels deep.
32
33use std::fmt;
34use std::ops::{BitAnd, BitOr, BitOrAssign};
35
36use serde_json::{Map, Number, Value as Json};
37
38use crate::number;
39use crate::types::{Array, ArrayKey, Extension, KeyRef, Str, Value, numeric_key};
40use crate::value;
41
42/// `JSON_*` option bits for `json_encode`, `json_decode` and `json_validate`.
43///
44/// PHP passes options as `int`; [`Flags::from_php`] keeps the low 32 bits
45/// like the engine's `(int)` cast. Unknown bits are ignored.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
47pub struct Flags(u32);
48
49impl Flags {
50    /// No options.
51    pub const NONE: Flags = Flags(0);
52    /// `JSON_OBJECT_AS_ARRAY` (decode): objects become arrays.
53    pub const OBJECT_AS_ARRAY: Flags = Flags(1 << 0);
54    /// `JSON_BIGINT_AS_STRING` (decode): integers beyond `i64` stay strings.
55    pub const BIGINT_AS_STRING: Flags = Flags(1 << 1);
56    /// `JSON_HEX_TAG`: `<` and `>` as `<`, `>`.
57    pub const HEX_TAG: Flags = Flags(1 << 0);
58    /// `JSON_HEX_AMP`: `&` as `&`.
59    pub const HEX_AMP: Flags = Flags(1 << 1);
60    /// `JSON_HEX_APOS`: `'` as `'`.
61    pub const HEX_APOS: Flags = Flags(1 << 2);
62    /// `JSON_HEX_QUOT`: `"` as `"`.
63    pub const HEX_QUOT: Flags = Flags(1 << 3);
64    /// `JSON_FORCE_OBJECT`: lists as objects.
65    pub const FORCE_OBJECT: Flags = Flags(1 << 4);
66    /// `JSON_NUMERIC_CHECK`: numeric strings as numbers.
67    pub const NUMERIC_CHECK: Flags = Flags(1 << 5);
68    /// `JSON_UNESCAPED_SLASHES`: `/` stays `/`.
69    pub const UNESCAPED_SLASHES: Flags = Flags(1 << 6);
70    /// `JSON_PRETTY_PRINT`: newlines and four-space indentation.
71    pub const PRETTY_PRINT: Flags = Flags(1 << 7);
72    /// `JSON_UNESCAPED_UNICODE`: non-ASCII characters stay raw (except U+2028/U+2029).
73    pub const UNESCAPED_UNICODE: Flags = Flags(1 << 8);
74    /// `JSON_PARTIAL_OUTPUT_ON_ERROR`: replace what cannot be encoded and keep going.
75    pub const PARTIAL_OUTPUT_ON_ERROR: Flags = Flags(1 << 9);
76    /// `JSON_PRESERVE_ZERO_FRACTION`: `1.0` stays `1.0`.
77    pub const PRESERVE_ZERO_FRACTION: Flags = Flags(1 << 10);
78    /// `JSON_UNESCAPED_LINE_TERMINATORS`: with `UNESCAPED_UNICODE`, U+2028/U+2029 stay raw.
79    pub const UNESCAPED_LINE_TERMINATORS: Flags = Flags(1 << 11);
80    /// `JSON_INVALID_UTF8_IGNORE`: drop invalid UTF-8.
81    pub const INVALID_UTF8_IGNORE: Flags = Flags(1 << 20);
82    /// `JSON_INVALID_UTF8_SUBSTITUTE`: replace invalid UTF-8 with U+FFFD.
83    pub const INVALID_UTF8_SUBSTITUTE: Flags = Flags(1 << 21);
84    /// `JSON_THROW_ON_ERROR`: PHP throws `JsonException` instead of setting the last error.
85    pub const THROW_ON_ERROR: Flags = Flags(1 << 22);
86
87    /// Options as PHP code passes them (an `int`, cast like the engine's `(int)`).
88    pub const fn from_php(options: i64) -> Flags {
89        Flags(options as u32)
90    }
91
92    /// The option bits, as PHP's `int`.
93    pub const fn bits(self) -> u32 {
94        self.0
95    }
96
97    /// Whether every bit of `other` is set.
98    pub const fn contains(self, other: Flags) -> bool {
99        self.0 & other.0 == other.0
100    }
101
102    /// Whether any bit of `other` is set.
103    pub const fn intersects(self, other: Flags) -> bool {
104        self.0 & other.0 != 0
105    }
106
107    const fn without(self, other: Flags) -> Flags {
108        Flags(self.0 & !other.0)
109    }
110}
111
112impl BitOr for Flags {
113    type Output = Flags;
114
115    /// Combines two option sets.
116    fn bitor(self, rhs: Flags) -> Flags {
117        Flags(self.0 | rhs.0)
118    }
119}
120
121impl BitOrAssign for Flags {
122    /// Adds the options of `rhs`.
123    fn bitor_assign(&mut self, rhs: Flags) {
124        self.0 |= rhs.0;
125    }
126}
127
128impl BitAnd for Flags {
129    type Output = Flags;
130
131    /// Keeps the options set in both.
132    fn bitand(self, rhs: Flags) -> Flags {
133        Flags(self.0 & rhs.0)
134    }
135}
136
137/// `JSON_ERROR_*`: what `json_last_error()` returns.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub enum ErrorCode {
140    /// `JSON_ERROR_NONE`: no error.
141    None = 0,
142    /// `JSON_ERROR_DEPTH`: the maximum nesting depth was exceeded.
143    Depth = 1,
144    /// `JSON_ERROR_STATE_MISMATCH`: mismatched brackets or invalid JSON.
145    StateMismatch = 2,
146    /// `JSON_ERROR_CTRL_CHAR`: an unescaped control character in a string.
147    CtrlChar = 3,
148    /// `JSON_ERROR_SYNTAX`: invalid JSON syntax.
149    Syntax = 4,
150    /// `JSON_ERROR_UTF8`: malformed UTF-8.
151    Utf8 = 5,
152    /// `JSON_ERROR_RECURSION`: a value contains itself.
153    Recursion = 6,
154    /// `JSON_ERROR_INF_OR_NAN`: `INF` or `NAN` cannot be encoded.
155    InfOrNan = 7,
156    /// `JSON_ERROR_UNSUPPORTED_TYPE`: a value of a type JSON cannot hold.
157    UnsupportedType = 8,
158    /// `JSON_ERROR_INVALID_PROPERTY_NAME`: an object key starting with a NUL byte.
159    InvalidPropertyName = 9,
160    /// `JSON_ERROR_UTF16`: an unpaired UTF-16 surrogate in a `\u` escape.
161    Utf16 = 10,
162    /// `JSON_ERROR_NON_BACKED_ENUM`: a non-backed enum cannot be encoded.
163    NonBackedEnum = 11,
164}
165
166impl ErrorCode {
167    /// `json_last_error()`.
168    pub fn code(self) -> i64 {
169        self as i64
170    }
171
172    /// `json_last_error_msg()`.
173    pub fn message(self) -> &'static str {
174        match self {
175            ErrorCode::None => "No error",
176            ErrorCode::Depth => "Maximum stack depth exceeded",
177            ErrorCode::StateMismatch => "State mismatch (invalid or malformed JSON)",
178            ErrorCode::CtrlChar => "Control character error, possibly incorrectly encoded",
179            ErrorCode::Syntax => "Syntax error",
180            ErrorCode::Utf8 => "Malformed UTF-8 characters, possibly incorrectly encoded",
181            ErrorCode::Recursion => "Recursion detected",
182            ErrorCode::InfOrNan => "Inf and NaN cannot be JSON encoded",
183            ErrorCode::UnsupportedType => "Type is not supported",
184            ErrorCode::InvalidPropertyName => "The decoded property name is invalid",
185            ErrorCode::Utf16 => "Single unpaired UTF-16 surrogate in unicode escape",
186            ErrorCode::NonBackedEnum => "Non-backed enums have no default serialization",
187        }
188    }
189}
190
191/// Why a JSON function failed.
192#[derive(Debug, Clone, PartialEq)]
193pub enum Error {
194    /// The value could not be encoded or the input decoded. Without
195    /// `JSON_THROW_ON_ERROR` PHP returns `false`/`null` and
196    /// `json_last_error()` is this code; with it PHP throws `JsonException`
197    /// (message [`ErrorCode::message`], code [`ErrorCode::code`]).
198    Json(ErrorCode),
199    /// `json_encode` with `JSON_PARTIAL_OUTPUT_ON_ERROR` after an error: PHP
200    /// returns `json` (with `null`, `0` or `""` where values failed) and sets
201    /// `json_last_error()` to `code`. It never throws, even with
202    /// `JSON_THROW_ON_ERROR`.
203    Partial {
204        /// The partial output PHP returns.
205        json: String,
206        /// The error `json_last_error()` reports.
207        code: ErrorCode,
208    },
209    /// An invalid argument: PHP throws `ValueError` with this message.
210    Value(String),
211    /// [`decode_value`] only: PHP decoded a number `serde_json::Value`
212    /// cannot hold (`1e999` is `INF` in PHP). Use [`decode`] for those.
213    Unrepresentable,
214}
215
216impl Error {
217    /// The PHP exception class this error corresponds to.
218    pub fn php_class(&self) -> &'static str {
219        match self {
220            Error::Json(_) | Error::Partial { .. } => "JsonException",
221            Error::Value(_) => "ValueError",
222            Error::Unrepresentable => "JsonException",
223        }
224    }
225
226    /// `json_last_error()` after the call that failed (`0` for a `ValueError`,
227    /// which PHP throws after resetting the last error).
228    pub fn code(&self) -> ErrorCode {
229        match self {
230            Error::Json(code) | Error::Partial { code, .. } => *code,
231            Error::Value(_) | Error::Unrepresentable => ErrorCode::None,
232        }
233    }
234
235    /// The exception message.
236    pub fn message(&self) -> &str {
237        match self {
238            Error::Json(code) | Error::Partial { code, .. } => code.message(),
239            Error::Value(message) => message,
240            Error::Unrepresentable => "The decoded value cannot be represented as serde_json::Value",
241        }
242    }
243}
244
245impl fmt::Display for Error {
246    /// Writes the message.
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.write_str(self.message())
249    }
250}
251
252impl std::error::Error for Error {}
253
254/// `PHP_JSON_PARSER_DEFAULT_DEPTH`: the default `$depth` of every function.
255pub const DEFAULT_DEPTH: i64 = 512;
256
257// ---------------------------------------------------------------------------
258// Encoding (ext/json/json_encoder.c)
259// ---------------------------------------------------------------------------
260
261/// `json_encode($value, $flags, $depth)`.
262///
263/// Returns the JSON text, or the error PHP reports: `Err(Error::Json)` where
264/// PHP returns `false` (or throws with `JSON_THROW_ON_ERROR`), and
265/// `Err(Error::Partial)` carrying the output PHP returns when
266/// `JSON_PARTIAL_OUTPUT_ON_ERROR` is set. `depth` is cast to a C `int` like
267/// PHP does; it is not validated (a depth below 1 fails on any array).
268pub fn encode<X: Extension>(value: &Value<X>, flags: Flags, depth: i64) -> Result<String, Error> {
269    let mut encoder =
270        Encoder { out: Vec::with_capacity(512), depth: 0, max_depth: depth as i32, error: ErrorCode::None };
271    // The engine ignores the encoder's return value here: the error code decides.
272    let _ = encoder.value(value, flags);
273    let json = String::from_utf8(encoder.out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
274    match encoder.error {
275        ErrorCode::None => Ok(json),
276        code if flags.contains(Flags::PARTIAL_OUTPUT_ON_ERROR) => Err(Error::Partial { json, code }),
277        code => Err(Error::Json(code)),
278    }
279}
280
281struct Encoder {
282    out: Vec<u8>,
283    depth: i32,
284    max_depth: i32,
285    error: ErrorCode,
286}
287
288/// The engine's `FAILURE` while encoding: the error code is in the encoder.
289struct Failed;
290
291const HEX: &[u8; 16] = b"0123456789abcdef";
292
293/// Appends `s` as `json_encode()` writes a string without options, and says whether it
294/// could: PHP refuses one that is not UTF-8, and what is appended then is not JSON.
295pub fn push_string(out: &mut Vec<u8>, s: &[u8]) -> bool {
296    let mut encoder = Encoder { out: std::mem::take(out), depth: 0, max_depth: 0, error: ErrorCode::None };
297    let written = encoder.string(s, Flags::NONE).is_ok();
298    *out = encoder.out;
299    written
300}
301
302/// Appends the decimal digits of `i` (no allocation).
303pub fn push_int(out: &mut Vec<u8>, i: i64) {
304    let mut buf = [0u8; 20];
305    let mut pos = buf.len();
306    let mut n = i.unsigned_abs();
307    loop {
308        pos -= 1;
309        buf[pos] = b'0' + (n % 10) as u8;
310        n /= 10;
311        if n == 0 {
312            break;
313        }
314    }
315    if i < 0 {
316        out.push(b'-');
317    }
318    out.extend_from_slice(&buf[pos..]);
319}
320
321/// Appends the bytes of `s` from `pos` that `php_json_escape_string` copies
322/// verbatim, eight at a time, and returns where the first byte it does not
323/// copy is (or the end). `<`, `>`, `&` and `'` stop the copy only when `hex`
324/// (some `JSON_HEX_*` option is set).
325#[inline]
326fn verbatim(out: &mut Vec<u8>, s: &[u8], mut pos: usize, hex: bool) -> usize {
327    let stops = |w: u64| {
328        let mut stop = bytes_ctrl_or_high(w) | bytes_eq(w, b'"') | bytes_eq(w, b'\\') | bytes_eq(w, b'/');
329        if hex {
330            stop |= bytes_eq(w, b'<') | bytes_eq(w, b'>') | bytes_eq(w, b'&') | bytes_eq(w, b'\'');
331        }
332        stop
333    };
334    while let Some(w) = word(s, pos) {
335        let stop = stops(w);
336        // The whole word (a fixed-size copy), then only its plain bytes kept.
337        out.extend_from_slice(&w.to_le_bytes());
338        if stop != 0 {
339            let plain = (stop.trailing_zeros() / 8) as usize;
340            out.truncate(out.len() - (8 - plain));
341            return pos + plain;
342        }
343        pos += 8;
344    }
345    // The last bytes, padded to a word with a plain byte.
346    let rest = s.len() - pos;
347    if rest == 0 {
348        return pos;
349    }
350    let w = match s.len().checked_sub(8).and_then(|last| word(s, last)) {
351        Some(last) => last >> (8 * (8 - rest)),
352        None => s[pos..].iter().rev().fold(0, |w, &b| w << 8 | u64::from(b)),
353    } | (ONES * u64::from(b'a')) << (8 * rest);
354    let plain = ((stops(w).trailing_zeros() / 8) as usize).min(rest);
355    out.extend_from_slice(&w.to_le_bytes());
356    out.truncate(out.len() - (8 - plain));
357    pos + plain
358}
359
360impl Encoder {
361    fn pretty_char(&mut self, flags: Flags, c: u8) {
362        if flags.contains(Flags::PRETTY_PRINT) {
363            self.out.push(c);
364        }
365    }
366
367    fn pretty_indent(&mut self, flags: Flags) {
368        if flags.contains(Flags::PRETTY_PRINT) {
369            for _ in 0..self.depth {
370                self.out.extend_from_slice(b"    ");
371            }
372        }
373    }
374
375    /// `php_json_encode_zval`.
376    fn value<X: Extension>(&mut self, value: &Value<X>, flags: Flags) -> Result<(), Failed> {
377        match value {
378            Value::Null => self.out.extend_from_slice(b"null"),
379            Value::Bool(true) => self.out.extend_from_slice(b"true"),
380            Value::Bool(false) => self.out.extend_from_slice(b"false"),
381            Value::Int(i) => push_int(&mut self.out, *i),
382            Value::Float(f) => {
383                if f.is_finite() {
384                    self.double(*f, flags);
385                } else {
386                    self.error = ErrorCode::InfOrNan;
387                    self.out.push(b'0');
388                }
389            }
390            Value::Str(s) => return self.string(s, flags),
391            Value::Array(a) => {
392                let as_object = flags.contains(Flags::FORCE_OBJECT) || !a.is_list();
393                return self.container(a, as_object, false, flags);
394            }
395            Value::Object(a) => return self.container(a, true, true, flags),
396            Value::Ext(x) => return self.container(&x.to_array(), true, true, flags),
397        }
398        Ok(())
399    }
400
401    /// `php_json_encode_double`.
402    fn double(&mut self, d: f64, flags: Flags) {
403        let start = self.out.len();
404        number::serialize_into(&mut self.out, d);
405        if flags.contains(Flags::PRESERVE_ZERO_FRACTION) && !self.out[start..].contains(&b'.') {
406            self.out.extend_from_slice(b".0");
407        }
408    }
409
410    /// `php_json_encode_array` for arrays and `stdClass` objects.
411    fn container<X: Extension>(
412        &mut self,
413        entries: &Array<X>,
414        as_object: bool,
415        is_object: bool,
416        flags: Flags,
417    ) -> Result<(), Failed> {
418        let mut need_comma = false;
419        self.out.push(if as_object { b'{' } else { b'[' });
420        self.depth += 1;
421        for (key, data) in entries.iter() {
422            if !as_object {
423                if need_comma {
424                    self.out.push(b',');
425                } else {
426                    need_comma = true;
427                }
428                self.pretty_char(flags, b'\n');
429                self.pretty_indent(flags);
430            } else {
431                match key {
432                    KeyRef::Str(k) => {
433                        if is_object && k.first() == Some(&0) {
434                            // Skip protected and private members.
435                            continue;
436                        }
437                        if need_comma {
438                            self.out.push(b',');
439                        } else {
440                            need_comma = true;
441                        }
442                        self.pretty_char(flags, b'\n');
443                        self.pretty_indent(flags);
444                        if self.string(k, flags.without(Flags::NUMERIC_CHECK)).is_err()
445                            && flags.contains(Flags::PARTIAL_OUTPUT_ON_ERROR)
446                        {
447                            self.out.truncate(self.out.len() - 4);
448                            self.out.extend_from_slice(b"\"\"");
449                        }
450                    }
451                    KeyRef::Int(index) => {
452                        if need_comma {
453                            self.out.push(b',');
454                        } else {
455                            need_comma = true;
456                        }
457                        self.pretty_char(flags, b'\n');
458                        self.pretty_indent(flags);
459                        self.out.push(b'"');
460                        push_int(&mut self.out, index);
461                        self.out.push(b'"');
462                    }
463                }
464                self.out.push(b':');
465                self.pretty_char(flags, b' ');
466            }
467            if self.value(data, flags).is_err() && !flags.contains(Flags::PARTIAL_OUTPUT_ON_ERROR) {
468                return Err(Failed);
469            }
470        }
471        if self.depth > self.max_depth {
472            self.error = ErrorCode::Depth;
473            if !flags.contains(Flags::PARTIAL_OUTPUT_ON_ERROR) {
474                return Err(Failed);
475            }
476        }
477        self.depth -= 1;
478        // Only keep the closing bracket on the same line for empty arrays/objects.
479        if need_comma {
480            self.pretty_char(flags, b'\n');
481            self.pretty_indent(flags);
482        }
483        self.out.push(if as_object { b'}' } else { b']' });
484        Ok(())
485    }
486
487    /// `php_json_escape_string`. Inlined up to the first byte that is not
488    /// copied as it is; [`Encoder::escape`] goes on from there.
489    #[inline]
490    fn string(&mut self, s: &[u8], flags: Flags) -> Result<(), Failed> {
491        if s.is_empty() {
492            self.out.extend_from_slice(b"\"\"");
493            return Ok(());
494        }
495        if flags.contains(Flags::NUMERIC_CHECK) && self.numeric(s, flags) {
496            return Ok(());
497        }
498        let checkpoint = self.out.len();
499        self.out.reserve(s.len() + 2);
500        self.out.push(b'"');
501        let hex = flags.intersects(Flags::HEX_TAG | Flags::HEX_AMP | Flags::HEX_APOS);
502        let pos = verbatim(&mut self.out, s, 0, hex);
503        if pos == s.len() {
504            self.out.push(b'"');
505            return Ok(());
506        }
507        self.escape(s, pos, checkpoint, flags)
508    }
509
510    /// `JSON_NUMERIC_CHECK`: writes `s` as a number when it is a numeric
511    /// string PHP encodes as one, and says whether it did.
512    #[inline(never)]
513    fn numeric(&mut self, s: &[u8], flags: Flags) -> bool {
514        match std::str::from_utf8(s).ok().and_then(value::numeric_str) {
515            Some(value::Number::Int(i)) => push_int(&mut self.out, i),
516            Some(value::Number::Float(d)) if d.is_finite() => self.double(d, flags),
517            _ => return false,
518        }
519        true
520    }
521
522    /// The rest of [`Encoder::string`] from `pos`, a byte to escape (or to
523    /// check, from 0x80), after the opening quote at `checkpoint`.
524    #[inline(never)]
525    fn escape(&mut self, s: &[u8], mut pos: usize, checkpoint: usize, flags: Flags) -> Result<(), Failed> {
526        let hex = flags.intersects(Flags::HEX_TAG | Flags::HEX_AMP | Flags::HEX_APOS);
527        loop {
528            let us = s[pos];
529            if us >= 0x80 {
530                match next_utf8_char(&s[pos..]) {
531                    Err(advance) => {
532                        if flags.contains(Flags::INVALID_UTF8_IGNORE) {
533                            // Ignore the invalid sequence.
534                        } else if flags.contains(Flags::INVALID_UTF8_SUBSTITUTE) {
535                            if flags.contains(Flags::UNESCAPED_UNICODE) {
536                                self.out.extend_from_slice("\u{fffd}".as_bytes());
537                            } else {
538                                self.out.extend_from_slice(b"\\ufffd");
539                            }
540                        } else {
541                            self.out.truncate(checkpoint);
542                            self.error = ErrorCode::Utf8;
543                            if flags.contains(Flags::PARTIAL_OUTPUT_ON_ERROR) {
544                                self.out.extend_from_slice(b"null");
545                            }
546                            return Err(Failed);
547                        }
548                        pos += advance;
549                    }
550                    Ok((c, len)) => {
551                        if flags.contains(Flags::UNESCAPED_UNICODE)
552                            && (flags.contains(Flags::UNESCAPED_LINE_TERMINATORS) || !(0x2028..=0x2029).contains(&c))
553                        {
554                            self.out.extend_from_slice(&s[pos..pos + len]);
555                        } else if c >= 0x10000 {
556                            let c = c - 0x10000;
557                            self.unicode_escape(0xd800 | (c >> 10));
558                            self.unicode_escape(0xdc00 | (c & 0x3ff));
559                        } else {
560                            self.unicode_escape(c);
561                        }
562                        pos += len;
563                    }
564                }
565            } else {
566                pos += 1;
567                // Each escape a fixed-size copy (a slice chosen at run time
568                // would be a `memcpy` call).
569                match us {
570                    b'"' if flags.contains(Flags::HEX_QUOT) => self.out.extend_from_slice(b"\\u0022"),
571                    b'"' => self.out.extend_from_slice(b"\\\""),
572                    b'\\' => self.out.extend_from_slice(b"\\\\"),
573                    b'/' if flags.contains(Flags::UNESCAPED_SLASHES) => self.out.push(b'/'),
574                    b'/' => self.out.extend_from_slice(b"\\/"),
575                    0x08 => self.out.extend_from_slice(b"\\b"),
576                    0x0c => self.out.extend_from_slice(b"\\f"),
577                    b'\n' => self.out.extend_from_slice(b"\\n"),
578                    b'\r' => self.out.extend_from_slice(b"\\r"),
579                    b'\t' => self.out.extend_from_slice(b"\\t"),
580                    b'<' if flags.contains(Flags::HEX_TAG) => self.out.extend_from_slice(b"\\u003C"),
581                    b'>' if flags.contains(Flags::HEX_TAG) => self.out.extend_from_slice(b"\\u003E"),
582                    b'&' if flags.contains(Flags::HEX_AMP) => self.out.extend_from_slice(b"\\u0026"),
583                    b'\'' if flags.contains(Flags::HEX_APOS) => self.out.extend_from_slice(b"\\u0027"),
584                    b'<' | b'>' | b'&' | b'\'' => self.out.push(us),
585                    c => self.unicode_escape(u32::from(c)),
586                }
587            }
588            pos = verbatim(&mut self.out, s, pos, hex);
589            if pos == s.len() {
590                break;
591            }
592        }
593        self.out.push(b'"');
594        Ok(())
595    }
596
597    fn unicode_escape(&mut self, us: u32) {
598        self.out.extend_from_slice(&[
599            b'\\',
600            b'u',
601            HEX[((us >> 12) & 0xf) as usize],
602            HEX[((us >> 8) & 0xf) as usize],
603            HEX[((us >> 4) & 0xf) as usize],
604            HEX[(us & 0xf) as usize],
605        ]);
606    }
607}
608
609/// `php_next_utf8_char`: the code point at the start of `s` and its length,
610/// or the number of bytes PHP skips as one invalid sequence (UTR #36
611/// strategy 2: an invalid sequence never swallows a byte that could start a
612/// valid one).
613pub fn next_utf8_char(s: &[u8]) -> Result<(u32, usize), usize> {
614    let lead = |c: u8| c < 0x80 || (0xc2..=0xf4).contains(&c);
615    let trail = |c: u8| (0x80..=0xbf).contains(&c);
616    let avail = s.len();
617    let c = *s.first().ok_or(1usize)?;
618    if c < 0x80 {
619        Ok((u32::from(c), 1))
620    } else if c < 0xc2 {
621        Err(1)
622    } else if c < 0xe0 {
623        if avail < 2 {
624            return Err(1);
625        }
626        if !trail(s[1]) {
627            return Err(if lead(s[1]) { 1 } else { 2 });
628        }
629        Ok(((u32::from(c) & 0x1f) << 6 | (u32::from(s[1]) & 0x3f), 2))
630    } else if c < 0xf0 {
631        if avail < 3 || !trail(s[1]) || !trail(s[2]) {
632            return Err(if avail < 2 || lead(s[1]) {
633                1
634            } else if avail < 3 || lead(s[2]) {
635                2
636            } else {
637                3
638            });
639        }
640        let ch = (u32::from(c) & 0x0f) << 12 | (u32::from(s[1]) & 0x3f) << 6 | (u32::from(s[2]) & 0x3f);
641        if ch < 0x800 || (0xd800..=0xdfff).contains(&ch) {
642            return Err(3);
643        }
644        Ok((ch, 3))
645    } else if c < 0xf5 {
646        if avail < 4 || !trail(s[1]) || !trail(s[2]) || !trail(s[3]) {
647            return Err(if avail < 2 || lead(s[1]) {
648                1
649            } else if avail < 3 || lead(s[2]) {
650                2
651            } else if avail < 4 || lead(s[3]) {
652                3
653            } else {
654                4
655            });
656        }
657        let ch = (u32::from(c) & 0x07) << 18
658            | (u32::from(s[1]) & 0x3f) << 12
659            | (u32::from(s[2]) & 0x3f) << 6
660            | (u32::from(s[3]) & 0x3f);
661        if !(0x10000..=0x10ffff).contains(&ch) {
662            return Err(4);
663        }
664        Ok((ch, 4))
665    } else {
666        Err(1)
667    }
668}
669
670// ---------------------------------------------------------------------------
671// Decoding (ext/json/json_scanner.re, ext/json/json_parser.y)
672// ---------------------------------------------------------------------------
673
674/// `json_decode($json, $assoc, $depth, $flags)`.
675///
676/// `assoc` overrides `JSON_OBJECT_AS_ARRAY` in `flags` when it is not
677/// `None`, as in PHP. Objects decode to [`Value::Object`] (`stdClass`) or, in
678/// array mode, to [`Value::Array`] with PHP's key rules (`"7"` is key `7`).
679/// Errors: [`Error::Json`] with PHP's code (empty input is a syntax error),
680/// [`Error::Value`] when `depth` is not in `1..=i32::MAX`.
681pub fn decode(json: &[u8], assoc: Option<bool>, depth: i64, flags: Flags) -> Result<Value, Error> {
682    decode_ext(json, assoc, depth, flags)
683}
684
685/// [`decode`] into a [`Value`] of any extension `X` (a decoded value never
686/// holds one), so a library with its own object type decodes without a copy.
687pub fn decode_ext<X: Extension>(json: &[u8], assoc: Option<bool>, depth: i64, flags: Flags) -> Result<Value<X>, Error> {
688    let mut flags = flags;
689    match assoc {
690        Some(true) => flags |= Flags::OBJECT_AS_ARRAY,
691        Some(false) => flags = flags.without(Flags::OBJECT_AS_ARRAY),
692        None => {}
693    }
694    let depth = decode_depth(json, depth, "json_decode(): Argument #3 ($depth)")?;
695    let builder = PhpBuilder::<X> { assoc: flags.contains(Flags::OBJECT_AS_ARRAY), ext: std::marker::PhantomData };
696    parse(json, flags, depth, &builder).map_err(ParseError::into_error)
697}
698
699/// `json_decode($json, true, $depth, $flags)` into the request model
700/// (`serde_json::Value`): PHP arrays that are lists become JSON arrays (so
701/// `{"0":"a"}` decodes to `["a"]`, as PHP's `[0 => 'a']` is a list), other
702/// arrays objects; empty objects become `[]`.
703///
704/// Fails with [`Error::Unrepresentable`] where PHP decodes a number to an
705/// infinite float (`1e999`), which `serde_json::Value` cannot hold.
706pub fn decode_value(json: &[u8], depth: i64, flags: Flags) -> Result<Json, Error> {
707    let depth = decode_depth(json, depth, "json_decode(): Argument #3 ($depth)")?;
708    parse(json, flags | Flags::OBJECT_AS_ARRAY, depth, &ValueBuilder).map_err(ParseError::into_error)
709}
710
711/// `json_validate($json, $depth, $flags)`: `Ok(())` when PHP returns `true`.
712///
713/// Only `JSON_INVALID_UTF8_IGNORE` is accepted in `flags` (PHP throws
714/// `ValueError` for anything else). Property names starting with NUL are
715/// valid here (they only fail when decoding to `stdClass`).
716pub fn validate(json: &[u8], depth: i64, flags: Flags) -> Result<(), Error> {
717    if flags != Flags::NONE && flags != Flags::INVALID_UTF8_IGNORE {
718        return Err(Error::Value(
719            "json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)"
720                .into(),
721        ));
722    }
723    let depth = decode_depth(json, depth, "json_validate(): Argument #2 ($depth)")?;
724    parse(json, flags, depth, &Validator).map_err(ParseError::into_error)
725}
726
727/// The argument checks `json_decode` and `json_validate` make before parsing.
728fn decode_depth(json: &[u8], depth: i64, argument: &str) -> Result<i32, Error> {
729    if json.is_empty() {
730        return Err(Error::Json(ErrorCode::Syntax));
731    }
732    if depth <= 0 {
733        return Err(Error::Value(format!("{argument} must be greater than 0")));
734    }
735    if depth > i64::from(i32::MAX) {
736        return Err(Error::Value(format!("{argument} must be less than {}", i32::MAX)));
737    }
738    Ok(depth as i32)
739}
740
741/// The text of a string token: the input bytes when the string has no
742/// escapes (valid UTF-8, as the scanner checked), or the decoded bytes (a
743/// short string inline, a longer one in a buffer of its size).
744enum Text<'a> {
745    Raw(&'a [u8]),
746    Short(Str),
747    Decoded(Vec<u8>),
748}
749
750impl Text<'_> {
751    /// The decoded bytes in `buf`, copied out.
752    fn decoded(buf: &[u8]) -> Self {
753        if buf.len() <= Str::INLINE { Text::Short(Str::copy_from(buf)) } else { Text::Decoded(buf.to_vec()) }
754    }
755
756    fn as_bytes(&self) -> &[u8] {
757        match self {
758            Text::Raw(b) => b,
759            Text::Short(s) => s,
760            Text::Decoded(v) => v,
761        }
762    }
763
764    /// The text as a PHP string (no copy of decoded bytes).
765    #[inline(always)]
766    fn into_str(self) -> Str {
767        match self {
768            Text::Raw(b) => Str::copy_from(b),
769            Text::Short(s) => s,
770            Text::Decoded(v) => Str::from(v),
771        }
772    }
773
774    /// The text as a Rust string (the scanner only produces UTF-8).
775    fn into_string(self) -> String {
776        match self {
777            Text::Raw(b) => String::from_utf8_lossy(b).into_owned(),
778            Text::Short(s) => String::from_utf8_lossy(&s).into_owned(),
779            Text::Decoded(v) => {
780                String::from_utf8(v).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
781            }
782        }
783    }
784}
785
786/// A token of PHP's JSON scanner. A number's or a string's value stays in
787/// the [`Scanner`] until it is taken, so a token fits in a register.
788#[derive(Clone, Copy, PartialEq, Eq)]
789enum Token {
790    LBrace,
791    RBrace,
792    LBracket,
793    RBracket,
794    Colon,
795    Comma,
796    Null,
797    True,
798    False,
799    /// [`Scanner::int`].
800    Int,
801    /// [`Scanner::double`].
802    Double,
803    /// [`Scanner::text`]: a string (also a big integer with `JSON_BIGINT_AS_STRING`).
804    Str,
805    /// The end of the input.
806    End,
807}
808
809/// The value of a scalar token, as the builders take it.
810enum Scalar<'a> {
811    Null,
812    True,
813    False,
814    Int(i64),
815    Double(f64),
816    Str(Text<'a>),
817}
818
819struct Scanner<'a> {
820    s: &'a [u8],
821    pos: usize,
822    flags: Flags,
823    /// Whether string tokens need their text (not when only validating).
824    keep: bool,
825    /// Where strings with escapes are decoded (reused for each).
826    buf: Vec<u8>,
827    /// The value of the last [`Token::Int`].
828    int: i64,
829    /// The value of the last [`Token::Double`].
830    double: f64,
831    /// The text of the last [`Token::Str`].
832    text: Text<'a>,
833}
834
835/// Length of the valid UTF-8 sequence (scanner byte ranges) at the start of
836/// `s`, if one starts there.
837fn utf8_len(s: &[u8]) -> Option<usize> {
838    let t = |i: usize| s.get(i).is_some_and(|b| (0x80..=0xbf).contains(b));
839    let c = *s.first()?;
840    match c {
841        0x00..=0x7f => Some(1),
842        0xc2..=0xdf if t(1) => Some(2),
843        0xe0 if s.get(1).is_some_and(|b| (0xa0..=0xbf).contains(b)) && t(2) => Some(3),
844        0xe1..=0xec | 0xee..=0xef if t(1) && t(2) => Some(3),
845        0xed if s.get(1).is_some_and(|b| (0x80..=0x9f).contains(b)) && t(2) => Some(3),
846        0xf0 if s.get(1).is_some_and(|b| (0x90..=0xbf).contains(b)) && t(2) && t(3) => Some(4),
847        0xf1..=0xf3 if t(1) && t(2) && t(3) => Some(4),
848        0xf4 if s.get(1).is_some_and(|b| (0x80..=0x8f).contains(b)) && t(2) && t(3) => Some(4),
849        _ => None,
850    }
851}
852
853const ONES: u64 = 0x0101_0101_0101_0101;
854const HIGH: u64 = 0x8080_8080_8080_8080;
855
856/// The eight bytes of `s` at `pos`, little-endian, when there are eight.
857#[inline(always)]
858fn word(s: &[u8], pos: usize) -> Option<u64> {
859    let chunk: [u8; 8] = s.get(pos..pos + 8)?.try_into().ok()?;
860    Some(u64::from_le_bytes(chunk))
861}
862
863/// The high bit of each byte of `w` equal to `b`. Exact up to the first match:
864/// a borrow can only mark bytes after a byte that matched.
865#[inline(always)]
866fn bytes_eq(w: u64, b: u8) -> u64 {
867    let x = w ^ (ONES * u64::from(b));
868    x.wrapping_sub(ONES) & !x & HIGH
869}
870
871/// The high bit of each byte of `w` below 0x20 or from 0x80 (exact up to the
872/// first match, as in [`bytes_eq`]).
873#[inline(always)]
874fn bytes_ctrl_or_high(w: u64) -> u64 {
875    (w | w.wrapping_sub(ONES * 0x20)) & HIGH
876}
877
878/// Where the first byte from `pos` that is not JSON whitespace (space, tab,
879/// CR, LF) is.
880#[inline(always)]
881fn whitespace(s: &[u8], mut pos: usize) -> usize {
882    while let Some(b' ' | b'\t' | b'\r' | b'\n') = s.get(pos) {
883        pos += 1;
884    }
885    pos
886}
887
888/// Where the first special string byte from `pos` is (a quote, a backslash,
889/// a control character, or a byte from 0x80), stepping eight bytes at a
890/// time; within the last seven bytes of `s`, `pos` itself (the caller reads
891/// those one by one).
892#[inline]
893fn plain(s: &[u8], mut pos: usize) -> usize {
894    while let Some(w) = word(s, pos) {
895        let special = bytes_ctrl_or_high(w) | bytes_eq(w, b'"') | bytes_eq(w, b'\\');
896        if special != 0 {
897            return pos + (special.trailing_zeros() / 8) as usize;
898        }
899        pos += 8;
900    }
901    pos
902}
903
904fn hex4(s: &[u8]) -> Option<u32> {
905    if s.len() < 4 {
906        return None;
907    }
908    let mut v = 0;
909    for &b in &s[..4] {
910        v = v << 4 | char::from(b).to_digit(16)?;
911    }
912    Some(v)
913}
914
915impl<'a> Scanner<'a> {
916    /// `php_json_scan`: the next token, or the scanner's error.
917    fn next(&mut self) -> Result<Token, ErrorCode> {
918        let s = self.s;
919        self.pos = whitespace(s, self.pos);
920        let Some(&c) = s.get(self.pos) else {
921            // The NUL terminator after the input.
922            return Ok(Token::End);
923        };
924        let token = match c {
925            b'{' => Token::LBrace,
926            b'}' => Token::RBrace,
927            b'[' => Token::LBracket,
928            b']' => Token::RBracket,
929            b':' => Token::Colon,
930            b',' => Token::Comma,
931            b'"' => {
932                self.pos += 1;
933                return self.string();
934            }
935            b'-' | b'0'..=b'9' => {
936                if let Some(t) = self.number() {
937                    return Ok(t);
938                }
939                return Err(ErrorCode::Syntax);
940            }
941            _ if s[self.pos..].starts_with(b"null") => {
942                self.pos += 4;
943                return Ok(Token::Null);
944            }
945            _ if s[self.pos..].starts_with(b"true") => {
946                self.pos += 4;
947                return Ok(Token::True);
948            }
949            _ if s[self.pos..].starts_with(b"false") => {
950                self.pos += 5;
951                return Ok(Token::False);
952            }
953            0x00..=0x1f => return Err(ErrorCode::CtrlChar),
954            _ => {
955                return Err(if utf8_len(&s[self.pos..]).is_some() { ErrorCode::Syntax } else { ErrorCode::Utf8 });
956            }
957        };
958        self.pos += 1;
959        Ok(token)
960    }
961
962    /// The text of the last [`Token::Str`], taken.
963    #[inline]
964    fn take_text(&mut self) -> Text<'a> {
965        std::mem::replace(&mut self.text, Text::Raw(b""))
966    }
967
968    /// The value of a scalar token just read (`None` for other tokens).
969    #[inline]
970    fn scalar(&mut self, token: Token) -> Option<Scalar<'a>> {
971        Some(match token {
972            Token::Null => Scalar::Null,
973            Token::True => Scalar::True,
974            Token::False => Scalar::False,
975            Token::Int => Scalar::Int(self.int),
976            Token::Double => Scalar::Double(self.double),
977            Token::Str => Scalar::Str(self.take_text()),
978            _ => return None,
979        })
980    }
981
982    /// `INT`, `FLOAT` or `EXP` at the cursor (longest match), or `None` when
983    /// none matches (a lone `-`).
984    fn number(&mut self) -> Option<Token> {
985        let s = self.s;
986        let start = self.pos;
987        let mut i = start;
988        let negative = s[i] == b'-';
989        if negative {
990            i += 1;
991        }
992        match s.get(i) {
993            Some(b'0') => i += 1,
994            Some(b'1'..=b'9') => {
995                while s.get(i).is_some_and(u8::is_ascii_digit) {
996                    i += 1;
997                }
998            }
999            _ => return None,
1000        }
1001        let int_end = i;
1002        let mut is_double = false;
1003        if s.get(i) == Some(&b'.') && s.get(i + 1).is_some_and(u8::is_ascii_digit) {
1004            i += 2;
1005            while s.get(i).is_some_and(u8::is_ascii_digit) {
1006                i += 1;
1007            }
1008            is_double = true;
1009        }
1010        if matches!(s.get(i), Some(b'e' | b'E')) {
1011            let mut j = i + 1;
1012            if matches!(s.get(j), Some(b'+' | b'-')) {
1013                j += 1;
1014            }
1015            if s.get(j).is_some_and(u8::is_ascii_digit) {
1016                while s.get(j).is_some_and(u8::is_ascii_digit) {
1017                    j += 1;
1018                }
1019                i = j;
1020                is_double = true;
1021            }
1022        }
1023        self.pos = i;
1024        // The token is ASCII digits, signs, '.', 'e': valid UTF-8.
1025        let text = || std::str::from_utf8(&s[start..i]).unwrap_or("0");
1026        if is_double {
1027            self.double = text().parse().unwrap_or(0.0);
1028            return Some(Token::Double);
1029        }
1030        debug_assert_eq!(int_end, i);
1031        let digits = &s[start + usize::from(negative)..int_end];
1032        let bigint = digits.len() > 19
1033            || (digits.len() == 19
1034                && !(digits < &b"9223372036854775808"[..] || (digits == b"9223372036854775808" && negative)));
1035        if !bigint {
1036            // At most 19 digits within the range of `i64` (or its minimum).
1037            let magnitude = digits.iter().fold(0u64, |m, d| m * 10 + u64::from(d - b'0'));
1038            let i = if negative { 0u64.wrapping_sub(magnitude) as i64 } else { magnitude as i64 };
1039            self.int = i;
1040            return Some(Token::Int);
1041        }
1042        if self.flags.contains(Flags::BIGINT_AS_STRING) {
1043            self.text = Text::Raw(&s[start..i]);
1044            return Some(Token::Str);
1045        }
1046        self.double = text().parse().unwrap_or(0.0);
1047        Some(Token::Double)
1048    }
1049
1050    /// A string after its opening quote (`STR_P1`, then `STR_P2`).
1051    fn string(&mut self) -> Result<Token, ErrorCode> {
1052        let s = self.s;
1053        let start = self.pos;
1054        // The common case: no escapes and valid UTF-8, borrowed from the input.
1055        loop {
1056            self.pos = plain(s, self.pos);
1057            let Some(&c) = s.get(self.pos) else {
1058                // The NUL terminator is a control character inside a string.
1059                return Err(ErrorCode::CtrlChar);
1060            };
1061            match c {
1062                0x00..=0x1f => return Err(ErrorCode::CtrlChar),
1063                b'"' => {
1064                    let raw = &s[start..self.pos];
1065                    self.pos += 1;
1066                    self.text = Text::Raw(raw);
1067                    return Ok(Token::Str);
1068                }
1069                b'\\' => break,
1070                0x20..=0x7f => self.pos += 1,
1071                _ => match utf8_len(&s[self.pos..]) {
1072                    Some(n) => self.pos += n,
1073                    None => break,
1074                },
1075            }
1076        }
1077        self.decode_string(start)
1078    }
1079
1080    /// The rest of a string that has escapes or invalid UTF-8, decoded into
1081    /// the scanner's buffer, then copied out at its size.
1082    fn decode_string(&mut self, start: usize) -> Result<Token, ErrorCode> {
1083        let s = self.s;
1084        let substitute = self.flags.contains(Flags::INVALID_UTF8_SUBSTITUTE);
1085        let tolerant = self.flags.intersects(Flags::INVALID_UTF8_IGNORE | Flags::INVALID_UTF8_SUBSTITUTE);
1086        let keep = self.keep;
1087        let out = &mut self.buf;
1088        out.clear();
1089        if keep {
1090            out.extend_from_slice(&s[start..self.pos]);
1091        }
1092        let push_char = |out: &mut Vec<u8>, c: char| {
1093            if keep {
1094                out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
1095            }
1096        };
1097        let mut run = self.pos;
1098        loop {
1099            // Between escapes too (`\/` in every URL PHP encodes).
1100            self.pos = plain(s, self.pos);
1101            let Some(&c) = s.get(self.pos) else {
1102                // The NUL terminator is a control character inside a string.
1103                return Err(ErrorCode::CtrlChar);
1104            };
1105            match c {
1106                0x00..=0x1f => return Err(ErrorCode::CtrlChar),
1107                b'"' => {
1108                    self.pos += 1;
1109                    if keep {
1110                        out.extend_from_slice(&s[run..self.pos - 1]);
1111                        self.text = Text::decoded(out);
1112                    }
1113                    return Ok(Token::Str);
1114                }
1115                b'\\' => {
1116                    if keep {
1117                        out.extend_from_slice(&s[run..self.pos]);
1118                    }
1119                    let esc = s.get(self.pos + 1).copied();
1120                    let decoded = match esc {
1121                        Some(b'"') => b'"',
1122                        Some(b'\\') => b'\\',
1123                        Some(b'/') => b'/',
1124                        Some(b'b') => 0x08,
1125                        Some(b'f') => 0x0c,
1126                        Some(b'n') => b'\n',
1127                        Some(b'r') => b'\r',
1128                        Some(b't') => b'\t',
1129                        Some(b'u') => {
1130                            let Some(code) = hex4(&s[self.pos + 2..]) else {
1131                                return Err(ErrorCode::Syntax);
1132                            };
1133                            if (0xd800..=0xdbff).contains(&code)
1134                                && s.get(self.pos + 6) == Some(&b'\\')
1135                                && s.get(self.pos + 7) == Some(&b'u')
1136                                && let Some(low) = hex4(&s[self.pos + 8..]).filter(|l| (0xdc00..=0xdfff).contains(l))
1137                            {
1138                                let c = 0x10000 + ((code & 0x3ff) << 10) + (low & 0x3ff);
1139                                push_char(out, char::from_u32(c).unwrap_or('\u{fffd}'));
1140                                self.pos += 12;
1141                                run = self.pos;
1142                                continue;
1143                            }
1144                            match char::from_u32(code) {
1145                                Some(ch) => {
1146                                    push_char(out, ch);
1147                                    self.pos += 6;
1148                                    run = self.pos;
1149                                    continue;
1150                                }
1151                                None => return Err(ErrorCode::Utf16),
1152                            }
1153                        }
1154                        _ => return Err(ErrorCode::Syntax),
1155                    };
1156                    if keep {
1157                        out.push(decoded);
1158                    }
1159                    self.pos += 2;
1160                    run = self.pos;
1161                }
1162                0x20..=0x7f => self.pos += 1,
1163                _ => match utf8_len(&s[self.pos..]) {
1164                    Some(n) => self.pos += n,
1165                    None if tolerant => {
1166                        if keep {
1167                            out.extend_from_slice(&s[run..self.pos]);
1168                        }
1169                        if substitute {
1170                            push_char(out, '\u{fffd}');
1171                        }
1172                        self.pos += 1;
1173                        run = self.pos;
1174                    }
1175                    None => return Err(ErrorCode::Utf8),
1176                },
1177            }
1178        }
1179    }
1180}
1181
1182/// How the parser builds values: `stdClass`/arrays as [`Value`], the request
1183/// model as `serde_json::Value`, or nothing (`json_validate`). Containers are
1184/// built once complete, from their entries, so they are allocated at their size.
1185trait Build {
1186    type Value;
1187    type Key;
1188
1189    /// Whether strings are needed (their text is not decoded otherwise).
1190    fn text(&self) -> bool {
1191        true
1192    }
1193    /// The value of a scalar token.
1194    fn scalar(&self, token: Scalar<'_>) -> Result<Self::Value, ParseError>;
1195    /// The key of a member, when the member is complete (`php_json_parser_object_update`'s checks).
1196    fn key(&self, key: Text<'_>) -> Result<Self::Key, ParseError>;
1197    /// An array of these elements.
1198    fn array(&self, items: Vec<Self::Value>) -> Self::Value;
1199    /// An object of these members, assigned in order.
1200    fn object(&self, members: Vec<(Self::Key, Self::Value)>) -> Self::Value;
1201}
1202
1203enum ParseError {
1204    Code(ErrorCode),
1205    Unrepresentable,
1206}
1207
1208impl From<ErrorCode> for ParseError {
1209    /// The error `code`.
1210    fn from(code: ErrorCode) -> Self {
1211        ParseError::Code(code)
1212    }
1213}
1214
1215impl ParseError {
1216    fn into_error(self) -> Error {
1217        match self {
1218            ParseError::Code(code) => Error::Json(code),
1219            ParseError::Unrepresentable => Error::Unrepresentable,
1220        }
1221    }
1222}
1223
1224struct PhpBuilder<X> {
1225    assoc: bool,
1226    ext: std::marker::PhantomData<fn() -> X>,
1227}
1228
1229impl<X: Extension> Build for PhpBuilder<X> {
1230    type Value = Value<X>;
1231    type Key = ArrayKey;
1232
1233    /// The PHP value of a scalar token.
1234    #[inline(always)]
1235    fn scalar(&self, token: Scalar<'_>) -> Result<Value<X>, ParseError> {
1236        Ok(match token {
1237            Scalar::Null => Value::Null,
1238            Scalar::True => Value::Bool(true),
1239            Scalar::False => Value::Bool(false),
1240            Scalar::Int(i) => Value::Int(i),
1241            Scalar::Double(d) => Value::Float(d),
1242            Scalar::Str(s) => Value::Str(s.into_str()),
1243        })
1244    }
1245
1246    /// A normalised key in assoc mode; a property name (not starting with NUL) otherwise.
1247    fn key(&self, key: Text<'_>) -> Result<ArrayKey, ParseError> {
1248        if self.assoc {
1249            // `zend_symtable_update`.
1250            return Ok(match numeric_key(key.as_bytes()) {
1251                Some(i) => ArrayKey::Int(i),
1252                None => ArrayKey::Str(key.into_str()),
1253            });
1254        }
1255        if key.as_bytes().first() == Some(&0) {
1256            return Err(ParseError::Code(ErrorCode::InvalidPropertyName));
1257        }
1258        Ok(ArrayKey::Str(key.into_str()))
1259    }
1260
1261    /// The decoded list as a PHP array.
1262    fn array(&self, items: Vec<Value<X>>) -> Value<X> {
1263        if items.is_empty() {
1264            return Value::Array(Array::new());
1265        }
1266        Value::Array(Array::from_list(items))
1267    }
1268
1269    /// The object as a PHP array (assoc mode) or a `stdClass`.
1270    fn object(&self, members: Vec<(ArrayKey, Value<X>)>) -> Value<X> {
1271        // Each member assigned in order, as `$a[$k] = $v`.
1272        let object = Array::from_pairs(members);
1273        if self.assoc { Value::Array(object) } else { Value::Object(object) }
1274    }
1275}
1276
1277struct ValueBuilder;
1278
1279impl Build for ValueBuilder {
1280    type Value = Json;
1281    type Key = String;
1282
1283    /// The `serde_json::Value` of a scalar token (`Unrepresentable` for `INF`).
1284    fn scalar(&self, token: Scalar<'_>) -> Result<Json, ParseError> {
1285        Ok(match token {
1286            Scalar::Null => Json::Null,
1287            Scalar::True => Json::Bool(true),
1288            Scalar::False => Json::Bool(false),
1289            Scalar::Int(i) => Json::from(i),
1290            Scalar::Double(d) => Json::Number(Number::from_f64(d).ok_or(ParseError::Unrepresentable)?),
1291            Scalar::Str(s) => Json::String(s.into_string()),
1292        })
1293    }
1294
1295    /// The member name.
1296    fn key(&self, key: Text<'_>) -> Result<String, ParseError> {
1297        Ok(key.into_string())
1298    }
1299
1300    /// The JSON array.
1301    fn array(&self, items: Vec<Json>) -> Json {
1302        Json::Array(items)
1303    }
1304
1305    /// The JSON object (a repeated key replaces the value in place, as
1306    /// `zend_symtable_update` does), or a JSON array when its keys are
1307    /// `0, 1, 2...` (as PHP's array would be a list).
1308    fn object(&self, members: Vec<(String, Json)>) -> Json {
1309        let mut object = Map::with_capacity(members.len());
1310        for (k, v) in members {
1311            object.insert(k, v);
1312        }
1313        let is_list = object.keys().enumerate().all(|(i, k)| numeric_key(k.as_bytes()) == Some(i as i64));
1314        if is_list { Json::Array(object.into_iter().map(|(_, v)| v).collect()) } else { Json::Object(object) }
1315    }
1316}
1317
1318struct Validator;
1319
1320impl Build for Validator {
1321    type Value = ();
1322    type Key = ();
1323
1324    /// No: validating needs no text.
1325    fn text(&self) -> bool {
1326        false
1327    }
1328
1329    /// Accepts any scalar.
1330    fn scalar(&self, _: Scalar<'_>) -> Result<(), ParseError> {
1331        Ok(())
1332    }
1333
1334    /// Accepts any member name.
1335    fn key(&self, _: Text<'_>) -> Result<(), ParseError> {
1336        Ok(())
1337    }
1338
1339    /// Builds nothing.
1340    fn array(&self, _: Vec<()>) {}
1341
1342    /// Builds nothing.
1343    fn object(&self, _: Vec<((), ())>) {}
1344}
1345
1346/// `YYMAXDEPTH`: the bison parser stack never holds this many states; the
1347/// push that would reach it fails with "memory exhausted", a syntax error.
1348const PARSER_STACK_LIMIT: usize = 10000;
1349
1350/// An open array or object, where its entries start on the parser's
1351/// value stacks, and how many parser-stack entries it holds.
1352enum Frame {
1353    /// `'[' $@ element ','?`
1354    Array { start: usize, entries: usize },
1355    /// `'{' $@ (member ',')? key ':'`, the key on the parser's key stack.
1356    Object { start: usize, entries: usize },
1357}
1358
1359struct Parser<'a> {
1360    scanner: Scanner<'a>,
1361    /// `parser->depth` (starts at 1) and `max_depth`.
1362    depth: i32,
1363    max_depth: i32,
1364    /// Entries on bison's state stack.
1365    stack: usize,
1366}
1367
1368impl Parser<'_> {
1369    /// A push onto bison's state stack (a shift, or the reduction of an
1370    /// empty rule).
1371    fn push(&mut self) -> Result<(), ErrorCode> {
1372        self.stack += 1;
1373        if self.stack >= PARSER_STACK_LIMIT { Err(ErrorCode::Syntax) } else { Ok(()) }
1374    }
1375
1376    /// `PHP_JSON_DEPTH_INC` (the mid-rule action after `[` or `{`).
1377    fn enter(&mut self) -> Result<(), ErrorCode> {
1378        if self.max_depth != 0 && self.depth >= self.max_depth {
1379            return Err(ErrorCode::Depth);
1380        }
1381        self.depth += 1;
1382        self.push()
1383    }
1384}
1385
1386/// The entries of `stack` from `start`, moved out in one copy into a buffer
1387/// of their size (the stack keeps its buffer for the entries to come).
1388fn tail<T>(stack: &mut Vec<T>, start: usize) -> Vec<T> {
1389    if start > 0 {
1390        return stack.split_off(start);
1391    }
1392    let mut all = Vec::with_capacity(stack.len());
1393    all.append(stack);
1394    all
1395}
1396
1397/// `php_json_yyparse`, without recursion: the same tokens are read in the
1398/// same order and the same error is reported first.
1399fn parse<B: Build>(json: &[u8], flags: Flags, max_depth: i32, builder: &B) -> Result<B::Value, ParseError> {
1400    let mut p = Parser {
1401        scanner: Scanner {
1402            s: json,
1403            pos: 0,
1404            flags,
1405            keep: builder.text(),
1406            buf: Vec::new(),
1407            int: 0,
1408            double: 0.0,
1409            text: Text::Raw(b""),
1410        },
1411        depth: 1,
1412        max_depth,
1413        // State 0.
1414        stack: 1,
1415    };
1416    let mut frames: Vec<Frame> = Vec::new();
1417    // The key of the member being parsed in each open object, innermost last.
1418    let mut keys: Vec<Text<'_>> = Vec::new();
1419    // The elements and members of the open containers, innermost last.
1420    let mut items: Vec<B::Value> = Vec::new();
1421    let mut members: Vec<(B::Key, B::Value)> = Vec::with_capacity((json.len() / 16).min(64));
1422    // The next token, when it was read ahead.
1423    let mut ahead: Option<Token> = None;
1424    loop {
1425        // Parse a value.
1426        let token = match ahead.take() {
1427            Some(t) => t,
1428            None => p.scanner.next()?,
1429        };
1430        let mut value = match token {
1431            Token::LBracket => {
1432                p.push()?;
1433                p.enter()?;
1434                let token = p.scanner.next()?;
1435                match token {
1436                    Token::RBracket => {
1437                        // `elements: %empty`, then `]`.
1438                        p.push()?;
1439                        p.push()?;
1440                        p.depth -= 1;
1441                        p.stack -= 3;
1442                        builder.array(Vec::new())
1443                    }
1444                    Token::RBrace => {
1445                        p.push()?;
1446                        p.push()?;
1447                        return Err(ErrorCode::StateMismatch.into());
1448                    }
1449                    t => {
1450                        frames.push(Frame::Array { start: items.len(), entries: 2 });
1451                        ahead = Some(t);
1452                        continue;
1453                    }
1454                }
1455            }
1456            Token::LBrace => {
1457                p.push()?;
1458                p.enter()?;
1459                match p.scanner.next()? {
1460                    Token::RBrace => {
1461                        // `members: %empty`, then `}`.
1462                        p.push()?;
1463                        p.push()?;
1464                        p.depth -= 1;
1465                        p.stack -= 3;
1466                        builder.object(Vec::new())
1467                    }
1468                    Token::RBracket => {
1469                        p.push()?;
1470                        p.push()?;
1471                        return Err(ErrorCode::StateMismatch.into());
1472                    }
1473                    Token::Str => {
1474                        // The key, then `:`.
1475                        let key = p.scanner.take_text();
1476                        p.push()?;
1477                        if !matches!(p.scanner.next()?, Token::Colon) {
1478                            return Err(ErrorCode::Syntax.into());
1479                        }
1480                        p.push()?;
1481                        keys.push(key);
1482                        frames.push(Frame::Object { start: members.len(), entries: 4 });
1483                        continue;
1484                    }
1485                    _ => return Err(ErrorCode::Syntax.into()),
1486                }
1487            }
1488            Token::RBrace | Token::RBracket | Token::Colon | Token::Comma | Token::End => {
1489                return Err(ErrorCode::Syntax.into());
1490            }
1491            token => {
1492                p.push()?;
1493                match p.scanner.scalar(token) {
1494                    Some(scalar) => builder.scalar(scalar)?,
1495                    None => builder.scalar(Scalar::Null)?,
1496                }
1497            }
1498        };
1499        // `value` is complete and occupies one stack entry: close every
1500        // container it completes.
1501        loop {
1502            let Some(frame) = frames.last_mut() else {
1503                // `start: value EOI`.
1504                return match p.scanner.next()? {
1505                    Token::End => Ok(value),
1506                    _ => Err(ErrorCode::Syntax.into()),
1507                };
1508            };
1509            match frame {
1510                Frame::Array { start, entries } => {
1511                    // `element: value` or `element: element ',' value`.
1512                    p.stack -= *entries - 2;
1513                    *entries = 3;
1514                    let start = *start;
1515                    items.push(value);
1516                    match p.scanner.next()? {
1517                        Token::Comma => {
1518                            p.push()?;
1519                            *entries = 4;
1520                            break;
1521                        }
1522                        Token::RBracket => {
1523                            p.push()?;
1524                            p.depth -= 1;
1525                            p.stack -= 3;
1526                            frames.pop();
1527                            value = builder.array(tail(&mut items, start));
1528                        }
1529                        Token::RBrace => {
1530                            p.push()?;
1531                            return Err(ErrorCode::StateMismatch.into());
1532                        }
1533                        _ => return Err(ErrorCode::Syntax.into()),
1534                    }
1535                }
1536                Frame::Object { start, entries } => {
1537                    // `member: key ':' value` or `member: member ',' key ':' value`.
1538                    p.stack -= *entries - 2;
1539                    *entries = 3;
1540                    let start = *start;
1541                    let k = builder.key(keys.pop().unwrap_or(Text::Raw(b"")))?;
1542                    members.push((k, value));
1543                    match p.scanner.next()? {
1544                        Token::Comma => {
1545                            p.push()?;
1546                            match p.scanner.next()? {
1547                                Token::Str => {
1548                                    p.push()?;
1549                                    keys.push(p.scanner.take_text());
1550                                }
1551                                _ => return Err(ErrorCode::Syntax.into()),
1552                            }
1553                            if !matches!(p.scanner.next()?, Token::Colon) {
1554                                return Err(ErrorCode::Syntax.into());
1555                            }
1556                            p.push()?;
1557                            *entries = 6;
1558                            break;
1559                        }
1560                        Token::RBrace => {
1561                            p.push()?;
1562                            p.depth -= 1;
1563                            p.stack -= 3;
1564                            frames.pop();
1565                            value = builder.object(tail(&mut members, start));
1566                        }
1567                        Token::RBracket => {
1568                            p.push()?;
1569                            return Err(ErrorCode::StateMismatch.into());
1570                        }
1571                        _ => return Err(ErrorCode::Syntax.into()),
1572                    }
1573                }
1574            }
1575        }
1576    }
1577}
1578
1579#[cfg(test)]
1580mod tests {
1581    use super::*;
1582    use serde_json::json;
1583
1584    fn v(j: Json) -> Value {
1585        Value::from_json(&j)
1586    }
1587
1588    fn enc(j: &Json, flags: Flags) -> String {
1589        encode(&v(j.clone()), flags, DEFAULT_DEPTH).unwrap()
1590    }
1591
1592    #[test]
1593    fn encodes_like_php() {
1594        assert_eq!(enc(&json!({"a": [], "b": {}, "c": [1, 2]}), Flags::NONE), r#"{"a":[],"b":{},"c":[1,2]}"#);
1595        assert_eq!(enc(&json!({"0": "x", "1": "y"}), Flags::NONE), r#"["x","y"]"#);
1596        assert_eq!(enc(&json!("a/\u{e9}\u{1f600}"), Flags::NONE), "\"a\\/\\u00e9\\ud83d\\ude00\"");
1597        assert_eq!(enc(&json!("a/é"), Flags::UNESCAPED_SLASHES | Flags::UNESCAPED_UNICODE), r#""a/é""#);
1598        assert_eq!(enc(&json!(1.0), Flags::PRESERVE_ZERO_FRACTION), "1.0");
1599        assert_eq!(enc(&json!(0.1), Flags::NONE), "0.1");
1600        assert_eq!(enc(&json!([1, {}]), Flags::PRETTY_PRINT), "[\n    1,\n    {}\n]");
1601        assert_eq!(enc(&json!([1]), Flags::FORCE_OBJECT), r#"{"0":1}"#);
1602    }
1603
1604    #[test]
1605    fn encode_errors_like_php() {
1606        let bad: Value =
1607            Value::Array([Value::Float(f64::INFINITY), Value::Str(Str::from(vec![0xff]))].into_iter().collect());
1608        assert_eq!(encode(&bad, Flags::NONE, 512), Err(Error::Json(ErrorCode::Utf8)));
1609        assert_eq!(
1610            encode(&bad, Flags::PARTIAL_OUTPUT_ON_ERROR, 512),
1611            Err(Error::Partial { json: "[0,null]".into(), code: ErrorCode::Utf8 })
1612        );
1613        assert_eq!(encode(&v(json!([[1]])), Flags::NONE, 1), Err(Error::Json(ErrorCode::Depth)));
1614        assert_eq!(encode(&v(json!([[1]])), Flags::NONE, 4294967298), Ok("[[1]]".into()));
1615    }
1616
1617    #[test]
1618    fn decodes_like_php() {
1619        assert_eq!(decode_value(br#"{"0":1,"1":2}"#, 512, Flags::NONE).unwrap(), json!([1, 2]));
1620        assert_eq!(decode_value(br#"{"1":1,"0":2}"#, 512, Flags::NONE).unwrap(), json!({"1": 1, "0": 2}));
1621        assert_eq!(decode_value(b"{}", 512, Flags::NONE).unwrap(), json!([]));
1622        assert_eq!(decode(b"-0", None, 512, Flags::NONE).unwrap(), Value::Int(0));
1623        assert_eq!(
1624            decode(b"9223372036854775808", None, 512, Flags::NONE).unwrap(),
1625            Value::Float(9223372036854775808.0)
1626        );
1627        assert_eq!(decode(b"-9223372036854775808", None, 512, Flags::NONE).unwrap(), Value::Int(i64::MIN));
1628        let object = decode(br#"{"a":1,"a":2,"b":3}"#, None, 512, Flags::NONE).unwrap();
1629        assert_eq!(object.to_json(), json!({"a": 2, "b": 3}));
1630        assert!(matches!(object, Value::Object(_)));
1631    }
1632
1633    #[test]
1634    fn decode_errors_like_php() {
1635        let code = |s: &[u8], depth: i64| decode(s, Some(true), depth, Flags::NONE).unwrap_err().code();
1636        assert_eq!(code(b"[\x01", 1), ErrorCode::Depth);
1637        assert_eq!(code(b"[]", 1), ErrorCode::Depth);
1638        assert_eq!(code(b"\"abc", 512), ErrorCode::CtrlChar);
1639        assert_eq!(code(b"1\0", 512), ErrorCode::CtrlChar);
1640        assert_eq!(code(b"[1}", 512), ErrorCode::StateMismatch);
1641        assert_eq!(code(b"[1,}", 512), ErrorCode::Syntax);
1642        assert_eq!(code(br#""\ud800""#, 512), ErrorCode::Utf16);
1643        assert_eq!(code(b"\xff", 512), ErrorCode::Utf8);
1644        assert_eq!(code("é".as_bytes(), 512), ErrorCode::Syntax);
1645        assert_eq!(
1646            decode(br#"{"\u0000a":1 x"#, Some(false), 512, Flags::NONE),
1647            Err(Error::Json(ErrorCode::InvalidPropertyName))
1648        );
1649        let nest = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
1650        assert!(decode(nest(4998).as_bytes(), Some(true), 100000, Flags::NONE).is_ok());
1651        assert_eq!(code(nest(4999).as_bytes(), 100000), ErrorCode::Syntax);
1652        assert!(matches!(decode(b"1", None, 0, Flags::NONE), Err(Error::Value(_))));
1653        assert_eq!(code(b"", 0), ErrorCode::Syntax);
1654    }
1655}