grippo 0.1.3

Parse, match and scrub data at scale.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
// Project:   grippo
// File:      src/record/json.rs
// Purpose:   Raw JSON bytes as a record, read lazily with no value tree
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A JSON object's bytes as a [`Record`]. On x86-64 and aarch64 each read is
//! a sonic-rs lookup on the bytes, with UTF-8 checked only up to the value
//! read. sonic-rs builds nowhere else, so there each object on a path is read
//! with `serde_json`, and a fault anywhere in that object is `Malformed`.
//! A walk reads the whole record in two passes of its own on every target:
//! one checks it and finds where each container ends, one visits.

use std::borrow::Cow;
use std::ops::Range;

use super::{Kind, Miss, Node, Record, Typed, Walk, number};
#[cfg(feature = "expr")]
use crate::json::{Path as JsonPath, Paths, Slot, Slots};
#[cfg(feature = "expr")]
use crate::path::unescape;

/// Raw JSON bytes, read as a record. A record with duplicate keys is outside
/// what's defined.
#[derive(Debug, Clone, Copy)]
pub struct Json<'a> {
    bytes: &'a [u8],
}

impl<'a> Json<'a> {
    /// [`Record::find`] with no root key ruled out unread.
    fn find_unfiltered<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
        let Some((first, rest)) = path.split_first() else {
            return Err(Miss::MissingRoot);
        };
        if let Some(raw) = backend::lookup(self.bytes, path) {
            return Ok(raw);
        }
        walk(root(self.bytes, first.as_ref())?, rest)
    }

    /// The record in `bytes`.
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

impl<'a> Record<'a> for Json<'a> {
    /// The value's JSON text.
    type At = &'a str;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
        let Some(first) = path.first() else {
            return Err(Miss::MissingRoot);
        };
        let key = first.as_ref().as_bytes();
        if plain(key)
            && root_absent(
                self.bytes,
                key,
                memchr::memmem::find_iter(self.bytes, key),
                &mut None,
            )
        {
            return Err(Miss::MissingRoot);
        }
        self.find_unfiltered(path)
    }

    fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
        below(at, path)
    }

    fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
        typed(at)
    }

    fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
        text(at)
    }

    #[allow(clippy::type_complexity, reason = "the trait's signature")]
    fn raw_json(self) -> Option<(&'a [u8], fn(&'a str) -> &'a str)> {
        Some((self.bytes, |at| at))
    }
}

impl<'a> Walk<'a> for Json<'a> {
    fn walk<F: FnMut(Node<'a, &'a str>)>(self, mut visit: F) -> Result<(), Miss> {
        let text = std::str::from_utf8(self.bytes).map_err(|_| Miss::Malformed)?;
        let object = text.as_bytes().get(space(text.as_bytes(), 0)) == Some(&b'{');
        values(text, |level, key, kind, at| {
            // An object root is the record itself, so its members are at depth 0.
            let depth = if object {
                level.checked_sub(1)
            } else {
                Some(level)
            };
            if let Some(depth) = depth {
                visit(Node {
                    depth,
                    key,
                    kind,
                    at,
                });
            }
        })
    }
}

impl<'a> Json<'a> {
    /// Writes the record to `out` with each value in `strings` replaced by a
    /// JSON string of the bytes given for it, invalid UTF-8 as U+FFFD.
    ///
    /// Each value is an `At` from this record, in document order, none
    /// inside another, as [`Walk::walk`] gives them.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when an `At` isn't from this record or comes
    /// before the end of the last one, with `out` left as it was.
    pub fn splice_strings<B: AsRef<[u8]>>(
        self,
        strings: &[(&'a str, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let mark = out.len();
        let mut copied = 0;
        for (at, value) in strings {
            let Some(span) = span_in(self.bytes, at).filter(|s| s.start >= copied) else {
                out.truncate(mark);
                return Err(Miss::Malformed);
            };
            out.extend_from_slice(&self.bytes[copied..span.start]);
            push_string(out, value.as_ref());
            copied = span.end;
        }
        out.extend_from_slice(&self.bytes[copied..]);
        Ok(())
    }
}

#[cfg(feature = "expr")]
impl<'a> Json<'a> {
    /// Reads every path of `read` in one pass, giving `out` each path's
    /// position and what [`Record::find`] gives for it on well-formed JSON.
    ///
    /// A value is `Malformed` when the record isn't UTF-8 up to its end, and
    /// a path that found nothing when the record isn't UTF-8 at all. A root
    /// key [`Record::find`] rules out with no read is `MissingRoot`. A lone
    /// one-key path to a scalar is read as [`root_scalar`] reads it.
    pub(crate) fn find_all(
        self,
        read: &ReadPlan,
        scratch: &mut Slots,
        mut out: impl FnMut(usize, Result<&'a str, Miss>),
    ) {
        let n = read.keys.len();
        if let Some(path) = &read.single {
            let got = match read.roots.first() {
                Some(root) if root.plain => {
                    let hit = root.quoted.find(self.bytes);
                    if hit.is_none() && !has_unicode_escape(self.bytes, &mut None) {
                        Err(Miss::MissingRoot)
                    } else if path.len() == 1 {
                        root_scalar(self.bytes, &root.quoted, hit)
                            .unwrap_or_else(|| self.find_unfiltered(path))
                    } else {
                        self.find_unfiltered(path)
                    }
                }
                _ => self.find_unfiltered(path),
            };
            out(0, got);
            return;
        }
        if !is_object_record(self.bytes) {
            (0..n).for_each(|i| out(i, Err(Miss::MissingRoot)));
            return;
        }
        let mut escape = None;
        let mut absent: u128 = 0;
        for (r, root) in read.roots.iter().enumerate().take(128) {
            if root.absent(self.bytes, &mut escape) {
                absent |= 1 << r;
            }
        }
        let is_absent = |i: usize| read.root_of[i] < 128 && absent >> read.root_of[i] & 1 == 1;
        if (0..n).all(is_absent) {
            (0..n).for_each(|i| out(i, Err(Miss::MissingRoot)));
            return;
        }
        let values = read.paths.read(self.bytes, scratch);
        let mut limit = 0;
        for (i, slot) in values.iter().enumerate() {
            if !is_absent(i) {
                limit = limit.max(slot.found().map_or(self.bytes.len(), |raw| raw.span().end));
            }
        }
        let head = &self.bytes[..limit];
        let valid = if head.is_ascii() {
            limit
        } else {
            std::str::from_utf8(head).map_or_else(|e| e.valid_up_to(), str::len)
        };
        for (i, (slot, &keys)) in values.iter().zip(&read.keys).enumerate() {
            let read_to = slot.found().map_or(self.bytes.len(), |raw| raw.span().end);
            out(
                i,
                if is_absent(i) {
                    Err(Miss::MissingRoot)
                } else if read_to > valid {
                    Err(Miss::Malformed)
                } else {
                    from_slot(slot, keys)
                },
            );
        }
    }
}

/// A compiled set of paths for [`Json::find_all`], with each root key's
/// prefilter.
#[cfg(feature = "expr")]
#[derive(Debug)]
pub struct ReadPlan {
    paths: Paths,
    /// Each path's key count.
    keys: Box<[usize]>,
    /// Each path's root key, by position in `roots`.
    root_of: Box<[usize]>,
    roots: Box<[RootKey]>,
    /// The one path, when there's only one: a single lookup beats the walk.
    single: Option<Box<[String]>>,
}

#[cfg(feature = "expr")]
impl ReadPlan {
    /// The plan for `paths`, each a list of keys, in order.
    pub fn new(paths: &[&[String]]) -> Self {
        let mut names: Vec<&str> = Vec::new();
        let mut root_of = Vec::with_capacity(paths.len());
        let mut compiled = Vec::with_capacity(paths.len());
        for keys in paths {
            let first = keys.first().map_or("", String::as_str);
            let at = names.iter().position(|n| *n == first).unwrap_or_else(|| {
                names.push(first);
                names.len() - 1
            });
            root_of.push(at);
            compiled.extend(JsonPath::from_keys(keys.iter().cloned()).ok());
        }
        Self {
            paths: Paths::new(compiled),
            keys: paths.iter().map(|k| k.len()).collect(),
            root_of: root_of.into_boxed_slice(),
            roots: names.into_iter().map(RootKey::new).collect(),
            single: match paths {
                [one] => Some(one.to_vec().into_boxed_slice()),
                _ => None,
            },
        }
    }
}

/// Whether a key may be ruled out by its spelling: it isn't empty and holds
/// no `"`, `\`, `/` or control character, the bytes an escape other than
/// `\u` can spell.
fn plain(key: &[u8]) -> bool {
    !key.is_empty()
        && !key
            .iter()
            .any(|&b| b < 0x20 || matches!(b, b'"' | b'\\' | b'/'))
}

/// Whether the root key `key`, found in `json` at `hits`, is surely not in
/// it: no hit sits between quotes and `json` holds no `\u` escape, cached in
/// `escape`.
fn root_absent(
    json: &[u8],
    key: &[u8],
    mut hits: impl Iterator<Item = usize>,
    escape: &mut Option<bool>,
) -> bool {
    let quoted =
        hits.any(|at| at > 0 && json[at - 1] == b'"' && json.get(at + key.len()) == Some(&b'"'));
    !quoted && !has_unicode_escape(json, escape)
}

/// Whether `json` holds a `\u` escape, found once and kept in `escape`.
fn has_unicode_escape(json: &[u8], escape: &mut Option<bool>) -> bool {
    !*escape.get_or_insert_with(|| {
        !memchr::memchr_iter(b'\\', json).any(|at| json.get(at + 1) == Some(&b'u'))
    })
}

/// A root key with a finder for its quoted spelling built once.
#[cfg(feature = "expr")]
#[derive(Debug)]
struct RootKey {
    quoted: memchr::memmem::Finder<'static>,
    plain: bool,
}

#[cfg(feature = "expr")]
impl RootKey {
    fn new(key: &str) -> Self {
        let quoted = format!("\"{key}\"");
        Self {
            quoted: memchr::memmem::Finder::new(quoted.as_bytes()).into_owned(),
            plain: plain(key.as_bytes()),
        }
    }

    /// As [`root_absent`], for this key.
    fn absent(&self, json: &[u8], escape: &mut Option<bool>) -> bool {
        self.plain && self.quoted.find(json).is_none() && !has_unicode_escape(json, escape)
    }
}

/// What [`Record::find`] gives for a path of `keys` keys, from its slot in a
/// [`Paths`] read of an object record.
#[cfg(feature = "expr")]
fn from_slot(slot: Slot<'_>, keys: usize) -> Result<&str, Miss> {
    let missing = |step: usize| {
        if step == 0 {
            Miss::MissingRoot
        } else {
            Miss::MissingField
        }
    };
    match slot {
        Slot::Found(raw) => Ok(raw.text()),
        Slot::MissingKey => Err(missing(keys.saturating_sub(1))),
        Slot::MissingParent(step) => Err(missing(step)),
        Slot::WrongParentType(0) => Err(Miss::MissingRoot),
        Slot::WrongParentType(_) => Err(Miss::WrongParentType),
        Slot::Malformed => Err(Miss::Malformed),
    }
}

/// How far into a record [`root_scalar`] scans: past it, sonic-rs's SIMD
/// skip costs less than the scan's byte loop.
#[cfg(feature = "expr")]
const ROOT_SCAN_BYTES: usize = 256;

/// The value of the first root member whose quoted name `quoted` finds, when
/// every member before it holds a scalar. `hit` is where `quoted` first
/// matches. Each member's punctuation is checked, a string passed over is
/// read by its quotes only, and the value found is checked in full with the
/// record's UTF-8 up to its end. `None` where the scan can't answer: a
/// container, an escaped name or a fault.
#[cfg(feature = "expr")]
fn root_scalar<'a>(
    json: &'a [u8],
    quoted_name: &memchr::memmem::Finder<'_>,
    mut hit: Option<usize>,
) -> Option<Result<&'a str, Miss>> {
    if hit.is_some_and(|h| h > ROOT_SCAN_BYTES) {
        return None;
    }
    let mut at = space(json, 0);
    if json.get(at) != Some(&b'{') {
        return None;
    }
    at = space(json, at + 1);
    if json.get(at) == Some(&b'}') {
        return Some(Err(Miss::MissingRoot));
    }
    loop {
        if at > ROOT_SCAN_BYTES || json.get(at) != Some(&b'"') {
            return None;
        }
        if hit.is_some_and(|h| h < at) {
            hit = quoted_name.find(&json[at..]).map(|i| at + i);
        }
        // A plain name's quoted spelling at the member's own quote is that name.
        let wanted = hit == Some(at);
        let close = if wanted {
            at + quoted_name.needle().len() - 1
        } else {
            let name = quoted(json, at + 1)?;
            if name.escaped {
                return None;
            }
            name.close
        };
        at = space(json, close + 1);
        if json.get(at) != Some(&b':') {
            return None;
        }
        let start = space(json, at + 1);
        let (end, plain_string) = scalar_end(json, start)?;
        if wanted {
            let head = std::str::from_utf8(&json[..end]).ok()?;
            let raw = &head[start..];
            let sound = plain_string
                || json[start] != b'"'
                || unescape(&json[start + 1..end - 1], |_| {}).is_ok();
            return sound.then_some(Ok(raw));
        }
        at = space(json, end);
        match json.get(at) {
            Some(b',') => at = space(json, at + 1),
            Some(b'}') => return Some(Err(Miss::MissingRoot)),
            _ => return None,
        }
    }
}

/// A JSON string read from just past its opening quote.
#[cfg(feature = "expr")]
struct Quoted {
    /// The closing quote's offset.
    close: usize,
    /// It holds a backslash.
    escaped: bool,
    /// It may hold a raw control character.
    control: bool,
}

/// The bytes of a string read one at a time before a memchr search takes over.
#[cfg(feature = "expr")]
const SHORT_STRING: usize = 32;

/// The string opening just before `from`, read to its closing quote.
#[cfg(feature = "expr")]
fn quoted(json: &[u8], from: usize) -> Option<Quoted> {
    let mut read = Quoted {
        close: from,
        escaped: false,
        control: false,
    };
    while read.close < from + SHORT_STRING {
        match *json.get(read.close)? {
            b'"' => return Some(read),
            b'\\' => {
                read.escaped = true;
                read.close += 2;
            }
            b => {
                read.control |= b < 0x20;
                read.close += 1;
            }
        }
    }
    let (close, escaped) = crate::path::string_end(json, read.close).ok()?;
    Some(Quoted {
        close,
        escaped: read.escaped || escaped,
        control: true,
    })
}

/// The end of the scalar starting at `at`, and whether it's a string with no
/// escape or control character. `None` for a container, a fault, or a number
/// or literal followed by a byte that can't end it.
#[cfg(feature = "expr")]
fn scalar_end(json: &[u8], at: usize) -> Option<(usize, bool)> {
    let end = match *json.get(at)? {
        b'"' => {
            let s = quoted(json, at + 1)?;
            return Some((s.close + 1, !s.escaped && !s.control));
        }
        b'-' | b'0'..=b'9' => number_end(json, at).ok()?,
        b't' if json[at..].starts_with(b"true") => at + 4,
        b'f' if json[at..].starts_with(b"false") => at + 5,
        b'n' if json[at..].starts_with(b"null") => at + 4,
        _ => return None,
    };
    match json.get(end) {
        None | Some(b',' | b'}' | b' ' | b'\t' | b'\n' | b'\r') => Some((end, false)),
        Some(_) => None,
    }
}

/// Whether the record's first byte past whitespace opens an object.
fn is_object_record(json: &[u8]) -> bool {
    json.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{')
}

/// Where `at` sits in `bytes`, `None` when it isn't inside them.
pub(super) fn span_in(bytes: &[u8], at: &str) -> Option<Range<usize>> {
    let start = at.as_ptr().addr().checked_sub(bytes.as_ptr().addr())?;
    let end = start.checked_add(at.len())?;
    (end <= bytes.len()).then_some(start..end)
}

/// Appends `value` as a JSON string, invalid UTF-8 as U+FFFD.
pub(super) fn push_string(out: &mut Vec<u8>, value: &[u8]) {
    // Writing to a Vec can't fail.
    let _ = serde_json::to_writer(&mut *out, &*String::from_utf8_lossy(value));
}

/// JSON whitespace from `at` on, skipped.
fn space(bytes: &[u8], mut at: usize) -> usize {
    while matches!(bytes.get(at), Some(b' ' | b'\t' | b'\n' | b'\r')) {
        at += 1;
    }
    at
}

/// Calls `visit` with each value in the JSON text `text`: its nesting level,
/// 0 for the root, its key in an object, its kind and its raw text, in
/// document order. The whole text is checked before the first call.
pub(super) fn values<'a>(
    text: &'a str,
    mut visit: impl FnMut(usize, Option<Cow<'a, str>>, Kind, &'a str),
) -> Result<(), Miss> {
    let mut ends = Vec::new();
    scan(text, &mut ends, false, &mut visit)?;
    scan(text, &mut ends, true, &mut visit)
}

/// One pass over `text`. The first, with `emit` off, checks the grammar and
/// records where each container ends, in the order they open. The second
/// calls `visit`, a container's raw text known when it opens.
fn scan<'a, F: FnMut(usize, Option<Cow<'a, str>>, Kind, &'a str)>(
    text: &'a str,
    ends: &mut Vec<usize>,
    emit: bool,
    visit: &mut F,
) -> Result<(), Miss> {
    let b = text.as_bytes();
    // Each open container: whether it is an object, and its slot in `ends`.
    let mut open: Vec<(bool, usize)> = Vec::new();
    let mut opened = 0;
    let mut key: Option<Cow<'a, str>> = None;
    let mut at = space(b, 0);
    loop {
        let start = at;
        let kind = match b.get(at) {
            Some(b'{') => Kind::Map,
            Some(b'[') => Kind::List,
            Some(b'"') => Kind::Str,
            Some(b't' | b'f') => Kind::Bool,
            Some(b'n') => Kind::Null,
            Some(b'-' | b'0'..=b'9') => Kind::Number,
            _ => return Err(Miss::Malformed),
        };
        if let Kind::Map | Kind::List = kind {
            let slot = opened;
            opened += 1;
            if emit {
                let end = *ends.get(slot).ok_or(Miss::Malformed)?;
                visit(
                    open.len(),
                    key.take(),
                    kind,
                    text.get(start..end).ok_or(Miss::Malformed)?,
                );
            } else {
                ends.push(0);
            }
            let object = kind == Kind::Map;
            open.push((object, slot));
            at = space(b, at + 1);
            let close = if object { b'}' } else { b']' };
            if b.get(at) != Some(&close) {
                if object {
                    key = Some(member_key(text, &mut at, emit)?);
                }
                continue;
            }
        } else {
            let end = match kind {
                Kind::Str => string_end(b, at)?,
                Kind::Number => number_end(b, at)?,
                _ => {
                    let word: &[u8] = match b[at] {
                        b't' => b"true",
                        b'f' => b"false",
                        _ => b"null",
                    };
                    if !b[at..].starts_with(word) {
                        return Err(Miss::Malformed);
                    }
                    at + word.len()
                }
            };
            let raw = &text[start..end];
            if emit {
                visit(open.len(), key.take(), kind, raw);
            } else if kind == Kind::Str && memchr::memchr(b'\\', raw.as_bytes()).is_some() {
                string(raw)?;
            }
            at = space(b, end);
        }
        // After a value: a comma before the next, or the closes that follow.
        loop {
            let Some(&(object, slot)) = open.last() else {
                return if at == b.len() {
                    Ok(())
                } else {
                    Err(Miss::Malformed)
                };
            };
            match b.get(at) {
                Some(b',') => {
                    at = space(b, at + 1);
                    if object {
                        key = Some(member_key(text, &mut at, emit)?);
                    }
                    break;
                }
                Some(b'}') if object => {}
                Some(b']') if !object => {}
                _ => return Err(Miss::Malformed),
            }
            if !emit {
                ends[slot] = at + 1;
            }
            open.pop();
            at = space(b, at + 1);
        }
    }
}

/// The member key at `at`, decoded when `emit` is on and checked either way,
/// with `at` moved past its colon.
fn member_key<'a>(text: &'a str, at: &mut usize, emit: bool) -> Result<Cow<'a, str>, Miss> {
    let b = text.as_bytes();
    if b.get(*at) != Some(&b'"') {
        return Err(Miss::Malformed);
    }
    let end = string_end(b, *at)?;
    let raw = &text[*at..end];
    let key = if emit || memchr::memchr(b'\\', raw.as_bytes()).is_some() {
        string(raw)?
    } else {
        Cow::Borrowed("")
    };
    *at = space(b, end);
    if b.get(*at) != Some(&b':') {
        return Err(Miss::Malformed);
    }
    *at = space(b, *at + 1);
    Ok(key)
}

/// The end of the JSON string opening at `at`, its escapes checked.
fn string_end(b: &[u8], at: usize) -> Result<usize, Miss> {
    let mut i = at + 1;
    loop {
        match b.get(i) {
            Some(b'"') => return Ok(i + 1),
            Some(b'\\') => {
                i += match b.get(i + 1) {
                    Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => 2,
                    Some(b'u')
                        if b.get(i + 2..i + 6)
                            .is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit)) =>
                    {
                        6
                    }
                    _ => return Err(Miss::Malformed),
                };
            }
            Some(0x00..=0x1f) | None => return Err(Miss::Malformed),
            Some(_) => i += 1,
        }
    }
}

/// The end of the JSON number starting at `at`, held to JSON's grammar.
fn number_end(b: &[u8], at: usize) -> Result<usize, Miss> {
    let digits = |mut i: usize| {
        while b.get(i).is_some_and(u8::is_ascii_digit) {
            i += 1;
        }
        i
    };
    let mut i = at + usize::from(b.get(at) == Some(&b'-'));
    i = match b.get(i) {
        Some(b'0') => i + 1,
        Some(b'1'..=b'9') => digits(i + 1),
        _ => return Err(Miss::Malformed),
    };
    if b.get(i) == Some(&b'.') {
        let after = digits(i + 1);
        if after == i + 1 {
            return Err(Miss::Malformed);
        }
        i = after;
    }
    if matches!(b.get(i), Some(b'e' | b'E')) {
        i += 1 + usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
        let after = digits(i);
        if after == i {
            return Err(Miss::Malformed);
        }
        i = after;
    }
    Ok(i)
}

/// Whether raw JSON text is an object.
fn is_object(raw: &str) -> bool {
    raw.as_bytes().first() == Some(&b'{')
}

/// The raw text of the root field `key` in the record `json`. A record that
/// isn't a JSON object has no root fields.
fn root<'a>(json: &'a [u8], key: &str) -> Result<&'a str, Miss> {
    if !is_object_record(json) {
        return Err(Miss::MissingRoot);
    }
    backend::root(json, key)?.ok_or(Miss::MissingRoot)
}

/// The raw text at `path` below the JSON value `obj`, one lookup when it's
/// there.
pub(super) fn below<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    if path.is_empty() {
        return Ok(obj);
    }
    if !is_object(obj) {
        return Err(Miss::WrongParentType);
    }
    if let Some(raw) = backend::lookup_str(obj, path) {
        return Ok(raw);
    }
    walk(obj, path)
}

/// Each key of `path` read in turn from `at`, naming the first miss.
fn walk<'a, K: AsRef<str>>(mut at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    for key in path {
        if !is_object(at) {
            return Err(Miss::WrongParentType);
        }
        at = backend::member(at, key.as_ref())?.ok_or(Miss::MissingField)?;
    }
    Ok(at)
}

/// Types the raw JSON text of a value.
pub(super) fn typed(raw: &str) -> Result<Typed<'_>, Miss> {
    match raw.as_bytes().first() {
        Some(b'"') => string(raw).map(Typed::Str),
        Some(b't') => Ok(Typed::Bool(true)),
        Some(b'f') => Ok(Typed::Bool(false)),
        Some(b'n') => Ok(Typed::Null),
        Some(b'[') => Ok(Typed::List),
        Some(b'{') => Ok(Typed::Map),
        Some(b'-' | b'0'..=b'9') => number(raw),
        _ => Err(Miss::Malformed),
    }
}

/// The raw JSON text of a value as text: a string decoded, anything else as
/// written.
pub(super) fn text(raw: &str) -> Result<Cow<'_, str>, Miss> {
    if raw.as_bytes().first() == Some(&b'"') {
        string(raw)
    } else {
        Ok(Cow::Borrowed(raw))
    }
}

/// A JSON string's text decoded, borrowed when it holds no escape.
fn string(raw: &str) -> Result<Cow<'_, str>, Miss> {
    let inner = raw
        .get(1..raw.len().saturating_sub(1))
        .ok_or(Miss::Malformed)?;
    // A field value is short, where core's search beats memchr's dispatch.
    if inner.as_bytes().contains(&b'\\') {
        backend::decode(raw).map(Cow::Owned)
    } else {
        Ok(Cow::Borrowed(inner))
    }
}

/// A JSON object's keys, decoded, in document order where sonic-rs builds
/// and in key order elsewhere.
#[cfg(feature = "expr")]
pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
    backend::object_keys(obj)
}

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use simd as backend;

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
use portable as backend;

/// The reads on sonic-rs, which builds only for x86-64 and aarch64.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
mod simd {
    use std::borrow::Cow;

    use super::Miss;

    /// The raw text at `path` in `json`, when one lookup finds it in place.
    pub(super) fn lookup<'a, K: AsRef<str>>(json: &'a [u8], path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_slice(json, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// As [`lookup`] on text, with no UTF-8 check.
    pub(super) fn lookup_str<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_str(obj, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// The value's raw text, when sonic-rs could hand it back in place.
    fn borrowed<'a>(v: &sonic_rs::LazyValue<'a>) -> Option<&'a str> {
        match v.as_raw_cow() {
            Cow::Borrowed(raw) => Some(raw),
            Cow::Owned(_) => None,
        }
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_slice(json, [key]))
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_str(obj, [key]))
    }

    fn found(got: sonic_rs::Result<sonic_rs::LazyValue<'_>>) -> Result<Option<&str>, Miss> {
        match got {
            Ok(v) => match v.as_raw_cow() {
                Cow::Borrowed(raw) => Ok(Some(raw)),
                Cow::Owned(_) => Err(Miss::Malformed),
            },
            Err(e) if e.is_not_found() => Ok(None),
            Err(_) => Err(Miss::Malformed),
        }
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        sonic_rs::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        sonic_rs::to_object_iter(obj)
            .map(|pair| {
                pair.map(|(key, _)| key.into_owned())
                    .map_err(|_| Miss::Malformed)
            })
            .collect()
    }
}

/// The reads on `serde_json`, for every target sonic-rs doesn't build on.
#[cfg(any(test, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
mod portable {
    use std::borrow::Cow;
    use std::collections::BTreeMap;

    use serde_json::value::RawValue;

    use super::Miss;

    /// Members by key, each value's raw text borrowed.
    type Members<'a> = BTreeMap<Cow<'a, str>, &'a RawValue>;

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup<'a, K: AsRef<str>>(_json: &'a [u8], _path: &[K]) -> Option<&'a str> {
        None
    }

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup_str<'a, K: AsRef<str>>(
        _obj: &'a str,
        _path: &[K],
    ) -> Option<&'a str> {
        None
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        member(std::str::from_utf8(json).map_err(|_| Miss::Malformed)?, key)
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        let members: Members<'a> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.get(key).map(|v| v.get()))
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        serde_json::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        let members: Members<'_> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.into_keys().map(Cow::into_owned).collect())
    }
}

#[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))]
mod tests {
    use super::{Miss, portable, simd};

    /// The `serde_json` reads give what the sonic-rs reads give, misses included.
    #[test]
    fn the_portable_reads_agree_with_sonic() {
        let objects = [
            r#"{"a":1,"b":{"c":"x"},"d":[1,2],"e":null}"#,
            r#" { "a" : "q\"r" , "b" : true } "#,
            "{}",
            r#"{"a":}"#,
            r#"{"a":1"#,
            "[1]",
        ];
        for obj in objects {
            for key in ["a", "b", "d", "e", "z"] {
                let want = simd::member(obj, key);
                let got = portable::member(obj, key);
                let malformed = Err(Miss::Malformed);
                // sonic-rs reads lazily, so a fault past the key it found is never seen.
                assert!(
                    got == want || got == malformed,
                    "{obj} {key}: {got:?} {want:?}"
                );
                if obj.starts_with('{') {
                    let root = (
                        simd::root(obj.as_bytes(), key),
                        portable::root(obj.as_bytes(), key),
                    );
                    assert!(
                        root.1 == root.0 || root.1 == malformed,
                        "{obj} {key}: {root:?}"
                    );
                }
            }
            if simd::object_keys(obj).is_ok() {
                let mut want = simd::object_keys(obj);
                if let Ok(keys) = want.as_mut() {
                    keys.sort();
                }
                assert_eq!(portable::object_keys(obj), want, "{obj}");
            }
        }
        for raw in [r#""a\nb""#, r#""\u00e9""#, r#""\q""#] {
            assert_eq!(portable::decode(raw), simd::decode(raw), "{raw}");
        }
        assert_eq!(portable::lookup(b"{}", &["a"]), None);
        assert_eq!(portable::lookup_str("{}", &["a"]), None);
    }
}