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