grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
// Project:   grippo
// File:      src/json/paths.rs
// Purpose:   Many JSON field paths read from a raw record in one pass, with no value tree
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Many field paths read from a raw JSON record in one pass.
//!
//! [`Paths`] compiles a set of [`Path`]s into a tree of wanted keys. A read
//! walks the record once: each object on a wanted path has its keys looked
//! up in that tree, every other value is skipped by its brackets and quotes,
//! and the walk stops once every wanted key has been seen. Each path gets a
//! [`Slot`]: the value's exact text and its [`Kind`], or why there's none.
//!
//! ```
//! use grippo::json::{Kind, Path, Paths, Slot, Slots};
//!
//! let paths = Paths::new([
//!     Path::parse("event.dns.type")?,
//!     Path::parse(r#"labels["app.kind"]"#)?,
//!     Path::whole_key_first("tags.event_type")?,
//!     Path::parse("host.name")?,
//! ]);
//! let mut slots = Slots::new();
//! let record = br#"{"event":{"dns":{"type":"query"}},"labels":{"app.kind":"web"},"tags.event_type":"auth","host":"h1"}"#;
//! let values = paths.read(record, &mut slots);
//!
//! let dns = values.get(0).and_then(Slot::found);
//! assert_eq!(dns.map(|v| (v.text(), v.kind())), Some((r#""query""#, Kind::String)));
//! let app = values.get(1).and_then(Slot::found).and_then(|v| v.to_str());
//! assert_eq!(app.as_deref(), Some("web"));
//! assert!(values.get(2).and_then(Slot::found).is_some());
//! assert_eq!(values.get(3), Some(Slot::WrongParentType(1)));
//! # Ok::<(), grippo::json::PathError>(())
//! ```

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

use memchr::memchr;

use super::{BLOCK, Classes, ODD_BITS, prefix_xor};
pub(super) use crate::path::{Malformed, string_end, unescape};
use crate::path::{Path, Step};

/// The type of value a step reads into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Holder {
    Object,
    Array,
    Either,
}

impl Holder {
    const fn of(step: &Step) -> Self {
        match step {
            Step::Key(_) => Self::Object,
            Step::Index(_) => Self::Array,
            Step::Either(..) => Self::Either,
        }
    }

    const fn holds(self, kind: Kind) -> bool {
        matches!(
            (self, kind),
            (Self::Object | Self::Either, Kind::Object) | (Self::Array | Self::Either, Kind::Array)
        )
    }
}

/// A JSON value's type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// `{...}`
    Object,
    /// `[...]`
    Array,
    /// `"..."`
    String,
    /// A number, as JSON's grammar spells one.
    Number,
    /// `true` or `false`.
    Bool,
    /// `null`.
    Null,
}

impl Kind {
    /// The type a value starting with `byte` has, if any.
    pub(super) const fn of(byte: u8) -> Option<Self> {
        match byte {
            b'{' => Some(Self::Object),
            b'[' => Some(Self::Array),
            b'"' => Some(Self::String),
            b't' | b'f' => Some(Self::Bool),
            b'n' => Some(Self::Null),
            b'-' | b'0'..=b'9' => Some(Self::Number),
            _ => None,
        }
    }
}

/// A value found in the record: its exact text and its type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raw<'a> {
    text: &'a str,
    kind: Kind,
    /// The value's first byte in the record.
    start: usize,
}

impl<'a> Raw<'a> {
    /// A value at `start` in its record whose text has been through
    /// [`checked`] as `kind`.
    pub(super) const fn new(text: &'a str, kind: Kind, start: usize) -> Self {
        Self { text, kind, start }
    }

    /// The value's offsets in the record it was read from.
    #[must_use]
    pub const fn span(self) -> Range<usize> {
        self.start..self.start + self.text.len()
    }

    /// The value as the record spells it: a string with its quotes and
    /// escapes, a number as written, an object or array with its insides.
    #[must_use]
    pub const fn text(self) -> &'a str {
        self.text
    }

    /// The value's type.
    #[must_use]
    pub const fn kind(self) -> Kind {
        self.kind
    }

    /// A string's contents with its escapes decoded, borrowed when it holds
    /// none. `None` for any other type.
    #[must_use]
    pub fn to_str(self) -> Option<Cow<'a, str>> {
        if self.kind != Kind::String {
            return None;
        }
        let inner = self.text.strip_prefix('"')?.strip_suffix('"')?;
        if memchr(b'\\', inner.as_bytes()).is_none() {
            return Some(Cow::Borrowed(inner));
        }
        let mut out = Vec::with_capacity(inner.len());
        unescape(inner.as_bytes(), |part| out.extend_from_slice(part)).ok()?;
        String::from_utf8(out).ok().map(Cow::Owned)
    }
}

/// What the record holds at one path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot<'a> {
    /// The value at the path.
    Found(Raw<'a>),
    /// The last key isn't in its parent object, or the last index is past
    /// the end of its array.
    MissingKey,
    /// The step at this index of the path, before the last, isn't in its
    /// parent.
    MissingParent(usize),
    /// The value that should hold the step at this index of the path isn't
    /// an object for a key or an array for an index. 0 is the record itself.
    WrongParentType(usize),
    /// The record is malformed where the path was read.
    Malformed,
}

impl<'a> Slot<'a> {
    /// The value, when one was found.
    #[must_use]
    pub const fn found(self) -> Option<Raw<'a>> {
        match self {
            Self::Found(raw) => Some(raw),
            _ => None,
        }
    }
}

/// A compiled set of paths, read together from each record. `Send + Sync`,
/// so one set serves every worker.
#[derive(Debug, Clone)]
pub struct Paths {
    /// Node 0 is the record. Every other node is a key or an index below
    /// its parent.
    nodes: Vec<Node>,
    /// Each node's children by key, sorted by key length and then bytes.
    edges: Vec<Edge>,
    /// Each node's children by index, sorted by index: the index and the child.
    items: Vec<(usize, usize)>,
    slots: Vec<Plan>,
    /// The longest wanted key in bytes, as far as an escaped key is decoded.
    longest: usize,
}

#[derive(Debug, Clone, Copy)]
struct Node {
    first: usize,
    count: usize,
    items_first: usize,
    items_count: usize,
    /// A reading ends here, so the value's end is wanted.
    wanted: bool,
}

#[derive(Debug, Clone)]
struct Edge {
    key: Box<str>,
    node: usize,
    /// The key holds a control character, which a record can only escape.
    control: bool,
}

#[derive(Debug, Clone)]
struct Plan {
    /// Each reading's chain of nodes from the record down, with the type of
    /// value each is read from, in the order tried.
    readings: Box<[Box<[(usize, Holder)]>]>,
    /// The reading whose miss the slot reports when none finds a value.
    plain: usize,
}

impl Paths {
    /// Compiles `paths`, one slot each in the order given.
    #[must_use]
    pub fn new<I: IntoIterator<Item = Path>>(paths: I) -> Self {
        let mut tree = Tree::default();
        let slots = paths
            .into_iter()
            .map(|path| {
                let (readings, plain) = path.readings();
                Plan {
                    readings: readings.into_iter().map(|keys| tree.insert(keys)).collect(),
                    plain,
                }
            })
            .collect();
        tree.finish(slots)
    }

    /// The number of paths.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.slots.len()
    }

    /// Whether the set has no paths.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.slots.is_empty()
    }

    /// Reads every path from the record `json` in one pass, into `slots`.
    ///
    /// `slots` is scratch reused from one record to the next, so a read
    /// allocates nothing once it has grown to this set's size. The record is
    /// read only as far as the last wanted key, and its bytes are checked as
    /// [`Values::get`] says.
    pub fn read<'s, 'a>(&'s self, json: &'a [u8], slots: &'s mut Slots) -> Values<'s, 'a> {
        let Slots { visits, key } = slots;
        visits.clear();
        visits.resize(self.nodes.len(), Visit::default());
        if !self.slots.is_empty() {
            Walk {
                paths: self,
                json,
                at: 0,
                visits: visits.as_mut_slice(),
                key,
            }
            .record();
        }
        Values {
            paths: self,
            visits: visits.as_slice(),
            json,
        }
    }
}

/// The key tree as it's built.
struct Tree {
    children: Vec<Vec<(String, usize)>>,
    items: Vec<Vec<(usize, usize)>>,
    wanted: Vec<bool>,
    index: HashMap<(usize, Child), usize>,
}

/// How a node is reached from its parent.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Child {
    Key(String),
    Index(usize),
}

impl Default for Tree {
    fn default() -> Self {
        Self {
            children: vec![Vec::new()],
            items: vec![Vec::new()],
            wanted: vec![false],
            index: HashMap::new(),
        }
    }
}

impl Tree {
    /// The chain of nodes `steps` goes through, adding the ones that are new.
    /// An `Either` step's node is its key's, and is the child at its index too.
    fn insert(&mut self, steps: Vec<Step>) -> Box<[(usize, Holder)]> {
        let mut at = 0;
        let mut chain = Vec::with_capacity(steps.len());
        for step in steps {
            let holder = Holder::of(&step);
            let (child, index) = match step {
                Step::Key(key) => (Child::Key(key), None),
                Step::Index(i) => (Child::Index(i), None),
                Step::Either(key, i) => (Child::Key(key), Some(i)),
            };
            let node = self.node(at, child);
            if let Some(i) = index
                && !self.items[at].contains(&(i, node))
            {
                self.items[at].push((i, node));
            }
            chain.push((node, holder));
            at = node;
        }
        self.wanted[at] = true;
        chain.into_boxed_slice()
    }

    /// The child of `at` that `child` names, added when it's new.
    fn node(&mut self, at: usize, child: Child) -> usize {
        let next = self.children.len();
        let node = *self.index.entry((at, child.clone())).or_insert(next);
        if node == next {
            self.children.push(Vec::new());
            self.items.push(Vec::new());
            self.wanted.push(false);
            match child {
                Child::Key(key) => self.children[at].push((key, node)),
                Child::Index(i) => self.items[at].push((i, node)),
            }
        }
        node
    }

    fn finish(self, slots: Vec<Plan>) -> Paths {
        let mut nodes = Vec::with_capacity(self.children.len());
        let mut edges = Vec::new();
        let mut all_items = Vec::new();
        let mut longest = 0;
        for ((mut children, mut items), wanted) in
            self.children.into_iter().zip(self.items).zip(self.wanted)
        {
            children.sort_unstable_by(|(a, _), (b, _)| by_length(a.as_bytes(), b.as_bytes()));
            items.sort_unstable();
            nodes.push(Node {
                first: edges.len(),
                count: children.len(),
                items_first: all_items.len(),
                items_count: items.len(),
                wanted,
            });
            all_items.extend(items);
            for (key, node) in children {
                longest = longest.max(key.len());
                edges.push(Edge {
                    control: key.bytes().any(|b| b < 0x20),
                    key: key.into_boxed_str(),
                    node,
                });
            }
        }
        Paths {
            nodes,
            edges,
            items: all_items,
            slots,
            longest,
        }
    }
}

/// Orders keys by length, then by bytes.
fn by_length(a: &[u8], b: &[u8]) -> std::cmp::Ordering {
    a.len().cmp(&b.len()).then_with(|| a.cmp(b))
}

/// Scratch for [`Paths::read`], reused from one record to the next. One
/// `Slots` serves any set, and grows to the largest it has read.
#[derive(Debug, Clone, Default)]
pub struct Slots {
    visits: Vec<Visit>,
    /// An escaped key, decoded to compare.
    key: Vec<u8>,
}

impl Slots {
    /// Empty scratch. The first read sizes it.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            visits: Vec::new(),
            key: Vec::new(),
        }
    }
}

/// What a read found at one node.
#[derive(Debug, Clone, Copy, Default)]
struct Visit {
    start: usize,
    /// Set, never 0, once the whole value has been passed.
    end: usize,
    /// Set once the value has been passed, or as an object's walk starts.
    kind: Option<Kind>,
    /// The walk reached the object's closing brace.
    closed: bool,
}

/// One record's slots, from [`Paths::read`].
#[derive(Debug, Clone, Copy)]
pub struct Values<'s, 'a> {
    paths: &'s Paths,
    visits: &'s [Visit],
    json: &'a [u8],
}

impl<'a> Values<'_, 'a> {
    /// The slot for path `i`, in the order the set was built, or `None` past
    /// the last.
    ///
    /// A found value is checked in full here: its UTF-8, and a number's
    /// grammar, a literal's spelling, or a string's escapes and control
    /// characters, so a bad one is [`Slot::Malformed`]. The read checks the
    /// colons, commas and braces of each object it walks, and the escapes of
    /// any key that has one. A value it passes over, and the inside of a found
    /// object or array, is read by its brackets and quotes only.
    #[must_use]
    pub fn get(&self, i: usize) -> Option<Slot<'a>> {
        self.paths.slots.get(i).map(|plan| self.slot(plan))
    }

    /// Every slot, in path order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Slot<'a>> {
        self.paths.slots.iter().map(|plan| self.slot(plan))
    }

    /// The number of slots.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.paths.slots.len()
    }

    /// Whether there are no slots.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.paths.slots.is_empty()
    }

    fn slot(&self, plan: &Plan) -> Slot<'a> {
        let mut miss = Slot::Malformed;
        for (i, chain) in plan.readings.iter().enumerate() {
            match self.reading(chain) {
                Slot::Malformed => return Slot::Malformed,
                found @ Slot::Found(_) => return found,
                other if i == plan.plain => miss = other,
                _ => {}
            }
        }
        miss
    }

    fn reading(&self, chain: &[(usize, Holder)]) -> Slot<'a> {
        let json = self.json;
        let mut parent = self.visits[0];
        for (i, &(node, holder)) in chain.iter().enumerate() {
            match parent.kind {
                Some(kind) if holder.holds(kind) => {}
                Some(_) => return Slot::WrongParentType(i),
                None => return Slot::Malformed,
            }
            let visit = self.visits[node];
            let last = i + 1 == chain.len();
            let Some(kind) = visit.kind else {
                return match (parent.closed, last) {
                    (false, _) => Slot::Malformed,
                    (true, true) => Slot::MissingKey,
                    (true, false) => Slot::MissingParent(i),
                };
            };
            if last {
                if visit.end == 0 {
                    return Slot::Malformed;
                }
                return checked(kind, &json[visit.start..visit.end])
                    .map_or(Slot::Malformed, |text| {
                        Slot::Found(Raw::new(text, kind, visit.start))
                    });
            }
            parent = visit;
        }
        Slot::Malformed
    }
}

/// The text of a found value, once it's checked as its type.
pub(super) fn checked(kind: Kind, text: &[u8]) -> Option<&str> {
    let well_formed = match kind {
        Kind::Object | Kind::Array => true,
        Kind::String => text
            .strip_prefix(b"\"")
            .and_then(|t| t.strip_suffix(b"\""))
            .is_some_and(|inner| unescape(inner, |_| {}).is_ok()),
        Kind::Number => number(text),
        Kind::Bool => text == b"true" || text == b"false",
        Kind::Null => text == b"null",
    };
    if well_formed {
        std::str::from_utf8(text).ok()
    } else {
        None
    }
}

/// Checks that `json[from..to]` is one JSON value read in full: each string's
/// escapes and UTF-8, each number and literal, and containers nested no more
/// than `depth` deep. Gives the offset of the first token that fails.
#[cfg(feature = "json-keys")]
pub(super) fn valid(json: &[u8], from: usize, to: usize, depth: usize) -> Result<(), usize> {
    let json = &json[..to];
    let space = |mut at: usize| {
        while matches!(json.get(at), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            at += 1;
        }
        at
    };
    // One bit per open container, set for an object, innermost lowest.
    let mut open: u128 = 0;
    let mut n = 0;
    let mut at = from;
    loop {
        at = space(at);
        match json.get(at) {
            Some(b'"') => at = valid_string(json, at)?,
            Some(&b @ (b'{' | b'[')) => {
                if n >= depth.min(128) {
                    return Err(at);
                }
                let object = b == b'{';
                open = (open << 1) | u128::from(object);
                n += 1;
                at = space(at + 1);
                let empty = json.get(at) == Some(if object { &b'}' } else { &b']' });
                if !empty {
                    if object {
                        at = valid_key(json, at, space)?;
                    }
                    continue;
                }
                at += 1;
                open >>= 1;
                n -= 1;
            }
            Some(b't') if json[at..].starts_with(b"true") => at += 4,
            Some(b'f') if json[at..].starts_with(b"false") => at += 5,
            Some(b'n') if json[at..].starts_with(b"null") => at += 4,
            Some(b'-' | b'0'..=b'9') => {
                let len = json[at..]
                    .iter()
                    .position(|&b| {
                        !(b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E'))
                    })
                    .unwrap_or(json.len() - at);
                let text = &json[at..at + len];
                if !number(text) || !in_range(text) {
                    return Err(at);
                }
                at += len;
            }
            _ => return Err(at),
        }
        // Past a value: close what it ends, or take the comma to the next.
        loop {
            if n == 0 {
                return if at == json.len() { Ok(()) } else { Err(at) };
            }
            at = space(at);
            let object = open & 1 == 1;
            match json.get(at) {
                Some(b',') => {
                    at = space(at + 1);
                    if object {
                        at = valid_key(json, at, space)?;
                    }
                    break;
                }
                Some(b'}') if object => {}
                Some(b']') if !object => {}
                _ => return Err(at),
            }
            at += 1;
            open >>= 1;
            n -= 1;
        }
    }
}

/// Whether a number `serde_json` reads as an f64 stays finite. An integer
/// short of 309 digits is finite whatever type it lands in.
#[cfg(feature = "json-keys")]
fn in_range(text: &[u8]) -> bool {
    let float = text.len() > 308 || text.iter().any(|&b| matches!(b, b'e' | b'E'));
    !float
        || std::str::from_utf8(text)
            .ok()
            .and_then(|t| t.parse::<f64>().ok())
            .is_some_and(f64::is_finite)
}

/// Past a checked key and its colon, from the key's opening quote.
#[cfg(feature = "json-keys")]
fn valid_key(json: &[u8], at: usize, space: impl Fn(usize) -> usize) -> Result<usize, usize> {
    if json.get(at) != Some(&b'"') {
        return Err(at);
    }
    let colon = space(valid_string(json, at)?);
    if json.get(colon) != Some(&b':') {
        return Err(colon);
    }
    Ok(colon + 1)
}

/// Past a checked string, from its opening quote.
#[cfg(feature = "json-keys")]
fn valid_string(json: &[u8], at: usize) -> Result<usize, usize> {
    let (end, _) = string_end(json, at + 1).map_err(|_| at)?;
    let inner = &json[at + 1..end];
    if std::str::from_utf8(inner).is_err() || unescape(inner, |_| {}).is_err() {
        return Err(at);
    }
    Ok(end + 1)
}

/// Whether `text` is a number by JSON's grammar.
fn number(text: &[u8]) -> bool {
    let digits = |from: usize| {
        text.get(from..)
            .map_or(0, |t| t.iter().take_while(|b| b.is_ascii_digit()).count())
    };
    let mut at = usize::from(text.first() == Some(&b'-'));
    match text.get(at) {
        Some(b'0') => at += 1,
        Some(b'1'..=b'9') => at += digits(at),
        _ => return false,
    }
    if text.get(at) == Some(&b'.') {
        let n = digits(at + 1);
        if n == 0 {
            return false;
        }
        at += 1 + n;
    }
    if matches!(text.get(at), Some(b'e' | b'E')) {
        at += 1;
        if matches!(text.get(at), Some(b'+' | b'-')) {
            at += 1;
        }
        let n = digits(at);
        if n == 0 {
            return false;
        }
        at += n;
    }
    at == text.len()
}

/// A read in progress.
struct Walk<'p, 'a, 'v> {
    paths: &'p Paths,
    json: &'a [u8],
    at: usize,
    visits: &'v mut [Visit],
    key: &'v mut Vec<u8>,
}

impl Walk<'_, '_, '_> {
    fn record(&mut self) {
        self.space();
        match self.json.get(self.at) {
            // A malformed record keeps what was read before the fault.
            Some(b'{') => {
                self.visits[0].kind = Some(Kind::Object);
                self.at += 1;
                let _ = self.object(0, false);
            }
            Some(b'[') if self.paths.nodes[0].items_count > 0 => {
                self.visits[0].kind = Some(Kind::Array);
                self.at += 1;
                let _ = self.array(0, false);
            }
            Some(&b) => self.visits[0].kind = Kind::of(b),
            None => {}
        }
    }

    /// Walks the object at `node` from just past its `{` until every child of
    /// `node` has been seen, then skips to its end when `to_end` is set. `true`
    /// once past the closing brace, `false` when it stopped short of it because
    /// nothing later in the record is wanted.
    fn object(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
        let Node { first, count, .. } = self.paths.nodes[node];
        let mut left = count;
        self.space();
        if self.peek() == Some(b'}') {
            self.at += 1;
            self.visits[node].closed = true;
            return Ok(true);
        }
        loop {
            if self.byte()? != b'"' {
                return Err(Malformed);
            }
            let child = self.key(first, count)?;
            self.space();
            if self.byte()? != b':' {
                return Err(Malformed);
            }
            self.space();
            if let Some(child) = child {
                // The child's end is needed for its own text, a later sibling, or this object's end.
                let need = to_end || left > 1 || self.paths.nodes[child].wanted;
                let ended = self.value(child, need)?;
                left -= 1;
                if left == 0 || !ended {
                    if to_end {
                        self.at = close(self.json, self.at)?;
                    }
                    return Ok(to_end);
                }
            } else {
                self.skip()?;
            }
            self.space();
            match self.byte()? {
                b',' => self.space(),
                b'}' => {
                    self.visits[node].closed = true;
                    return Ok(true);
                }
                _ => return Err(Malformed),
            }
        }
    }

    /// Reads a key from just past its opening quote to just past its closing
    /// one, and gives the child among `edges[first..first + count]` it names,
    /// unless that child was seen before: the first of two equal keys wins.
    fn key(&mut self, first: usize, count: usize) -> Result<Option<usize>, Malformed> {
        let json = self.json;
        let paths = self.paths;
        let start = self.at;
        let (end, escaped) = string_end(json, start)?;
        self.at = end + 1;
        let edges = &paths.edges[first..first + count];
        let edge = if escaped {
            let limit = paths.longest;
            let decoded = &mut *self.key;
            decoded.clear();
            let mut over = false;
            unescape(&json[start..end], |part| {
                if over || decoded.len() + part.len() > limit {
                    over = true;
                } else {
                    decoded.extend_from_slice(part);
                }
            })?;
            if over {
                None
            } else {
                find(edges, decoded.as_slice())
            }
        } else {
            match find(edges, &json[start..end]) {
                Some(edge) if edge.control => return Err(Malformed),
                found => found,
            }
        };
        Ok(edge
            .map(|edge| edge.node)
            .filter(|&node| self.visits[node].kind.is_none()))
    }

    /// Passes the value at `node`, walking into it when it's an object holding
    /// wanted keys, and records where it lies. `false` when the walk stopped
    /// inside it, as [`Self::object`] does when `to_end` is unset.
    fn value(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
        let start = self.at;
        let kind = self.peek().and_then(Kind::of).ok_or(Malformed)?;
        let Node {
            count, items_count, ..
        } = self.paths.nodes[node];
        let walk = match kind {
            Kind::Object => count > 0,
            Kind::Array => items_count > 0,
            _ => false,
        };
        if walk {
            // Set before the walk, so a key found inside keeps its answer past a later fault.
            self.visits[node].kind = Some(kind);
            self.at += 1;
            let passed = if kind == Kind::Object {
                self.object(node, to_end)?
            } else {
                self.array(node, to_end)?
            };
            if !passed {
                return Ok(false);
            }
        } else {
            self.pass(kind)?;
        }
        let visit = &mut self.visits[node];
        visit.start = start;
        visit.end = self.at;
        visit.kind = Some(kind);
        Ok(true)
    }

    /// Walks the array at `node` from just past its `[` as [`Self::object`]
    /// walks an object, reading the elements at its children's indexes. Two
    /// children at one index each read that element.
    fn array(&mut self, node: usize, to_end: bool) -> Result<bool, Malformed> {
        let paths = self.paths;
        let Node {
            items_first,
            items_count,
            ..
        } = paths.nodes[node];
        let items = &paths.items[items_first..items_first + items_count];
        self.space();
        if self.peek() == Some(b']') {
            self.at += 1;
            self.visits[node].closed = true;
            return Ok(true);
        }
        let mut next = 0;
        let mut i = 0;
        loop {
            let from = next;
            while items.get(next).is_some_and(|&(index, _)| index == i) {
                next += 1;
            }
            if from == next {
                self.skip()?;
            } else {
                let start = self.at;
                let mut ended = true;
                for (k, &(_, child)) in items.iter().enumerate().take(next).skip(from) {
                    self.at = start;
                    // As in an object: the end is needed for its text, a later child, or this array's end.
                    let need = to_end || k + 1 < items.len() || paths.nodes[child].wanted;
                    ended = self.value(child, need)?;
                }
                if next == items.len() || !ended {
                    if to_end {
                        self.at = close(self.json, self.at)?;
                    }
                    return Ok(to_end);
                }
            }
            self.space();
            match self.byte()? {
                b',' => self.space(),
                b']' => {
                    self.visits[node].closed = true;
                    return Ok(true);
                }
                _ => return Err(Malformed),
            }
            i += 1;
        }
    }

    /// Passes a value nothing wants.
    fn skip(&mut self) -> Result<(), Malformed> {
        let kind = self.peek().and_then(Kind::of).ok_or(Malformed)?;
        self.pass(kind)
    }

    /// Moves past the value of type `kind` that starts here, as [`value_end`] does.
    fn pass(&mut self, kind: Kind) -> Result<(), Malformed> {
        self.at = value_end(self.json, self.at, kind)?;
        Ok(())
    }

    #[inline]
    fn space(&mut self) {
        while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.json.get(self.at) {
            self.at += 1;
        }
    }

    #[inline]
    fn peek(&self) -> Option<u8> {
        self.json.get(self.at).copied()
    }

    #[inline]
    fn byte(&mut self) -> Result<u8, Malformed> {
        let b = self.peek().ok_or(Malformed)?;
        self.at += 1;
        Ok(b)
    }
}

/// The offset just past the value of type `kind` at `at`, found by its
/// brackets and quotes. A number or literal must be followed by a byte that
/// can end it, so a record cut short never yields a shortened one.
pub(super) fn value_end(json: &[u8], at: usize, kind: Kind) -> Result<usize, Malformed> {
    match kind {
        Kind::Object | Kind::Array => close(json, at + 1),
        Kind::String => Ok(string_end(json, at + 1)?.0 + 1),
        Kind::Number | Kind::Bool | Kind::Null => {
            let rest = json.get(at..).ok_or(Malformed)?;
            let len = rest
                .iter()
                .position(|&b| !(b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')))
                .ok_or(Malformed)?;
            if !matches!(rest[len], b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r') {
                return Err(Malformed);
            }
            Ok(at + len)
        }
    }
}

/// The edge for `key`, by binary search on length and then bytes.
#[inline]
fn find<'e>(edges: &'e [Edge], key: &[u8]) -> Option<&'e Edge> {
    edges
        .binary_search_by(|edge| by_length(edge.key.as_bytes(), key))
        .ok()
        .map(|i| &edges[i])
}

/// The offset just past the bracket closing the container whose contents
/// start at `from`, found 64 bytes a step on json.rs's byte classes. Bracket
/// pairs aren't matched by type, and a backslash outside a string is malformed.
pub(super) fn close(json: &[u8], from: usize) -> Result<usize, Malformed> {
    let rest = json.get(from..).ok_or(Malformed)?;
    let (blocks, tail) = rest.as_chunks::<BLOCK>();
    let mut skip = Skip::default();
    for (i, block) in blocks.iter().enumerate() {
        if let Some(bit) = skip.block(Classes::of(block))? {
            return Ok(from + i * BLOCK + bit + 1);
        }
    }
    if tail.is_empty() {
        return Err(Malformed);
    }
    let classes = json.last_chunk::<BLOCK>().map_or_else(
        || {
            // A zero byte is in no class, so the padding changes nothing.
            let mut padded = [0; BLOCK];
            padded[..tail.len()].copy_from_slice(tail);
            Classes::of(&padded)
        },
        // Re-read the last 64 bytes and shift out the ones before the tail.
        |last| Classes::of(last).skip(BLOCK - tail.len()),
    );
    let bit = skip.block(classes)?.ok_or(Malformed)?;
    Ok(from + blocks.len() * BLOCK + bit + 1)
}

/// Container skip state carried from one block to the next.
struct Skip {
    depth: usize,
    /// All ones while a string is open across a block boundary.
    in_string: u64,
    /// 1 when a backslash ending the last block escapes this block's first byte.
    escaped: u64,
}

impl Default for Skip {
    fn default() -> Self {
        Self {
            depth: 1,
            in_string: 0,
            escaped: 0,
        }
    }
}

impl Skip {
    /// The bit of the byte in this block that closes the container, if one does.
    #[inline]
    fn block(&mut self, classes: Classes) -> Result<Option<usize>, Malformed> {
        let Classes {
            quotes,
            backslashes,
            opens,
            closes,
        } = classes;
        // The escape and string masks are depth_within's.
        let (escaped, next_escaped) = if backslashes == 0 {
            (self.escaped, 0)
        } else {
            let potential = backslashes & !self.escaped;
            let codes = ((potential << 1) | ODD_BITS).wrapping_sub(potential) ^ ODD_BITS;
            (
                codes ^ (backslashes | self.escaped),
                (codes & backslashes) >> 63,
            )
        };
        let strings = prefix_xor(quotes & !escaped) ^ self.in_string;
        let shut = self.walk(opens & !strings, closes & !strings);
        let read = shut.map_or(u64::MAX, |bit| u64::MAX >> (63 - bit));
        if backslashes & !strings & read != 0 {
            return Err(Malformed);
        }
        self.in_string = 0_u64.wrapping_sub(strings >> 63);
        self.escaped = next_escaped;
        Ok(shut)
    }

    /// Applies one block's brackets in order, and gives the bit where the
    /// depth reaches zero.
    #[inline]
    const fn walk(&mut self, opens: u64, closes: u64) -> Option<usize> {
        let n_close = closes.count_ones() as usize;
        if n_close < self.depth {
            self.depth = self.depth + opens.count_ones() as usize - n_close;
            return None;
        }
        let mut marks = opens | closes;
        while marks != 0 {
            let bit = marks.trailing_zeros();
            if (closes >> bit) & 1 == 1 {
                self.depth -= 1;
                if self.depth == 0 {
                    return Some(bit as usize);
                }
            } else {
                self.depth += 1;
            }
            marks &= marks - 1;
        }
        None
    }
}

#[cfg(test)]
pub(super) mod tests;