grippo 0.2.3

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

//! Records split from a stream fed a read at a time: LF lines, RFC 6587
//! octet-counted frames mixed with LF lines, NUL-delimited frames, and JSON
//! values back to back or as an RFC 7464 sequence.
//!
//! A record an input holds whole is a slice of it. One cut across inputs is
//! held, never past `max_bytes`, and owned once its end arrives. A record over
//! `max_bytes` is passed without being held, and reported with its head and
//! length once it ends.

use std::borrow::Cow;

use memchr::memchr;
use serde::{Deserialize, Serialize};

use super::Frame;
use super::json::{RS, Scan, Step, space};
use crate::parse::ParseError;

/// Where [`StreamConfig`] ends one record and starts the next.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StreamSplit {
    /// Each record then `\n`. The `\r`s before the `\n` are dropped or kept as
    /// [`CarriageReturns`] says, and an empty line is no record.
    #[default]
    Lf,
    /// RFC 6587 octet counting, `<length> <record>`, as RFC 5425 sends
    /// syslog over TLS, mixed with LF lines: a frame that starts with a
    /// count of 1 to 9 then digits, one space and `<` is counted, and any
    /// other is an LF line. A count over `max_frame_bytes` isn't trusted and
    /// reads as an LF line too.
    OctetCounted,
    /// Each record then a NUL byte, as GELF goes over TCP. An empty frame is
    /// no record.
    Nul,
    /// JSON values back to back, with or without whitespace between them.
    JsonConcat,
    /// RFC 7464 JSON text sequences: an RS byte (0x1E) before each value
    /// and an LF after it. A text an RS cuts short, and a top-level number
    /// or literal with no whitespace after it, is dropped as RFC 7464 says.
    JsonSeq,
    /// One top-level JSON array, each element a record the moment it is
    /// complete. The `[`, the `]`, whitespace and the commas between elements
    /// are consumed. Bytes before the `[` or after the `]`, a missing comma and
    /// a stray comma are malformed, and the end of input before the `]` is a
    /// cut.
    JsonArray,
}

/// What an LF line keeps of the `\r`s before its `\n`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum CarriageReturns {
    /// Drop every one: `a\r\n` is the record `a`, and a line of only `\r`s is
    /// no record.
    #[default]
    Strip,
    /// Keep them: `a\r\n` is the record `a\r`, and `\r\n` is the record `\r`.
    Keep,
}

/// Settings for [`FramingConfig::Stream`](super::FramingConfig::Stream).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct StreamConfig {
    /// Where one record ends and the next begins.
    pub split: StreamSplit,
    /// Most bytes one record holds. A longer one is reported as oversize and
    /// is skipped without being held.
    pub max_bytes: usize,
    /// Whether an LF line keeps the `\r`s before its `\n`. Nul and JSON
    /// splits ignore it.
    pub carriage_returns: CarriageReturns,
    /// Octet counting only: the largest count taken as a frame, read as at
    /// least `max_bytes`. A frame between `max_bytes` and this is skipped
    /// whole, and a count over it isn't trusted: the bytes from the count to
    /// the next `\n` read as an LF line.
    pub max_frame_bytes: usize,
}

impl Default for StreamConfig {
    fn default() -> Self {
        Self {
            split: StreamSplit::Lf,
            max_bytes: 1 << 20,
            carriage_returns: CarriageReturns::Strip,
            max_frame_bytes: 16 << 20,
        }
    }
}

/// What a [`StreamFramer`] found in the bytes fed to it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamEvent<'a> {
    /// One record: borrowed when the input held it whole, owned when it was
    /// joined across inputs.
    Record(Cow<'a, [u8]>),
    /// A record over `max_bytes`, left out.
    Oversize {
        /// Its first `max_bytes` bytes, or all of them when it is shorter.
        head: Vec<u8>,
        /// Its length in the stream, a counted frame's header and a line's
        /// delimiter included. For one the end of input cut short, the bytes
        /// seen.
        len: u64,
    },
    /// Bytes that don't frame: what a JSON split could not read.
    Malformed {
        /// Where, as a stream offset.
        offset: u64,
        /// What is wrong there.
        reason: &'static str,
    },
    /// The end of input came inside a frame: a counted frame, a JSON value or
    /// a sequence text.
    Cut {
        /// The bytes seen of it.
        len: u64,
    },
}

/// Splits a stream into records as it is fed, with no
/// [`FramingConfig`](super::FramingConfig) around it.
///
/// [`push`](Self::push) each read, whatever its cut, then
/// [`finish`](Self::finish) at the end of input. The framer holds a record cut
/// across reads, never more than `max_bytes` of one.
///
/// ```
/// use grippo::parse::{StreamConfig, StreamEvent, StreamFramer, StreamSplit};
///
/// let mut config = StreamConfig::default();
/// config.split = StreamSplit::OctetCounted;
/// let mut framer = StreamFramer::new(config);
/// let mut events = Vec::new();
/// framer.push(b"15 <13>hello w", &mut events);
/// framer.push(b"orld<14>bye\n", &mut events);
/// let records: Vec<&[u8]> = events
///     .iter()
///     .filter_map(|event| match event {
///         StreamEvent::Record(record) => Some(record.as_ref()),
///         _ => None,
///     })
///     .collect();
/// assert_eq!(records, [&b"<13>hello world"[..], b"<14>bye"]);
/// assert_eq!(framer.taken(), 26);
/// assert!(!framer.mid_frame());
/// ```
#[derive(Debug, Clone)]
pub struct StreamFramer {
    config: StreamConfig,
    held: Held,
}

impl StreamFramer {
    /// A framer for `config`.
    #[must_use]
    pub fn new(config: StreamConfig) -> Self {
        Self {
            config,
            held: Held::default(),
        }
    }

    /// Split `input`, the next bytes of the stream, appending what it holds
    /// to `out`.
    pub fn push<'a>(&mut self, input: &'a [u8], out: &mut Vec<StreamEvent<'a>>) {
        feed(&self.config, input, &mut self.held, &mut |event| {
            out.push(event);
        });
    }

    /// End the stream. A last LF or NUL line with no delimiter goes out with
    /// its ASCII whitespace trimmed, and is dropped when nothing is
    /// left. A frame cut short is a [`StreamEvent::Cut`], and an oversize one
    /// still being passed is a [`StreamEvent::Oversize`].
    pub fn finish(&mut self, out: &mut Vec<StreamEvent<'static>>) {
        end(&self.config, &mut self.held, &mut |event| out.push(event));
    }

    /// Stream bytes in the events emitted so far, delimiters, blank lines and
    /// oversize frames included: the offset just past the last frame.
    #[must_use]
    pub fn taken(&self) -> u64 {
        self.held.taken()
    }

    /// Whether a frame has begun and not ended: bytes are held past the last
    /// event, or an oversize frame is still being passed.
    #[must_use]
    pub const fn mid_frame(&self) -> bool {
        self.held.mid_frame()
    }
}

/// A record over the cap being passed, and what is known of it.
#[derive(Debug, Clone)]
struct Over {
    /// Its first `max_bytes` bytes.
    head: Vec<u8>,
    /// Its bytes in the stream so far.
    len: u64,
}

impl Over {
    /// An oversize record that began with the held bytes `head`, of which
    /// `max` are kept.
    fn from_held(mut head: Vec<u8>, max: usize) -> Self {
        let len = wide(head.len());
        head.truncate(max);
        Self { head, len }
    }

    /// Count `bytes` of the record, keeping its head up to `max`.
    fn take(&mut self, max: usize, bytes: &[u8]) {
        let room = max.saturating_sub(self.head.len());
        self.head.extend_from_slice(&bytes[..bytes.len().min(room)]);
        self.len += wide(bytes.len());
    }
}

/// A record cut across inputs, and what the stream is passing over.
#[derive(Debug, Default, Clone)]
pub(super) struct Held {
    /// The record's bytes so far, a counted frame's header included.
    bytes: Vec<u8>,
    /// Bytes still to pass of a counted frame over the cap.
    skip: u64,
    /// Pass bytes up to and including this delimiter: the rest of a record
    /// over the cap, or of a sequence text that isn't well formed.
    discard: Option<u8>,
    /// The JSON value being read, when one is cut across inputs.
    scan: Option<Scan>,
    /// Whether that value began as a number or a literal.
    scalar: bool,
    /// The record over the cap being passed, whose bytes go unheld.
    over: Option<Over>,
    /// Stream bytes fed so far.
    pushed: u64,
    /// Where a `json_array` stream stands.
    array: ArrayAt,
    /// The stream offset of that array's `[`.
    opened: u64,
    /// Whether the last bytes read were a run of junk already reported.
    junk: bool,
}

impl Held {
    /// Bytes held of a record cut across inputs.
    #[cfg(test)]
    pub(super) const fn held(&self) -> usize {
        self.bytes.len()
    }

    fn taken(&self) -> u64 {
        self.pushed - wide(self.bytes.len())
    }

    const fn mid_frame(&self) -> bool {
        !self.bytes.is_empty() || self.over.is_some()
    }
}

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

/// The longest header a counted frame has: 20 digits, a space and `<`.
const HEAD_MAX: usize = 22;

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

/// The first error an input met, for the driver path.
#[derive(Default)]
struct First(Option<ParseError>);

impl First {
    /// Note the error `event` stands for, when it stands for one.
    #[cold]
    #[inline(never)]
    fn note(&mut self, event: &StreamEvent<'_>, max: usize, base: u64) {
        let error = match *event {
            StreamEvent::Oversize { len, .. } => ParseError::FrameTooLong { len, max },
            StreamEvent::Malformed { offset, reason } => ParseError::Malformed {
                offset: usize::try_from(offset.saturating_sub(base)).unwrap_or(usize::MAX),
                reason,
            },
            StreamEvent::Record(_) | StreamEvent::Cut { .. } => return,
        };
        if self.0.is_none() {
            self.0 = Some(error);
        }
    }
}

/// Split `input`, the next bytes of the stream, appending each finished
/// record to `out`.
pub(super) fn frame<'a>(
    c: &StreamConfig,
    input: &'a [u8],
    held: &mut Held,
    out: &mut Vec<Frame<'a>>,
) -> Result<(), ParseError> {
    let mut first = First::default();
    let base = held.pushed;
    feed(c, input, held, &mut |event| match event {
        StreamEvent::Record(bytes) => out.push(Frame::new(bytes)),
        other => first.note(&other, c.max_bytes, base),
    });
    first.0.map_or(Ok(()), Err)
}

/// End the stream. A last record with no delimiter after it goes to `out`.
/// One cut short, a counted frame or a JSON value, is dropped.
pub(super) fn finish(c: &StreamConfig, held: &mut Held, out: &mut Vec<Frame<'static>>) {
    end(c, held, &mut |event| {
        if let StreamEvent::Record(bytes) = event {
            out.push(Frame::new(bytes));
        }
    });
}

/// Split `input` as `c.split` says and count it as fed.
fn feed<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    input: &'a [u8],
    held: &mut Held,
    emit: &mut E,
) {
    match c.split {
        StreamSplit::Lf => delimited(c, b'\n', input, held, emit),
        StreamSplit::Nul => delimited(c, 0, input, held, emit),
        StreamSplit::OctetCounted => counted(c, input, held, emit),
        StreamSplit::JsonConcat => json(c, false, input, held, emit),
        StreamSplit::JsonSeq => json(c, true, input, held, emit),
        StreamSplit::JsonArray => array(c, input, held, emit),
    }
    held.pushed += wide(input.len());
}

/// What the end of input leaves of the held record.
fn end<E: FnMut(StreamEvent<'static>)>(c: &StreamConfig, held: &mut Held, emit: &mut E) {
    let pushed = held.pushed;
    let Held {
        mut bytes,
        scalar,
        over,
        array,
        opened,
        ..
    } = std::mem::replace(
        held,
        Held {
            pushed,
            ..Held::default()
        },
    );
    if let Some(Over { head, len }) = over {
        emit(StreamEvent::Oversize { head, len });
        if c.split != StreamSplit::JsonArray {
            return;
        }
    }
    if c.split == StreamSplit::JsonArray {
        if matches!(array, ArrayAt::First | ArrayAt::Next | ArrayAt::After) {
            emit(StreamEvent::Cut {
                len: pushed - opened,
            });
        }
        return;
    }
    if bytes.is_empty() {
        return;
    }
    let whole = match c.split {
        StreamSplit::Lf | StreamSplit::Nul => true,
        StreamSplit::OctetCounted => !matches!(head(&bytes, frame_limit(c)), Head::Counted { .. }),
        // A number or literal ends where the input does. RFC 7464 drops one
        // with no whitespace after it.
        StreamSplit::JsonConcat => scalar,
        StreamSplit::JsonSeq | StreamSplit::JsonArray => false,
    };
    if !whole {
        emit(StreamEvent::Cut {
            len: wide(bytes.len()),
        });
        return;
    }
    if matches!(
        c.split,
        StreamSplit::Lf | StreamSplit::Nul | StreamSplit::OctetCounted
    ) {
        let end = bytes
            .iter()
            .rposition(|b| !b.is_ascii_whitespace())
            .map_or(0, |i| i + 1);
        bytes.truncate(end);
        let start = bytes
            .iter()
            .position(|b| !b.is_ascii_whitespace())
            .unwrap_or(end);
        bytes.drain(..start);
    }
    if !bytes.is_empty() {
        emit(StreamEvent::Record(Cow::Owned(bytes)));
    }
}

/// Report the oversize record being passed, now that it has ended.
fn report<'a, E: FnMut(StreamEvent<'a>)>(held: &mut Held, emit: &mut E) {
    if let Some(Over { head, len }) = held.over.take() {
        emit(StreamEvent::Oversize { head, len });
    }
}

/// Pass what's left of a skipped record from `at`, returning where the
/// stream picks up.
fn pass<'a, E: FnMut(StreamEvent<'a>)>(
    max: usize,
    held: &mut Held,
    input: &[u8],
    mut at: usize,
    emit: &mut E,
) -> usize {
    if held.skip > 0 {
        let left = input.len() - at;
        let n = usize::try_from(held.skip).map_or(left, |skip| skip.min(left));
        held.skip -= wide(n);
        if let Some(over) = &mut held.over {
            over.take(max, &input[at..at + n]);
        }
        at += n;
        if held.skip == 0 {
            report(held, emit);
        }
    }
    if held.skip == 0
        && let Some(delimiter) = held.discard
    {
        let rest = &input[at..];
        let found = memchr(delimiter, rest);
        if let Some(over) = &mut held.over {
            over.take(max, &rest[..found.unwrap_or(rest.len())]);
        }
        if let Some(i) = found {
            held.discard = None;
            if let Some(over) = &mut held.over {
                over.len += 1;
            }
            report(held, emit);
            at += i + 1;
        } else {
            at = input.len();
        }
    }
    at
}

/// Hold `tail`, the start of a record whose end hasn't arrived, or start
/// passing it when that takes the record past `max`, up to `delimiter` when
/// the end is a byte to find.
fn keep(max: usize, held: &mut Held, tail: &[u8], delimiter: Option<u8>) {
    if held.bytes.len() + tail.len() > max {
        let mut over = Over::from_held(std::mem::take(&mut held.bytes), max);
        over.take(max, tail);
        held.over = Some(over);
        held.discard = delimiter;
    } else {
        held.bytes.extend_from_slice(tail);
    }
}

/// The held record with `tail`, its last bytes, added, or `None` when that
/// takes it past `max`, which reports it with `ends` delimiter bytes after it.
fn join<'a, E: FnMut(StreamEvent<'a>)>(
    max: usize,
    held: &mut Held,
    tail: &[u8],
    ends: u64,
    emit: &mut E,
) -> Option<Vec<u8>> {
    if held.bytes.len() + tail.len() > max {
        let mut over = Over::from_held(std::mem::take(&mut held.bytes), max);
        over.take(max, tail);
        over.len += ends;
        emit(StreamEvent::Oversize {
            head: over.head,
            len: over.len,
        });
        return None;
    }
    held.bytes.extend_from_slice(tail);
    Some(std::mem::take(&mut held.bytes))
}

/// Report a record over `max` that `record` holds whole, with `ends`
/// delimiter bytes after it.
#[cold]
#[inline(never)]
fn too_long<'a, E: FnMut(StreamEvent<'a>)>(max: usize, record: &[u8], ends: u64, emit: &mut E) {
    emit(StreamEvent::Oversize {
        head: record[..max].to_vec(),
        len: wide(record.len()) + ends,
    });
}

/// Append a line as a record: with its `\r`s dropped when `strip`, an empty
/// one left out.
#[inline]
fn line<'a, E: FnMut(StreamEvent<'a>)>(emit: &mut E, mut bytes: Cow<'a, [u8]>, strip: bool) {
    if strip && bytes.last() == Some(&b'\r') {
        let kept = bytes.iter().rposition(|&b| b != b'\r').map_or(0, |i| i + 1);
        match &mut bytes {
            Cow::Borrowed(b) => *b = &b[..kept],
            Cow::Owned(v) => v.truncate(kept),
        }
    }
    if !bytes.is_empty() {
        emit(StreamEvent::Record(bytes));
    }
}

fn delimited<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    delimiter: u8,
    input: &'a [u8],
    held: &mut Held,
    emit: &mut E,
) {
    let max = c.max_bytes;
    let strip = delimiter == b'\n' && c.carriage_returns == CarriageReturns::Strip;
    let mut at = pass(max, held, input, 0, emit);
    if !held.bytes.is_empty() {
        let rest = &input[at..];
        let Some(i) = memchr(delimiter, rest) else {
            keep(max, held, rest, Some(delimiter));
            return;
        };
        at += i + 1;
        if let Some(record) = join(max, held, &rest[..i], 1, emit) {
            line(emit, Cow::Owned(record), strip);
        }
    }
    while let Some(i) = memchr(delimiter, &input[at..]) {
        let record = &input[at..at + i];
        at += i + 1;
        if record.len() > max {
            too_long(max, record, 1, emit);
        } else {
            line(emit, Cow::Borrowed(record), strip);
        }
    }
    keep(max, held, &input[at..], Some(delimiter));
}

/// The largest octet count taken as a frame.
fn frame_limit(c: &StreamConfig) -> u64 {
    wide(c.max_frame_bytes.max(c.max_bytes))
}

/// How the frame at the front of `bytes` is framed, trusting a count up to
/// `limit`.
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,
            start: digits + 1,
        },
        (None, _) | (Some(b' '), None) => Head::More,
        _ => Head::Line,
    }
}

fn counted<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    input: &'a [u8],
    held: &mut Held,
    emit: &mut E,
) {
    let max = c.max_bytes;
    let limit = frame_limit(c);
    let strip = c.carriage_returns == CarriageReturns::Strip;
    let mut at = pass(max, held, input, 0, emit);
    if !held.bytes.is_empty() && at < input.len() {
        at = resume_counted(c, input, at, held, emit);
    }
    while at < input.len() {
        if held.skip > 0 || held.discard.is_some() {
            at = pass(max, held, input, at, emit);
            continue;
        }
        let rest = &input[at..];
        match head(rest, limit) {
            Head::Counted { count, start } => {
                let Some(len) = usize::try_from(count).ok().filter(|&len| len <= max) else {
                    held.over = Some(Over {
                        head: Vec::new(),
                        len: wide(start),
                    });
                    held.skip = count;
                    at += start;
                    continue;
                };
                if rest.len() - start < len {
                    held.bytes.extend_from_slice(rest);
                    return;
                }
                emit(StreamEvent::Record(Cow::Borrowed(
                    &rest[start..start + len],
                )));
                at += start + len;
            }
            Head::More => {
                held.bytes.extend_from_slice(rest);
                return;
            }
            Head::Line => {
                let Some(i) = memchr(b'\n', rest) else {
                    keep(max, held, rest, Some(b'\n'));
                    return;
                };
                at += i + 1;
                if i > max {
                    too_long(max, &rest[..i], 1, emit);
                } else {
                    line(emit, Cow::Borrowed(&rest[..i]), strip);
                }
            }
        }
    }
}

/// Go on with the frame an earlier input began, from `at`, returning where
/// the stream picks up after it.
fn resume_counted<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    input: &'a [u8],
    mut at: usize,
    held: &mut Held,
    emit: &mut E,
) -> usize {
    let max = c.max_bytes;
    let limit = frame_limit(c);
    let kind = match head(&held.bytes, limit) {
        Head::More => {
            let mut probe = held.bytes.clone();
            probe.extend_from_slice(&input[at..input.len().min(at + HEAD_MAX)]);
            head(&probe, limit)
        }
        kind => kind,
    };
    match kind {
        Head::More => {
            held.bytes.extend_from_slice(&input[at..]);
            input.len()
        }
        Head::Counted { count, start } => {
            let have = held.bytes.len();
            let Some(len) = usize::try_from(count).ok().filter(|&len| len <= max) else {
                let mut over = Over {
                    head: Vec::new(),
                    len: wide(have.min(start)),
                };
                over.take(max, &held.bytes[start.min(have)..]);
                over.len += wide(start.saturating_sub(have));
                let seen = wide(have.saturating_sub(start));
                held.over = Some(over);
                held.skip = count - seen.min(count);
                held.bytes.clear();
                return at + start.saturating_sub(have);
            };
            let need = (start + len).saturating_sub(have);
            let take = need.min(input.len() - at);
            held.bytes.extend_from_slice(&input[at..at + take]);
            at += take;
            if take == need {
                let mut record = std::mem::take(&mut held.bytes);
                record.drain(..start);
                emit(StreamEvent::Record(Cow::Owned(record)));
            }
            at
        }
        Head::Line => {
            let rest = &input[at..];
            let Some(i) = memchr(b'\n', rest) else {
                keep(max, held, rest, Some(b'\n'));
                return input.len();
            };
            if let Some(record) = join(max, held, &rest[..i], 1, emit) {
                let strip = c.carriage_returns == CarriageReturns::Strip;
                line(emit, Cow::Owned(record), strip);
            }
            at + i + 1
        }
    }
}

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

/// Under `seq`, whether a number or literal that ended at `end` has the
/// whitespace RFC 7464 asks for after it.
fn ends_well(input: &[u8], end: usize, seq: bool, scalar: bool) -> bool {
    !(seq && scalar) || input.get(end).is_some_and(|&b| space(b))
}

/// A `Malformed` event for the byte `offset` into this input, `base` bytes
/// into the stream.
fn bad<'a>(base: u64, offset: usize, reason: &'static str) -> StreamEvent<'a> {
    StreamEvent::Malformed {
        offset: base + wide(offset),
        reason,
    }
}

fn json<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    seq: bool,
    input: &'a [u8],
    held: &mut Held,
    emit: &mut E,
) {
    let max = c.max_bytes;
    let base = held.pushed;
    let mut at = pass(max, held, input, 0, emit);
    let Some(next) = resume_value(c, seq, input, at, held, emit) else {
        return;
    };
    at = next;
    loop {
        at = between(input, at, seq);
        let Some(&byte) = input.get(at) else {
            return;
        };
        let Some(scan) = Scan::open(byte) else {
            if seq {
                emit(bad(base, at, "a byte no JSON value starts with"));
                held.discard = Some(RS);
                at = pass(max, held, input, at, emit);
            } else {
                junk(
                    held,
                    emit,
                    base + wide(at),
                    "a byte no JSON value starts with",
                );
                at += 1;
            }
            continue;
        };
        held.junk = false;
        let Some(next) = fresh(c, seq, input, at, scan, held, emit) else {
            return;
        };
        at = next;
    }
}

/// Report junk at the stream offset `offset` unless it continues a run
/// already reported, so a run of junk is one event however it is cut.
fn junk<'a, E: FnMut(StreamEvent<'a>)>(
    held: &mut Held,
    emit: &mut E,
    offset: u64,
    reason: &'static str,
) {
    if !held.junk {
        held.junk = true;
        emit(StreamEvent::Malformed { offset, reason });
    }
}

/// Go on from `at` with the JSON value an earlier input began, returning
/// where the stream picks up after it, or `None` when this input ends inside
/// it too. With no value held it returns `at`.
fn resume_value<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    seq: bool,
    input: &'a [u8],
    mut at: usize,
    held: &mut Held,
    emit: &mut E,
) -> Option<usize> {
    let max = c.max_bytes;
    let base = held.pushed;
    let Some(mut scan) = held.scan.take() else {
        return Some(at);
    };
    match scan.run(input, at, seq) {
        Step::End(end) => {
            let scalar = std::mem::take(&mut held.scalar);
            let tail = &input[at..end];
            at = end;
            if !ends_well(input, end, seq, scalar) {
                held.over = None;
                held.bytes.clear();
                emit(bad(
                    base,
                    end,
                    "a number or literal with no whitespace after it",
                ));
                held.discard = Some(RS);
                at = pass(max, held, input, at, emit);
            } else if let Some(over) = &mut held.over {
                over.take(max, tail);
                report(held, emit);
            } else if let Some(record) = join(max, held, tail, 0, emit) {
                emit(StreamEvent::Record(Cow::Owned(record)));
            }
            Some(at)
        }
        Step::More => {
            if let Some(over) = &mut held.over {
                over.take(max, &input[at..]);
            } else {
                keep(max, held, &input[at..], None);
            }
            held.scan = Some(scan);
            None
        }
        Step::Cut(i) => {
            held.over = None;
            held.bytes.clear();
            held.scalar = false;
            emit(bad(base, i, "a sequence text cut short by an RS"));
            Some(i)
        }
    }
}

/// Read the JSON value `scan` opened at `start`, returning where the stream
/// picks up after it, or `None` when the input ends inside it.
fn fresh<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    seq: bool,
    input: &'a [u8],
    start: usize,
    mut scan: Scan,
    held: &mut Held,
    emit: &mut E,
) -> Option<usize> {
    let max = c.max_bytes;
    let base = held.pushed;
    let scalar = scan.scalar();
    match scan.run(input, start + 1, seq) {
        Step::End(end) => {
            if ends_well(input, end, seq, scalar) {
                if end - start > max {
                    too_long(max, &input[start..end], 0, emit);
                } else {
                    emit(StreamEvent::Record(Cow::Borrowed(&input[start..end])));
                }
                Some(end)
            } else {
                emit(bad(
                    base,
                    end,
                    "a number or literal with no whitespace after it",
                ));
                held.discard = Some(RS);
                Some(pass(max, held, input, end, emit))
            }
        }
        Step::More => {
            keep(max, held, &input[start..], None);
            held.scalar = scalar;
            held.scan = Some(scan);
            None
        }
        Step::Cut(i) => {
            emit(bad(base, i, "a sequence text cut short by an RS"));
            Some(i)
        }
    }
}

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

fn array<'a, E: FnMut(StreamEvent<'a>)>(
    c: &StreamConfig,
    input: &'a [u8],
    held: &mut Held,
    emit: &mut E,
) {
    let base = held.pushed;
    let mut at = 0;
    if held.scan.is_some() {
        let Some(next) = resume_value(c, false, input, at, held, emit) else {
            return;
        };
        at = next;
        held.array = ArrayAt::After;
    }
    loop {
        at = between(input, at, false);
        let Some(&byte) = input.get(at) else {
            return;
        };
        match (held.array, byte) {
            (ArrayAt::Spent, _) => return,
            (ArrayAt::Open, b'[') => {
                held.array = ArrayAt::First;
                held.opened = base + wide(at);
                at += 1;
            }
            (ArrayAt::Open, _) => {
                emit(bad(base, at, "bytes before the `[` of a JSON array"));
                held.array = ArrayAt::Spent;
            }
            (ArrayAt::Done, _) => {
                emit(bad(base, at, "bytes after the `]` of a JSON array"));
                held.array = ArrayAt::Spent;
            }
            (ArrayAt::First | ArrayAt::Next | ArrayAt::After, b']') => {
                held.junk = false;
                if held.array == ArrayAt::Next {
                    emit(bad(base, at, "a comma before the `]`"));
                }
                held.array = ArrayAt::Done;
                at += 1;
            }
            (ArrayAt::After, b',') => {
                held.junk = false;
                held.array = ArrayAt::Next;
                at += 1;
            }
            (ArrayAt::First | ArrayAt::Next, b',') => {
                junk(
                    held,
                    emit,
                    base + wide(at),
                    "a comma with no element before it",
                );
                at += 1;
            }
            (state, _) => {
                if state == ArrayAt::After {
                    emit(bad(base, at, "no comma between elements"));
                    held.array = ArrayAt::Next;
                }
                let Some(scan) = Scan::open(byte) else {
                    junk(
                        held,
                        emit,
                        base + wide(at),
                        "a byte no JSON value starts with",
                    );
                    at += 1;
                    continue;
                };
                held.junk = false;
                let Some(next) = fresh(c, false, input, at, scan, held, emit) else {
                    return;
                };
                at = next;
                held.array = ArrayAt::After;
            }
        }
    }
}