grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/io/scan.rs
// Purpose:   The sans-IO scanner that finds frames in a buffer the caller owns
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scanner`] reads the front of a buffer the caller owns and says what the
//! next frame is and how many bytes to drop. It never copies and never holds
//! bytes: a frame cut across reads stays in the caller's buffer until its end
//! arrives, and one over `max_bytes` is reported and then dropped as it
//! arrives.

use std::ops::Range;

use memchr::memchr;

use super::{Frame, frame_of};
use crate::parse::{CarriageReturns, RS, Scan, ScanStep, StreamConfig, StreamSplit, space};

/// What [`Scanner::next`] found at the front of the buffer.
///
/// Each variant with a `consume` says how many bytes to drop from the front
/// of the buffer before the next call. Ranges index the buffer that call
/// was given.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Step {
    /// One record, at `record`. `consume` covers it, its delimiter and any
    /// blank lines or whitespace before it.
    Record {
        /// Bytes to drop.
        consume: usize,
        /// Where the record is.
        record: Range<usize>,
    },
    /// A frame over `max_bytes`, left out.
    Oversize {
        /// Bytes to drop.
        consume: usize,
        /// Its length in the stream, a counted frame's header and a line's
        /// delimiter included, when its end or its count is in the buffer.
        /// Otherwise the bytes seen so far, and
        /// [`discarding`](Scanner::discarding) is true until later steps
        /// have dropped the rest of it.
        len: u64,
        /// Its first `max_bytes` bytes, or fewer when the end of input came
        /// first.
        head: Range<usize>,
    },
    /// Bytes a JSON split couldn't read.
    Malformed {
        /// Bytes to drop.
        consume: usize,
        /// Where, as a stream offset.
        offset: u64,
        /// What is wrong there.
        reason: &'static str,
    },
    /// Bytes to drop with nothing to report: blank lines, whitespace, a run
    /// of junk already reported or the rest of an oversize frame.
    Skip {
        /// Bytes to drop.
        consume: usize,
    },
    /// The end of input came inside a counted frame, a JSON value, a sequence
    /// text or a JSON array before its `]`. The last step of a stream: drop
    /// the buffer.
    Cut {
        /// The bytes seen of it.
        len: u64,
    },
    /// No frame ends in the buffer. Call again with more bytes after the
    /// same front, or with `eof` at the end of input.
    Need,
}

impl Step {
    /// The bytes to drop from the front of `buf`, the buffer the step was
    /// read from: all of it for [`Cut`](Self::Cut), none for
    /// [`Need`](Self::Need).
    #[must_use]
    #[inline]
    pub const fn consume(&self, buf: &[u8]) -> usize {
        match *self {
            Self::Record { consume, .. }
            | Self::Oversize { consume, .. }
            | Self::Malformed { consume, .. }
            | Self::Skip { consume } => consume,
            Self::Cut { .. } => buf.len(),
            Self::Need => 0,
        }
    }
}

/// Finds the frames of a [`StreamConfig`] split in a buffer the caller owns.
///
/// Call [`next`](Self::next) with the buffer, drop the step's bytes from its
/// front, and call again. On [`Step::Need`] read more bytes onto the end of
/// the buffer first. Pass `eof` once the input has ended. The scanner
/// remembers how far it searched, so a frame cut across many reads is
/// searched once.
///
/// ```
/// use grippo::io::{Scanner, Step};
/// use grippo::parse::{StreamConfig, StreamSplit};
///
/// let mut config = StreamConfig::default();
/// config.split = StreamSplit::OctetCounted;
/// let mut scanner = Scanner::new(&config);
/// let mut buf = b"15 <13>hello w".to_vec();
/// assert_eq!(scanner.next(&buf, false), Step::Need);
/// buf.extend_from_slice(b"orld<14>bye\n");
/// let mut records = Vec::new();
/// loop {
///     let step = scanner.next(&buf, false);
///     if let Step::Record { record, .. } = &step {
///         records.push(buf[record.clone()].to_vec());
///     }
///     if step == Step::Need {
///         break;
///     }
///     buf.drain(..step.consume(&buf));
/// }
/// assert_eq!(records, [&b"<13>hello world"[..], b"<14>bye"]);
/// assert_eq!(scanner.consumed(), 26);
/// assert_eq!(scanner.partial_len(), 0);
/// ```
#[derive(Debug, Clone)]
pub struct Scanner {
    split: StreamSplit,
    /// An LF or NUL split's delimiter and whether it strips `\r`s, for the
    /// inlined path. `None` until the stream's start has ruled a byte order
    /// mark in or out, so that path needs no check of its own.
    line: Option<(u8, bool)>,
    /// What `line` becomes once the start is settled.
    line_split: Option<(u8, bool)>,
    /// Whether a byte order mark may still be at the stream's start.
    bom: bool,
    max: usize,
    /// Whether an LF line drops the `\r`s before its `\n`.
    strip: bool,
    /// The largest octet count taken as a frame.
    limit: u64,
    consumed: u64,
    partial: usize,
    /// Bytes at the front of the buffer already searched for the frame's end.
    seen: usize,
    skip: Skip,
    /// The JSON value at the front of the buffer, when it has no end yet.
    value: Option<Value>,
    array: ArrayAt,
    /// The stream offset of a JSON array's `[`.
    opened: u64,
    /// Whether the last bytes read were a run of junk already reported.
    junk: bool,
}

/// What the scanner drops before it frames again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Skip {
    Off,
    /// Up to and including this byte.
    To(u8),
    /// This many bytes.
    Count(u64),
    /// To the end of this JSON value.
    Value(Value),
}

/// A JSON value being read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Value {
    scan: Scan,
    /// Whether it began as a number or a literal.
    scalar: bool,
}

impl Value {
    const fn new(scan: Scan) -> Self {
        Self {
            scan,
            scalar: scan.scalar(),
        }
    }
}

/// Where the stream stands in the one JSON array a `json_array` split reads.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum ArrayAt {
    /// Before the `[`.
    #[default]
    Open,
    /// After the `[`: an element or the `]`.
    First,
    /// After a comma: an element.
    Next,
    /// After an element: a comma or the `]`.
    After,
    /// After the `]`.
    Done,
    /// After bytes that aren't an array, which the rest of the stream is.
    Spent,
}

/// How the frame at the front of an octet-counted stream is framed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Head {
    /// Counted: `count` record bytes after a header of `body` bytes.
    Counted { count: u64, body: usize },
    /// Not known until more bytes arrive.
    More,
    /// An LF line.
    Line,
}

const NO_VALUE: &str = "a byte no JSON value starts with";

/// The UTF-8 byte order mark.
const BOM: &[u8; 3] = b"\xef\xbb\xbf";

#[inline]
fn wide(n: usize) -> u64 {
    u64::try_from(n).unwrap_or(u64::MAX)
}

impl Scanner {
    /// A scanner for `config`.
    #[must_use]
    pub fn new(config: &StreamConfig) -> Self {
        let strip = config.carriage_returns == CarriageReturns::Strip;
        let line_split = match config.split {
            StreamSplit::Lf => Some((b'\n', strip)),
            StreamSplit::Nul => Some((0, false)),
            _ => None,
        };
        Self {
            split: config.split,
            line: if config.strip_bom { None } else { line_split },
            line_split,
            bom: config.strip_bom,
            max: config.max_bytes,
            strip,
            limit: wide(config.max_frame_bytes.max(config.max_bytes)),
            consumed: 0,
            partial: 0,
            seen: 0,
            skip: Skip::Off,
            value: None,
            array: ArrayAt::Open,
            opened: 0,
            junk: false,
        }
    }

    /// Read the front of `buf`, the stream's bytes not yet dropped, for the
    /// next frame. `eof` says no bytes follow `buf`.
    ///
    /// The caller drops the step's [`consume`](Step::consume) bytes from the
    /// front of `buf` before the next call, and keeps the rest.
    #[inline]
    pub fn next(&mut self, buf: &[u8], eof: bool) -> Step {
        // A whole LF or NUL line at the front is the common step, so it inlines into the caller's loop.
        if let Some((delimiter, strip)) = self.line
            && matches!(self.skip, Skip::Off)
            && let Some(unseen) = buf.get(self.seen..)
            && let Some(i) = memchr(delimiter, unseen)
        {
            let end = self.seen + i;
            let stop = if strip && end > 0 && buf[end - 1] == b'\r' {
                before_crs(buf, 0, end)
            } else {
                end
            };
            if stop > 0 && end <= self.max {
                self.seen = 0;
                self.partial = 0;
                self.consumed += wide(end + 1);
                return Step::Record {
                    consume: end + 1,
                    record: 0..stop,
                };
            }
        }
        self.slow(buf, eof)
    }

    /// Give `f` every frame `buf` holds, in order, and return how many bytes
    /// to drop from its front: the steps [`next`](Self::next) would take,
    /// run until it would say [`Step::Need`]. A [`Frame::Cut`] ends the
    /// stream and drops all of `buf`.
    ///
    /// The batch form of `next`: whole LF and NUL lines go through one
    /// memchr loop with the scanner's state in locals, which costs less per
    /// frame than a call each.
    ///
    /// ```
    /// use grippo::io::{Frame, Scanner};
    /// use grippo::parse::StreamConfig;
    ///
    /// let mut scanner = Scanner::new(&StreamConfig::default());
    /// let mut buf = b"a\nb\r\n\nc".to_vec();
    /// let mut records = Vec::new();
    /// let used = scanner.each(&buf, false, |frame| {
    ///     if let Frame::Record(line) = frame {
    ///         records.push(line.to_vec());
    ///     }
    /// });
    /// buf.drain(..used);
    /// assert_eq!(records, [b"a".to_vec(), b"b".to_vec()]);
    /// assert_eq!(buf, b"c");
    /// ```
    #[inline]
    pub fn each<'b>(
        &mut self,
        buf: &'b [u8],
        eof: bool,
        mut f: impl FnMut(Frame<&'b [u8]>),
    ) -> usize {
        let mut at = 0;
        loop {
            // The one inlined call of `f`, so the caller's closure builds its frame in place.
            at += self.lines(&buf[at..], |line| f(Frame::Record(line)));
            let rest = &buf[at..];
            let step = self.next(rest, eof);
            if step == Step::Need {
                return at;
            }
            at += give(&step, rest, &mut f);
            if matches!(step, Step::Cut { .. }) {
                return buf.len();
            }
        }
    }

    /// Give `each` every whole LF or NUL line at the front of `buf`, blank
    /// lines dropped, and return the bytes they took: one memchr a line with
    /// the scanner's state kept in locals. It stops at the first frame that
    /// needs [`next`](Self::next): an oversize line, a split that isn't LF or
    /// NUL, a skip, or no delimiter, whose search it saves.
    #[inline]
    pub(crate) fn lines<'b>(&mut self, buf: &'b [u8], mut each: impl FnMut(&'b [u8])) -> usize {
        let Some((delimiter, strip)) = self.line else {
            return 0;
        };
        // A line searched part way is the step's to finish.
        if !matches!(self.skip, Skip::Off) || self.seen > 0 {
            return 0;
        }
        let max = self.max;
        let mut at = 0;
        loop {
            let Some(i) = memchr(delimiter, &buf[at..]) else {
                // The next step starts its search past the bytes this one searched.
                self.seen = buf.len() - at;
                break;
            };
            let line = &buf[at..at + i];
            if line.len() > max {
                break;
            }
            at += i + 1;
            let line = match line {
                [rest @ .., b'\r'] if strip => trim_crs(rest),
                _ => line,
            };
            if !line.is_empty() {
                each(line);
            }
        }
        self.partial = 0;
        self.consumed += wide(at);
        at
    }

    /// Every step the inlined path in [`next`](Self::next) doesn't take.
    #[inline(never)]
    fn slow(&mut self, buf: &[u8], eof: bool) -> Step {
        let step = self.step(buf, eof);
        self.partial = 0;
        match &step {
            Step::Need => self.partial = buf.len(),
            Step::Cut { .. } => {
                self.consumed += wide(buf.len());
                self.restart();
            }
            Step::Record { consume, .. }
            | Step::Oversize { consume, .. }
            | Step::Malformed { consume, .. }
            | Step::Skip { consume } => self.consumed += wide(*consume),
        }
        step
    }

    /// Stream bytes the steps so far have dropped: the stream offset of the
    /// buffer's front.
    #[must_use]
    pub const fn consumed(&self) -> u64 {
        self.consumed
    }

    /// Bytes at the front of the buffer the last step left there: the start
    /// of a frame whose end hasn't arrived. Zero after any step but
    /// [`Step::Need`].
    #[must_use]
    pub const fn partial_len(&self) -> usize {
        self.partial
    }

    /// Whether the scanner is dropping the rest of an oversize frame it has
    /// reported, or of a sequence text that isn't well formed.
    #[must_use]
    pub const fn discarding(&self) -> bool {
        !matches!(self.skip, Skip::Off)
    }

    /// The stream's start has ruled a byte order mark in or out.
    const fn settle(&mut self) {
        self.bom = false;
        self.line = self.line_split;
    }

    /// Forget the frame in progress after a cut, keeping the count.
    const fn restart(&mut self) {
        self.seen = 0;
        self.skip = Skip::Off;
        self.value = None;
        self.array = ArrayAt::Open;
        self.opened = 0;
        self.junk = false;
    }

    fn step(&mut self, buf: &[u8], eof: bool) -> Step {
        if self.bom {
            if buf.starts_with(BOM) {
                self.settle();
                return Step::Skip { consume: BOM.len() };
            }
            // A start that may yet be a mark is held, and one that can't be frames as it is.
            if BOM.starts_with(buf) && !eof {
                return Step::Need;
            }
            self.settle();
        }
        if !matches!(self.skip, Skip::Off) {
            if let Some(step) = self.pass(buf) {
                return step;
            }
            // Still skipping here means `buf` is empty.
            if !matches!(self.skip, Skip::Off) {
                if !eof {
                    return Step::Need;
                }
                self.skip = Skip::Off;
            }
        }
        match self.split {
            StreamSplit::Lf => self.delimited(b'\n', self.strip, buf, eof),
            StreamSplit::Nul => self.delimited(0, false, buf, eof),
            StreamSplit::OctetCounted => self.counted(buf, eof),
            StreamSplit::JsonConcat => self.json(false, buf, eof),
            StreamSplit::JsonSeq => self.json(true, buf, eof),
            StreamSplit::JsonArray => self.array(buf, eof),
        }
    }

    /// Drop what `buf` holds of the frame being skipped, or `None` when the
    /// skip ends at its front or `buf` is empty.
    fn pass(&mut self, buf: &[u8]) -> Option<Step> {
        while !buf.is_empty() {
            let consume = match self.skip {
                Skip::Off => return None,
                Skip::To(delimiter) => memchr(delimiter, buf).map_or(buf.len(), |i| {
                    self.skip = Skip::Off;
                    i + 1
                }),
                Skip::Count(n) => {
                    let take = usize::try_from(n).map_or(buf.len(), |n| n.min(buf.len()));
                    let left = n - wide(take);
                    self.skip = if left == 0 {
                        Skip::Off
                    } else {
                        Skip::Count(left)
                    };
                    take
                }
                Skip::Value(mut value) => {
                    let seq = self.split == StreamSplit::JsonSeq;
                    match value.scan.run(buf, 0, seq) {
                        ScanStep::End(end) => {
                            // RFC 7464 drops a number with no whitespace after it up to the next RS.
                            let bad = seq && value.scalar && !ends_well(buf, end);
                            self.skip = if bad { Skip::To(RS) } else { Skip::Off };
                            if self.split == StreamSplit::JsonArray {
                                self.array = ArrayAt::After;
                            }
                            end
                        }
                        ScanStep::Cut(at) => {
                            self.skip = Skip::Off;
                            at
                        }
                        ScanStep::More => {
                            self.skip = Skip::Value(value);
                            buf.len()
                        }
                    }
                }
            };
            if consume > 0 {
                return Some(Step::Skip { consume });
            }
        }
        None
    }

    /// Wait for more bytes after a frame that starts at `start`, searched to
    /// `searched`, dropping what comes before it first.
    const fn wait(&mut self, start: usize, searched: usize) -> Step {
        self.seen = searched - start;
        if start > 0 {
            Step::Skip { consume: start }
        } else {
            Step::Need
        }
    }

    /// Report the frame from `start` as oversize, `consume` bytes dropped.
    fn oversize(&mut self, consume: usize, len: u64, start: usize, buf: &[u8]) -> Step {
        self.seen = 0;
        let head_end = (start + self.max).min(buf.len());
        Step::Oversize {
            consume,
            len,
            head: start..head_end,
        }
    }

    fn bad(&self, consume: usize, at: usize, reason: &'static str) -> Step {
        Step::Malformed {
            consume,
            offset: self.consumed + wide(at),
            reason,
        }
    }

    /// The last line, from `start` to the end of input, with its ASCII
    /// whitespace trimmed, or nothing when none is left.
    fn last(&mut self, buf: &[u8], start: usize) -> Step {
        self.seen = 0;
        let line = &buf[start..];
        let end = line
            .iter()
            .rposition(|b| !b.is_ascii_whitespace())
            .map_or(0, |i| i + 1);
        let begin = line[..end]
            .iter()
            .position(|b| !b.is_ascii_whitespace())
            .unwrap_or(end);
        if begin < end {
            Step::Record {
                consume: buf.len(),
                record: start + begin..start + end,
            }
        } else if buf.is_empty() {
            Step::Need
        } else {
            Step::Skip { consume: buf.len() }
        }
    }

    fn delimited(&mut self, delimiter: u8, strip: bool, buf: &[u8], eof: bool) -> Step {
        let mut start = 0;
        let mut from = self.seen.min(buf.len());
        while let Some(i) = memchr(delimiter, &buf[from..]) {
            let end = from + i;
            let consume = end + 1;
            if end - start > self.max {
                return self.oversize(consume, wide(consume - start), start, buf);
            }
            let stop = if strip {
                before_crs(buf, start, end)
            } else {
                end
            };
            if stop > start {
                self.seen = 0;
                return Step::Record {
                    consume,
                    record: start..stop,
                };
            }
            start = consume;
            from = consume;
        }
        self.tail(delimiter, buf, start, eof)
    }

    /// The bytes from `start`, a line with no delimiter in `buf`.
    fn tail(&mut self, delimiter: u8, buf: &[u8], start: usize, eof: bool) -> Step {
        let len = buf.len() - start;
        if len > self.max {
            self.skip = Skip::To(delimiter);
            return self.oversize(buf.len(), wide(len), start, buf);
        }
        if eof {
            return self.last(buf, start);
        }
        self.wait(start, buf.len())
    }

    fn counted(&mut self, buf: &[u8], eof: bool) -> Step {
        let mut start = 0;
        loop {
            match head(&buf[start..], self.limit) {
                Head::Counted { count, body } => return self.frame(buf, start, body, count, eof),
                Head::More if eof => return self.last(buf, start),
                Head::More => return self.wait(start, start),
                Head::Line => {
                    let from = if start == 0 {
                        self.seen.min(buf.len())
                    } else {
                        start
                    };
                    let Some(i) = memchr(b'\n', &buf[from..]) else {
                        return self.tail(b'\n', buf, start, eof);
                    };
                    let end = from + i;
                    let consume = end + 1;
                    if end - start > self.max {
                        return self.oversize(consume, wide(consume - start), start, buf);
                    }
                    let stop = if self.strip {
                        before_crs(buf, start, end)
                    } else {
                        end
                    };
                    self.seen = 0;
                    if stop > start {
                        return Step::Record {
                            consume,
                            record: start..stop,
                        };
                    }
                    start = consume;
                }
            }
        }
    }

    /// The counted frame of `count` bytes after a `body`-byte header at
    /// `start`.
    fn frame(&mut self, buf: &[u8], start: usize, body: usize, count: u64, eof: bool) -> Step {
        let have = buf.len() - start - body;
        let Some(len) = usize::try_from(count).ok().filter(|&len| len <= self.max) else {
            if have < self.max && !eof {
                return self.wait(start, start);
            }
            let total = wide(body).saturating_add(count);
            let in_buf = buf.len() - start;
            let take = usize::try_from(total).map_or(in_buf, |total| total.min(in_buf));
            let left = total - wide(take);
            if left > 0 {
                self.skip = Skip::Count(left);
            }
            self.seen = 0;
            return Step::Oversize {
                consume: start + take,
                len: total,
                head: start + body..start + body + have.min(self.max),
            };
        };
        if have < len {
            if eof {
                return Step::Cut {
                    len: wide(buf.len() - start),
                };
            }
            return self.wait(start, start);
        }
        self.seen = 0;
        let from = start + body;
        Step::Record {
            consume: from + len,
            record: from..from + len,
        }
    }

    fn json(&mut self, seq: bool, buf: &[u8], eof: bool) -> Step {
        let (start, value, from) = match self.value.take() {
            Some(value) => (0, value, self.seen.min(buf.len())),
            None => match self.open(seq, buf) {
                Ok(found) => found,
                Err(step) => return step,
            },
        };
        self.read(seq, buf, eof, start, value, from)
    }

    /// Find where the next JSON value starts, or the step to take first.
    fn open(&mut self, seq: bool, buf: &[u8]) -> Result<(usize, Value, usize), Step> {
        let mut at = 0;
        loop {
            at = between(buf, at, seq);
            let Some(&byte) = buf.get(at) else {
                self.seen = 0;
                return Err(if at > 0 {
                    Step::Skip { consume: at }
                } else {
                    Step::Need
                });
            };
            if let Some(scan) = Scan::open(byte) {
                self.junk = false;
                return Ok((at, Value::new(scan), at + 1));
            }
            if seq {
                let consume = memchr(RS, &buf[at..]).map_or_else(
                    || {
                        self.skip = Skip::To(RS);
                        buf.len()
                    },
                    |i| at + i + 1,
                );
                return Err(self.bad(consume, at, NO_VALUE));
            }
            // A run of junk is one event however it is cut, whitespace inside it included.
            let end = buf[at..]
                .iter()
                .position(|&b| Scan::open(b).is_some())
                .map_or(buf.len(), |i| at + i);
            if !self.junk {
                self.junk = true;
                return Err(self.bad(end, at, NO_VALUE));
            }
            at = end;
        }
    }

    /// Read the JSON value that starts at `start`, scanned to `from`.
    fn read(
        &mut self,
        seq: bool,
        buf: &[u8],
        eof: bool,
        start: usize,
        mut value: Value,
        from: usize,
    ) -> Step {
        match value.scan.run(buf, from, seq) {
            ScanStep::End(end) => {
                // RFC 7464 drops a number with no whitespace after it up to the next RS.
                let bad = seq && value.scalar && !ends_well(buf, end);
                if bad {
                    self.skip = Skip::To(RS);
                }
                if end - start > self.max {
                    return self.oversize(end, wide(end - start), start, buf);
                }
                self.seen = 0;
                if bad {
                    return self.bad(end, end, "a number or literal with no whitespace after it");
                }
                Step::Record {
                    consume: end,
                    record: start..end,
                }
            }
            ScanStep::Cut(at) => {
                if at - start > self.max {
                    return self.oversize(at, wide(at - start), start, buf);
                }
                self.seen = 0;
                self.bad(at, at, "a sequence text cut short by an RS")
            }
            ScanStep::More => {
                let len = buf.len() - start;
                if len > self.max {
                    self.skip = Skip::Value(value);
                    return self.oversize(buf.len(), wide(len), start, buf);
                }
                if eof {
                    self.seen = 0;
                    // A number or literal ends where the input does, and RFC 7464 drops one.
                    if !seq && value.scalar {
                        return Step::Record {
                            consume: buf.len(),
                            record: start..buf.len(),
                        };
                    }
                    return Step::Cut { len: wide(len) };
                }
                self.value = Some(value);
                self.wait(start, buf.len())
            }
        }
    }

    fn array(&mut self, buf: &[u8], eof: bool) -> Step {
        if let Some(value) = self.value.take() {
            let from = self.seen.min(buf.len());
            return self.element(buf, eof, 0, value, from);
        }
        let mut at = 0;
        loop {
            at = between(buf, at, false);
            let Some(&byte) = buf.get(at) else {
                if eof {
                    return self.close(buf);
                }
                return self.wait(at, at);
            };
            match (self.array, byte) {
                (ArrayAt::Spent, _) => {
                    self.seen = 0;
                    return Step::Skip { consume: buf.len() };
                }
                (ArrayAt::Open, b'[') => {
                    self.array = ArrayAt::First;
                    self.opened = self.consumed + wide(at);
                    at += 1;
                }
                (ArrayAt::Open, _) => {
                    self.array = ArrayAt::Spent;
                    return self.bad(buf.len(), at, "bytes before the `[` of a JSON array");
                }
                (ArrayAt::Done, _) => {
                    self.array = ArrayAt::Spent;
                    return self.bad(buf.len(), at, "bytes after the `]` of a JSON array");
                }
                (ArrayAt::First | ArrayAt::Next | ArrayAt::After, b']') => {
                    self.junk = false;
                    let comma = self.array == ArrayAt::Next;
                    self.array = ArrayAt::Done;
                    at += 1;
                    if comma {
                        return self.bad(at, at - 1, "a comma before the `]`");
                    }
                }
                (ArrayAt::After, b',') => {
                    self.junk = false;
                    self.array = ArrayAt::Next;
                    at += 1;
                }
                (ArrayAt::First | ArrayAt::Next, b',') => {
                    at += 1;
                    if !self.junk {
                        self.junk = true;
                        return self.bad(at, at - 1, "a comma with no element before it");
                    }
                }
                (state, _) => {
                    if state == ArrayAt::After {
                        self.array = ArrayAt::Next;
                        return self.bad(at, at, "no comma between elements");
                    }
                    let Some(scan) = Scan::open(byte) else {
                        at += 1;
                        if !self.junk {
                            self.junk = true;
                            return self.bad(at, at - 1, NO_VALUE);
                        }
                        continue;
                    };
                    self.junk = false;
                    return self.element(buf, eof, at, Value::new(scan), at + 1);
                }
            }
        }
    }

    /// Read the array element that starts at `start`, scanned to `from`.
    fn element(
        &mut self,
        buf: &[u8],
        eof: bool,
        start: usize,
        mut value: Value,
        from: usize,
    ) -> Step {
        // Outside a sequence no RS cuts a value, so a cut is read as its end.
        let (ScanStep::End(end) | ScanStep::Cut(end)) = value.scan.run(buf, from, false) else {
            let len = buf.len() - start;
            if len > self.max {
                self.skip = Skip::Value(value);
                return self.oversize(buf.len(), wide(len), start, buf);
            }
            if eof {
                return self.close(buf);
            }
            self.value = Some(value);
            return self.wait(start, buf.len());
        };
        self.array = ArrayAt::After;
        if end - start > self.max {
            return self.oversize(end, wide(end - start), start, buf);
        }
        self.seen = 0;
        Step::Record {
            consume: end,
            record: start..end,
        }
    }

    /// The end of input in a `json_array` stream: a cut when the array is
    /// open, counted from its `[`.
    fn close(&mut self, buf: &[u8]) -> Step {
        self.seen = 0;
        if matches!(self.array, ArrayAt::First | ArrayAt::Next | ArrayAt::After) {
            return Step::Cut {
                len: self.consumed + wide(buf.len()) - self.opened,
            };
        }
        if buf.is_empty() {
            Step::Need
        } else {
            Step::Skip { consume: buf.len() }
        }
    }
}

/// The end of the line from `start` to `end` before its `\r`s.
#[inline]
const fn before_crs(buf: &[u8], start: usize, end: usize) -> usize {
    let mut stop = end;
    while stop > start && buf[stop - 1] == b'\r' {
        stop -= 1;
    }
    stop
}

/// Give `f` the frame `step` read from `buf`, when it has one, and return
/// the bytes the step drops.
#[cold]
#[inline(never)]
fn give<'b>(step: &Step, buf: &'b [u8], f: &mut impl FnMut(Frame<&'b [u8]>)) -> usize {
    if let Some(frame) = frame_of(step, buf, |bytes| bytes) {
        f(frame);
    }
    step.consume(buf)
}

/// `line` with the `\r`s at its end dropped.
#[inline]
const fn trim_crs(mut line: &[u8]) -> &[u8] {
    while let [rest @ .., b'\r'] = line {
        line = rest;
    }
    line
}

/// Whether a number or literal that ended at `end` has whitespace after it.
fn ends_well(buf: &[u8], end: usize) -> bool {
    buf.get(end).is_some_and(|&b| space(b))
}

/// The first byte at or after `at` that isn't between two values: JSON
/// whitespace, and in a sequence, RS.
fn between(buf: &[u8], at: usize, seq: bool) -> usize {
    buf.get(at..)
        .and_then(|rest| rest.iter().position(|&b| !(space(b) || (seq && b == RS))))
        .map_or(buf.len(), |i| at + i)
}

/// How the frame at the front of `bytes` is framed, trusting a count up to
/// `limit`: a count of 1 to 9 then digits, one space and `<` is counted.
fn head(bytes: &[u8], limit: u64) -> Head {
    match bytes.first() {
        None => return Head::More,
        Some(b'1'..=b'9') => {}
        Some(_) => return Head::Line,
    }
    let digits = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
    let count = bytes[..digits].iter().try_fold(0_u64, |n, &d| {
        n.checked_mul(10)?.checked_add(u64::from(d - b'0'))
    });
    let Some(count) = count.filter(|&count| count <= limit) else {
        return Head::Line;
    };
    match (bytes.get(digits), bytes.get(digits + 1)) {
        (Some(b' '), Some(b'<')) => Head::Counted {
            count,
            body: digits + 1,
        },
        (None, _) | (Some(b' '), None) => Head::More,
        _ => Head::Line,
    }
}