grippo 0.1.1

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
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
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
// 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 std::str::FromStr;

use memchr::{memchr, memchr2};
use thiserror::Error;

use super::{BLOCK, Classes, ODD_BITS, prefix_xor};

/// The most dotted parts a whole-key-first path may have: a path of `n` parts
/// has `2^(n-1)` readings.
pub const MAX_DOTTED_PARTS: usize = 8;

/// One field path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
    reading: Reading,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Reading {
    /// One step per key or index.
    Steps(Vec<Step>),
    /// The text as one key, then each dot as a step, left to right.
    WholeKeyFirst(String),
}

/// One step down a path.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Step {
    /// A key of an object.
    Key(String),
    /// An element of an array, by position.
    Index(usize),
    /// A key of an object or an element of an array, as a JSON Pointer's
    /// numeric segment is read.
    Either(String, usize),
}

/// 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)
        )
    }
}

/// Why a path can't be built.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PathError {
    /// A path with no keys.
    #[error("a path needs at least one key")]
    Empty,
    /// [`Path::parse`] text that isn't a path.
    #[error("{why} at byte {at}")]
    Syntax {
        /// The byte offset where reading stopped.
        at: usize,
        /// What was expected there.
        why: &'static str,
    },
    /// A whole-key-first path with more than [`MAX_DOTTED_PARTS`] parts.
    #[error("{parts} dotted parts, past the {max} a whole-key-first path takes", max = MAX_DOTTED_PARTS)]
    TooManyParts {
        /// The parts the text has.
        parts: usize,
    },
}

impl Path {
    /// A path in text: `a.b.c` steps through three keys, `["a.b"]` is one key
    /// with a dot in it, written as a JSON string, `a[0]` is the first element
    /// of the array at `a`, and `a["b.c"][2].d` mixes them.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] for empty text, [`PathError::Syntax`] for an empty
    /// name, a bracket holding neither one JSON string nor an index, or text
    /// after a `]` that isn't `.` or `[`.
    pub fn parse(text: &str) -> Result<Self, PathError> {
        if text.is_empty() {
            return Err(PathError::Empty);
        }
        let bytes = text.as_bytes();
        let mut keys = Vec::new();
        let mut at = 0;
        let mut after_dot = false;
        loop {
            if bytes.get(at) == Some(&b'[') && !after_dot {
                let (step, next) = if bytes.get(at + 1).is_some_and(u8::is_ascii_digit) {
                    bracketed_index(bytes, at)?
                } else {
                    let (key, next) = quoted(bytes, at)?;
                    (Step::Key(key), next)
                };
                keys.push(step);
                at = next;
            } else {
                let len = bytes[at..]
                    .iter()
                    .position(|&b| b == b'.' || b == b'[')
                    .unwrap_or(bytes.len() - at);
                if len == 0 {
                    return Err(syntax(at, "a key name"));
                }
                keys.push(Step::Key(text[at..at + len].to_owned()));
                at += len;
            }
            after_dot = false;
            match bytes.get(at) {
                None => return Ok(Self::steps(keys)),
                Some(b'.') => {
                    at += 1;
                    after_dot = true;
                }
                Some(b'[') => {}
                Some(_) => return Err(syntax(at, "`.` or `[` after `]`")),
            }
        }
    }

    /// The keys as given, one step each, with no reading of dots or brackets.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] when there are no keys.
    pub fn from_keys<I, K>(keys: I) -> Result<Self, PathError>
    where
        I: IntoIterator<Item = K>,
        K: Into<String>,
    {
        let keys: Vec<Step> = keys.into_iter().map(|k| Step::Key(k.into())).collect();
        if keys.is_empty() {
            return Err(PathError::Empty);
        }
        Ok(Self::steps(keys))
    }

    /// A JSON Pointer (RFC 6901): `/data/0/message` steps through `data`, `0`
    /// and `message`, with `~1` read as `/` and `~0` as `~`. A segment that's
    /// an array index, `0` or digits with no leading zero, is read as a key
    /// in an object and a position in an array.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] for `""`, which names the whole record, and
    /// [`PathError::Syntax`] for text that doesn't start with `/` or a `~`
    /// not followed by `0` or `1`.
    pub fn from_pointer(text: &str) -> Result<Self, PathError> {
        let Some(rest) = text.strip_prefix('/') else {
            return Err(if text.is_empty() {
                PathError::Empty
            } else {
                syntax(0, "`/` to start a pointer")
            });
        };
        let mut at = 1;
        let mut steps = Vec::new();
        for segment in rest.split('/') {
            let mut key = String::with_capacity(segment.len());
            let mut chars = segment.char_indices();
            while let Some((i, c)) = chars.next() {
                if c == '~' {
                    match chars.next() {
                        Some((_, '0')) => key.push('~'),
                        Some((_, '1')) => key.push('/'),
                        _ => return Err(syntax(at + i, "`~0` or `~1`")),
                    }
                } else {
                    key.push(c);
                }
            }
            at += segment.len() + 1;
            let is_index = !key.is_empty()
                && key.bytes().all(|b| b.is_ascii_digit())
                && (key == "0" || !key.starts_with('0'));
            let index = if is_index {
                key.parse::<usize>().ok()
            } else {
                None
            };
            steps.push(match index {
                Some(i) => Step::Either(key, i),
                None => Step::Key(key),
            });
        }
        Ok(Self::steps(steps))
    }

    /// Dotted text read whole key first: `a.b.c` is tried as the one key
    /// `a.b.c`, then with each dot from the left as a step, the rest read the
    /// same way inside that key's object. The first reading that finds a value
    /// wins, so `a`, `b.c` comes before `a`, `b`, `c`, which comes before
    /// `a.b`, `c`. That reads literal dotted keys at any depth.
    ///
    /// # Errors
    ///
    /// [`PathError::TooManyParts`] past [`MAX_DOTTED_PARTS`] parts.
    pub fn whole_key_first(text: &str) -> Result<Self, PathError> {
        let parts = text.split('.').count();
        if parts > MAX_DOTTED_PARTS {
            return Err(PathError::TooManyParts { parts });
        }
        Ok(Self {
            reading: Reading::WholeKeyFirst(text.to_owned()),
        })
    }

    const fn steps(steps: Vec<Step>) -> Self {
        Self {
            reading: Reading::Steps(steps),
        }
    }

    /// Each step list this path is read as, in the order tried, and the one
    /// whose miss is reported when none finds a value.
    fn readings(&self) -> (Vec<Vec<Step>>, usize) {
        match &self.reading {
            Reading::Steps(steps) => (vec![steps.clone()], 0),
            Reading::WholeKeyFirst(text) => {
                let parts: Vec<&str> = text.split('.').collect();
                let readings: Vec<Vec<Step>> = groupings(&parts)
                    .into_iter()
                    .map(|keys| keys.into_iter().map(Step::Key).collect())
                    .collect();
                let plain = readings
                    .iter()
                    .position(|keys| keys.len() == parts.len())
                    .unwrap_or(0);
                (readings, plain)
            }
        }
    }
}

/// The `[N]` at `at`, and the offset just past its `]`.
fn bracketed_index(bytes: &[u8], at: usize) -> Result<(Step, usize), PathError> {
    let digits = bytes[at + 1..]
        .iter()
        .take_while(|b| b.is_ascii_digit())
        .count();
    let text = &bytes[at + 1..at + 1 + digits];
    if text.len() > 1 && text[0] == b'0' {
        return Err(syntax(at + 1, "an index with no leading zero"));
    }
    let index = std::str::from_utf8(text)
        .ok()
        .and_then(|t| t.parse::<usize>().ok())
        .ok_or_else(|| syntax(at + 1, "an index that fits a usize"))?;
    if bytes.get(at + 1 + digits) != Some(&b']') {
        return Err(syntax(at + 1 + digits, "`]` after the index"));
    }
    Ok((Step::Index(index), at + 2 + digits))
}

impl FromStr for Path {
    type Err = PathError;

    fn from_str(text: &str) -> Result<Self, PathError> {
        Self::parse(text)
    }
}

const fn syntax(at: usize, why: &'static str) -> PathError {
    PathError::Syntax { at, why }
}

/// The key in the `["..."]` at `at`, and the offset just past its `]`.
fn quoted(bytes: &[u8], at: usize) -> Result<(String, usize), PathError> {
    if bytes.get(at + 1) != Some(&b'"') {
        return Err(syntax(at + 1, "a JSON string after `[`"));
    }
    let (end, _) = string_end(bytes, at + 2).map_err(|_| syntax(at + 1, "a closing quote"))?;
    let mut key = Vec::new();
    unescape(&bytes[at + 2..end], |part| key.extend_from_slice(part))
        .map_err(|_| syntax(at + 1, "a JSON string"))?;
    let key = String::from_utf8(key).map_err(|_| syntax(at + 1, "a JSON string"))?;
    if bytes.get(end + 1) != Some(&b']') {
        return Err(syntax(end + 1, "`]` after the key"));
    }
    Ok((key, end + 2))
}

/// Every grouping of `parts` into dotted keys, in the whole-key-first order.
fn groupings(parts: &[&str]) -> Vec<Vec<String>> {
    let mut out = vec![vec![parts.join(".")]];
    for cut in 1..parts.len() {
        let head = parts[..cut].join(".");
        for rest in groupings(&parts[cut..]) {
            let mut keys = Vec::with_capacity(rest.len() + 1);
            keys.push(head.clone());
            keys.extend(rest);
            out.push(keys);
        }
    }
    out
}

/// 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()
}

/// The record ends, or holds something that isn't JSON, where a read needs more.
#[derive(Debug)]
pub(super) struct Malformed;

/// 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 of the quote closing the string whose contents start at `from`,
/// and whether the string holds a backslash.
#[inline]
pub(super) fn string_end(json: &[u8], from: usize) -> Result<(usize, bool), Malformed> {
    let mut at = from;
    let mut escaped = false;
    loop {
        let rest = json.get(at..).ok_or(Malformed)?;
        let i = memchr2(b'"', b'\\', rest).ok_or(Malformed)?;
        if rest[i] == b'"' {
            return Ok((at + i, escaped));
        }
        escaped = true;
        at += i + 2;
    }
}

/// 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
    }
}

/// Decodes a JSON string's contents, between its quotes, handing each piece
/// to `out`. A raw control character, a bad escape or a lone surrogate is
/// malformed.
pub(super) fn unescape(mut raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
    loop {
        let run = memchr(b'\\', raw).unwrap_or(raw.len());
        let (text, rest) = raw.split_at(run);
        if text.iter().any(|&b| b < 0x20) {
            return Err(Malformed);
        }
        out(text);
        let Some((_, rest)) = rest.split_first() else {
            return Ok(());
        };
        let (&escape, rest) = rest.split_first().ok_or(Malformed)?;
        raw = rest;
        let byte = match escape {
            b'"' => b'"',
            b'\\' => b'\\',
            b'/' => b'/',
            b'b' => 0x08,
            b'f' => 0x0c,
            b'n' => b'\n',
            b'r' => b'\r',
            b't' => b'\t',
            b'u' => {
                let (c, rest) = code_point(raw)?;
                raw = rest;
                out(c.encode_utf8(&mut [0; 4]).as_bytes());
                continue;
            }
            _ => return Err(Malformed),
        };
        out(&[byte]);
    }
}

/// The character a `\u` escape spells, from its first hex digit, and what
/// follows it. A high surrogate takes the `\u` low surrogate after it.
fn code_point(raw: &[u8]) -> Result<(char, &[u8]), Malformed> {
    let high = hex4(raw)?;
    let mut rest = &raw[4..];
    let code = match high {
        0xD800..=0xDBFF => {
            let low = hex4(rest.strip_prefix(b"\\u").ok_or(Malformed)?)?;
            if !(0xDC00..=0xDFFF).contains(&low) {
                return Err(Malformed);
            }
            rest = &rest[6..];
            0x1_0000 + ((high - 0xD800) << 10) + (low - 0xDC00)
        }
        0xDC00..=0xDFFF => return Err(Malformed),
        code => code,
    };
    Ok((char::from_u32(code).ok_or(Malformed)?, rest))
}

/// Four hex digits at the start of `raw`.
fn hex4(raw: &[u8]) -> Result<u32, Malformed> {
    raw.get(..4)
        .ok_or(Malformed)?
        .iter()
        .try_fold(0, |code, &b| {
            let digit = char::from(b).to_digit(16).ok_or(Malformed)?;
            Ok((code << 4) | digit)
        })
}

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