Skip to main content

lifegraph_json/
lib.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::io::{Read, Write};
4use std::ops::{Index, IndexMut};
5
6
7#[derive(Clone, Debug, PartialEq)]
8pub enum JsonNumber {
9    I64(i64),
10    U64(u64),
11    F64(f64),
12}
13
14
15impl JsonNumber {
16    pub fn is_i64(&self) -> bool {
17        matches!(self, Self::I64(_))
18    }
19
20    pub fn is_u64(&self) -> bool {
21        matches!(self, Self::U64(_))
22    }
23
24    pub fn is_f64(&self) -> bool {
25        matches!(self, Self::F64(_))
26    }
27
28    pub fn as_i64(&self) -> Option<i64> {
29        match self {
30            Self::I64(value) => Some(*value),
31            Self::U64(value) => (*value <= i64::MAX as u64).then_some(*value as i64),
32            Self::F64(_) => None,
33        }
34    }
35
36    pub fn as_u64(&self) -> Option<u64> {
37        match self {
38            Self::I64(value) => (*value >= 0).then_some(*value as u64),
39            Self::U64(value) => Some(*value),
40            Self::F64(_) => None,
41        }
42    }
43
44    pub fn as_f64(&self) -> Option<f64> {
45        match self {
46            Self::I64(value) => Some(*value as f64),
47            Self::U64(value) => Some(*value as f64),
48            Self::F64(value) => Some(*value),
49        }
50    }
51
52    pub fn from_f64(value: f64) -> Option<Self> {
53        value.is_finite().then_some(Self::F64(value))
54    }
55}
56
57#[derive(Clone, Debug, PartialEq)]
58pub enum JsonValue {
59    Null,
60    Bool(bool),
61    Number(JsonNumber),
62    String(String),
63    Array(Vec<JsonValue>),
64    Object(Vec<(String, JsonValue)>),
65}
66
67pub type Value = JsonValue;
68pub type Number = JsonNumber;
69pub type Map = Vec<(String, JsonValue)>;
70
71#[derive(Clone, Debug, PartialEq)]
72pub enum BorrowedJsonValue<'a> {
73    Null,
74    Bool(bool),
75    Number(JsonNumber),
76    String(Cow<'a, str>),
77    Array(Vec<BorrowedJsonValue<'a>>),
78    Object(Vec<(Cow<'a, str>, BorrowedJsonValue<'a>)>),
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct CompiledObjectSchema {
83    fields: Vec<CompiledField>,
84    capacity_hint: usize,
85}
86
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct CompiledRowSchema {
89    object: CompiledObjectSchema,
90    row_capacity_hint: usize,
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct JsonTape {
95    pub tokens: Vec<TapeToken>,
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct TapeToken {
100    pub kind: TapeTokenKind,
101    pub start: usize,
102    pub end: usize,
103    pub parent: Option<usize>,
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum TapeTokenKind {
108    Null,
109    Bool,
110    Number,
111    String,
112    Key,
113    Array,
114    Object,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub struct TapeValue<'a> {
119    tape: &'a JsonTape,
120    input: &'a str,
121    index: usize,
122}
123
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub struct TapeObjectIndex {
126    buckets: Vec<Vec<(u64, usize, usize)>>,
127}
128
129#[derive(Clone, Copy, Debug)]
130pub struct IndexedTapeObject<'a> {
131    object: TapeValue<'a>,
132    index: &'a TapeObjectIndex,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct CompiledTapeKey {
137    key: String,
138    hash: u64,
139}
140
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct CompiledTapeKeys {
143    keys: Vec<CompiledTapeKey>,
144}
145
146#[derive(Clone, Debug, PartialEq, Eq)]
147struct CompiledField {
148    key: String,
149    rendered_prefix: Vec<u8>,
150}
151
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub enum JsonError {
154    NonFiniteNumber,
155    Io,
156}
157
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub enum JsonParseError {
160    InvalidUtf8,
161    UnexpectedEnd,
162    UnexpectedTrailingCharacters(usize),
163    UnexpectedCharacter { index: usize, found: char },
164    InvalidLiteral { index: usize },
165    InvalidNumber { index: usize },
166    InvalidEscape { index: usize },
167    InvalidUnicodeEscape { index: usize },
168    InvalidUnicodeScalar { index: usize },
169    ExpectedColon { index: usize },
170    ExpectedCommaOrEnd { index: usize, context: &'static str },
171}
172
173impl fmt::Display for JsonError {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        match self {
176            Self::NonFiniteNumber => {
177                f.write_str("cannot serialize non-finite floating-point value")
178            }
179            Self::Io => f.write_str("i/o error while serializing JSON"),
180        }
181    }
182}
183
184impl fmt::Display for JsonParseError {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        match self {
187            Self::InvalidUtf8 => f.write_str("input is not valid UTF-8"),
188            Self::UnexpectedEnd => f.write_str("unexpected end of JSON input"),
189            Self::UnexpectedTrailingCharacters(index) => {
190                write!(f, "unexpected trailing characters at byte {index}")
191            }
192            Self::UnexpectedCharacter { index, found } => {
193                write!(f, "unexpected character '{found}' at byte {index}")
194            }
195            Self::InvalidLiteral { index } => write!(f, "invalid literal at byte {index}"),
196            Self::InvalidNumber { index } => write!(f, "invalid number at byte {index}"),
197            Self::InvalidEscape { index } => write!(f, "invalid escape sequence at byte {index}"),
198            Self::InvalidUnicodeEscape { index } => {
199                write!(f, "invalid unicode escape at byte {index}")
200            }
201            Self::InvalidUnicodeScalar { index } => {
202                write!(f, "invalid unicode scalar at byte {index}")
203            }
204            Self::ExpectedColon { index } => write!(f, "expected ':' at byte {index}"),
205            Self::ExpectedCommaOrEnd { index, context } => {
206                write!(f, "expected ',' or end of {context} at byte {index}")
207            }
208        }
209    }
210}
211
212impl std::error::Error for JsonError {}
213impl std::error::Error for JsonParseError {}
214
215impl JsonValue {
216    pub fn object(entries: Vec<(impl Into<String>, JsonValue)>) -> Self {
217        Self::Object(
218            entries
219                .into_iter()
220                .map(|(key, value)| (key.into(), value))
221                .collect(),
222        )
223    }
224
225    pub fn array(values: Vec<JsonValue>) -> Self {
226        Self::Array(values)
227    }
228
229    pub fn to_json_string(&self) -> Result<String, JsonError> {
230        let mut out = Vec::with_capacity(initial_json_capacity(self));
231        write_json_value(&mut out, self)?;
232        Ok(unsafe { String::from_utf8_unchecked(out) })
233    }
234
235    pub fn push_field(&mut self, key: impl Into<String>, value: impl Into<JsonValue>) {
236        match self {
237            Self::Object(entries) => entries.push((key.into(), value.into())),
238            _ => panic!("push_field called on non-object JSON value"),
239        }
240    }
241
242    pub fn push_item(&mut self, value: impl Into<JsonValue>) {
243        match self {
244            Self::Array(values) => values.push(value.into()),
245            _ => panic!("push_item called on non-array JSON value"),
246        }
247    }
248
249    pub fn is_null(&self) -> bool {
250        self.as_null().is_some()
251    }
252
253    pub fn as_null(&self) -> Option<()> {
254        matches!(self, Self::Null).then_some(())
255    }
256
257    pub fn is_boolean(&self) -> bool {
258        matches!(self, Self::Bool(_))
259    }
260
261    pub fn is_number(&self) -> bool {
262        matches!(self, Self::Number(_))
263    }
264
265    pub fn is_string(&self) -> bool {
266        matches!(self, Self::String(_))
267    }
268
269    pub fn is_array(&self) -> bool {
270        matches!(self, Self::Array(_))
271    }
272
273    pub fn is_object(&self) -> bool {
274        matches!(self, Self::Object(_))
275    }
276
277    pub fn as_bool(&self) -> Option<bool> {
278        match self {
279            Self::Bool(value) => Some(*value),
280            _ => None,
281        }
282    }
283
284    pub fn as_number(&self) -> Option<&JsonNumber> {
285        match self {
286            Self::Number(number) => Some(number),
287            _ => None,
288        }
289    }
290
291    pub fn is_i64(&self) -> bool {
292        self.as_number().is_some_and(JsonNumber::is_i64)
293    }
294
295    pub fn is_u64(&self) -> bool {
296        self.as_number().is_some_and(JsonNumber::is_u64)
297    }
298
299    pub fn is_f64(&self) -> bool {
300        self.as_number().is_some_and(JsonNumber::is_f64)
301    }
302
303    pub fn as_i64(&self) -> Option<i64> {
304        self.as_number().and_then(JsonNumber::as_i64)
305    }
306
307    pub fn as_u64(&self) -> Option<u64> {
308        self.as_number().and_then(JsonNumber::as_u64)
309    }
310
311    pub fn as_f64(&self) -> Option<f64> {
312        self.as_number().and_then(JsonNumber::as_f64)
313    }
314
315    pub fn as_str(&self) -> Option<&str> {
316        match self {
317            Self::String(value) => Some(value.as_str()),
318            _ => None,
319        }
320    }
321
322    pub fn as_array(&self) -> Option<&Vec<JsonValue>> {
323        match self {
324            Self::Array(values) => Some(values),
325            _ => None,
326        }
327    }
328
329    pub fn as_array_mut(&mut self) -> Option<&mut Vec<JsonValue>> {
330        match self {
331            Self::Array(values) => Some(values),
332            _ => None,
333        }
334    }
335
336    pub fn as_object(&self) -> Option<&Map> {
337        match self {
338            Self::Object(entries) => Some(entries),
339            _ => None,
340        }
341    }
342
343    pub fn as_object_mut(&mut self) -> Option<&mut Map> {
344        match self {
345            Self::Object(entries) => Some(entries),
346            _ => None,
347        }
348    }
349
350    pub fn get<I>(&self, index: I) -> Option<&JsonValue>
351    where
352        I: ValueIndex,
353    {
354        index.index_into(self)
355    }
356
357    pub fn get_mut<I>(&mut self, index: I) -> Option<&mut JsonValue>
358    where
359        I: ValueIndex,
360    {
361        index.index_into_mut(self)
362    }
363
364    pub fn len(&self) -> usize {
365        match self {
366            Self::Array(values) => values.len(),
367            Self::Object(entries) => entries.len(),
368            _ => 0,
369        }
370    }
371
372    pub fn is_empty(&self) -> bool {
373        self.len() == 0
374    }
375
376    pub fn as_i128(&self) -> Option<i128> {
377        self.as_i64().map(|v| v as i128)
378    }
379
380    pub fn as_u128(&self) -> Option<u128> {
381        self.as_u64().map(|v| v as u128)
382    }
383
384    pub fn as_f32(&self) -> Option<f32> {
385        self.as_f64().map(|v| v as f32)
386    }
387
388    pub fn get_index(&self, index: usize) -> Option<&JsonValue> {
389        match self {
390            Self::Array(values) => values.get(index),
391            _ => None,
392        }
393    }
394
395    pub fn get_index_mut(&mut self, index: usize) -> Option<&mut JsonValue> {
396        match self {
397            Self::Array(values) => values.get_mut(index),
398            _ => None,
399        }
400    }
401
402    pub fn take(&mut self) -> JsonValue {
403        std::mem::replace(self, JsonValue::Null)
404    }
405
406    pub fn pointer(&self, pointer: &str) -> Option<&JsonValue> {
407        if pointer.is_empty() {
408            return Some(self);
409        }
410        if !pointer.starts_with('/') {
411            return None;
412        }
413        let mut current = self;
414        for segment in pointer.split('/').skip(1) {
415            let token = decode_pointer_segment(segment);
416            current = match current {
417                JsonValue::Object(entries) => entries
418                    .iter()
419                    .find(|(key, _)| key == &token)
420                    .map(|(_, value)| value)?,
421                JsonValue::Array(values) => values.get(token.parse::<usize>().ok()?)?,
422                _ => return None,
423            };
424        }
425        Some(current)
426    }
427
428    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut JsonValue> {
429        if pointer.is_empty() {
430            return Some(self);
431        }
432        if !pointer.starts_with('/') {
433            return None;
434        }
435        let mut current = self;
436        for segment in pointer.split('/').skip(1) {
437            let token = decode_pointer_segment(segment);
438            current = match current {
439                JsonValue::Object(entries) => entries
440                    .iter_mut()
441                    .find(|(key, _)| key == &token)
442                    .map(|(_, value)| value)?,
443                JsonValue::Array(values) => values.get_mut(token.parse::<usize>().ok()?)?,
444                _ => return None,
445            };
446        }
447        Some(current)
448    }
449
450    pub fn sort_all_objects(&mut self) {
451        match self {
452            JsonValue::Object(entries) => {
453                entries.sort_by(|a, b| a.0.cmp(&b.0));
454                for (_, value) in entries.iter_mut() {
455                    value.sort_all_objects();
456                }
457            }
458            JsonValue::Array(values) => {
459                for value in values.iter_mut() {
460                    value.sort_all_objects();
461                }
462            }
463            _ => {}
464        }
465    }
466}
467
468impl<'a> BorrowedJsonValue<'a> {
469    pub fn into_owned(self) -> JsonValue {
470        match self {
471            Self::Null => JsonValue::Null,
472            Self::Bool(value) => JsonValue::Bool(value),
473            Self::Number(value) => JsonValue::Number(value),
474            Self::String(value) => JsonValue::String(value.into_owned()),
475            Self::Array(values) => JsonValue::Array(
476                values
477                    .into_iter()
478                    .map(BorrowedJsonValue::into_owned)
479                    .collect(),
480            ),
481            Self::Object(entries) => JsonValue::Object(
482                entries
483                    .into_iter()
484                    .map(|(key, value)| (key.into_owned(), value.into_owned()))
485                    .collect(),
486            ),
487        }
488    }
489}
490
491impl CompiledObjectSchema {
492    pub fn new(keys: &[&str]) -> Self {
493        let mut fields = Vec::with_capacity(keys.len());
494        let mut capacity_hint = 2;
495        for (index, key) in keys.iter().enumerate() {
496            let mut rendered_prefix = Vec::with_capacity(key.len() + 4);
497            if index > 0 {
498                rendered_prefix.push(b',');
499            }
500            write_json_key(&mut rendered_prefix, key);
501            capacity_hint += rendered_prefix.len() + 8;
502            fields.push(CompiledField {
503                key: (*key).to_owned(),
504                rendered_prefix,
505            });
506        }
507        Self {
508            fields,
509            capacity_hint,
510        }
511    }
512
513    pub fn keys(&self) -> impl ExactSizeIterator<Item = &str> {
514        self.fields.iter().map(|field| field.key.as_str())
515    }
516
517    pub fn to_json_string<'a, I>(&self, values: I) -> Result<String, JsonError>
518    where
519        I: IntoIterator<Item = &'a JsonValue>,
520    {
521        let mut out = Vec::with_capacity(self.capacity_hint);
522        self.write_json_bytes(&mut out, values)?;
523        Ok(unsafe { String::from_utf8_unchecked(out) })
524    }
525
526    pub fn write_json_bytes<'a, I>(&self, out: &mut Vec<u8>, values: I) -> Result<(), JsonError>
527    where
528        I: IntoIterator<Item = &'a JsonValue>,
529    {
530        out.push(b'{');
531        let mut iter = values.into_iter();
532        for field in &self.fields {
533            let Some(value) = iter.next() else {
534                panic!(
535                    "compiled object schema expected {} values",
536                    self.fields.len()
537                );
538            };
539            out.extend_from_slice(&field.rendered_prefix);
540            write_json_value(out, value)?;
541        }
542        if iter.next().is_some() {
543            panic!(
544                "compiled object schema received more than {} values",
545                self.fields.len()
546            );
547        }
548        out.push(b'}');
549        Ok(())
550    }
551}
552
553impl CompiledRowSchema {
554    pub fn new(keys: &[&str]) -> Self {
555        let object = CompiledObjectSchema::new(keys);
556        let row_capacity_hint = object.capacity_hint;
557        Self {
558            object,
559            row_capacity_hint,
560        }
561    }
562
563    pub fn object_schema(&self) -> &CompiledObjectSchema {
564        &self.object
565    }
566
567    pub fn to_json_string<'a, R, I>(&self, rows: R) -> Result<String, JsonError>
568    where
569        R: IntoIterator<Item = I>,
570        I: IntoIterator<Item = &'a JsonValue>,
571    {
572        let iter = rows.into_iter();
573        let (lower, _) = iter.size_hint();
574        let mut out = Vec::with_capacity(2 + lower.saturating_mul(self.row_capacity_hint + 1));
575        self.write_json_bytes_from_iter(&mut out, iter)?;
576        Ok(unsafe { String::from_utf8_unchecked(out) })
577    }
578
579    pub fn write_json_bytes<'a, R, I>(&self, out: &mut Vec<u8>, rows: R) -> Result<(), JsonError>
580    where
581        R: IntoIterator<Item = I>,
582        I: IntoIterator<Item = &'a JsonValue>,
583    {
584        self.write_json_bytes_from_iter(out, rows.into_iter())
585    }
586
587    pub fn write_row_json_bytes<'a, I>(&self, out: &mut Vec<u8>, values: I) -> Result<(), JsonError>
588    where
589        I: IntoIterator<Item = &'a JsonValue>,
590    {
591        self.object.write_json_bytes(out, values)
592    }
593
594    fn write_json_bytes_from_iter<'a, R, I>(
595        &self,
596        out: &mut Vec<u8>,
597        mut rows: R,
598    ) -> Result<(), JsonError>
599    where
600        R: Iterator<Item = I>,
601        I: IntoIterator<Item = &'a JsonValue>,
602    {
603        out.push(b'[');
604        if let Some(first_row) = rows.next() {
605            self.object.write_json_bytes(out, first_row)?;
606            for row in rows {
607                out.push(b',');
608                self.object.write_json_bytes(out, row)?;
609            }
610        }
611        out.push(b']');
612        Ok(())
613    }
614}
615
616impl From<bool> for JsonValue {
617    fn from(value: bool) -> Self {
618        Self::Bool(value)
619    }
620}
621
622impl From<String> for JsonValue {
623    fn from(value: String) -> Self {
624        Self::String(value)
625    }
626}
627
628impl From<&str> for JsonValue {
629    fn from(value: &str) -> Self {
630        Self::String(value.to_owned())
631    }
632}
633
634impl From<i8> for JsonValue {
635    fn from(value: i8) -> Self {
636        Self::Number(JsonNumber::I64(value as i64))
637    }
638}
639
640impl From<i16> for JsonValue {
641    fn from(value: i16) -> Self {
642        Self::Number(JsonNumber::I64(value as i64))
643    }
644}
645
646impl From<i32> for JsonValue {
647    fn from(value: i32) -> Self {
648        Self::Number(JsonNumber::I64(value as i64))
649    }
650}
651
652impl From<i64> for JsonValue {
653    fn from(value: i64) -> Self {
654        Self::Number(JsonNumber::I64(value))
655    }
656}
657
658impl From<isize> for JsonValue {
659    fn from(value: isize) -> Self {
660        Self::Number(JsonNumber::I64(value as i64))
661    }
662}
663
664impl From<u8> for JsonValue {
665    fn from(value: u8) -> Self {
666        Self::Number(JsonNumber::U64(value as u64))
667    }
668}
669
670impl From<u16> for JsonValue {
671    fn from(value: u16) -> Self {
672        Self::Number(JsonNumber::U64(value as u64))
673    }
674}
675
676impl From<u32> for JsonValue {
677    fn from(value: u32) -> Self {
678        Self::Number(JsonNumber::U64(value as u64))
679    }
680}
681
682impl From<u64> for JsonValue {
683    fn from(value: u64) -> Self {
684        Self::Number(JsonNumber::U64(value))
685    }
686}
687
688impl From<usize> for JsonValue {
689    fn from(value: usize) -> Self {
690        Self::Number(JsonNumber::U64(value as u64))
691    }
692}
693
694impl From<f32> for JsonValue {
695    fn from(value: f32) -> Self {
696        Self::Number(JsonNumber::F64(value as f64))
697    }
698}
699
700impl From<f64> for JsonValue {
701    fn from(value: f64) -> Self {
702        Self::Number(JsonNumber::F64(value))
703    }
704}
705
706impl<T> From<Option<T>> for JsonValue
707where
708    T: Into<JsonValue>,
709{
710    fn from(value: Option<T>) -> Self {
711        match value {
712            Some(value) => value.into(),
713            None => Self::Null,
714        }
715    }
716}
717
718impl<T> From<Vec<T>> for JsonValue
719where
720    T: Into<JsonValue>,
721{
722    fn from(values: Vec<T>) -> Self {
723        Self::Array(values.into_iter().map(Into::into).collect())
724    }
725}
726
727
728impl<K, V> std::iter::FromIterator<(K, V)> for JsonValue
729where
730    K: Into<String>,
731    V: Into<JsonValue>,
732{
733    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
734        Self::Object(
735            iter.into_iter()
736                .map(|(key, value)| (key.into(), value.into()))
737                .collect(),
738        )
739    }
740}
741
742impl<T> std::iter::FromIterator<T> for JsonValue
743where
744    T: Into<JsonValue>,
745{
746    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
747        Self::Array(iter.into_iter().map(Into::into).collect())
748    }
749}
750
751pub fn escape_json_string(input: &str) -> String {
752    let mut out = Vec::with_capacity(input.len() + 2);
753    write_escaped_json_string(&mut out, input);
754    unsafe { String::from_utf8_unchecked(out) }
755}
756
757pub fn parse_json(input: &str) -> Result<JsonValue, JsonParseError> {
758    let mut parser = Parser::new(input);
759    let value = parser.parse_value()?;
760    parser.skip_whitespace();
761    if parser.is_eof() {
762        Ok(value)
763    } else {
764        Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
765    }
766}
767
768pub fn parse_json_borrowed(input: &str) -> Result<BorrowedJsonValue<'_>, JsonParseError> {
769    let mut parser = Parser::new(input);
770    let value = parser.parse_value_borrowed()?;
771    parser.skip_whitespace();
772    if parser.is_eof() {
773        Ok(value)
774    } else {
775        Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
776    }
777}
778
779pub fn parse_json_tape(input: &str) -> Result<JsonTape, JsonParseError> {
780    let mut parser = Parser::new(input);
781    let mut tokens = Vec::new();
782    parser.parse_tape_value(&mut tokens, None)?;
783    parser.skip_whitespace();
784    if parser.is_eof() {
785        Ok(JsonTape { tokens })
786    } else {
787        Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
788    }
789}
790
791
792pub fn from_str(input: &str) -> Result<JsonValue, JsonParseError> {
793    parse_json(input)
794}
795
796pub fn from_slice(input: &[u8]) -> Result<JsonValue, JsonParseError> {
797    let input = std::str::from_utf8(input).map_err(|_| JsonParseError::InvalidUtf8)?;
798    parse_json(input)
799}
800
801pub fn to_string(value: &JsonValue) -> Result<String, JsonError> {
802    value.to_json_string()
803}
804
805pub fn to_vec(value: &JsonValue) -> Result<Vec<u8>, JsonError> {
806    let mut out = Vec::with_capacity(initial_json_capacity(value));
807    write_json_value(&mut out, value)?;
808    Ok(out)
809}
810
811pub fn from_reader<R: Read>(mut reader: R) -> Result<JsonValue, JsonParseError> {
812    let mut input = String::new();
813    reader
814        .read_to_string(&mut input)
815        .map_err(|_| JsonParseError::InvalidUtf8)?;
816    parse_json(&input)
817}
818
819pub fn to_writer<W: Write>(mut writer: W, value: &JsonValue) -> Result<(), JsonError> {
820    let bytes = to_vec(value)?;
821    writer.write_all(&bytes).map_err(|_| JsonError::Io)
822}
823
824pub fn to_string_pretty(value: &JsonValue) -> Result<String, JsonError> {
825    let mut out = Vec::with_capacity(initial_json_capacity(value) + 16);
826    write_json_value_pretty(&mut out, value, 0)?;
827    Ok(unsafe { String::from_utf8_unchecked(out) })
828}
829
830pub fn to_vec_pretty(value: &JsonValue) -> Result<Vec<u8>, JsonError> {
831    let mut out = Vec::with_capacity(initial_json_capacity(value) + 16);
832    write_json_value_pretty(&mut out, value, 0)?;
833    Ok(out)
834}
835
836pub fn to_writer_pretty<W: Write>(mut writer: W, value: &JsonValue) -> Result<(), JsonError> {
837    let bytes = to_vec_pretty(value)?;
838    writer.write_all(&bytes).map_err(|_| JsonError::Io)
839}
840
841impl JsonTape {
842    pub fn root<'a>(&'a self, input: &'a str) -> Option<TapeValue<'a>> {
843        (!self.tokens.is_empty()).then_some(TapeValue {
844            tape: self,
845            input,
846            index: 0,
847        })
848    }
849}
850
851impl<'a> TapeValue<'a> {
852    pub fn kind(&self) -> TapeTokenKind {
853        self.tape.tokens[self.index].kind
854    }
855
856    pub fn as_str(&self) -> Option<&'a str> {
857        let token = &self.tape.tokens[self.index];
858        match token.kind {
859            TapeTokenKind::String | TapeTokenKind::Key => {
860                if self.input.as_bytes()[token.start] == b'"'
861                    && self.input.as_bytes()[token.end - 1] == b'"'
862                {
863                    Some(&self.input[token.start + 1..token.end - 1])
864                } else {
865                    None
866                }
867            }
868            _ => None,
869        }
870    }
871
872    pub fn get(&self, key: &str) -> Option<TapeValue<'a>> {
873        if self.kind() != TapeTokenKind::Object {
874            return None;
875        }
876        self.get_linear(key)
877    }
878
879    pub fn build_object_index(&self) -> Option<TapeObjectIndex> {
880        if self.kind() != TapeTokenKind::Object {
881            return None;
882        }
883        let parent = self.index;
884        let tokens = &self.tape.tokens;
885        let mut entries = Vec::new();
886        let mut i = self.index + 1;
887        while i + 1 < tokens.len() {
888            if tokens[i].parent != Some(parent) {
889                i += 1;
890                continue;
891            }
892            if tokens[i].kind == TapeTokenKind::Key && tokens[i + 1].parent == Some(parent) {
893                let candidate = TapeValue {
894                    tape: self.tape,
895                    input: self.input,
896                    index: i,
897                };
898                let key = candidate.as_str().unwrap_or("");
899                let hash = hash_key(key.as_bytes());
900                entries.push((hash, i, i + 1));
901                i += 2;
902            } else {
903                i += 1;
904            }
905        }
906        let bucket_count = (entries.len().next_power_of_two().max(1)) * 2;
907        let mut buckets = vec![Vec::new(); bucket_count];
908        for entry in entries {
909            let bucket = (entry.0 as usize) & (bucket_count - 1);
910            buckets[bucket].push(entry);
911        }
912        Some(TapeObjectIndex { buckets })
913    }
914
915    pub fn with_index<'b>(&'b self, index: &'b TapeObjectIndex) -> IndexedTapeObject<'b> {
916        IndexedTapeObject {
917            object: TapeValue {
918                tape: self.tape,
919                input: self.input,
920                index: self.index,
921            },
922            index,
923        }
924    }
925
926    fn get_linear(&self, key: &str) -> Option<TapeValue<'a>> {
927        let parent = self.index;
928        let tokens = &self.tape.tokens;
929        let mut i = self.index + 1;
930        while i < tokens.len() {
931            if tokens[i].parent != Some(parent) {
932                i += 1;
933                continue;
934            }
935            if tokens[i].kind != TapeTokenKind::Key {
936                i += 1;
937                continue;
938            }
939            let candidate = TapeValue {
940                tape: self.tape,
941                input: self.input,
942                index: i,
943            };
944            if candidate.as_str() == Some(key) {
945                let value_index = i + 1;
946                if value_index < tokens.len() && tokens[value_index].parent == Some(parent) {
947                    return Some(TapeValue {
948                        tape: self.tape,
949                        input: self.input,
950                        index: value_index,
951                    });
952                }
953                return None;
954            }
955            i += 1;
956        }
957        None
958    }
959}
960
961impl TapeObjectIndex {
962    pub fn get<'a>(&self, object: TapeValue<'a>, key: &str) -> Option<TapeValue<'a>> {
963        self.get_hashed(object, hash_key(key.as_bytes()), key)
964    }
965
966    pub fn get_compiled<'a>(&self, object: TapeValue<'a>, key: &CompiledTapeKey) -> Option<TapeValue<'a>> {
967        self.get_hashed(object, key.hash, &key.key)
968    }
969
970    fn get_hashed<'a>(&self, object: TapeValue<'a>, hash: u64, key: &str) -> Option<TapeValue<'a>> {
971        let bucket = (hash as usize) & (self.buckets.len() - 1);
972        for (entry_hash, key_index, value_index) in &self.buckets[bucket] {
973            if *entry_hash != hash {
974                continue;
975            }
976            let candidate = TapeValue {
977                tape: object.tape,
978                input: object.input,
979                index: *key_index,
980            };
981            if candidate.as_str() == Some(key) {
982                return Some(TapeValue {
983                    tape: object.tape,
984                    input: object.input,
985                    index: *value_index,
986                });
987            }
988        }
989        None
990    }
991}
992
993impl CompiledTapeKey {
994    pub fn new(key: impl Into<String>) -> Self {
995        let key = key.into();
996        let hash = hash_key(key.as_bytes());
997        Self { key, hash }
998    }
999
1000    pub fn as_str(&self) -> &str {
1001        &self.key
1002    }
1003}
1004
1005impl CompiledTapeKeys {
1006    pub fn new(keys: &[&str]) -> Self {
1007        Self {
1008            keys: keys.iter().map(|key| CompiledTapeKey::new(*key)).collect(),
1009        }
1010    }
1011
1012    pub fn iter(&self) -> impl Iterator<Item = &CompiledTapeKey> {
1013        self.keys.iter()
1014    }
1015}
1016
1017impl<'a> IndexedTapeObject<'a> {
1018    pub fn get(&self, key: &str) -> Option<TapeValue<'a>> {
1019        self.index.get(self.object, key)
1020    }
1021
1022    pub fn get_compiled(&self, key: &CompiledTapeKey) -> Option<TapeValue<'a>> {
1023        self.index.get_compiled(self.object, key)
1024    }
1025
1026    pub fn get_many<'b>(
1027        &'b self,
1028        keys: &'b [&'b str],
1029    ) -> impl Iterator<Item = Option<TapeValue<'a>>> + 'b {
1030        keys.iter().map(|key| self.get(key))
1031    }
1032
1033    pub fn get_compiled_many<'b>(
1034        &'b self,
1035        keys: &'b CompiledTapeKeys,
1036    ) -> impl Iterator<Item = Option<TapeValue<'a>>> + 'b {
1037        keys.iter().map(|key| self.get_compiled(key))
1038    }
1039}
1040
1041
1042impl fmt::Display for JsonValue {
1043    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044        match self.to_json_string() {
1045            Ok(json) => f.write_str(&json),
1046            Err(_) => Err(fmt::Error),
1047        }
1048    }
1049}
1050
1051static JSON_NULL: JsonValue = JsonValue::Null;
1052
1053pub trait ValueIndex {
1054    fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue>;
1055    fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue>;
1056}
1057
1058impl ValueIndex for usize {
1059    fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1060        match value {
1061            JsonValue::Array(values) => values.get(*self),
1062            _ => None,
1063        }
1064    }
1065
1066    fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1067        match value {
1068            JsonValue::Array(values) => values.get_mut(*self),
1069            _ => None,
1070        }
1071    }
1072}
1073
1074impl ValueIndex for str {
1075    fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1076        match value {
1077            JsonValue::Object(entries) => object_get(entries, self),
1078            _ => None,
1079        }
1080    }
1081
1082    fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1083        match value {
1084            JsonValue::Object(entries) => object_get_mut(entries, self),
1085            _ => None,
1086        }
1087    }
1088}
1089
1090impl ValueIndex for String {
1091    fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1092        self.as_str().index_into(value)
1093    }
1094
1095    fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1096        self.as_str().index_into_mut(value)
1097    }
1098}
1099
1100impl<T> ValueIndex for &T
1101where
1102    T: ?Sized + ValueIndex,
1103{
1104    fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1105        (**self).index_into(value)
1106    }
1107
1108    fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1109        (**self).index_into_mut(value)
1110    }
1111}
1112
1113fn object_get<'a>(entries: &'a [(String, JsonValue)], key: &str) -> Option<&'a JsonValue> {
1114    entries
1115        .iter()
1116        .find(|(candidate, _)| candidate == key)
1117        .map(|(_, value)| value)
1118}
1119
1120fn object_get_mut<'a>(entries: &'a mut Vec<(String, JsonValue)>, key: &str) -> Option<&'a mut JsonValue> {
1121    entries
1122        .iter_mut()
1123        .find(|(candidate, _)| candidate == key)
1124        .map(|(_, value)| value)
1125}
1126
1127fn object_index_or_insert<'a>(value: &'a mut JsonValue, key: &str) -> &'a mut JsonValue {
1128    if matches!(value, JsonValue::Null) {
1129        *value = JsonValue::Object(Vec::new());
1130    }
1131    match value {
1132        JsonValue::Object(entries) => {
1133            if let Some(pos) = entries.iter().position(|(candidate, _)| candidate == key) {
1134                &mut entries[pos].1
1135            } else {
1136                entries.push((key.to_owned(), JsonValue::Null));
1137                &mut entries.last_mut().unwrap().1
1138            }
1139        }
1140        JsonValue::Null => unreachable!(),
1141        JsonValue::Bool(_) => panic!("cannot access key {:?} in JSON boolean", key),
1142        JsonValue::Number(_) => panic!("cannot access key {:?} in JSON number", key),
1143        JsonValue::String(_) => panic!("cannot access key {:?} in JSON string", key),
1144        JsonValue::Array(_) => panic!("cannot access key {:?} in JSON array", key),
1145    }
1146}
1147
1148fn array_index_or_panic(value: &mut JsonValue, index: usize) -> &mut JsonValue {
1149    match value {
1150        JsonValue::Array(values) => {
1151            let len = values.len();
1152            values.get_mut(index).unwrap_or_else(|| panic!("cannot access index {} of JSON array of length {}", index, len))
1153        }
1154        JsonValue::Null => panic!("cannot access index {} of JSON null", index),
1155        JsonValue::Bool(_) => panic!("cannot access index {} of JSON boolean", index),
1156        JsonValue::Number(_) => panic!("cannot access index {} of JSON number", index),
1157        JsonValue::String(_) => panic!("cannot access index {} of JSON string", index),
1158        JsonValue::Object(_) => panic!("cannot access index {} of JSON object", index),
1159    }
1160}
1161
1162impl Index<&str> for JsonValue {
1163    type Output = JsonValue;
1164
1165    fn index(&self, index: &str) -> &Self::Output {
1166        match self {
1167            JsonValue::Object(entries) => object_get(entries, index).unwrap_or(&JSON_NULL),
1168            _ => &JSON_NULL,
1169        }
1170    }
1171}
1172
1173impl Index<String> for JsonValue {
1174    type Output = JsonValue;
1175
1176    fn index(&self, index: String) -> &Self::Output {
1177        self.index(index.as_str())
1178    }
1179}
1180
1181impl Index<usize> for JsonValue {
1182    type Output = JsonValue;
1183
1184    fn index(&self, index: usize) -> &Self::Output {
1185        match self {
1186            JsonValue::Array(values) => values.get(index).unwrap_or(&JSON_NULL),
1187            _ => &JSON_NULL,
1188        }
1189    }
1190}
1191
1192impl IndexMut<&str> for JsonValue {
1193    fn index_mut(&mut self, index: &str) -> &mut Self::Output {
1194        object_index_or_insert(self, index)
1195    }
1196}
1197
1198impl IndexMut<String> for JsonValue {
1199    fn index_mut(&mut self, index: String) -> &mut Self::Output {
1200        object_index_or_insert(self, &index)
1201    }
1202}
1203
1204impl IndexMut<usize> for JsonValue {
1205    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1206        array_index_or_panic(self, index)
1207    }
1208}
1209
1210#[macro_export]
1211macro_rules! json {
1212    (null) => {
1213        $crate::JsonValue::Null
1214    };
1215    ([$($element:tt),* $(,)?]) => {
1216        $crate::JsonValue::Array(vec![$($crate::json!($element)),*])
1217    };
1218    ({$($key:literal : $value:tt),* $(,)?}) => {
1219        $crate::JsonValue::Object(vec![$(($key.to_owned(), $crate::json!($value))),*])
1220    };
1221    ($other:expr) => {
1222        $crate::JsonValue::from($other)
1223    };
1224}
1225
1226fn decode_pointer_segment(segment: &str) -> String {
1227    let mut out = String::with_capacity(segment.len());
1228    let bytes = segment.as_bytes();
1229    let mut i = 0;
1230    while i < bytes.len() {
1231        if bytes[i] == b'~' && i + 1 < bytes.len() {
1232            match bytes[i + 1] {
1233                b'0' => {
1234                    out.push('~');
1235                    i += 2;
1236                    continue;
1237                }
1238                b'1' => {
1239                    out.push('/');
1240                    i += 2;
1241                    continue;
1242                }
1243                _ => {}
1244            }
1245        }
1246        out.push(bytes[i] as char);
1247        i += 1;
1248    }
1249    out
1250}
1251
1252fn write_indent(out: &mut Vec<u8>, depth: usize) {
1253    for _ in 0..depth {
1254        out.extend_from_slice(b"  ");
1255    }
1256}
1257
1258fn write_json_value_pretty(out: &mut Vec<u8>, value: &JsonValue, depth: usize) -> Result<(), JsonError> {
1259    match value {
1260        JsonValue::Null | JsonValue::Bool(_) | JsonValue::Number(_) | JsonValue::String(_) => {
1261            write_json_value(out, value)
1262        }
1263        JsonValue::Array(values) => {
1264            out.push(b'[');
1265            if !values.is_empty() {
1266                out.push(b'\n');
1267                for (index, value) in values.iter().enumerate() {
1268                    if index > 0 {
1269                        out.extend_from_slice(b",\n");
1270                    }
1271                    write_indent(out, depth + 1);
1272                    write_json_value_pretty(out, value, depth + 1)?;
1273                }
1274                out.push(b'\n');
1275                write_indent(out, depth);
1276            }
1277            out.push(b']');
1278            Ok(())
1279        }
1280        JsonValue::Object(entries) => {
1281            out.push(b'{');
1282            if !entries.is_empty() {
1283                out.push(b'\n');
1284                for (index, (key, value)) in entries.iter().enumerate() {
1285                    if index > 0 {
1286                        out.extend_from_slice(b",\n");
1287                    }
1288                    write_indent(out, depth + 1);
1289                    write_json_key(out, key);
1290                    out.push(b' ');
1291                    write_json_value_pretty(out, value, depth + 1)?;
1292                }
1293                out.push(b'\n');
1294                write_indent(out, depth);
1295            }
1296            out.push(b'}');
1297            Ok(())
1298        }
1299    }
1300}
1301
1302fn hash_key(bytes: &[u8]) -> u64 {
1303    let mut hash = 1469598103934665603u64;
1304    for &byte in bytes {
1305        hash ^= byte as u64;
1306        hash = hash.wrapping_mul(1099511628211u64);
1307    }
1308    hash
1309}
1310
1311#[inline]
1312fn write_json_value(out: &mut Vec<u8>, value: &JsonValue) -> Result<(), JsonError> {
1313    match value {
1314        JsonValue::Null => out.extend_from_slice(b"null"),
1315        JsonValue::Bool(value) => {
1316            if *value {
1317                out.extend_from_slice(b"true");
1318            } else {
1319                out.extend_from_slice(b"false");
1320            }
1321        }
1322        JsonValue::Number(number) => write_json_number(out, number)?,
1323        JsonValue::String(value) => {
1324            write_escaped_json_string(out, value);
1325        }
1326        JsonValue::Array(values) => {
1327            write_json_array(out, values)?;
1328        }
1329        JsonValue::Object(entries) => {
1330            write_json_object(out, entries)?;
1331        }
1332    }
1333    Ok(())
1334}
1335
1336#[inline]
1337fn write_json_number(out: &mut Vec<u8>, value: &JsonNumber) -> Result<(), JsonError> {
1338    match value {
1339        JsonNumber::I64(value) => {
1340            append_i64(out, *value);
1341            Ok(())
1342        }
1343        JsonNumber::U64(value) => {
1344            append_u64(out, *value);
1345            Ok(())
1346        }
1347        JsonNumber::F64(value) => {
1348            if !value.is_finite() {
1349                return Err(JsonError::NonFiniteNumber);
1350            }
1351            out.extend_from_slice(value.to_string().as_bytes());
1352            Ok(())
1353        }
1354    }
1355}
1356
1357#[inline]
1358fn write_escaped_json_string(out: &mut Vec<u8>, input: &str) {
1359    out.push(b'"');
1360    let bytes = input.as_bytes();
1361    let mut fast_index = 0usize;
1362    while fast_index < bytes.len() {
1363        let byte = bytes[fast_index];
1364        if needs_escape(byte) {
1365            break;
1366        }
1367        fast_index += 1;
1368    }
1369    if fast_index == bytes.len() {
1370        out.extend_from_slice(bytes);
1371        out.push(b'"');
1372        return;
1373    }
1374
1375    if fast_index > 0 {
1376        out.extend_from_slice(&bytes[..fast_index]);
1377    }
1378
1379    let mut chunk_start = fast_index;
1380    for (index, byte) in bytes.iter().copied().enumerate().skip(fast_index) {
1381        let escape = match byte {
1382            b'"' => Some(br#"\""#.as_slice()),
1383            b'\\' => Some(br#"\\"#.as_slice()),
1384            0x08 => Some(br#"\b"#.as_slice()),
1385            0x0c => Some(br#"\f"#.as_slice()),
1386            b'\n' => Some(br#"\n"#.as_slice()),
1387            b'\r' => Some(br#"\r"#.as_slice()),
1388            b'\t' => Some(br#"\t"#.as_slice()),
1389            _ => None,
1390        };
1391        if let Some(escape) = escape {
1392            if chunk_start < index {
1393                out.extend_from_slice(&bytes[chunk_start..index]);
1394            }
1395            out.extend_from_slice(escape);
1396            chunk_start = index + 1;
1397            continue;
1398        }
1399        if byte <= 0x1f {
1400            if chunk_start < index {
1401                out.extend_from_slice(&bytes[chunk_start..index]);
1402            }
1403            out.extend_from_slice(br#"\u00"#);
1404            out.push(hex_digit((byte >> 4) & 0x0f));
1405            out.push(hex_digit(byte & 0x0f));
1406            chunk_start = index + 1;
1407        }
1408    }
1409    if chunk_start < input.len() {
1410        out.extend_from_slice(&bytes[chunk_start..]);
1411    }
1412    out.push(b'"');
1413}
1414
1415#[inline]
1416fn needs_escape(byte: u8) -> bool {
1417    matches!(byte, b'"' | b'\\' | 0x00..=0x1f)
1418}
1419
1420#[inline]
1421fn write_json_array(out: &mut Vec<u8>, values: &[JsonValue]) -> Result<(), JsonError> {
1422    out.push(b'[');
1423    match values {
1424        [] => {}
1425        [one] => {
1426            write_json_value(out, one)?;
1427        }
1428        [a, b] => {
1429            write_json_value(out, a)?;
1430            out.push(b',');
1431            write_json_value(out, b)?;
1432        }
1433        [a, b, c] => {
1434            write_json_value(out, a)?;
1435            out.push(b',');
1436            write_json_value(out, b)?;
1437            out.push(b',');
1438            write_json_value(out, c)?;
1439        }
1440        _ => {
1441            let mut iter = values.iter();
1442            if let Some(first) = iter.next() {
1443                write_json_value(out, first)?;
1444                for value in iter {
1445                    out.push(b',');
1446                    write_json_value(out, value)?;
1447                }
1448            }
1449        }
1450    }
1451    out.push(b']');
1452    Ok(())
1453}
1454
1455#[inline]
1456fn write_json_object(out: &mut Vec<u8>, entries: &[(String, JsonValue)]) -> Result<(), JsonError> {
1457    out.push(b'{');
1458    match entries {
1459        [] => {}
1460        [(k1, v1)] => {
1461            write_json_key(out, k1);
1462            write_json_value(out, v1)?;
1463        }
1464        [(k1, v1), (k2, v2)] => {
1465            write_json_key(out, k1);
1466            write_json_value(out, v1)?;
1467            out.push(b',');
1468            write_json_key(out, k2);
1469            write_json_value(out, v2)?;
1470        }
1471        [(k1, v1), (k2, v2), (k3, v3)] => {
1472            write_json_key(out, k1);
1473            write_json_value(out, v1)?;
1474            out.push(b',');
1475            write_json_key(out, k2);
1476            write_json_value(out, v2)?;
1477            out.push(b',');
1478            write_json_key(out, k3);
1479            write_json_value(out, v3)?;
1480        }
1481        _ => {
1482            let mut iter = entries.iter();
1483            if let Some((first_key, first_value)) = iter.next() {
1484                write_json_key(out, first_key);
1485                write_json_value(out, first_value)?;
1486                for (key, value) in iter {
1487                    out.push(b',');
1488                    write_json_key(out, key);
1489                    write_json_value(out, value)?;
1490                }
1491            }
1492        }
1493    }
1494    out.push(b'}');
1495    Ok(())
1496}
1497
1498#[inline]
1499fn write_json_key(out: &mut Vec<u8>, key: &str) {
1500    let bytes = key.as_bytes();
1501    if is_plain_json_string(bytes) {
1502        out.push(b'"');
1503        out.extend_from_slice(bytes);
1504        out.extend_from_slice(b"\":");
1505    } else {
1506        write_escaped_json_string(out, key);
1507        out.push(b':');
1508    }
1509}
1510
1511#[inline]
1512fn is_plain_json_string(bytes: &[u8]) -> bool {
1513    for &byte in bytes {
1514        if needs_escape(byte) {
1515            return false;
1516        }
1517    }
1518    true
1519}
1520
1521fn initial_json_capacity(value: &JsonValue) -> usize {
1522    match value {
1523        JsonValue::Null => 4,
1524        JsonValue::Bool(true) => 4,
1525        JsonValue::Bool(false) => 5,
1526        JsonValue::Number(JsonNumber::I64(value)) => estimate_i64_len(*value),
1527        JsonValue::Number(JsonNumber::U64(value)) => estimate_u64_len(*value),
1528        JsonValue::Number(JsonNumber::F64(_)) => 24,
1529        JsonValue::String(value) => estimate_escaped_string_len(value),
1530        JsonValue::Array(values) => 2 + values.len().saturating_mul(16),
1531        JsonValue::Object(entries) => {
1532            2 + entries
1533                .iter()
1534                .map(|(key, _)| estimate_escaped_string_len(key) + 8)
1535                .sum::<usize>()
1536        }
1537    }
1538}
1539
1540fn estimate_escaped_string_len(value: &str) -> usize {
1541    let mut len = 2;
1542    for ch in value.chars() {
1543        len += match ch {
1544            '"' | '\\' | '\u{08}' | '\u{0C}' | '\n' | '\r' | '\t' => 2,
1545            ch if ch <= '\u{1F}' => 6,
1546            ch => ch.len_utf8(),
1547        };
1548    }
1549    len
1550}
1551
1552fn estimate_u64_len(mut value: u64) -> usize {
1553    let mut len = 1;
1554    while value >= 10 {
1555        value /= 10;
1556        len += 1;
1557    }
1558    len
1559}
1560
1561fn estimate_i64_len(value: i64) -> usize {
1562    if value < 0 {
1563        1 + estimate_u64_len(value.unsigned_abs())
1564    } else {
1565        estimate_u64_len(value as u64)
1566    }
1567}
1568
1569fn append_i64(out: &mut Vec<u8>, value: i64) {
1570    if value < 0 {
1571        out.push(b'-');
1572        append_u64(out, value.unsigned_abs());
1573    } else {
1574        append_u64(out, value as u64);
1575    }
1576}
1577
1578fn append_u64(out: &mut Vec<u8>, mut value: u64) {
1579    let mut buf = [0u8; 20];
1580    let mut index = buf.len();
1581    loop {
1582        index -= 1;
1583        buf[index] = b'0' + (value % 10) as u8;
1584        value /= 10;
1585        if value == 0 {
1586            break;
1587        }
1588    }
1589    out.extend_from_slice(&buf[index..]);
1590}
1591
1592fn hex_digit(value: u8) -> u8 {
1593    match value {
1594        0..=9 => b'0' + value,
1595        10..=15 => b'a' + (value - 10),
1596        _ => unreachable!(),
1597    }
1598}
1599
1600struct Parser<'a> {
1601    input: &'a str,
1602    bytes: &'a [u8],
1603    index: usize,
1604}
1605
1606impl<'a> Parser<'a> {
1607    fn new(input: &'a str) -> Self {
1608        Self {
1609            input,
1610            bytes: input.as_bytes(),
1611            index: 0,
1612        }
1613    }
1614
1615    fn parse_value(&mut self) -> Result<JsonValue, JsonParseError> {
1616        self.skip_whitespace();
1617        match self.peek_byte() {
1618            Some(b'n') => self.parse_literal(b"null", JsonValue::Null),
1619            Some(b't') => self.parse_literal(b"true", JsonValue::Bool(true)),
1620            Some(b'f') => self.parse_literal(b"false", JsonValue::Bool(false)),
1621            Some(b'"') => Ok(JsonValue::String(self.parse_string()?)),
1622            Some(b'[') => self.parse_array(),
1623            Some(b'{') => self.parse_object(),
1624            Some(b'-' | b'0'..=b'9') => self.parse_number().map(JsonValue::Number),
1625            Some(found) => Err(JsonParseError::UnexpectedCharacter {
1626                index: self.index,
1627                found: found as char,
1628            }),
1629            None => Err(JsonParseError::UnexpectedEnd),
1630        }
1631    }
1632
1633    fn parse_value_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
1634        self.skip_whitespace();
1635        match self.peek_byte() {
1636            Some(b'n') => self.parse_literal_borrowed(b"null", BorrowedJsonValue::Null),
1637            Some(b't') => self.parse_literal_borrowed(b"true", BorrowedJsonValue::Bool(true)),
1638            Some(b'f') => self.parse_literal_borrowed(b"false", BorrowedJsonValue::Bool(false)),
1639            Some(b'"') => Ok(BorrowedJsonValue::String(self.parse_string_borrowed()?)),
1640            Some(b'[') => self.parse_array_borrowed(),
1641            Some(b'{') => self.parse_object_borrowed(),
1642            Some(b'-' | b'0'..=b'9') => self.parse_number().map(BorrowedJsonValue::Number),
1643            Some(found) => Err(JsonParseError::UnexpectedCharacter {
1644                index: self.index,
1645                found: found as char,
1646            }),
1647            None => Err(JsonParseError::UnexpectedEnd),
1648        }
1649    }
1650
1651    fn parse_tape_value(
1652        &mut self,
1653        tokens: &mut Vec<TapeToken>,
1654        parent: Option<usize>,
1655    ) -> Result<usize, JsonParseError> {
1656        self.skip_whitespace();
1657        match self.peek_byte() {
1658            Some(b'n') => self.parse_tape_literal(tokens, parent, b"null", TapeTokenKind::Null),
1659            Some(b't') => self.parse_tape_literal(tokens, parent, b"true", TapeTokenKind::Bool),
1660            Some(b'f') => self.parse_tape_literal(tokens, parent, b"false", TapeTokenKind::Bool),
1661            Some(b'"') => self.parse_tape_string(tokens, parent, TapeTokenKind::String),
1662            Some(b'[') => self.parse_tape_array(tokens, parent),
1663            Some(b'{') => self.parse_tape_object(tokens, parent),
1664            Some(b'-' | b'0'..=b'9') => self.parse_tape_number(tokens, parent),
1665            Some(found) => Err(JsonParseError::UnexpectedCharacter {
1666                index: self.index,
1667                found: found as char,
1668            }),
1669            None => Err(JsonParseError::UnexpectedEnd),
1670        }
1671    }
1672
1673    fn parse_literal(
1674        &mut self,
1675        expected: &[u8],
1676        value: JsonValue,
1677    ) -> Result<JsonValue, JsonParseError> {
1678        if self.bytes[self.index..].starts_with(expected) {
1679            self.index += expected.len();
1680            Ok(value)
1681        } else {
1682            Err(JsonParseError::InvalidLiteral { index: self.index })
1683        }
1684    }
1685
1686    fn parse_literal_borrowed(
1687        &mut self,
1688        expected: &[u8],
1689        value: BorrowedJsonValue<'a>,
1690    ) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
1691        if self.bytes[self.index..].starts_with(expected) {
1692            self.index += expected.len();
1693            Ok(value)
1694        } else {
1695            Err(JsonParseError::InvalidLiteral { index: self.index })
1696        }
1697    }
1698
1699    fn parse_tape_literal(
1700        &mut self,
1701        tokens: &mut Vec<TapeToken>,
1702        parent: Option<usize>,
1703        expected: &[u8],
1704        kind: TapeTokenKind,
1705    ) -> Result<usize, JsonParseError> {
1706        let start = self.index;
1707        if self.bytes[self.index..].starts_with(expected) {
1708            self.index += expected.len();
1709            let token_index = tokens.len();
1710            tokens.push(TapeToken {
1711                kind,
1712                start,
1713                end: self.index,
1714                parent,
1715            });
1716            Ok(token_index)
1717        } else {
1718            Err(JsonParseError::InvalidLiteral { index: self.index })
1719        }
1720    }
1721
1722    fn parse_array(&mut self) -> Result<JsonValue, JsonParseError> {
1723        self.consume_byte(b'[')?;
1724        self.skip_whitespace();
1725        let mut values = Vec::new();
1726        if self.try_consume_byte(b']') {
1727            return Ok(JsonValue::Array(values));
1728        }
1729        loop {
1730            values.push(self.parse_value()?);
1731            self.skip_whitespace();
1732            if self.try_consume_byte(b']') {
1733                break;
1734            }
1735            if !self.try_consume_byte(b',') {
1736                return Err(JsonParseError::ExpectedCommaOrEnd {
1737                    index: self.index,
1738                    context: "array",
1739                });
1740            }
1741            self.skip_whitespace();
1742        }
1743        Ok(JsonValue::Array(values))
1744    }
1745
1746    fn parse_array_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
1747        self.consume_byte(b'[')?;
1748        self.skip_whitespace();
1749        let mut values = Vec::new();
1750        if self.try_consume_byte(b']') {
1751            return Ok(BorrowedJsonValue::Array(values));
1752        }
1753        loop {
1754            values.push(self.parse_value_borrowed()?);
1755            self.skip_whitespace();
1756            if self.try_consume_byte(b']') {
1757                break;
1758            }
1759            if !self.try_consume_byte(b',') {
1760                return Err(JsonParseError::ExpectedCommaOrEnd {
1761                    index: self.index,
1762                    context: "array",
1763                });
1764            }
1765            self.skip_whitespace();
1766        }
1767        Ok(BorrowedJsonValue::Array(values))
1768    }
1769
1770    fn parse_tape_array(
1771        &mut self,
1772        tokens: &mut Vec<TapeToken>,
1773        parent: Option<usize>,
1774    ) -> Result<usize, JsonParseError> {
1775        let start = self.index;
1776        self.consume_byte(b'[')?;
1777        let token_index = tokens.len();
1778        tokens.push(TapeToken {
1779            kind: TapeTokenKind::Array,
1780            start,
1781            end: start,
1782            parent,
1783        });
1784        self.skip_whitespace();
1785        if self.try_consume_byte(b']') {
1786            tokens[token_index].end = self.index;
1787            return Ok(token_index);
1788        }
1789        loop {
1790            self.parse_tape_value(tokens, Some(token_index))?;
1791            self.skip_whitespace();
1792            if self.try_consume_byte(b']') {
1793                tokens[token_index].end = self.index;
1794                break;
1795            }
1796            if !self.try_consume_byte(b',') {
1797                return Err(JsonParseError::ExpectedCommaOrEnd {
1798                    index: self.index,
1799                    context: "array",
1800                });
1801            }
1802            self.skip_whitespace();
1803        }
1804        Ok(token_index)
1805    }
1806
1807    fn parse_object(&mut self) -> Result<JsonValue, JsonParseError> {
1808        self.consume_byte(b'{')?;
1809        self.skip_whitespace();
1810        let mut entries = Vec::new();
1811        if self.try_consume_byte(b'}') {
1812            return Ok(JsonValue::Object(entries));
1813        }
1814        loop {
1815            if self.peek_byte() != Some(b'"') {
1816                return match self.peek_byte() {
1817                    Some(found) => Err(JsonParseError::UnexpectedCharacter {
1818                        index: self.index,
1819                        found: found as char,
1820                    }),
1821                    None => Err(JsonParseError::UnexpectedEnd),
1822                };
1823            }
1824            let key = self.parse_string()?;
1825            self.skip_whitespace();
1826            if !self.try_consume_byte(b':') {
1827                return Err(JsonParseError::ExpectedColon { index: self.index });
1828            }
1829            let value = self.parse_value()?;
1830            entries.push((key, value));
1831            self.skip_whitespace();
1832            if self.try_consume_byte(b'}') {
1833                break;
1834            }
1835            if !self.try_consume_byte(b',') {
1836                return Err(JsonParseError::ExpectedCommaOrEnd {
1837                    index: self.index,
1838                    context: "object",
1839                });
1840            }
1841            self.skip_whitespace();
1842        }
1843        Ok(JsonValue::Object(entries))
1844    }
1845
1846    fn parse_object_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
1847        self.consume_byte(b'{')?;
1848        self.skip_whitespace();
1849        let mut entries = Vec::new();
1850        if self.try_consume_byte(b'}') {
1851            return Ok(BorrowedJsonValue::Object(entries));
1852        }
1853        loop {
1854            if self.peek_byte() != Some(b'"') {
1855                return match self.peek_byte() {
1856                    Some(found) => Err(JsonParseError::UnexpectedCharacter {
1857                        index: self.index,
1858                        found: found as char,
1859                    }),
1860                    None => Err(JsonParseError::UnexpectedEnd),
1861                };
1862            }
1863            let key = self.parse_string_borrowed()?;
1864            self.skip_whitespace();
1865            if !self.try_consume_byte(b':') {
1866                return Err(JsonParseError::ExpectedColon { index: self.index });
1867            }
1868            let value = self.parse_value_borrowed()?;
1869            entries.push((key, value));
1870            self.skip_whitespace();
1871            if self.try_consume_byte(b'}') {
1872                break;
1873            }
1874            if !self.try_consume_byte(b',') {
1875                return Err(JsonParseError::ExpectedCommaOrEnd {
1876                    index: self.index,
1877                    context: "object",
1878                });
1879            }
1880            self.skip_whitespace();
1881        }
1882        Ok(BorrowedJsonValue::Object(entries))
1883    }
1884
1885    fn parse_tape_object(
1886        &mut self,
1887        tokens: &mut Vec<TapeToken>,
1888        parent: Option<usize>,
1889    ) -> Result<usize, JsonParseError> {
1890        let start = self.index;
1891        self.consume_byte(b'{')?;
1892        let token_index = tokens.len();
1893        tokens.push(TapeToken {
1894            kind: TapeTokenKind::Object,
1895            start,
1896            end: start,
1897            parent,
1898        });
1899        self.skip_whitespace();
1900        if self.try_consume_byte(b'}') {
1901            tokens[token_index].end = self.index;
1902            return Ok(token_index);
1903        }
1904        loop {
1905            if self.peek_byte() != Some(b'"') {
1906                return match self.peek_byte() {
1907                    Some(found) => Err(JsonParseError::UnexpectedCharacter {
1908                        index: self.index,
1909                        found: found as char,
1910                    }),
1911                    None => Err(JsonParseError::UnexpectedEnd),
1912                };
1913            }
1914            self.parse_tape_string(tokens, Some(token_index), TapeTokenKind::Key)?;
1915            self.skip_whitespace();
1916            if !self.try_consume_byte(b':') {
1917                return Err(JsonParseError::ExpectedColon { index: self.index });
1918            }
1919            self.parse_tape_value(tokens, Some(token_index))?;
1920            self.skip_whitespace();
1921            if self.try_consume_byte(b'}') {
1922                tokens[token_index].end = self.index;
1923                break;
1924            }
1925            if !self.try_consume_byte(b',') {
1926                return Err(JsonParseError::ExpectedCommaOrEnd {
1927                    index: self.index,
1928                    context: "object",
1929                });
1930            }
1931            self.skip_whitespace();
1932        }
1933        Ok(token_index)
1934    }
1935
1936    fn parse_string(&mut self) -> Result<String, JsonParseError> {
1937        self.consume_byte(b'"')?;
1938        let start = self.index;
1939        loop {
1940            let Some(byte) = self.next_byte() else {
1941                return Err(JsonParseError::UnexpectedEnd);
1942            };
1943            match byte {
1944                b'"' => {
1945                    let slice = &self.input[start..self.index - 1];
1946                    return Ok(slice.to_owned());
1947                }
1948                b'\\' => {
1949                    let mut out = String::with_capacity(self.index - start + 8);
1950                    out.push_str(&self.input[start..self.index - 1]);
1951                    self.parse_escape_into(&mut out, self.index - 1)?;
1952                    return self.parse_string_slow(out);
1953                }
1954                0x00..=0x1f => {
1955                    return Err(JsonParseError::UnexpectedCharacter {
1956                        index: self.index - 1,
1957                        found: byte as char,
1958                    })
1959                }
1960                _ => {}
1961            }
1962        }
1963    }
1964
1965    fn parse_string_borrowed(&mut self) -> Result<Cow<'a, str>, JsonParseError> {
1966        self.consume_byte(b'"')?;
1967        let start = self.index;
1968        loop {
1969            let Some(byte) = self.next_byte() else {
1970                return Err(JsonParseError::UnexpectedEnd);
1971            };
1972            match byte {
1973                b'"' => {
1974                    let slice = &self.input[start..self.index - 1];
1975                    return Ok(Cow::Borrowed(slice));
1976                }
1977                b'\\' => {
1978                    let mut out = String::with_capacity(self.index - start + 8);
1979                    out.push_str(&self.input[start..self.index - 1]);
1980                    self.parse_escape_into(&mut out, self.index - 1)?;
1981                    return self.parse_string_slow_borrowed(out);
1982                }
1983                0x00..=0x1f => {
1984                    return Err(JsonParseError::UnexpectedCharacter {
1985                        index: self.index - 1,
1986                        found: byte as char,
1987                    })
1988                }
1989                _ => {}
1990            }
1991        }
1992    }
1993
1994    fn parse_tape_string(
1995        &mut self,
1996        tokens: &mut Vec<TapeToken>,
1997        parent: Option<usize>,
1998        kind: TapeTokenKind,
1999    ) -> Result<usize, JsonParseError> {
2000        let start = self.index;
2001        self.skip_string_bytes()?;
2002        let token_index = tokens.len();
2003        tokens.push(TapeToken {
2004            kind,
2005            start,
2006            end: self.index,
2007            parent,
2008        });
2009        Ok(token_index)
2010    }
2011
2012    fn skip_string_bytes(&mut self) -> Result<(), JsonParseError> {
2013        self.consume_byte(b'"')?;
2014        loop {
2015            let Some(byte) = self.next_byte() else {
2016                return Err(JsonParseError::UnexpectedEnd);
2017            };
2018            match byte {
2019                b'"' => return Ok(()),
2020                b'\\' => {
2021                    let escape_index = self.index - 1;
2022                    let escaped = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2023                    match escaped {
2024                        b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
2025                        b'u' => {
2026                            let scalar = self.parse_hex_quad(escape_index)?;
2027                            if (0xD800..=0xDBFF).contains(&scalar) {
2028                                if self.next_byte() != Some(b'\\') || self.next_byte() != Some(b'u')
2029                                {
2030                                    return Err(JsonParseError::InvalidUnicodeScalar {
2031                                        index: escape_index,
2032                                    });
2033                                }
2034                                let low = self.parse_hex_quad(escape_index)?;
2035                                if !(0xDC00..=0xDFFF).contains(&low) {
2036                                    return Err(JsonParseError::InvalidUnicodeScalar {
2037                                        index: escape_index,
2038                                    });
2039                                }
2040                            } else if (0xDC00..=0xDFFF).contains(&scalar) {
2041                                return Err(JsonParseError::InvalidUnicodeScalar {
2042                                    index: escape_index,
2043                                });
2044                            }
2045                        }
2046                        _ => {
2047                            return Err(JsonParseError::InvalidEscape {
2048                                index: escape_index,
2049                            })
2050                        }
2051                    }
2052                }
2053                0x00..=0x1f => {
2054                    return Err(JsonParseError::UnexpectedCharacter {
2055                        index: self.index - 1,
2056                        found: byte as char,
2057                    })
2058                }
2059                _ => {}
2060            }
2061        }
2062    }
2063
2064    fn parse_string_slow(&mut self, mut out: String) -> Result<String, JsonParseError> {
2065        let mut chunk_start = self.index;
2066        loop {
2067            let Some(byte) = self.next_byte() else {
2068                return Err(JsonParseError::UnexpectedEnd);
2069            };
2070            match byte {
2071                b'"' => {
2072                    if chunk_start < self.index - 1 {
2073                        out.push_str(&self.input[chunk_start..self.index - 1]);
2074                    }
2075                    return Ok(out);
2076                }
2077                b'\\' => {
2078                    if chunk_start < self.index - 1 {
2079                        out.push_str(&self.input[chunk_start..self.index - 1]);
2080                    }
2081                    self.parse_escape_into(&mut out, self.index - 1)?;
2082                    chunk_start = self.index;
2083                }
2084                0x00..=0x1f => {
2085                    return Err(JsonParseError::UnexpectedCharacter {
2086                        index: self.index - 1,
2087                        found: byte as char,
2088                    })
2089                }
2090                _ => {}
2091            }
2092        }
2093    }
2094
2095    fn parse_string_slow_borrowed(
2096        &mut self,
2097        mut out: String,
2098    ) -> Result<Cow<'a, str>, JsonParseError> {
2099        let mut chunk_start = self.index;
2100        loop {
2101            let Some(byte) = self.next_byte() else {
2102                return Err(JsonParseError::UnexpectedEnd);
2103            };
2104            match byte {
2105                b'"' => {
2106                    if chunk_start < self.index - 1 {
2107                        out.push_str(&self.input[chunk_start..self.index - 1]);
2108                    }
2109                    return Ok(Cow::Owned(out));
2110                }
2111                b'\\' => {
2112                    if chunk_start < self.index - 1 {
2113                        out.push_str(&self.input[chunk_start..self.index - 1]);
2114                    }
2115                    self.parse_escape_into(&mut out, self.index - 1)?;
2116                    chunk_start = self.index;
2117                }
2118                0x00..=0x1f => {
2119                    return Err(JsonParseError::UnexpectedCharacter {
2120                        index: self.index - 1,
2121                        found: byte as char,
2122                    })
2123                }
2124                _ => {}
2125            }
2126        }
2127    }
2128
2129    fn parse_escape_into(
2130        &mut self,
2131        out: &mut String,
2132        escape_index: usize,
2133    ) -> Result<(), JsonParseError> {
2134        let escaped = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2135        match escaped {
2136            b'"' => out.push('"'),
2137            b'\\' => out.push('\\'),
2138            b'/' => out.push('/'),
2139            b'b' => out.push('\u{0008}'),
2140            b'f' => out.push('\u{000C}'),
2141            b'n' => out.push('\n'),
2142            b'r' => out.push('\r'),
2143            b't' => out.push('\t'),
2144            b'u' => out.push(self.parse_unicode_escape(escape_index)?),
2145            _ => {
2146                return Err(JsonParseError::InvalidEscape {
2147                    index: escape_index,
2148                })
2149            }
2150        }
2151        Ok(())
2152    }
2153
2154    fn parse_unicode_escape(&mut self, index: usize) -> Result<char, JsonParseError> {
2155        let scalar = self.parse_hex_quad(index)?;
2156        if (0xD800..=0xDBFF).contains(&scalar) {
2157            if self.next_byte() != Some(b'\\') || self.next_byte() != Some(b'u') {
2158                return Err(JsonParseError::InvalidUnicodeScalar { index });
2159            }
2160            let low = self.parse_hex_quad(index)?;
2161            if !(0xDC00..=0xDFFF).contains(&low) {
2162                return Err(JsonParseError::InvalidUnicodeScalar { index });
2163            }
2164            let high = scalar - 0xD800;
2165            let low = low - 0xDC00;
2166            let combined = 0x10000 + ((high << 10) | low);
2167            char::from_u32(combined).ok_or(JsonParseError::InvalidUnicodeScalar { index })
2168        } else if (0xDC00..=0xDFFF).contains(&scalar) {
2169            Err(JsonParseError::InvalidUnicodeScalar { index })
2170        } else {
2171            char::from_u32(scalar).ok_or(JsonParseError::InvalidUnicodeScalar { index })
2172        }
2173    }
2174
2175    fn parse_hex_quad(&mut self, index: usize) -> Result<u32, JsonParseError> {
2176        let mut value = 0u32;
2177        for _ in 0..4 {
2178            let ch = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2179            let digit = match ch {
2180                b'0'..=b'9' => (ch - b'0') as u32,
2181                b'a'..=b'f' => 10 + (ch - b'a') as u32,
2182                b'A'..=b'F' => 10 + (ch - b'A') as u32,
2183                _ => return Err(JsonParseError::InvalidUnicodeEscape { index }),
2184            };
2185            value = (value << 4) | digit;
2186        }
2187        Ok(value)
2188    }
2189
2190    fn parse_number(&mut self) -> Result<JsonNumber, JsonParseError> {
2191        let start = self.index;
2192        self.try_consume_byte(b'-');
2193        if self.try_consume_byte(b'0') {
2194            if matches!(self.peek_byte(), Some(b'0'..=b'9')) {
2195                return Err(JsonParseError::InvalidNumber { index: start });
2196            }
2197        } else {
2198            self.consume_digits(start)?;
2199        }
2200
2201        let mut is_float = false;
2202        if self.try_consume_byte(b'.') {
2203            is_float = true;
2204            self.consume_digits(start)?;
2205        }
2206        if matches!(self.peek_byte(), Some(b'e' | b'E')) {
2207            is_float = true;
2208            self.index += 1;
2209            if matches!(self.peek_byte(), Some(b'+' | b'-')) {
2210                self.index += 1;
2211            }
2212            self.consume_digits(start)?;
2213        }
2214
2215        let token = &self.input[start..self.index];
2216        if is_float {
2217            let value = token
2218                .parse::<f64>()
2219                .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2220            if !value.is_finite() {
2221                return Err(JsonParseError::InvalidNumber { index: start });
2222            }
2223            Ok(JsonNumber::F64(value))
2224        } else if token.starts_with('-') {
2225            let value = token
2226                .parse::<i64>()
2227                .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2228            Ok(JsonNumber::I64(value))
2229        } else {
2230            let value = token
2231                .parse::<u64>()
2232                .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2233            Ok(JsonNumber::U64(value))
2234        }
2235    }
2236
2237    fn parse_tape_number(
2238        &mut self,
2239        tokens: &mut Vec<TapeToken>,
2240        parent: Option<usize>,
2241    ) -> Result<usize, JsonParseError> {
2242        let start = self.index;
2243        let _ = self.parse_number()?;
2244        let token_index = tokens.len();
2245        tokens.push(TapeToken {
2246            kind: TapeTokenKind::Number,
2247            start,
2248            end: self.index,
2249            parent,
2250        });
2251        Ok(token_index)
2252    }
2253
2254    fn consume_digits(&mut self, index: usize) -> Result<(), JsonParseError> {
2255        let start = self.index;
2256        while matches!(self.peek_byte(), Some(b'0'..=b'9')) {
2257            self.index += 1;
2258        }
2259        if self.index == start {
2260            return Err(JsonParseError::InvalidNumber { index });
2261        }
2262        Ok(())
2263    }
2264
2265    fn consume_byte(&mut self, expected: u8) -> Result<(), JsonParseError> {
2266        match self.next_byte() {
2267            Some(found) if found == expected => Ok(()),
2268            Some(found) => Err(JsonParseError::UnexpectedCharacter {
2269                index: self.index.saturating_sub(1),
2270                found: found as char,
2271            }),
2272            None => Err(JsonParseError::UnexpectedEnd),
2273        }
2274    }
2275
2276    fn try_consume_byte(&mut self, expected: u8) -> bool {
2277        if self.peek_byte() == Some(expected) {
2278            self.index += 1;
2279            true
2280        } else {
2281            false
2282        }
2283    }
2284
2285    fn skip_whitespace(&mut self) {
2286        while matches!(self.peek_byte(), Some(b' ' | b'\n' | b'\r' | b'\t')) {
2287            self.index += 1;
2288        }
2289    }
2290
2291    fn peek_byte(&self) -> Option<u8> {
2292        self.bytes.get(self.index).copied()
2293    }
2294
2295    fn next_byte(&mut self) -> Option<u8> {
2296        let byte = self.peek_byte()?;
2297        self.index += 1;
2298        Some(byte)
2299    }
2300
2301    fn is_eof(&self) -> bool {
2302        self.index >= self.input.len()
2303    }
2304}
2305
2306#[cfg(test)]
2307mod tests {
2308    use super::*;
2309
2310    #[test]
2311    fn escapes_control_characters_and_quotes() {
2312        let escaped = escape_json_string("hello\t\"world\"\n\u{0007}");
2313        assert_eq!(escaped, "\"hello\\t\\\"world\\\"\\n\\u0007\"");
2314    }
2315
2316    #[test]
2317    fn serializes_nested_values() {
2318        let value = JsonValue::object(vec![
2319            ("name", "node-1".into()),
2320            ("ok", true.into()),
2321            (
2322                "values",
2323                JsonValue::array(vec![1u32.into(), 2u32.into(), JsonValue::Null]),
2324            ),
2325        ]);
2326        assert_eq!(
2327            value.to_json_string().unwrap(),
2328            "{\"name\":\"node-1\",\"ok\":true,\"values\":[1,2,null]}"
2329        );
2330    }
2331
2332    #[test]
2333    fn rejects_non_finite_float() {
2334        let value = JsonValue::from(f64::NAN);
2335        assert_eq!(value.to_json_string(), Err(JsonError::NonFiniteNumber));
2336    }
2337
2338    #[test]
2339    fn parses_basic_json_values() {
2340        assert_eq!(parse_json("null").unwrap(), JsonValue::Null);
2341        assert_eq!(parse_json("true").unwrap(), JsonValue::Bool(true));
2342        assert_eq!(
2343            parse_json("\"hello\"").unwrap(),
2344            JsonValue::String("hello".into())
2345        );
2346        assert_eq!(
2347            parse_json("123").unwrap(),
2348            JsonValue::Number(JsonNumber::U64(123))
2349        );
2350        assert_eq!(
2351            parse_json("-123").unwrap(),
2352            JsonValue::Number(JsonNumber::I64(-123))
2353        );
2354    }
2355
2356    #[test]
2357    fn parses_unicode_and_escapes() {
2358        let value = parse_json("\"line\\n\\u03bb\\uD83D\\uDE80\"").unwrap();
2359        assert_eq!(value, JsonValue::String("line\nλ🚀".into()));
2360    }
2361
2362    #[test]
2363    fn borrowed_parse_avoids_allocating_plain_strings() {
2364        let value = parse_json_borrowed("{\"name\":\"hello\",\"n\":1}").unwrap();
2365        match value {
2366            BorrowedJsonValue::Object(entries) => {
2367                assert!(matches!(entries[0].0, Cow::Borrowed(_)));
2368                assert!(matches!(
2369                    entries[0].1,
2370                    BorrowedJsonValue::String(Cow::Borrowed(_))
2371                ));
2372            }
2373            other => panic!("unexpected value: {other:?}"),
2374        }
2375    }
2376
2377    #[test]
2378    fn borrowed_parse_allocates_when_unescaping_is_needed() {
2379        let value = parse_json_borrowed("\"line\\nvalue\"").unwrap();
2380        match value {
2381            BorrowedJsonValue::String(Cow::Owned(text)) => assert_eq!(text, "line\nvalue"),
2382            other => panic!("unexpected value: {other:?}"),
2383        }
2384    }
2385
2386    #[test]
2387    fn compiled_schema_serializes_expected_shape() {
2388        let schema = CompiledObjectSchema::new(&["id", "name", "enabled"]);
2389        let values = [
2390            JsonValue::from(7u64),
2391            JsonValue::from("node-7"),
2392            JsonValue::from(true),
2393        ];
2394        let json = schema.to_json_string(values.iter()).unwrap();
2395        assert_eq!(json, "{\"id\":7,\"name\":\"node-7\",\"enabled\":true}");
2396    }
2397
2398    #[test]
2399    fn compiled_row_schema_serializes_array_of_objects() {
2400        let schema = CompiledRowSchema::new(&["id", "name"]);
2401        let row1 = [JsonValue::from(1u64), JsonValue::from("a")];
2402        let row2 = [JsonValue::from(2u64), JsonValue::from("b")];
2403        let json = schema.to_json_string([row1.iter(), row2.iter()]).unwrap();
2404        assert_eq!(json, r#"[{"id":1,"name":"a"},{"id":2,"name":"b"}]"#);
2405    }
2406
2407    #[test]
2408    fn tape_parse_records_structure_tokens() {
2409        let tape = parse_json_tape(r#"{"a":[1,"x"],"b":true}"#).unwrap();
2410        assert_eq!(tape.tokens[0].kind, TapeTokenKind::Object);
2411        assert_eq!(tape.tokens[1].kind, TapeTokenKind::Key);
2412        assert_eq!(tape.tokens[2].kind, TapeTokenKind::Array);
2413        assert_eq!(tape.tokens[3].kind, TapeTokenKind::Number);
2414        assert_eq!(tape.tokens[4].kind, TapeTokenKind::String);
2415        assert_eq!(tape.tokens[5].kind, TapeTokenKind::Key);
2416        assert_eq!(tape.tokens[6].kind, TapeTokenKind::Bool);
2417    }
2418
2419    #[test]
2420    fn tape_object_lookup_finds_child_values() {
2421        let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2422        let tape = parse_json_tape(input).unwrap();
2423        let root = tape.root(input).unwrap();
2424        let name = root.get("name").unwrap();
2425        assert_eq!(name.kind(), TapeTokenKind::String);
2426        assert_eq!(name.as_str(), Some("hello"));
2427        let nested = root.get("nested").unwrap();
2428        assert_eq!(nested.kind(), TapeTokenKind::Object);
2429        assert!(root.get("missing").is_none());
2430    }
2431
2432    #[test]
2433    fn tape_object_index_lookup_finds_child_values() {
2434        let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2435        let tape = parse_json_tape(input).unwrap();
2436        let root = tape.root(input).unwrap();
2437        let index = root.build_object_index().unwrap();
2438        let flag = index.get(root, "flag").unwrap();
2439        assert_eq!(flag.kind(), TapeTokenKind::Bool);
2440        assert!(index.get(root, "missing").is_none());
2441    }
2442
2443    #[test]
2444    fn indexed_tape_object_compiled_lookup_finds_child_values() {
2445        let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2446        let tape = parse_json_tape(input).unwrap();
2447        let root = tape.root(input).unwrap();
2448        let index = root.build_object_index().unwrap();
2449        let indexed = root.with_index(&index);
2450        let keys = CompiledTapeKeys::new(&["name", "flag", "missing"]);
2451        let got = indexed
2452            .get_compiled_many(&keys)
2453            .map(|value| value.map(|value| value.kind()))
2454            .collect::<Vec<_>>();
2455        assert_eq!(got, vec![Some(TapeTokenKind::String), Some(TapeTokenKind::Bool), None]);
2456    }
2457
2458    #[test]
2459    fn serde_style_convenience_api_works() {
2460        let value = from_str(r#"{"ok":true,"n":7,"items":[1,2,3],"msg":"hello"}"#).unwrap();
2461        assert!(value.is_object());
2462        assert_eq!(value["ok"].as_bool(), Some(true));
2463        assert_eq!(value["n"].as_i64(), Some(7));
2464        assert_eq!(value["msg"].as_str(), Some("hello"));
2465        assert_eq!(value["items"][1].as_u64(), Some(2));
2466        assert!(value["missing"].is_null());
2467        assert_eq!(to_string(&value).unwrap(), r#"{"ok":true,"n":7,"items":[1,2,3],"msg":"hello"}"#);
2468        assert_eq!(from_slice(br#"[1,true,"x"]"#).unwrap()[2].as_str(), Some("x"));
2469        assert_eq!(to_vec(&value).unwrap(), value.to_json_string().unwrap().into_bytes());
2470    }
2471
2472    #[test]
2473    fn json_macro_builds_values() {
2474        let value = json!({"ok": true, "items": [1, 2, null], "msg": "x"});
2475        assert_eq!(value["ok"].as_bool(), Some(true));
2476        assert_eq!(value["items"][0].as_u64(), Some(1));
2477        assert!(value["items"][2].is_null());
2478        assert_eq!(value["msg"].as_str(), Some("x"));
2479    }
2480
2481    #[test]
2482    fn from_slice_rejects_invalid_utf8() {
2483        assert!(matches!(from_slice(&[0xff]), Err(JsonParseError::InvalidUtf8)));
2484    }
2485
2486    #[test]
2487    fn pointer_take_and_pretty_helpers_work() {
2488        let mut value = from_str(r#"{"a":{"b":[10,20,{"~key/":"x"}]}}"#).unwrap();
2489        assert_eq!(value.pointer("/a/b/1").and_then(JsonValue::as_u64), Some(20));
2490        assert_eq!(value.pointer("/a/b/2/~0key~1").and_then(JsonValue::as_str), Some("x"));
2491        *value.pointer_mut("/a/b/0").unwrap() = JsonValue::from(99u64);
2492        assert_eq!(value.pointer("/a/b/0").and_then(JsonValue::as_u64), Some(99));
2493
2494        let taken = value.pointer_mut("/a/b/2").unwrap().take();
2495        assert!(value.pointer("/a/b/2").unwrap().is_null());
2496        assert_eq!(taken["~key/"].as_str(), Some("x"));
2497
2498        let pretty = to_string_pretty(&value).unwrap();
2499        assert!(pretty.contains("\"a\": {"));
2500        let mut out = Vec::new();
2501        to_writer_pretty(&mut out, &value).unwrap();
2502        assert_eq!(String::from_utf8(out).unwrap(), pretty);
2503    }
2504
2505    #[test]
2506    fn reader_writer_and_collection_helpers_work() {
2507        let value = from_reader(std::io::Cursor::new(br#"{"a":1,"b":[true,false]}"# as &[u8])).unwrap();
2508        assert_eq!(value["a"].as_u64(), Some(1));
2509        assert_eq!(value["b"].len(), 2);
2510        assert_eq!(value["b"].get_index(1).and_then(JsonValue::as_bool), Some(false));
2511
2512        let mut out = Vec::new();
2513        to_writer(&mut out, &value).unwrap();
2514        assert_eq!(String::from_utf8(out).unwrap(), value.to_json_string().unwrap());
2515
2516        let object = JsonValue::from_iter([("x", 1u64), ("y", 2u64)]);
2517        assert_eq!(object["x"].as_u64(), Some(1));
2518        let array = JsonValue::from_iter([1u64, 2u64, 3u64]);
2519        assert_eq!(array.get_index(2).and_then(JsonValue::as_u64), Some(3));
2520    }
2521
2522    #[test]
2523    fn signature_and_sort_parity_helpers_work() {
2524        let mut value = json!({"z": {"b": 2, "a": 1}, "a": [{"d": 4, "c": 3}]});
2525        assert_eq!(value.as_object().unwrap().len(), 2);
2526        assert_eq!(value["a"].as_array().unwrap().len(), 1);
2527        value.sort_all_objects();
2528        let root_keys = value.as_object().unwrap().iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>();
2529        assert_eq!(root_keys, vec!["a", "z"]);
2530        let nested_keys = value["z"].as_object().unwrap().iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>();
2531        assert_eq!(nested_keys, vec!["a", "b"]);
2532    }
2533
2534    #[test]
2535    fn generic_get_and_get_mut_index_parity_work() {
2536        let mut value = json!({"obj": {"x": 1}, "arr": [10, 20, 30]});
2537        let key = String::from("obj");
2538        assert_eq!(value.get("obj").and_then(|v| v.get("x")).and_then(JsonValue::as_u64), Some(1));
2539        assert_eq!(value.get(&key).and_then(|v| v.get("x")).and_then(JsonValue::as_u64), Some(1));
2540        assert_eq!(value.get("arr").and_then(|v| v.get(1)).and_then(JsonValue::as_u64), Some(20));
2541        *value.get_mut("arr").unwrap().get_mut(2).unwrap() = JsonValue::from(99u64);
2542        assert_eq!(value["arr"][2].as_u64(), Some(99));
2543    }
2544
2545    #[test]
2546    fn number_and_mut_index_parity_helpers_work() {
2547        let int = JsonValue::from(7i64);
2548        assert!(int.is_i64());
2549        assert!(!int.is_u64());
2550        assert!(!int.is_f64());
2551        assert_eq!(int.as_number().and_then(JsonNumber::as_i64), Some(7));
2552
2553        let float = JsonValue::Number(JsonNumber::from_f64(2.5).unwrap());
2554        assert!(float.is_f64());
2555        assert_eq!(float.as_f64(), Some(2.5));
2556        assert_eq!(JsonValue::Null.as_null(), Some(()));
2557
2558        let mut value = JsonValue::Null;
2559        value["a"]["b"]["c"] = JsonValue::from(true);
2560        assert_eq!(value.pointer("/a/b/c").and_then(JsonValue::as_bool), Some(true));
2561
2562        value["arr"] = json!([1, 2, 3]);
2563        value["arr"][1] = JsonValue::from(9u64);
2564        assert_eq!(value.pointer("/arr/1").and_then(JsonValue::as_u64), Some(9));
2565    }
2566
2567    #[test]
2568    fn rejects_invalid_json_inputs() {
2569        assert!(matches!(
2570            parse_json("{"),
2571            Err(JsonParseError::UnexpectedEnd)
2572        ));
2573        assert!(matches!(
2574            parse_json("{\"a\" 1}"),
2575            Err(JsonParseError::ExpectedColon { .. })
2576        ));
2577        assert!(matches!(
2578            parse_json("[1 2]"),
2579            Err(JsonParseError::ExpectedCommaOrEnd {
2580                context: "array",
2581                ..
2582            })
2583        ));
2584        assert!(matches!(
2585            parse_json("{\"a\":1 trailing"),
2586            Err(JsonParseError::ExpectedCommaOrEnd {
2587                context: "object",
2588                ..
2589            })
2590        ));
2591        assert!(matches!(
2592            parse_json("00"),
2593            Err(JsonParseError::InvalidNumber { .. })
2594        ));
2595    }
2596
2597    #[test]
2598    fn roundtrips_specific_structures() {
2599        let values = [
2600            JsonValue::Null,
2601            JsonValue::Bool(false),
2602            JsonValue::String("tab\tquote\"slash\\snowman☃".into()),
2603            JsonValue::Number(JsonNumber::I64(-9_223_372_036_854_775_808)),
2604            JsonValue::Number(JsonNumber::U64(u64::MAX)),
2605            JsonValue::Number(JsonNumber::F64(12345.125)),
2606            JsonValue::Array(vec![
2607                JsonValue::Bool(true),
2608                JsonValue::String("nested".into()),
2609                JsonValue::Object(vec![("x".into(), 1u64.into())]),
2610            ]),
2611        ];
2612        for value in values {
2613            let text = value.to_json_string().unwrap();
2614            let reparsed = parse_json(&text).unwrap();
2615            assert_json_equivalent(&value, &reparsed);
2616        }
2617    }
2618
2619    #[test]
2620    fn deterministic_fuzz_roundtrip_strings_and_values() {
2621        let mut rng = Rng::new(0x5eed_1234_5678_9abc);
2622        for _ in 0..2_000 {
2623            let input = random_string(&mut rng, 48);
2624            let escaped = escape_json_string(&input);
2625            let parsed = parse_json(&escaped).unwrap();
2626            assert_eq!(parsed, JsonValue::String(input));
2627        }
2628
2629        for _ in 0..1_000 {
2630            let value = random_json_value(&mut rng, 0, 4);
2631            let text = value.to_json_string().unwrap();
2632            let reparsed = parse_json(&text).unwrap();
2633            assert_json_equivalent(&value, &reparsed);
2634        }
2635    }
2636
2637    fn assert_json_equivalent(expected: &JsonValue, actual: &JsonValue) {
2638        match (expected, actual) {
2639            (JsonValue::Null, JsonValue::Null) => {}
2640            (JsonValue::Bool(a), JsonValue::Bool(b)) => assert_eq!(a, b),
2641            (JsonValue::String(a), JsonValue::String(b)) => assert_eq!(a, b),
2642            (JsonValue::Number(a), JsonValue::Number(b)) => assert_numbers_equivalent(a, b),
2643            (JsonValue::Array(a), JsonValue::Array(b)) => {
2644                assert_eq!(a.len(), b.len());
2645                for (left, right) in a.iter().zip(b.iter()) {
2646                    assert_json_equivalent(left, right);
2647                }
2648            }
2649            (JsonValue::Object(a), JsonValue::Object(b)) => {
2650                assert_eq!(a.len(), b.len());
2651                for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
2652                    assert_eq!(left_key, right_key);
2653                    assert_json_equivalent(left_value, right_value);
2654                }
2655            }
2656            _ => panic!("json values differ: expected {expected:?}, actual {actual:?}"),
2657        }
2658    }
2659
2660    fn assert_numbers_equivalent(expected: &JsonNumber, actual: &JsonNumber) {
2661        match (expected, actual) {
2662            (JsonNumber::I64(a), JsonNumber::I64(b)) => assert_eq!(a, b),
2663            (JsonNumber::U64(a), JsonNumber::U64(b)) => assert_eq!(a, b),
2664            (JsonNumber::F64(a), JsonNumber::F64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
2665            (JsonNumber::I64(a), JsonNumber::U64(b)) if *a >= 0 => assert_eq!(*a as u64, *b),
2666            (JsonNumber::U64(a), JsonNumber::I64(b)) if *b >= 0 => assert_eq!(*a, *b as u64),
2667            (JsonNumber::I64(a), JsonNumber::F64(b)) => assert_eq!(*a as f64, *b),
2668            (JsonNumber::U64(a), JsonNumber::F64(b)) => assert_eq!(*a as f64, *b),
2669            (JsonNumber::F64(a), JsonNumber::I64(b)) => assert_eq!(*a, *b as f64),
2670            (JsonNumber::F64(a), JsonNumber::U64(b)) => assert_eq!(*a, *b as f64),
2671            (left, right) => panic!("json numbers differ: expected {left:?}, actual {right:?}"),
2672        }
2673    }
2674
2675    #[derive(Clone, Debug)]
2676    struct Rng {
2677        state: u64,
2678    }
2679
2680    impl Rng {
2681        fn new(seed: u64) -> Self {
2682            Self { state: seed }
2683        }
2684
2685        fn next_u64(&mut self) -> u64 {
2686            self.state = self
2687                .state
2688                .wrapping_mul(6364136223846793005)
2689                .wrapping_add(1442695040888963407);
2690            self.state
2691        }
2692
2693        fn choose(&mut self, upper_exclusive: usize) -> usize {
2694            (self.next_u64() % upper_exclusive as u64) as usize
2695        }
2696
2697        fn bool(&mut self) -> bool {
2698            (self.next_u64() & 1) == 1
2699        }
2700    }
2701
2702    fn random_string(rng: &mut Rng, max_len: usize) -> String {
2703        let len = rng.choose(max_len + 1);
2704        let mut out = String::new();
2705        for _ in 0..len {
2706            let ch = match rng.choose(12) {
2707                0 => '"',
2708                1 => '\\',
2709                2 => '\n',
2710                3 => '\r',
2711                4 => '\t',
2712                5 => '\u{0007}',
2713                6 => 'λ',
2714                7 => '🚀',
2715                8 => '☃',
2716                _ => (b'a' + rng.choose(26) as u8) as char,
2717            };
2718            out.push(ch);
2719        }
2720        out
2721    }
2722
2723    fn random_json_value(rng: &mut Rng, depth: usize, max_depth: usize) -> JsonValue {
2724        if depth >= max_depth {
2725            return random_leaf(rng);
2726        }
2727        match rng.choose(7) {
2728            0 | 1 | 2 | 3 => random_leaf(rng),
2729            4 => {
2730                let len = rng.choose(5);
2731                let mut values = Vec::with_capacity(len);
2732                for _ in 0..len {
2733                    values.push(random_json_value(rng, depth + 1, max_depth));
2734                }
2735                JsonValue::Array(values)
2736            }
2737            _ => {
2738                let len = rng.choose(5);
2739                let mut entries = Vec::with_capacity(len);
2740                for index in 0..len {
2741                    entries.push((
2742                        format!("k{depth}_{index}_{}", random_string(rng, 6)),
2743                        random_json_value(rng, depth + 1, max_depth),
2744                    ));
2745                }
2746                JsonValue::Object(entries)
2747            }
2748        }
2749    }
2750
2751    fn random_leaf(rng: &mut Rng) -> JsonValue {
2752        match rng.choose(6) {
2753            0 => JsonValue::Null,
2754            1 => JsonValue::Bool(rng.bool()),
2755            2 => JsonValue::String(random_string(rng, 24)),
2756            3 => JsonValue::Number(JsonNumber::I64(
2757                (rng.next_u64() >> 1) as i64 * if rng.bool() { 1 } else { -1 },
2758            )),
2759            4 => JsonValue::Number(JsonNumber::U64(rng.next_u64())),
2760            _ => {
2761                let mantissa = (rng.next_u64() % 1_000_000) as f64 / 1000.0;
2762                let sign = if rng.bool() { 1.0 } else { -1.0 };
2763                JsonValue::Number(JsonNumber::F64(sign * mantissa))
2764            }
2765        }
2766    }
2767}