nosj 0.2.2

Pull, push and fused-cursor JSON parsers plus a streaming writer, for hosts that build native values during the parse — SIMD-accelerated (NEON, SSE2, runtime-detected AVX2)
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
//! RFC 6901 JSON Pointer resolution: partial parsing's front door.
//!
//! Resolution is a forward byte cursor: it tokenizes only the navigation
//! levels it walks through and steps over everything else. Sibling
//! containers are skipped by [`crate::stage1::container_end`] (64-byte
//! blocks classified exactly like indexing, but consuming only bracket
//! bits, stopping at the matching closer, and building no index), so the
//! cost of a query is proportional to how far into the document the
//! target sits, not to the document's size. The matched value comes back
//! as its raw text, ready to feed to any nosj entry point, or to keep
//! as a lazy value.
//!
//! Miss semantics match `serde_json::Value::pointer`: a missing key, an
//! out-of-range index, or a token that is not valid array-index syntax
//! (`-`, `01`, non-digits) resolves to `Ok(None)`. Only malformed pointer
//! *syntax* (a non-empty pointer without a leading `/`) is an error.
//!
//! Duplicate keys resolve to the **first** occurrence (streaming
//! semantics; a last-wins map like serde's sees the last).
//!
//! The `_with` variants walk the grammar extensions of [`ParseOptions`],
//! so documents accepted by [`crate::parse_with`] resolve too.

use crate::cursor::ParseOptions;
use crate::reader::{Buffers, ErrorKind, ParseError};
use crate::scalars::{self, StrPart};
use crate::stage1;

/// Resolve `pointer` against `input`, returning the raw text of the
/// matched value (`None` if the pointer doesn't match anything).
///
/// ```
/// let mut bufs = nosj::Buffers::new();
/// let doc = r#"{"users":[{"name":"ada"},{"name":"grace"}]}"#;
/// let raw = nosj::pointer(doc, "/users/1/name", &mut bufs).unwrap();
/// assert_eq!(raw, Some("\"grace\""));
/// ```
#[doc(alias = "get")]
#[doc(alias = "dig")]
#[doc(alias = "json_pointer")]
pub fn pointer<'j>(
    input: &'j str,
    pointer: &str,
    bufs: &mut Buffers,
) -> Result<Option<&'j str>, ParseError> {
    // SAFETY: &str is valid UTF-8.
    unsafe { pointer_utf8_unchecked(input.as_bytes(), pointer, bufs) }
}

/// Like [`pointer()`], with grammar extensions from [`ParseOptions`].
pub fn pointer_with<'j>(
    input: &'j str,
    pointer: &str,
    bufs: &mut Buffers,
    opts: ParseOptions,
) -> Result<Option<&'j str>, ParseError> {
    // SAFETY: &str is valid UTF-8.
    unsafe { pointer_utf8_unchecked_with(input.as_bytes(), pointer, bufs, opts) }
}

/// Like [`pointer()`], for callers whose runtime vouches for UTF-8.
///
/// # Safety
///
/// `input` must be valid UTF-8.
pub unsafe fn pointer_utf8_unchecked<'j>(
    input: &'j [u8],
    pointer: &str,
    bufs: &mut Buffers,
) -> Result<Option<&'j str>, ParseError> {
    // SAFETY: forwarded contract.
    unsafe { pointer_utf8_unchecked_with(input, pointer, bufs, ParseOptions::default()) }
}

/// Like [`pointer_utf8_unchecked`], with grammar extensions from
/// [`ParseOptions`].
///
/// # Safety
///
/// `input` must be valid UTF-8.
pub unsafe fn pointer_utf8_unchecked_with<'j>(
    input: &'j [u8],
    pointer: &str,
    bufs: &mut Buffers,
    opts: ParseOptions,
) -> Result<Option<&'j str>, ParseError> {
    if !pointer.is_empty() && !pointer.starts_with('/') {
        return Err(ParseError {
            offset: 0,
            kind: ErrorKind::InvalidPointer,
        });
    }
    // SAFETY: forwarded contract; the caller vouches `input` is UTF-8.
    let range = unsafe { resolve(input, pointer, &mut bufs.scratch, opts) }?;
    // SAFETY: `input` is valid UTF-8 and the range falls on token edges
    // (ASCII boundaries).
    Ok(range.map(|(start, end)| unsafe { std::str::from_utf8_unchecked(&input[start..end]) }))
}

#[inline(always)]
fn skip_ws(input: &[u8], mut i: usize) -> usize {
    while let Some(&b) = input.get(i) {
        if matches!(b, b' ' | b'\t' | b'\n' | b'\r') {
            i += 1;
        } else {
            break;
        }
    }
    i
}

/// End offset of the value starting at `i` (whitespace already skipped).
/// Scalars run their tokenizer (fully validated); containers are skipped
/// structurally by [`stage1::container_end`].
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn value_end(
    input: &[u8],
    i: usize,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<usize, ParseError> {
    let eof = || ParseError::unexpected_end(input.len());
    match *input.get(i).ok_or_else(eof)? {
        // SAFETY: UTF-8 per this function's contract; `i` holds the `"`.
        b'"' => unsafe { scalars::parse_string(input, i, scratch) }
            .map(|(_, end)| end)
            .map_err(|e| ParseError::scalar(e, i)),
        b'-' | b'0'..=b'9' => scalars::parse_number(input, i)
            .map(|(_, end)| end)
            // `-Infinity` fails the number grammar first.
            .or_else(|e| nan_keyword_end(input, i, opts, ParseError::scalar(e, i))),
        b't' | b'f' | b'n' => scalars::parse_literal(input, i)
            .map(|(_, end)| end)
            .map_err(|e| ParseError::scalar(e, i)),
        b'{' | b'[' => stage1::container_end(input, i).ok_or_else(eof),
        _ => nan_keyword_end(input, i, opts, ParseError::unexpected_character(i)),
    }
}

/// End offset of the `allow_nan` keyword at `i`, or the error the strict
/// grammar reports there.
#[cold]
fn nan_keyword_end(
    input: &[u8],
    i: usize,
    opts: ParseOptions,
    strict: ParseError,
) -> Result<usize, ParseError> {
    if opts.allow_nan
        && let Some((_, end)) = scalars::parse_nan_keyword(input, i)
    {
        return Ok(end);
    }
    Err(strict)
}

/// After a member's `,` (whitespace skipped, `i` on the next token):
/// true when `opts` allow a trailing comma and `closer` ends the
/// container right here.
#[inline(always)]
fn trailing_close(input: &[u8], i: usize, opts: ParseOptions, closer: u8) -> bool {
    opts.allow_trailing_comma && input.get(i) == Some(&closer)
}

/// Walk the pointer tokens, returning the byte range of the match.
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn resolve(
    input: &[u8],
    pointer: &str,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<(usize, usize)>, ParseError> {
    let mut i = skip_ws(input, 0);

    if pointer.is_empty() {
        // The whole document is the match; enforce a complete document
        // like a full parse would.
        // SAFETY: forwarded UTF-8 contract.
        let end = unsafe { value_end(input, i, scratch, opts) }?;
        let trail = skip_ws(input, end);
        if trail != input.len() {
            return Err(ParseError::trailing_characters(trail));
        }
        return Ok(Some((i, end)));
    }

    let mut tokens = pointer.split('/').skip(1).peekable();
    while let Some(token) = tokens.next() {
        let is_last = tokens.peek().is_none();
        let value_pos = match input.get(i).copied() {
            None => return Err(ParseError::unexpected_end(input.len())),
            Some(b'{') => {
                // SAFETY: forwarded UTF-8 contract.
                unsafe { descend_object(input, i, token, scratch, opts) }?
            }
            Some(b'[') => {
                // SAFETY: forwarded UTF-8 contract.
                unsafe { descend_array(input, i, token, scratch, opts) }?
            }
            // A scalar cannot be descended into.
            Some(_) => None,
        };
        let Some(value_pos) = value_pos else {
            return Ok(None);
        };
        i = value_pos;
        if is_last {
            // SAFETY: forwarded UTF-8 contract.
            let end = unsafe { value_end(input, i, scratch, opts) }?;
            return Ok(Some((i, end)));
        }
    }
    unreachable!("the token loop returns on its last iteration");
}

/// Resolve many pointers in **one forward pass**, returning raw slices
/// positionally aligned with `pointers` (`None` where a pointer doesn't
/// match). Sequential [`pointer()`] calls re-scan the document prefix per
/// query; this walks it once, descending only into members some pointer
/// still needs and skipping everything else at block speed.
///
/// Duplicate keys resolve first-match, like [`pointer()`]. The walk stops
/// as soon as every pointer is resolved.
///
/// On **valid** JSON the result is exactly what resolving each pointer
/// individually would produce. On *malformed* documents the batch may
/// report an error where an individual [`pointer()`] call would return
/// `Ok(None)`: one pass scans every byte *some* pointer needs, so it can
/// reach malformed content that a lone query (which aborts at its first
/// missing key) never would.
///
/// ```
/// let mut bufs = nosj::Buffers::new();
/// let doc = r#"{"a":1,"b":{"c":2},"d":[3,4]}"#;
/// let got = nosj::pointers(doc, &["/d/1", "/a", "/x"], &mut bufs).unwrap();
/// assert_eq!(got, [Some("4"), Some("1"), None]);
/// ```
#[doc(alias = "get_many")]
pub fn pointers<'j>(
    input: &'j str,
    pointers: &[&str],
    bufs: &mut Buffers,
) -> Result<Vec<Option<&'j str>>, ParseError> {
    // SAFETY: &str is valid UTF-8.
    unsafe { pointers_utf8_unchecked(input.as_bytes(), pointers, bufs) }
}

/// Like [`pointers()`], with grammar extensions from [`ParseOptions`].
pub fn pointers_with<'j>(
    input: &'j str,
    pointers: &[&str],
    bufs: &mut Buffers,
    opts: ParseOptions,
) -> Result<Vec<Option<&'j str>>, ParseError> {
    // SAFETY: &str is valid UTF-8.
    unsafe { pointers_utf8_unchecked_with(input.as_bytes(), pointers, bufs, opts) }
}

/// Like [`pointers()`], for callers whose runtime vouches for UTF-8.
///
/// # Safety
///
/// `input` must be valid UTF-8.
pub unsafe fn pointers_utf8_unchecked<'j>(
    input: &'j [u8],
    pointers: &[&str],
    bufs: &mut Buffers,
) -> Result<Vec<Option<&'j str>>, ParseError> {
    // SAFETY: forwarded contract.
    unsafe { pointers_utf8_unchecked_with(input, pointers, bufs, ParseOptions::default()) }
}

/// Like [`pointers_utf8_unchecked`], with grammar extensions from
/// [`ParseOptions`].
///
/// # Safety
///
/// `input` must be valid UTF-8.
pub unsafe fn pointers_utf8_unchecked_with<'j>(
    input: &'j [u8],
    pointers: &[&str],
    bufs: &mut Buffers,
    opts: ParseOptions,
) -> Result<Vec<Option<&'j str>>, ParseError> {
    // Tokenize (and unescape) every pointer up front: once per token,
    // not once per level visit. The arena owns the tokens; queries borrow.
    let arena: Vec<Vec<Token<'_>>> = pointers
        .iter()
        .map(|ptr| {
            if ptr.is_empty() {
                Vec::new()
            } else {
                ptr.split('/').skip(1).map(Token::parse).collect()
            }
        })
        .collect();
    let mut queries: Vec<Query<'_>> = Vec::with_capacity(pointers.len());
    for (id, ptr) in pointers.iter().enumerate() {
        if !ptr.is_empty() && !ptr.starts_with('/') {
            return Err(ParseError {
                offset: 0,
                kind: ErrorKind::InvalidPointer,
            });
        }
        queries.push(Query {
            id,
            tokens: &arena[id],
        });
    }

    let mut results: Vec<Option<(usize, usize)>> = vec![None; pointers.len()];
    let mut remaining = queries.len();
    let start = skip_ws(input, 0);
    // SAFETY: forwarded UTF-8 contract.
    unsafe {
        resolve_set(
            input,
            start,
            &queries,
            &mut results,
            &mut remaining,
            &mut bufs.scratch,
            opts,
        )
    }?;
    // Root pointers keep the single-pointer contract of validating a
    // complete document; a root query always resolves, so its recorded
    // end is always available.
    if let Some(root) = pointers.iter().position(|p| p.is_empty()) {
        let (_, end) = results[root].expect("the root pointer always matches");
        let trail = skip_ws(input, end);
        if trail != input.len() {
            return Err(ParseError::trailing_characters(trail));
        }
    }
    Ok(results
        .into_iter()
        // SAFETY: `input` is valid UTF-8 and the ranges fall on token
        // edges (ASCII boundaries).
        .map(|r| r.map(|(s, e)| unsafe { std::str::from_utf8_unchecked(&input[s..e]) }))
        .collect())
}

/// One pre-tokenized pointer still being resolved: its slot in the
/// results and the tokens below the current level.
#[derive(Clone, Copy)]
struct Query<'p> {
    id: usize,
    tokens: &'p [Token<'p>],
}

/// One pointer token, unescaped once, with its array-index reading
/// precomputed.
struct Token<'p> {
    text: std::borrow::Cow<'p, str>,
    /// `Some` when the raw token is valid index syntax (digits, no
    /// leading zeros).
    index: Option<usize>,
}

impl<'p> Token<'p> {
    fn parse(raw: &'p str) -> Token<'p> {
        let valid_index = !raw.is_empty()
            && raw.bytes().all(|b| b.is_ascii_digit())
            && (raw == "0" || !raw.starts_with('0'));
        Token {
            // `~1` -> `/`, then `~0` -> `~` (RFC 6901 order).
            text: if raw.contains('~') {
                raw.replace("~1", "/").replace("~0", "~").into()
            } else {
                raw.into()
            },
            index: if valid_index { raw.parse().ok() } else { None },
        }
    }
}

/// Resolve `queries` against the value at `i`. Returns `Some(end)` of the
/// value, or `None` when every pointer in the whole batch has been
/// resolved (the abort signal; no caller needs positions after that).
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn resolve_set(
    input: &[u8],
    i: usize,
    queries: &[Query<'_>],
    results: &mut Vec<Option<(usize, usize)>>,
    remaining: &mut usize,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<usize>, ParseError> {
    let deeper: Vec<Query<'_>> = queries
        .iter()
        .copied()
        .filter(|q| !q.tokens.is_empty())
        .collect();

    let end = match input.get(i).copied() {
        None => return Err(ParseError::unexpected_end(input.len())),
        Some(b'{') if !deeper.is_empty() => {
            // SAFETY: forwarded UTF-8 contract.
            let walked =
                unsafe { walk_object(input, i, &deeper, results, remaining, scratch, opts) }?;
            match walked {
                Some(end) => end,
                None => return Ok(None),
            }
        }
        Some(b'[') if !deeper.is_empty() => {
            // SAFETY: forwarded UTF-8 contract.
            let walked =
                unsafe { walk_array(input, i, &deeper, results, remaining, scratch, opts) }?;
            match walked {
                Some(end) => end,
                None => return Ok(None),
            }
        }
        // Scalar, or a container no pointer descends into: one skip.
        // SAFETY: forwarded UTF-8 contract.
        _ => unsafe { value_end(input, i, scratch, opts) }?,
    };

    for q in queries {
        if q.tokens.is_empty() {
            results[q.id] = Some((i, end));
            *remaining -= 1;
        }
    }
    if *remaining == 0 {
        return Ok(None);
    }
    Ok(Some(end))
}

/// Walk one object once, recursing into members some query names.
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn walk_object(
    input: &[u8],
    mut i: usize,
    deeper: &[Query<'_>],
    results: &mut Vec<Option<(usize, usize)>>,
    remaining: &mut usize,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<usize>, ParseError> {
    i = skip_ws(input, i + 1);
    if input.get(i) == Some(&b'}') {
        return Ok(Some(i + 1)); // empty object
    }
    // First-match-wins, hit or miss: the first member with a matching key
    // consumes the query, so a later duplicate key can never re-resolve
    // it (parity with single [`pointer()`] resolution).
    let mut live: Vec<Query<'_>> = deeper.to_vec();
    loop {
        if input.get(i) != Some(&b'"') {
            // Past the first member, so a `}` here follows a comma.
            if trailing_close(input, i, opts, b'}') {
                return Ok(Some(i + 1));
            }
            return Err(ParseError::expected("'\"'", i));
        }
        // SAFETY: forwarded UTF-8 contract; `i` holds a `"`.
        let (part, key_end) = unsafe { scalars::parse_string(input, i, scratch) }
            .map_err(|e| ParseError::scalar(e, i))?;
        // WTF-8 keys cannot equal a &str pointer token.
        let mut advanced: Vec<Query<'_>> = Vec::new();
        if let StrPart::Borrowed(k) | StrPart::Decoded(k) = part {
            live.retain(|q| {
                let hit = q.tokens[0].text == k;
                if hit {
                    advanced.push(Query {
                        id: q.id,
                        tokens: &q.tokens[1..],
                    });
                }
                !hit
            });
        }
        i = skip_ws(input, key_end);
        if input.get(i) != Some(&b':') {
            return Err(ParseError::expected("':'", i));
        }
        i = skip_ws(input, i + 1);
        let value_past = if advanced.is_empty() {
            // SAFETY: forwarded UTF-8 contract.
            unsafe { value_end(input, i, scratch, opts) }?
        } else {
            // SAFETY: forwarded UTF-8 contract.
            match unsafe { resolve_set(input, i, &advanced, results, remaining, scratch, opts) }? {
                Some(end) => end,
                None => return Ok(None),
            }
        };
        i = skip_ws(input, value_past);
        match input.get(i) {
            Some(b',') => i = skip_ws(input, i + 1),
            Some(b'}') => return Ok(Some(i + 1)),
            Some(_) => return Err(ParseError::expected("',' or '}'", i)),
            None => return Err(ParseError::unexpected_end(input.len())),
        }
    }
}

/// Walk one array once, recursing at indices some query names.
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn walk_array(
    input: &[u8],
    mut i: usize,
    deeper: &[Query<'_>],
    results: &mut Vec<Option<(usize, usize)>>,
    remaining: &mut usize,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<usize>, ParseError> {
    i = skip_ws(input, i + 1);
    if input.get(i) == Some(&b']') {
        return Ok(Some(i + 1)); // empty array
    }
    // Elements past the largest queried index are skipped, not walked.
    let max_wanted = deeper.iter().filter_map(|q| q.tokens[0].index).max();
    let mut element = 0usize;
    loop {
        let advanced: Vec<Query<'_>> = deeper
            .iter()
            .filter(|q| q.tokens[0].index == Some(element))
            .map(|q| Query {
                id: q.id,
                tokens: &q.tokens[1..],
            })
            .collect();
        let value_past = if advanced.is_empty() {
            // SAFETY: forwarded UTF-8 contract.
            unsafe { value_end(input, i, scratch, opts) }?
        } else {
            // SAFETY: forwarded UTF-8 contract.
            match unsafe { resolve_set(input, i, &advanced, results, remaining, scratch, opts) }? {
                Some(end) => end,
                None => return Ok(None),
            }
        };
        i = skip_ws(input, value_past);
        match input.get(i) {
            Some(b',') => {
                i = skip_ws(input, i + 1);
                if trailing_close(input, i, opts, b']') {
                    return Ok(Some(i + 1));
                }
            }
            Some(b']') => return Ok(Some(i + 1)),
            Some(_) => return Err(ParseError::expected("',' or ']'", i)),
            None => return Err(ParseError::unexpected_end(input.len())),
        }
        element += 1;
        // Nothing deeper wants later elements; no caller needs this
        // array's end if the whole batch resolves inside it, but the
        // parent still might, so skip the remainder structurally.
        if max_wanted.is_some_and(|m| element > m) {
            // Rewind to the opener is impossible; finish by skipping
            // element-by-element (cheap: container_end per element).
            loop {
                // SAFETY: forwarded UTF-8 contract.
                let past = unsafe { value_end(input, i, scratch, opts) }?;
                i = skip_ws(input, past);
                match input.get(i) {
                    Some(b',') => {
                        i = skip_ws(input, i + 1);
                        if trailing_close(input, i, opts, b']') {
                            return Ok(Some(i + 1));
                        }
                    }
                    Some(b']') => return Ok(Some(i + 1)),
                    Some(_) => return Err(ParseError::expected("',' or ']'", i)),
                    None => return Err(ParseError::unexpected_end(input.len())),
                }
            }
        }
    }
}

/// One object level: find `token`'s value, skipping non-matching members.
/// `i` is at the `{`; returns the matched value's position, or `None`
/// when the key is absent.
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn descend_object(
    input: &[u8],
    mut i: usize,
    token: &str,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<usize>, ParseError> {
    // Unescape once per level: `~1` -> `/`, then `~0` -> `~` (RFC 6901
    // order). Clean tokens compare borrowed.
    let unescaped: std::borrow::Cow<'_, str> = if token.contains('~') {
        token.replace("~1", "/").replace("~0", "~").into()
    } else {
        token.into()
    };
    i = skip_ws(input, i + 1);
    if input.get(i) == Some(&b'}') {
        return Ok(None); // empty object
    }
    loop {
        if input.get(i) != Some(&b'"') {
            // Past the first member, so a `}` here follows a comma.
            if trailing_close(input, i, opts, b'}') {
                return Ok(None); // key not present
            }
            return Err(ParseError::expected("'\"'", i));
        }
        // SAFETY: forwarded UTF-8 contract; `i` holds a `"`.
        let (part, key_end) = unsafe { scalars::parse_string(input, i, scratch) }
            .map_err(|e| ParseError::scalar(e, i))?;
        let matched = match part {
            StrPart::Borrowed(k) | StrPart::Decoded(k) => k == unescaped,
            // WTF-8 keys cannot equal a &str pointer token.
            StrPart::DecodedRaw(_) => false,
        };
        i = skip_ws(input, key_end);
        if input.get(i) != Some(&b':') {
            return Err(ParseError::expected("':'", i));
        }
        i = skip_ws(input, i + 1);
        if matched {
            return Ok(Some(i)); // the value at `i` is this level's match
        }
        // SAFETY: forwarded UTF-8 contract.
        let value_past = unsafe { value_end(input, i, scratch, opts) }?;
        i = skip_ws(input, value_past);
        match input.get(i) {
            Some(b',') => i = skip_ws(input, i + 1),
            Some(b'}') => return Ok(None), // key not present
            Some(_) => return Err(ParseError::expected("',' or '}'", i)),
            None => return Err(ParseError::unexpected_end(input.len())),
        }
    }
}

/// One array level: find element `token`'s position, skipping earlier
/// elements. `i` is at the `[`; returns `None` for out-of-range indices
/// or tokens that are not valid index syntax.
///
/// # Safety
///
/// `input` must be valid UTF-8.
unsafe fn descend_array(
    input: &[u8],
    mut i: usize,
    token: &str,
    scratch: &mut Vec<u8>,
    opts: ParseOptions,
) -> Result<Option<usize>, ParseError> {
    // Array-index tokens are digits without leading zeros; anything else
    // ("-", "01", "1x", "") cannot match.
    let valid = !token.is_empty()
        && token.bytes().all(|b| b.is_ascii_digit())
        && (token == "0" || !token.starts_with('0'));
    let target = if valid {
        token.parse::<usize>().ok()
    } else {
        None
    };
    let Some(target) = target else {
        return Ok(None);
    };
    i = skip_ws(input, i + 1);
    if input.get(i) == Some(&b']') {
        return Ok(None); // empty array
    }
    for _ in 0..target {
        // SAFETY: forwarded UTF-8 contract.
        let value_past = unsafe { value_end(input, i, scratch, opts) }?;
        i = skip_ws(input, value_past);
        match input.get(i) {
            Some(b',') => {
                i = skip_ws(input, i + 1);
                if trailing_close(input, i, opts, b']') {
                    return Ok(None); // out of range
                }
            }
            Some(b']') => return Ok(None), // out of range
            Some(_) => return Err(ParseError::expected("',' or ']'", i)),
            None => return Err(ParseError::unexpected_end(input.len())),
        }
    }
    Ok(Some(i))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get<'j>(doc: &'j str, ptr: &str) -> Option<&'j str> {
        let mut bufs = Buffers::new();
        pointer(doc, ptr, &mut bufs).unwrap()
    }

    /// The RFC 6901 §5 example document and pointer set.
    #[test]
    fn rfc6901_examples() {
        let doc = r#"{
            "foo": ["bar", "baz"],
            "": 0,
            "a/b": 1,
            "c%d": 2,
            "e^f": 3,
            "g|h": 4,
            "i\\j": 5,
            "k\"l": 6,
            " ": 7,
            "m~n": 8
        }"#;
        assert_eq!(get(doc, ""), Some(doc.trim()));
        assert_eq!(get(doc, "/foo"), Some(r#"["bar", "baz"]"#));
        assert_eq!(get(doc, "/foo/0"), Some("\"bar\""));
        assert_eq!(get(doc, "/"), Some("0"));
        assert_eq!(get(doc, "/a~1b"), Some("1"));
        assert_eq!(get(doc, "/c%d"), Some("2"));
        assert_eq!(get(doc, "/e^f"), Some("3"));
        assert_eq!(get(doc, "/g|h"), Some("4"));
        assert_eq!(get(doc, "/i\\j"), Some("5"));
        assert_eq!(get(doc, "/k\"l"), Some("6"));
        assert_eq!(get(doc, "/ "), Some("7"));
        assert_eq!(get(doc, "/m~0n"), Some("8"));
    }

    #[test]
    fn misses_are_none() {
        let doc = r#"{"a":[10,20],"b":{"c":true}}"#;
        assert_eq!(get(doc, "/missing"), None);
        assert_eq!(get(doc, "/a/2"), None); // out of range
        assert_eq!(get(doc, "/a/-"), None); // past-the-end token
        assert_eq!(get(doc, "/a/01"), None); // leading zero
        assert_eq!(get(doc, "/a/x"), None); // not an index
        assert_eq!(get(doc, "/a/0/deeper"), None); // scalar descent
        assert_eq!(get(doc, "/b/c/d"), None);
        assert_eq!(get("[]", "/0"), None); // empty array
    }

    #[test]
    fn nested_and_escaped() {
        let doc = r#"{"a":{"b":[{"deep":[1,{"x":"found"}]}]},"z":9}"#;
        assert_eq!(get(doc, "/a/b/0/deep/1/x"), Some("\"found\""));
        assert_eq!(get(doc, "/z"), Some("9"));
        // Keys with escapes in the document decode before comparing.
        let doc = r#"{"k\ney": 42}"#;
        assert_eq!(get(doc, "/k\ney"), Some("42"));
        // Duplicate keys: first occurrence wins.
        let doc = r#"{"d":1,"d":2}"#;
        assert_eq!(get(doc, "/d"), Some("1"));
        // Brackets and quotes inside skipped strings don't confuse the
        // structural skip.
        let doc = r#"{"skip":["}{][", "a\"b", {"x":"]"}],"hit":1}"#;
        assert_eq!(get(doc, "/hit"), Some("1"));
    }

    #[test]
    fn errors() {
        let mut bufs = Buffers::new();
        // Malformed pointer syntax.
        assert_eq!(
            pointer("{}", "no-slash", &mut bufs).unwrap_err().kind,
            ErrorKind::InvalidPointer
        );
        // Malformed document still errors even when skipping.
        assert!(pointer("{\"a\":", "/a", &mut bufs).is_err());
        assert!(pointer("[1,2", "/5", &mut bufs).is_err());
    }

    /// The batch resolver must agree with sequential single resolution
    /// on every pointer, in every combination.
    #[test]
    fn batch_matches_sequential() {
        let doc = r#"{
            "users": [{"name":"ada","tags":[1,2]},{"name":"grace"}],
            "a/b": 5, "m~n": {"deep": true}, "empty": {}, "arr": []
        }"#;
        let ptrs = [
            "/users/1/name",
            "/users/0/tags/1",
            "/users/0/name",
            "/missing",
            "/users/5",
            "/a~1b",
            "/m~0n/deep",
            "/empty/x",
            "/arr/0",
            "/users/0/tags",
            "",
        ];
        let mut bufs = Buffers::new();
        let batch = pointers(doc, &ptrs, &mut bufs).unwrap();
        for (ptr, got) in ptrs.iter().zip(&batch) {
            let single = pointer(doc, ptr, &mut bufs).unwrap();
            assert_eq!(*got, single, "pointer {ptr:?}");
        }
        // Duplicate pointers each get their own aligned answer.
        let batch = pointers(doc, &["/a~1b", "/a~1b"], &mut bufs).unwrap();
        assert_eq!(batch, [Some("5"), Some("5")]);
        // Empty batch is a no-op.
        assert_eq!(
            pointers(doc, &[], &mut bufs).unwrap(),
            Vec::<Option<&str>>::new()
        );
        // Malformed pointer syntax errors the whole call.
        assert!(pointers(doc, &["/ok", "bad"], &mut bufs).is_err());
    }

    /// A duplicate key must not re-resolve a query its first match
    /// already consumed, even when the first match was a dead end.
    #[test]
    fn batch_duplicate_keys_first_match_wins() {
        let mut bufs = Buffers::new();
        let doc = r#"{"a":8,"a":{"b":9}}"#;
        assert_eq!(pointer(doc, "/a/b", &mut bufs), Ok(None));
        assert_eq!(
            pointers(doc, &["/a/b", "/a"], &mut bufs).unwrap(),
            [None, Some("8")]
        );
    }

    /// Documented asymmetry: on malformed documents the batch resolver
    /// may error where single resolution misses, because one pass scans
    /// every byte some pointer needs.
    #[test]
    fn batch_validates_what_it_scans() {
        let mut bufs = Buffers::new();
        assert_eq!(pointer("-", "/", &mut bufs), Ok(None));
        assert!(pointers("-", &["/"], &mut bufs).is_err());
    }

    /// The matched slice re-parses to the same thing a full walk sees.
    #[test]
    fn slice_reparses() {
        let doc = r#"{"list":[{"n":1.5},{"n":"two"},{"n":[3]}]}"#;
        for (ptr, expected) in [
            ("/list/0", r#"{"n":1.5}"#),
            ("/list/1/n", "\"two\""),
            ("/list/2/n", "[3]"),
        ] {
            let raw = get(doc, ptr).unwrap();
            assert_eq!(raw, expected);
            let mut bufs = Buffers::new();
            let mut p = crate::Reader::new(raw, &mut bufs);
            p.skip_value().unwrap();
            p.finish().unwrap();
        }
    }

    /// Hits, misses past the extension, and whole-document pointers
    /// resolve under the matching option, single and batched alike,
    /// while the default resolvers keep rejecting what they walk into.
    #[test]
    fn parse_options_extend_resolution() {
        let trailing = ParseOptions {
            allow_trailing_comma: true,
            ..ParseOptions::default()
        };
        let nan = ParseOptions {
            allow_nan: true,
            ..ParseOptions::default()
        };
        let cases: &[(&str, ParseOptions, &str, Option<&str>)] = &[
            (r#"{"a":1,"b":[3,],}"#, trailing, "/b", Some("[3,]")),
            (r#"{"a":1,"b":[3,],}"#, trailing, "/z", None),
            (r#"{"a":1,"b":[3,],}"#, trailing, "/b/0", Some("3")),
            (r#"{"a":1,"b":[3,],}"#, trailing, "/b/1", None),
            ("[1,2,]", trailing, "/1", Some("2")),
            ("[1,2,]", trailing, "/2", None),
            ("[1, 2 , ]", trailing, "/5", None),
            ("[[1,],[2,],]", trailing, "/1/0", Some("2")),
            ("[1,2,]", trailing, "", Some("[1,2,]")),
            (r#"{"a":NaN,"b":1}"#, nan, "/b", Some("1")),
            (r#"{"a":NaN,"b":1}"#, nan, "/a", Some("NaN")),
            (r#"{"a":NaN,"b":1}"#, nan, "/z", None),
            ("[-Infinity,Infinity]", nan, "/1", Some("Infinity")),
            ("[-Infinity,Infinity]", nan, "/0", Some("-Infinity")),
            ("-Infinity", nan, "", Some("-Infinity")),
        ];
        let mut bufs = Buffers::new();
        for &(doc, opts, ptr, want) in cases {
            assert_eq!(
                pointer_with(doc, ptr, &mut bufs, opts).unwrap(),
                want,
                "{doc} {ptr}"
            );
            assert_eq!(
                pointers_with(doc, &[ptr], &mut bufs, opts).unwrap(),
                [want],
                "{doc} {ptr} batch"
            );
        }
        // Default resolvers stay strict wherever they walk the extension.
        for (doc, ptr) in [
            (r#"{"a":1,}"#, "/z"),
            ("[1,2,]", "/2"),
            (r#"{"a":NaN,"b":1}"#, "/b"),
            ("[NaN]", "/0"),
        ] {
            assert!(pointer(doc, ptr, &mut bufs).is_err(), "{doc} {ptr}");
            assert!(
                pointers(doc, &[ptr], &mut bufs).is_err(),
                "{doc} {ptr} batch"
            );
        }
        // Options never loosen anything else.
        for (doc, ptr) in [("[1,,]", "/5"), (r#"{"a":1,,}"#, "/z"), ("[,]", "/0")] {
            assert!(
                pointer_with(doc, ptr, &mut bufs, trailing).is_err(),
                "{doc} {ptr}"
            );
        }
        assert!(pointer_with("[Nan,1]", "/1", &mut bufs, nan).is_err());
    }
}