Skip to main content

lifegraph_json/
lib.rs

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