Skip to main content

sql_values/postgres/
jsonb.rs

1//! PostgreSQL 18's `jsonb`, read as `jsonb_in` reads it, printed as `jsonb_out` prints it, and
2//! equal, ordered and hashed as `compareJsonbContainers` compares it for the btree order.
3//!
4//! A value is held as the token stream `JsonbIteratorNext` walks, so parsing, printing,
5//! comparing and dropping never recurse, and nesting of any depth stays within the stack.
6
7use alloc::{string::String, vec::Vec};
8use core::{
9    cmp::Ordering,
10    fmt::{self, Write},
11    hash::{Hash, Hasher},
12    mem,
13};
14
15use super::numeric::{NumericError, PgNumeric};
16
17/// Why `jsonb_in` refuses a text, one variant per detail PostgreSQL gives, each printed as
18/// PostgreSQL's message and detail without the token it quotes.
19///
20/// ```
21/// use sql_values::postgres::{JsonbError, NumericError, PgJsonb};
22///
23/// assert_eq!(PgJsonb::parse(r#"{"a":1,}"#), Err(JsonbError::ExpectedString));
24/// assert_eq!(PgJsonb::parse("01"), Err(JsonbError::InvalidToken));
25/// assert_eq!(PgJsonb::parse(r#""\ud83d""#), Err(JsonbError::LowSurrogateExpected));
26/// assert_eq!(
27///     PgJsonb::parse("1e1000000"),
28///     Err(JsonbError::Numeric(NumericError::FormatOverflow)),
29/// );
30/// assert_eq!(
31///     PgJsonb::parse(r#""\u0000""#).unwrap_err().to_string(),
32///     r"unsupported Unicode escape sequence: \u0000 cannot be converted to text",
33/// );
34/// ```
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
36pub enum JsonbError {
37    /// A word other than `true`, `false` and `null`, a malformed number, a character that
38    /// starts no token, or a string the input ends inside.
39    #[error("invalid input syntax for type json: Token is invalid")]
40    InvalidToken,
41    /// A backslash followed by a character that escapes nothing.
42    #[error("invalid input syntax for type json: Escape sequence is invalid")]
43    InvalidEscape,
44    /// A control character below `0x20` written in a string without an escape.
45    #[error("invalid input syntax for type json: Character must be escaped")]
46    UnescapedControlCharacter,
47    /// A `\u` not followed by four hexadecimal digits.
48    #[error(
49        "invalid input syntax for type json: \"\\u\" must be followed by four hexadecimal digits"
50    )]
51    UnicodeEscapeFormat,
52    /// A high surrogate escape directly after another.
53    #[error(
54        "invalid input syntax for type json: Unicode high surrogate must not follow a high surrogate"
55    )]
56    HighSurrogateRepeated,
57    /// A low surrogate escape without a high surrogate before it, or a high surrogate escape
58    /// followed by anything but a low surrogate escape.
59    #[error(
60        "invalid input syntax for type json: Unicode low surrogate must follow a high surrogate"
61    )]
62    LowSurrogateExpected,
63    /// The escape `\u0000`, which `text` cannot hold.
64    #[error("unsupported Unicode escape sequence: \\u0000 cannot be converted to text")]
65    CodePointZero,
66    /// A token where a value belongs.
67    #[error("invalid input syntax for type json: Expected JSON value")]
68    ExpectedValue,
69    /// A token other than a key after a comma in an object.
70    #[error("invalid input syntax for type json: Expected string")]
71    ExpectedString,
72    /// A token other than a key or `}` after `{`.
73    #[error("invalid input syntax for type json: Expected string or \"}}\"")]
74    ExpectedStringOrObjectEnd,
75    /// A token other than `:` after a key.
76    #[error("invalid input syntax for type json: Expected \":\"")]
77    ExpectedColon,
78    /// A token other than `,` or `}` after a value in an object.
79    #[error("invalid input syntax for type json: Expected \",\" or \"}}\"")]
80    ExpectedCommaOrObjectEnd,
81    /// A token other than `,` or `]` after an element in an array.
82    #[error("invalid input syntax for type json: Expected \",\" or \"]\"")]
83    ExpectedCommaOrArrayEnd,
84    /// A token after the whole value.
85    #[error("invalid input syntax for type json: Expected end of input")]
86    ExpectedEnd,
87    /// Input that ends before its value does.
88    #[error("invalid input syntax for type json: The input string ended unexpectedly")]
89    UnexpectedEnd,
90    /// A number `numeric_in` refuses, one beyond the weight or scale PostgreSQL stores.
91    #[error(transparent)]
92    Numeric(NumericError),
93}
94
95/// The kind of a top-level `jsonb` value, as `cannotCastJsonbValue` names it when a cast to a
96/// scalar type refuses it.
97///
98/// ```
99/// use sql_values::postgres::JsonbKind;
100///
101/// assert_eq!(JsonbKind::Numeric.to_string(), "numeric");
102/// ```
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub enum JsonbKind {
105    /// `null`.
106    Null,
107    /// A string.
108    String,
109    /// A number.
110    Numeric,
111    /// `true` or `false`.
112    Boolean,
113    /// An array.
114    Array,
115    /// An object.
116    Object,
117}
118
119impl fmt::Display for JsonbKind {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(match self {
122            Self::Null => "null",
123            Self::String => "string",
124            Self::Numeric => "numeric",
125            Self::Boolean => "boolean",
126            Self::Array => "array",
127            Self::Object => "object",
128        })
129    }
130}
131
132/// A PostgreSQL `jsonb` value, its object keys in `jsonb`'s storage order with the last of
133/// duplicate keys kept, equal, ordered and hashed as `jsonb`'s btree operator class compares it.
134///
135/// The order puts an empty top-level array first, then `null`, strings, numbers, booleans,
136/// arrays and objects. Arrays compare by element count and then element by element, objects by
137/// pair count and then key and value in storage order, and numbers by value, so `1.0` equals
138/// `1`. Strings and keys compare by their bytes, as under the `C` collation. A server whose
139/// default collation is another one orders strings by it, while equality stays the same.
140///
141/// Its [`Display`](fmt::Display) is `jsonb_out`, so equal values can print differently.
142///
143/// ```
144/// use sql_values::postgres::PgJsonb;
145///
146/// let jsonb = |text| PgJsonb::parse(text).unwrap();
147/// assert_eq!(jsonb(r#"{"bb":1,"a":2,"c":3,"a":4}"#).to_string(), r#"{"a": 4, "c": 3, "bb": 1}"#);
148/// assert_eq!(jsonb(" [ 1 , {\"b\" : null } ] ").to_string(), r#"[1, {"b": null}]"#);
149/// assert_eq!(jsonb("1.0"), jsonb("1"));
150/// assert_eq!(jsonb("1.0").to_string(), "1.0");
151/// assert!(jsonb("[]") < jsonb("null"));
152/// assert!(jsonb(r#""B""#) < jsonb(r#""a""#));
153/// assert!(jsonb("true") < jsonb("[null]"));
154/// assert!(jsonb(r#"{"b": 1}"#) < jsonb(r#"{"a": 1, "b": 2}"#));
155/// ```
156#[derive(Debug, Clone)]
157pub struct PgJsonb {
158    /// The tokens in iteration order, each container's pairs or elements between its start and
159    /// end.
160    tokens: Vec<Token>,
161    /// The decoded text of every string and key, each token's span into it.
162    strings: String,
163}
164
165/// One token of a value, as `JsonbIteratorNext` yields it.
166#[derive(Debug, Clone)]
167enum Token {
168    Null,
169    Bool(bool),
170    Number(PgNumeric),
171    String(Span),
172    Key(Span),
173    /// An array's start and its element count.
174    ArrayStart(usize),
175    ArrayEnd,
176    /// An object's start and its pair count.
177    ObjectStart(usize),
178    ObjectEnd,
179}
180
181/// A byte range of [`PgJsonb::strings`] or of the input.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183struct Span {
184    start: usize,
185    end: usize,
186}
187
188impl Token {
189    /// The rank of the token's `jbvType`, the order between values of different types.
190    const fn rank(&self) -> u8 {
191        match self {
192            Self::Null => 0,
193            Self::String(_) | Self::Key(_) => 1,
194            Self::Number(_) => 2,
195            Self::Bool(_) => 3,
196            Self::ArrayStart(_) | Self::ArrayEnd => 4,
197            Self::ObjectStart(_) | Self::ObjectEnd => 5,
198        }
199    }
200}
201
202impl PgJsonb {
203    /// PostgreSQL's `jsonb_in`, reading one JSON value between blanks, its numbers read by
204    /// `numeric_in` and its `\u` escapes decoded with surrogate pairs combined.
205    ///
206    /// PostgreSQL also refuses nesting deeper than its `max_stack_depth` allows and strings or
207    /// containers beyond the 256 MiB its binary format holds. Those limits depend on the
208    /// server, and this reads any depth and size.
209    ///
210    /// # Errors
211    ///
212    /// The [`JsonbError`] PostgreSQL raises, the first one in the text as it reads it.
213    ///
214    /// ```
215    /// use sql_values::postgres::{JsonbError, PgJsonb};
216    ///
217    /// let printed = |text| PgJsonb::parse(text).map(|jsonb| jsonb.to_string());
218    /// assert_eq!(printed("1e2").unwrap(), "100");
219    /// assert_eq!(printed("-0.0").unwrap(), "0.0");
220    /// assert_eq!(printed(r#""\u00e9 \ud83d\ude00 \/""#).unwrap(), "\"é 😀 /\"");
221    /// assert_eq!(printed("[1 2]"), Err(JsonbError::ExpectedCommaOrArrayEnd));
222    /// assert_eq!(printed("[1,"), Err(JsonbError::UnexpectedEnd));
223    /// ```
224    pub fn parse(text: &str) -> Result<Self, JsonbError> {
225        Parser {
226            text,
227            at: 0,
228            tokens: Vec::new(),
229            strings: String::new(),
230            open: Vec::new(),
231            keys: Vec::new(),
232        }
233        .parse()
234    }
235
236    /// The text of a string or key token's span.
237    fn text(&self, span: Span) -> &str {
238        &self.strings[span.start..span.end]
239    }
240
241    /// The top-level scalar, or `None` for an array or an object.
242    fn scalar(&self) -> Option<&Token> {
243        match self.tokens.as_slice() {
244            [scalar] => Some(scalar),
245            _ => None,
246        }
247    }
248
249    /// The kind of the top-level value.
250    fn kind(&self) -> JsonbKind {
251        match self.tokens[0] {
252            Token::Null => JsonbKind::Null,
253            Token::String(_) | Token::Key(_) => JsonbKind::String,
254            Token::Number(_) => JsonbKind::Numeric,
255            Token::Bool(_) => JsonbKind::Boolean,
256            Token::ArrayStart(_) | Token::ArrayEnd => JsonbKind::Array,
257            Token::ObjectStart(_) | Token::ObjectEnd => JsonbKind::Object,
258        }
259    }
260
261    /// The boolean `jsonb_bool` casts the value to, `None` for `null`.
262    pub(super) fn to_bool(&self) -> Result<Option<bool>, JsonbKind> {
263        match self.scalar() {
264            Some(Token::Null) => Ok(None),
265            Some(Token::Bool(value)) => Ok(Some(*value)),
266            _ => Err(self.kind()),
267        }
268    }
269
270    /// The number `jsonb_numeric` casts the value to, `None` for `null`.
271    pub(super) fn into_numeric(self) -> Result<Option<PgNumeric>, JsonbKind> {
272        let kind = self.kind();
273        match <[Token; 1]>::try_from(self.tokens) {
274            Ok([Token::Null]) => Ok(None),
275            Ok([Token::Number(value)]) => Ok(Some(value)),
276            _ => Err(kind),
277        }
278    }
279
280    /// `compareJsonbScalarValue` for two scalars, or the order of their `jbvType`s, between two
281    /// tokens at the same place of both streams.
282    fn cmp_token(&self, left: &Token, other: &Self, right: &Token) -> Ordering {
283        match (left, right) {
284            (Token::Bool(left), Token::Bool(right)) => left.cmp(right),
285            (Token::Number(left), Token::Number(right)) => left.cmp(right),
286            (Token::String(left) | Token::Key(left), Token::String(right) | Token::Key(right)) => {
287                self.text(*left).cmp(other.text(*right))
288            }
289            (Token::ArrayStart(left), Token::ArrayStart(right))
290            | (Token::ObjectStart(left), Token::ObjectStart(right)) => left.cmp(right),
291            _ => left.rank().cmp(&right.rank()),
292        }
293    }
294}
295
296/// The parse of one text, `jsonb_in`'s recursive descent run over explicit stacks.
297struct Parser<'a> {
298    text: &'a str,
299    /// The byte the next token starts at or before.
300    at: usize,
301    tokens: Vec<Token>,
302    strings: String,
303    /// The nonempty containers open around the current place, innermost last.
304    open: Vec<Open>,
305    /// The keys of every open object, the innermost object's last.
306    keys: Vec<Key>,
307}
308
309/// A nonempty container still open.
310#[derive(Clone, Copy)]
311struct Open {
312    /// Whether the container is an object.
313    object: bool,
314    /// The index of its start token.
315    start: usize,
316    /// The length of [`Parser::keys`] when it opened.
317    keys: usize,
318    /// The values read in it so far.
319    count: usize,
320}
321
322/// A key of an open object.
323#[derive(Clone, Copy)]
324struct Key {
325    /// The index of its token, which starts its pair.
326    token: usize,
327    /// Its decoded text.
328    span: Span,
329}
330
331/// A token of the JSON text, as `json_lex` reads it.
332#[derive(Clone, Copy, PartialEq, Eq)]
333enum Lexeme {
334    ObjectStart,
335    ObjectEnd,
336    ArrayStart,
337    ArrayEnd,
338    Comma,
339    Colon,
340    /// A string, decoded into the parser's strings.
341    String(Span),
342    /// A number, its span in the text.
343    Number(Span),
344    True,
345    False,
346    Null,
347    End,
348}
349
350/// `error`, or [`JsonbError::UnexpectedEnd`] when the token is the end of the input, as
351/// `report_parse_error` chooses.
352fn expected(lexeme: Lexeme, error: JsonbError) -> JsonbError {
353    if lexeme == Lexeme::End {
354        JsonbError::UnexpectedEnd
355    } else {
356        error
357    }
358}
359
360/// `JSON_ALPHANUMERIC_CHAR`, a byte the lexer reads as part of a word.
361const fn is_word_byte(byte: u8) -> bool {
362    byte.is_ascii_alphanumeric() || byte == b'_' || byte >= 0x80
363}
364
365/// `lengthCompareJsonbString`, the storage order of keys, shorter first and then by bytes.
366fn storage_order(left: &str, right: &str) -> Ordering {
367    left.len()
368        .cmp(&right.len())
369        .then_with(|| left.as_bytes().cmp(right.as_bytes()))
370}
371
372impl Parser<'_> {
373    /// `pg_parse_json` with `jsonb_in`'s semantic actions.
374    fn parse(mut self) -> Result<PgJsonb, JsonbError> {
375        let mut lexeme = self.lex()?;
376        'value: loop {
377            // `lexeme` starts a value.
378            match lexeme {
379                Lexeme::ObjectStart => {
380                    lexeme = self.lex()?;
381                    match lexeme {
382                        Lexeme::String(key) => {
383                            self.open(true);
384                            lexeme = self.key(key)?;
385                            continue 'value;
386                        }
387                        Lexeme::ObjectEnd => {
388                            lexeme = self.lex()?;
389                            self.tokens
390                                .extend([Token::ObjectStart(0), Token::ObjectEnd]);
391                        }
392                        other => {
393                            return Err(expected(other, JsonbError::ExpectedStringOrObjectEnd));
394                        }
395                    }
396                }
397                Lexeme::ArrayStart => {
398                    lexeme = self.lex()?;
399                    if lexeme != Lexeme::ArrayEnd {
400                        self.open(false);
401                        continue 'value;
402                    }
403                    lexeme = self.lex()?;
404                    self.tokens.extend([Token::ArrayStart(0), Token::ArrayEnd]);
405                }
406                Lexeme::String(_)
407                | Lexeme::Number(_)
408                | Lexeme::True
409                | Lexeme::False
410                | Lexeme::Null => {
411                    // `parse_scalar` lexes the next token before `numeric_in` reads a number.
412                    let next = self.lex()?;
413                    let token = match lexeme {
414                        Lexeme::String(span) => Token::String(span),
415                        Lexeme::Number(span) => Token::Number(
416                            PgNumeric::parse(&self.text[span.start..span.end])
417                                .map_err(JsonbError::Numeric)?,
418                        ),
419                        Lexeme::True => Token::Bool(true),
420                        Lexeme::False => Token::Bool(false),
421                        _ => Token::Null,
422                    };
423                    self.tokens.push(token);
424                    lexeme = next;
425                }
426                other => return Err(expected(other, JsonbError::ExpectedValue)),
427            }
428            // A value ended and `lexeme` follows it.
429            loop {
430                let Some(open) = self.open.last_mut() else {
431                    if lexeme != Lexeme::End {
432                        return Err(JsonbError::ExpectedEnd);
433                    }
434                    return Ok(PgJsonb {
435                        tokens: self.tokens,
436                        strings: self.strings,
437                    });
438                };
439                open.count += 1;
440                let closed = *open;
441                match (closed.object, lexeme) {
442                    (false, Lexeme::Comma) => {
443                        lexeme = self.lex()?;
444                        continue 'value;
445                    }
446                    (true, Lexeme::Comma) => {
447                        lexeme = self.lex()?;
448                        let Lexeme::String(key) = lexeme else {
449                            return Err(expected(lexeme, JsonbError::ExpectedString));
450                        };
451                        lexeme = self.key(key)?;
452                        continue 'value;
453                    }
454                    (false, Lexeme::ArrayEnd) => {
455                        lexeme = self.lex()?;
456                        self.open.pop();
457                        self.tokens[closed.start] = Token::ArrayStart(closed.count);
458                        self.tokens.push(Token::ArrayEnd);
459                    }
460                    (true, Lexeme::ObjectEnd) => {
461                        lexeme = self.lex()?;
462                        self.open.pop();
463                        self.close_object(closed);
464                    }
465                    (false, other) => {
466                        return Err(expected(other, JsonbError::ExpectedCommaOrArrayEnd));
467                    }
468                    (true, other) => {
469                        return Err(expected(other, JsonbError::ExpectedCommaOrObjectEnd));
470                    }
471                }
472            }
473        }
474    }
475
476    /// Opens a nonempty object or array, whose first key or element follows.
477    fn open(&mut self, object: bool) {
478        self.open.push(Open {
479            object,
480            start: self.tokens.len(),
481            keys: self.keys.len(),
482            count: 0,
483        });
484        self.tokens.push(if object {
485            Token::ObjectStart(0)
486        } else {
487            Token::ArrayStart(0)
488        });
489    }
490
491    /// Ends an object, its pairs put in storage order with the last of duplicate keys kept, as
492    /// `uniqueifyJsonbObject` leaves them.
493    fn close_object(&mut self, object: Open) {
494        let keys = &self.keys[object.keys..];
495        let text = |key: &Key| &self.strings[key.span.start..key.span.end];
496        let ordered = keys
497            .windows(2)
498            .all(|pair| storage_order(text(&pair[0]), text(&pair[1])).is_lt());
499        let count = if ordered {
500            keys.len()
501        } else {
502            self.reorder_pairs(object.keys)
503        };
504        self.keys.truncate(object.keys);
505        self.tokens[object.start] = Token::ObjectStart(count);
506        self.tokens.push(Token::ObjectEnd);
507    }
508
509    /// Puts the pairs of the object whose keys start at `first` of [`Parser::keys`] in storage
510    /// order, the last of duplicate keys kept, returning the pair count.
511    fn reorder_pairs(&mut self, first: usize) -> usize {
512        let keys = &self.keys[first..];
513        let base = keys[0].token;
514        let ends = keys[1..]
515            .iter()
516            .map(|key| key.token)
517            .chain([self.tokens.len()]);
518        // Each pair's key and its token range, counted from the first pair's.
519        let mut pairs: Vec<(Span, usize, usize)> = keys
520            .iter()
521            .zip(ends)
522            .map(|(key, end)| (key.span, key.token - base, end - base))
523            .collect();
524        let text = |span: Span| &self.strings[span.start..span.end];
525        // The later of equal keys first, so that removing duplicates keeps it.
526        pairs.sort_unstable_by(|left, right| {
527            storage_order(text(left.0), text(right.0)).then(right.1.cmp(&left.1))
528        });
529        pairs.dedup_by(|later, kept| text(later.0) == text(kept.0));
530        let mut tail = self.tokens.split_off(base);
531        for &(_, start, end) in &pairs {
532            self.tokens.extend(
533                tail[start..end]
534                    .iter_mut()
535                    .map(|token| mem::replace(token, Token::Null)),
536            );
537        }
538        pairs.len()
539    }
540
541    /// Reads an object's key, whose string was lexed, and its colon, returning the token that
542    /// starts its value.
543    fn key(&mut self, span: Span) -> Result<Lexeme, JsonbError> {
544        self.keys.push(Key {
545            token: self.tokens.len(),
546            span,
547        });
548        self.tokens.push(Token::Key(span));
549        let colon = self.lex()?;
550        if colon != Lexeme::Colon {
551            return Err(expected(colon, JsonbError::ExpectedColon));
552        }
553        self.lex()
554    }
555
556    /// `json_lex`, the next token after blanks.
557    fn lex(&mut self) -> Result<Lexeme, JsonbError> {
558        let bytes = self.text.as_bytes();
559        while matches!(bytes.get(self.at), Some(b' ' | b'\t' | b'\n' | b'\r')) {
560            self.at += 1;
561        }
562        let Some(&byte) = bytes.get(self.at) else {
563            return Ok(Lexeme::End);
564        };
565        let punctuation = match byte {
566            b'{' => Lexeme::ObjectStart,
567            b'}' => Lexeme::ObjectEnd,
568            b'[' => Lexeme::ArrayStart,
569            b']' => Lexeme::ArrayEnd,
570            b',' => Lexeme::Comma,
571            b':' => Lexeme::Colon,
572            b'"' => {
573                self.at += 1;
574                return self.string().map(Lexeme::String);
575            }
576            b'-' | b'0'..=b'9' => return self.number().map(Lexeme::Number),
577            _ => {
578                let start = self.at;
579                let length = bytes[start..]
580                    .iter()
581                    .take_while(|&&byte| is_word_byte(byte))
582                    .count();
583                self.at += length;
584                return match &bytes[start..self.at] {
585                    b"true" => Ok(Lexeme::True),
586                    b"false" => Ok(Lexeme::False),
587                    b"null" => Ok(Lexeme::Null),
588                    _ => Err(JsonbError::InvalidToken),
589                };
590            }
591        };
592        self.at += 1;
593        Ok(punctuation)
594    }
595
596    /// `json_lex_number`, an optional `-`, a `0` or digits not starting with `0`, an optional
597    /// point and digits, an optional exponent, and no word character after.
598    fn number(&mut self) -> Result<Span, JsonbError> {
599        let bytes = self.text.as_bytes();
600        let start = self.at;
601        let digits = |at: usize| {
602            bytes[at..]
603                .iter()
604                .take_while(|b| b.is_ascii_digit())
605                .count()
606        };
607        let mut at = start + usize::from(bytes[start] == b'-');
608        let mut valid = true;
609        match bytes.get(at) {
610            Some(b'0') => at += 1,
611            Some(b'1'..=b'9') => at += digits(at),
612            _ => valid = false,
613        }
614        if bytes.get(at) == Some(&b'.') {
615            at += 1;
616            let fraction = digits(at);
617            valid &= fraction > 0;
618            at += fraction;
619        }
620        if matches!(bytes.get(at), Some(b'e' | b'E')) {
621            at += 1;
622            at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
623            let exponent = digits(at);
624            valid &= exponent > 0;
625            at += exponent;
626        }
627        if !valid || bytes.get(at).copied().is_some_and(is_word_byte) {
628            return Err(JsonbError::InvalidToken);
629        }
630        self.at = at;
631        Ok(Span { start, end: at })
632    }
633
634    /// `json_lex_string` from after the opening quote, decoding the string into the parser's
635    /// strings, the refusals checked in the order PostgreSQL checks them.
636    fn string(&mut self) -> Result<Span, JsonbError> {
637        let bytes = self.text.as_bytes();
638        let start = self.strings.len();
639        let mut high_surrogate: Option<u32> = None;
640        loop {
641            match bytes.get(self.at) {
642                None => return Err(JsonbError::InvalidToken),
643                Some(b'"') => {
644                    self.at += 1;
645                    if high_surrogate.is_some() {
646                        return Err(JsonbError::LowSurrogateExpected);
647                    }
648                    return Ok(Span {
649                        start,
650                        end: self.strings.len(),
651                    });
652                }
653                Some(b'\\') => {
654                    self.at += 1;
655                    match bytes.get(self.at) {
656                        None => return Err(JsonbError::InvalidToken),
657                        Some(b'u') => {
658                            let mut code = 0;
659                            for _ in 0..4 {
660                                self.at += 1;
661                                let digit = bytes.get(self.at).ok_or(JsonbError::InvalidToken)?;
662                                code = code * 16
663                                    + char::from(*digit)
664                                        .to_digit(16)
665                                        .ok_or(JsonbError::UnicodeEscapeFormat)?;
666                            }
667                            self.at += 1;
668                            if (0xD800..0xDC00).contains(&code) {
669                                if high_surrogate.is_some() {
670                                    return Err(JsonbError::HighSurrogateRepeated);
671                                }
672                                high_surrogate = Some(code);
673                                continue;
674                            }
675                            if (0xDC00..0xE000).contains(&code) {
676                                let high = high_surrogate
677                                    .take()
678                                    .ok_or(JsonbError::LowSurrogateExpected)?;
679                                code = 0x10000 + ((high - 0xD800) << 10) + (code - 0xDC00);
680                            }
681                            if high_surrogate.is_some() {
682                                return Err(JsonbError::LowSurrogateExpected);
683                            }
684                            if code == 0 {
685                                return Err(JsonbError::CodePointZero);
686                            }
687                            self.strings.push(
688                                char::from_u32(code).expect("a scalar value after surrogates"),
689                            );
690                        }
691                        Some(&escaped) => {
692                            if high_surrogate.is_some() {
693                                return Err(JsonbError::LowSurrogateExpected);
694                            }
695                            self.strings.push(match escaped {
696                                b'"' => '"',
697                                b'\\' => '\\',
698                                b'/' => '/',
699                                b'b' => '\u{8}',
700                                b'f' => '\u{c}',
701                                b'n' => '\n',
702                                b'r' => '\r',
703                                b't' => '\t',
704                                _ => return Err(JsonbError::InvalidEscape),
705                            });
706                            self.at += 1;
707                        }
708                    }
709                }
710                Some(_) => {
711                    if high_surrogate.is_some() {
712                        return Err(JsonbError::LowSurrogateExpected);
713                    }
714                    let run = self.at;
715                    while let Some(&byte) = bytes.get(self.at) {
716                        match byte {
717                            b'"' | b'\\' => break,
718                            0..0x20 => return Err(JsonbError::UnescapedControlCharacter),
719                            _ => self.at += 1,
720                        }
721                    }
722                    self.strings.push_str(&self.text[run..self.at]);
723                }
724            }
725        }
726    }
727}
728
729/// `escape_json`, the string quoted with `"`, `\` and control characters escaped and every
730/// other character written as it is.
731fn write_string(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result {
732    f.write_char('"')?;
733    let mut written = 0;
734    for (at, byte) in text.bytes().enumerate() {
735        let escape = match byte {
736            b'"' => Some("\\\""),
737            b'\\' => Some("\\\\"),
738            0x08 => Some("\\b"),
739            0x0C => Some("\\f"),
740            b'\n' => Some("\\n"),
741            b'\r' => Some("\\r"),
742            b'\t' => Some("\\t"),
743            0..0x20 => None,
744            _ => continue,
745        };
746        f.write_str(&text[written..at])?;
747        match escape {
748            Some(escape) => f.write_str(escape)?,
749            None => write!(f, "\\u{byte:04x}")?,
750        }
751        written = at + 1;
752    }
753    f.write_str(&text[written..])?;
754    f.write_char('"')
755}
756
757/// `JsonbToCString`, keys and values joined by `": "`, pairs and elements by `", "`.
758impl fmt::Display for PgJsonb {
759    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760        let mut first = true;
761        for token in &self.tokens {
762            if !first && !matches!(token, Token::ArrayEnd | Token::ObjectEnd) {
763                f.write_str(", ")?;
764            }
765            first = false;
766            match token {
767                Token::Null => f.write_str("null")?,
768                Token::Bool(value) => f.write_str(if *value { "true" } else { "false" })?,
769                Token::Number(value) => write!(f, "{value}")?,
770                Token::String(span) => write_string(f, self.text(*span))?,
771                Token::Key(span) => {
772                    write_string(f, self.text(*span))?;
773                    f.write_str(": ")?;
774                    first = true;
775                }
776                Token::ArrayStart(_) => {
777                    f.write_char('[')?;
778                    first = true;
779                }
780                Token::ObjectStart(_) => {
781                    f.write_char('{')?;
782                    first = true;
783                }
784                Token::ArrayEnd => f.write_char(']')?,
785                Token::ObjectEnd => f.write_char('}')?,
786            }
787        }
788        Ok(())
789    }
790}
791
792impl PartialEq for PgJsonb {
793    fn eq(&self, other: &Self) -> bool {
794        self.cmp(other) == Ordering::Equal
795    }
796}
797
798impl Eq for PgJsonb {}
799
800impl PartialOrd for PgJsonb {
801    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
802        Some(self.cmp(other))
803    }
804}
805
806/// `compareJsonbContainers`, both token streams walked together to the first difference. A
807/// top-level scalar is a one-element pseudo array there, so it sorts after the empty array and
808/// before every other array and object.
809impl Ord for PgJsonb {
810    fn cmp(&self, other: &Self) -> Ordering {
811        match (self.scalar(), other.scalar()) {
812            (Some(left), Some(right)) => self.cmp_token(left, other, right),
813            (Some(_), None) => match other.tokens[0] {
814                Token::ArrayStart(0) => Ordering::Greater,
815                _ => Ordering::Less,
816            },
817            (None, Some(_)) => match self.tokens[0] {
818                Token::ArrayStart(0) => Ordering::Less,
819                _ => Ordering::Greater,
820            },
821            (None, None) => self
822                .tokens
823                .iter()
824                .zip(&other.tokens)
825                .map(|(left, right)| self.cmp_token(left, other, right))
826                .find(|order| order.is_ne())
827                .unwrap_or_else(|| self.tokens.len().cmp(&other.tokens.len())),
828        }
829    }
830}
831
832impl Hash for PgJsonb {
833    fn hash<H: Hasher>(&self, state: &mut H) {
834        for token in &self.tokens {
835            mem::discriminant(token).hash(state);
836            match token {
837                Token::Bool(value) => value.hash(state),
838                Token::Number(value) => value.hash(state),
839                Token::String(span) | Token::Key(span) => self.text(*span).hash(state),
840                Token::ArrayStart(count) | Token::ObjectStart(count) => count.hash(state),
841                Token::Null | Token::ArrayEnd | Token::ObjectEnd => {}
842            }
843        }
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use alloc::string::ToString;
850
851    use super::*;
852
853    #[test]
854    fn nesting_of_any_depth_parses_prints_compares_and_drops() {
855        let depth = 200_000;
856        let text = "[".repeat(depth) + &"]".repeat(depth);
857        let deep = PgJsonb::parse(&text).unwrap();
858        assert_eq!(deep.to_string(), text);
859        let shallower = PgJsonb::parse(&text[1..text.len() - 1]).unwrap();
860        assert!(shallower < deep);
861        assert_eq!(deep.clone(), deep);
862    }
863}