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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
// Project:   grippo
// File:      src/io/tests.rs
// Purpose:   Spec cases and split properties for the scanner, the writer and the sync helpers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use proptest::prelude::*;

use super::*;
use crate::parse::{CarriageReturns, StreamEncoding, StreamSplit};

const MB: usize = 1 << 20;

const SPLITS: [StreamSplit; 6] = [
    StreamSplit::Lf,
    StreamSplit::Nul,
    StreamSplit::OctetCounted,
    StreamSplit::JsonConcat,
    StreamSplit::JsonSeq,
    StreamSplit::JsonArray,
];

fn conf(split: StreamSplit, max_bytes: usize) -> StreamConfig {
    StreamConfig {
        split,
        max_bytes,
        ..StreamConfig::default()
    }
}

fn conf_keep(split: StreamSplit, max_bytes: usize) -> StreamConfig {
    StreamConfig {
        carriage_returns: CarriageReturns::Keep,
        ..conf(split, max_bytes)
    }
}

fn conf_cap(split: StreamSplit, max_bytes: usize, max_frame_bytes: usize) -> StreamConfig {
    StreamConfig {
        max_frame_bytes,
        ..conf(split, max_bytes)
    }
}

/// A frame with its bytes copied, for comparing.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Ev {
    Rec(Vec<u8>),
    Over(Vec<u8>, u64),
    Bad(u64),
    Cut(u64),
}

fn rec(bytes: &[u8]) -> Ev {
    Ev::Rec(bytes.to_vec())
}

fn over(head: &[u8], len: u64) -> Ev {
    Ev::Over(head.to_vec(), len)
}

fn ev(frame: Frame<Vec<u8>>) -> Ev {
    match frame {
        Frame::Record(bytes) => Ev::Rec(bytes),
        Frame::Oversize { len, head } => Ev::Over(head, len),
        Frame::Malformed { offset, .. } => Ev::Bad(offset),
        Frame::Cut { len } => Ev::Cut(len),
    }
}

/// The same frame with an oversize length dropped: the length is the bytes
/// seen when the frame passed the cap, which the read sizes decide.
fn headed(event: &Ev) -> Ev {
    match event {
        Ev::Over(head, _) => Ev::Over(head.clone(), 0),
        other => other.clone(),
    }
}

/// What a scanner gave for `inputs` read one after another into a buffer the
/// test owns, and its state before the end of input and after it.
#[derive(Debug)]
struct Scanned {
    events: Vec<Ev>,
    consumed: u64,
    mid_frame: bool,
    consumed_at_end: u64,
}

/// Run the scanner over `buf` until it needs more, checking every step's
/// ranges and dropping its bytes as a caller does.
fn drain(scanner: &mut Scanner, buf: &mut Vec<u8>, eof: bool, events: &mut Vec<Ev>) {
    // Each step drops a byte or moves the state on, so this is a generous bound.
    for _ in 0..4 * buf.len() + 16 {
        let step = scanner.next(buf, eof);
        let consume = step.consume(buf);
        assert!(consume <= buf.len(), "{step:?} past {}", buf.len());
        match &step {
            Step::Record { record, .. } => {
                assert!(record.end <= consume && !record.is_empty(), "{step:?}");
            }
            Step::Oversize { head, .. } => assert!(head.end <= consume, "{step:?}"),
            Step::Need => assert_eq!(scanner.partial_len(), buf.len()),
            _ => {}
        }
        if let Some(frame) = frame_of(&step, buf, <[u8]>::to_vec) {
            events.push(ev(frame));
        }
        buf.drain(..consume);
        if matches!(step, Step::Need | Step::Cut { .. }) {
            return;
        }
    }
    panic!("the scanner made no progress");
}

fn scan(c: &StreamConfig, inputs: &[&[u8]]) -> Scanned {
    let mut scanner = Scanner::new(c);
    let mut buf = Vec::new();
    let mut events = Vec::new();
    for input in inputs {
        buf.extend_from_slice(input);
        drain(&mut scanner, &mut buf, false, &mut events);
    }
    let consumed = scanner.consumed();
    let mid_frame = scanner.partial_len() > 0 || scanner.discarding();
    drain(&mut scanner, &mut buf, true, &mut events);
    assert!(buf.is_empty(), "the end of input left {buf:?}");
    assert!(!scanner.discarding());
    Scanned {
        events,
        consumed,
        mid_frame,
        consumed_at_end: scanner.consumed(),
    }
}

type EventCase<'c> = (&'c str, StreamConfig, Vec<&'c [u8]>, Vec<Ev>);

fn check_events(cases: Vec<EventCase<'_>>) {
    for (name, c, inputs, want) in cases {
        let got = scan(&c, &inputs);
        let total: usize = inputs.iter().map(|i| i.len()).sum();
        assert_eq!(got.events, want, "{name}");
        assert_eq!(
            got.consumed_at_end, total as u64,
            "{name}: consumed at the end"
        );
    }
}

#[test]
fn a_scanner_reports_each_frame_as_its_spec_says() {
    use StreamSplit::{Lf, Nul, OctetCounted};
    check_events(vec![
        (
            "lf: an oversize line has its head and its length with the LF",
            conf(Lf, 4),
            vec![b"abcdef\nok\n"],
            vec![over(b"abcd", 7), rec(b"ok")],
        ),
        (
            "lf: two oversize lines in one input are two frames",
            conf(Lf, 4),
            vec![b"abcdef\nghijkl\nok\n"],
            vec![over(b"abcd", 7), over(b"ghij", 7), rec(b"ok")],
        ),
        (
            "lf: an oversize line across reads is reported once it passes the cap, with the bytes seen",
            conf(Lf, 4),
            vec![b"abc", b"def", b"gh\nok\n"],
            vec![over(b"abcd", 6), rec(b"ok")],
        ),
        (
            "lf: an oversize line the end of input cuts",
            conf(Lf, 4),
            vec![b"abcdefgh"],
            vec![over(b"abcd", 8)],
        ),
        (
            "lf: the CRs before the LF count toward the cap",
            conf(Lf, 4),
            vec![b"abc\r\r\nok\n"],
            vec![over(b"abc\r", 6), rec(b"ok")],
        ),
        (
            "lf: CR LF, blank lines, a NUL and a last line with no LF",
            conf(Lf, MB),
            vec![b"a\nb\r\n\r\n\nc\0d\n e "],
            vec![rec(b"a"), rec(b"b"), rec(b"c\0d"), rec(b"e")],
        ),
        (
            "lf keep: the CRs are in the record",
            conf_keep(Lf, MB),
            vec![b"a\r\r\n\r\n\nb\r\n"],
            vec![rec(b"a\r\r"), rec(b"\r"), rec(b"b\r")],
        ),
        (
            "lf: a last line is trimmed, and no record when nothing is left",
            conf(Lf, MB),
            vec![b"a\n  b \t", b"\n  \r"],
            vec![rec(b"a"), rec(b"  b \t")],
        ),
        (
            "nul: an oversize frame has its head and its length with the NUL",
            conf(Nul, 3),
            vec![b"abcd\0ef\0"],
            vec![over(b"abc", 5), rec(b"ef")],
        ),
        (
            "nul: an LF and a CR stay in a frame, an empty frame is none, a last frame is trimmed",
            conf(Nul, MB),
            vec![b"{\"b\":\n2}\0\0a\r\0", b" tail \r"],
            vec![rec(b"{\"b\":\n2}"), rec(b"a\r"), rec(b"tail")],
        ),
        (
            "octet: a count over the cap is one frame with the header in its length",
            conf(OctetCounted, 8),
            vec![b"20 <1>aaaaaaaaaaaaaaaaa5 <2>bb"],
            vec![over(b"<1>aaaaa", 23), rec(b"<2>bb")],
        ),
        (
            "octet: a count over the cap cut across reads",
            conf(OctetCounted, 8),
            vec![b"2", b"0 <1>aaaa", b"aaaaaaaaaaaaa5 <2>bb"],
            vec![over(b"<1>aaaaa", 23), rec(b"<2>bb")],
        ),
        (
            "octet: an oversize frame the end of input cuts has its counted length",
            conf(OctetCounted, 4),
            vec![b"20 <1>aaa"],
            vec![over(b"<1>a", 23)],
        ),
        (
            "octet: a count over max_frame_bytes is an LF line with its head",
            conf_cap(OctetCounted, 8, 16),
            vec![b"20 <1>aaaaaaaaaaaaaaaaa\n5 <2>bb"],
            vec![over(b"20 <1>aa", 24), rec(b"<2>bb")],
        ),
        (
            "octet: a counted frame the end of input cuts is a cut",
            conf(OctetCounted, MB),
            vec![b"<1>a\n", b"9 <1>ab"],
            vec![rec(b"<1>a"), Ev::Cut(7)],
        ),
        (
            "octet: a last line is trimmed",
            conf(OctetCounted, MB),
            vec![b"4 <1>a", b"  x  "],
            vec![rec(b"<1>a"), rec(b"x")],
        ),
        (
            "octet keep: the CRs are in the record",
            conf_keep(OctetCounted, MB),
            vec![b"<1>a\r\n\r\n"],
            vec![rec(b"<1>a\r"), rec(b"\r")],
        ),
        (
            "octet: what isn't a count is an LF line, and the end after a count and its space is a last line",
            conf(OctetCounted, MB),
            vec![b"12x<1>a\n05 <1>b\n0 <1>c\n", b"4 "],
            vec![rec(b"12x<1>a"), rec(b"05 <1>b"), rec(b"0 <1>c"), rec(b"4")],
        ),
        (
            "octet: a count of 20 digits does not eat the stream",
            conf(OctetCounted, 8),
            vec![b"99999999999999999999 <1>a\nok\n"],
            vec![over(b"99999999", 26), rec(b"ok")],
        ),
        (
            "octet: a count of 20 digits cut across reads",
            conf(OctetCounted, 8),
            vec![b"9999999999", b"9999999999 <", b"1>a\nok\n"],
            vec![over(b"99999999", 10), rec(b"ok")],
        ),
    ]);
}

#[test]
fn a_json_scanner_reports_each_frame_as_its_spec_says() {
    use StreamSplit::{JsonArray, JsonConcat, JsonSeq};
    check_events(vec![
        (
            "concat: values with and without space between them",
            conf(JsonConcat, MB),
            vec![b"{\"a\":1}{\"b\":[1,{\"c\":\"}\"}]} \n 42 \"s\\\"\" true[]"],
            vec![
                rec(b"{\"a\":1}"),
                rec(b"{\"b\":[1,{\"c\":\"}\"}]}"),
                rec(b"42"),
                rec(b"\"s\\\"\""),
                rec(b"true"),
                rec(b"[]"),
            ],
        ),
        (
            "concat: values cut across reads, an escape included",
            conf(JsonConcat, MB),
            vec![b"{\"a\":\"x\\", b"\"y\"}[1", b",2]1", b"2"],
            vec![rec(b"{\"a\":\"x\\\"y\"}"), rec(b"[1,2]"), rec(b"12")],
        ),
        (
            "concat: a value the end of input cuts is a cut",
            conf(JsonConcat, MB),
            vec![b"{}{\"a\":"],
            vec![rec(b"{}"), Ev::Cut(5)],
        ),
        (
            "concat: an oversize value across reads is reported once it passes the cap",
            conf(JsonConcat, 8),
            vec![b"{\"a\":\"0123", b"456789\"}{}"],
            vec![over(b"{\"a\":\"01", 10), rec(b"{}")],
        ),
        (
            "concat: an oversize value found whole has its length",
            conf(JsonConcat, 8),
            vec![b"{\"a\":\"0123456789\"}{}"],
            vec![over(b"{\"a\":\"01", 18), rec(b"{}")],
        ),
        (
            "concat: a run of bytes no value starts with is one malformed, at its first stream offset",
            conf(JsonConcat, MB),
            vec![b"{}", b"],", b" x{}"],
            vec![rec(b"{}"), Ev::Bad(2), rec(b"{}")],
        ),
        (
            "seq: RS before and LF after, RS doubled",
            conf(JsonSeq, MB),
            vec![b"\x1e{\"a\":1}\n\x1e\x1e[2]\n\x1e3\n"],
            vec![rec(b"{\"a\":1}"), rec(b"[2]"), rec(b"3")],
        ),
        (
            "seq: a number the end of input reaches is a cut",
            conf(JsonSeq, MB),
            vec![b"\x1e12"],
            vec![Ev::Cut(2)],
        ),
        (
            "seq: a text an RS cuts short is malformed at the RS",
            conf(JsonSeq, MB),
            vec![b"\x1e{\"a\":", b"\x1e{}\n"],
            vec![Ev::Bad(6), rec(b"{}")],
        ),
        (
            "seq: a number with no whitespace after it is dropped to the next RS",
            conf(JsonSeq, MB),
            vec![b"\x1e123\x1e{}\n\x1e4", b"5\n"],
            vec![Ev::Bad(4), rec(b"{}"), rec(b"45")],
        ),
        (
            "seq: text before an RS is skipped to it",
            conf(JsonSeq, MB),
            vec![b"x y\x1e{}\n"],
            vec![Ev::Bad(0), rec(b"{}")],
        ),
        (
            "seq: an oversize text an RS cuts short is oversize, once",
            conf(JsonSeq, 4),
            vec![b"\x1e{\"abcdef\x1e{}\n"],
            vec![over(b"{\"ab", 8), rec(b"{}")],
        ),
        (
            "seq: an oversize text an RS cuts short, read a byte at a time, frames on at the RS",
            conf(JsonSeq, 2),
            vec![b"{", b"<", b"<", b"\x1e[]\n"],
            vec![over(b"{<", 3), rec(b"[]")],
        ),
        (
            "array: elements cut across reads",
            conf(JsonArray, MB),
            vec![b"  [{\"a\":", b"1}, [2", b",3] ,", b"4", b"2 ]"],
            vec![rec(b"{\"a\":1}"), rec(b"[2,3]"), rec(b"42")],
        ),
        (
            "array: a stream that ends before the closing bracket is a cut, counted from the opening one",
            conf(JsonArray, MB),
            vec![b"  [{\"a\":1},{\"b\"", b":2},3"],
            vec![rec(b"{\"a\":1}"), rec(b"{\"b\":2}"), Ev::Cut(18)],
        ),
        (
            "array: an oversize element is reported with its head, then the cut",
            conf(JsonArray, 4),
            vec![b"[\"abcdefg"],
            vec![over(b"\"abc", 8), Ev::Cut(9)],
        ),
        (
            "array: an element over the cap is skipped and the rest goes on",
            conf(JsonArray, 4),
            vec![b"[\"abcdef\",1,\"gh", b"ijkl\",2]"],
            vec![over(b"\"abc", 8), rec(b"1"), over(b"\"ghi", 8), rec(b"2")],
        ),
        (
            "array: a closed array is no cut, and bytes after it are malformed",
            conf(JsonArray, MB),
            vec![b"[1]", b" x", b"[2]"],
            vec![rec(b"1"), Ev::Bad(4)],
        ),
        (
            "array: bytes before the bracket",
            conf(JsonArray, MB),
            vec![b" x[1]"],
            vec![Ev::Bad(1)],
        ),
        (
            "array: a missing comma, a doubled one, a leading one and a trailing one",
            conf(JsonArray, MB),
            vec![b"[,1 2,,3,]"],
            vec![
                Ev::Bad(1),
                rec(b"1"),
                Ev::Bad(4),
                rec(b"2"),
                Ev::Bad(6),
                rec(b"3"),
                Ev::Bad(9),
            ],
        ),
        (
            "array: strings holding delimiters, escapes and nesting are single elements",
            conf(JsonArray, MB),
            vec![br#"["a,b[c]{d}", "he said \"hi\"", "path\\", [[1],{"k":[2]}]]"#],
            vec![
                rec(br#""a,b[c]{d}""#),
                rec(br#""he said \"hi\"""#),
                rec(br#""path\\""#),
                rec(br#"[[1],{"k":[2]}]"#),
            ],
        ),
    ]);
}

/// `consumed`, `partial_len` and `discarding` after each read, then at the end.
#[test]
fn a_scanner_says_what_it_consumed_holds_and_discards() {
    use StreamSplit::{JsonConcat, Lf, OctetCounted};
    // (name, config, [(read, consumed, partial_len, discarding)], consumed at the end)
    type Steps<'c> = (
        &'c str,
        StreamConfig,
        Vec<(&'c [u8], u64, usize, bool)>,
        u64,
    );
    let cases: Vec<Steps<'_>> = vec![
        (
            "lf: a held line, a blank line and a lone CR",
            conf(Lf, 8),
            vec![
                (b"ab", 0, 2, false),
                (b"c\n", 4, 0, false),
                (b"\n\r\n", 7, 0, false),
                (b"\r", 7, 1, false),
                (b"\n", 9, 0, false),
            ],
            9,
        ),
        (
            "lf: an oversize line is dropped as it arrives",
            conf(Lf, 4),
            vec![
                (b"abcdef", 6, 0, true),
                (b"gh", 8, 0, true),
                (b"\n", 9, 0, false),
            ],
            9,
        ),
        (
            "octet: a frame cut across reads",
            conf(OctetCounted, 8),
            vec![(b"5 <1", 0, 4, false), (b">ab", 7, 0, false)],
            7,
        ),
        (
            "octet: an oversize counted frame is dropped to its last byte",
            conf(OctetCounted, 4),
            vec![(b"10 <1>aaa", 9, 0, true), (b"aaaa", 13, 0, false)],
            13,
        ),
        (
            "json: a value cut across reads",
            conf(JsonConcat, 16),
            vec![(b"{\"a\":", 0, 5, false), (b"1} ", 8, 0, false)],
            8,
        ),
        (
            "lf: a last line with no LF is consumed at the end",
            conf(Lf, 8),
            vec![(b"a\nbc", 2, 2, false)],
            4,
        ),
    ];
    for (name, c, steps, at_end) in cases {
        let mut scanner = Scanner::new(&c);
        let mut buf = Vec::new();
        let mut events = Vec::new();
        for (n, (input, consumed, partial, discarding)) in steps.into_iter().enumerate() {
            buf.extend_from_slice(input);
            drain(&mut scanner, &mut buf, false, &mut events);
            assert_eq!(
                scanner.consumed(),
                consumed,
                "{name}: consumed after read {n}"
            );
            assert_eq!(
                scanner.partial_len(),
                partial,
                "{name}: partial after read {n}"
            );
            assert_eq!(
                scanner.discarding(),
                discarding,
                "{name}: discarding after read {n}"
            );
        }
        drain(&mut scanner, &mut buf, true, &mut events);
        assert_eq!(scanner.consumed(), at_end, "{name}: consumed at the end");
        assert_eq!(scanner.partial_len(), 0, "{name}: partial at the end");
        assert!(!scanner.discarding(), "{name}: discarding at the end");
    }
}

/// Real files that open with a UTF-8 byte order mark, framed for each split
/// with the mark kept at the stream's start, read whole and a byte at a time.
#[test]
fn a_byte_order_mark_at_the_stream_start_is_dropped_for_every_split() {
    use crate::shared_tests::corpus::file_bytes;
    let csv = file_bytes("jc", "tests/fixtures/generic/csv-utf-8-bom.csv");
    let json = file_bytes(
        "jsontestsuite",
        "test_parsing/i_structure_UTF-8_BOM_empty_object.json",
    );
    let (bom, text) = csv.split_at(3);
    assert_eq!(bom, b"\xef\xbb\xbf");
    assert!(json.starts_with(bom));
    let lines: Vec<&[u8]> = text
        .split(|&b| b == b'\n')
        .map(|l| l.strip_suffix(b"\r").unwrap_or(l))
        .filter(|l| !l.is_empty())
        .collect();
    let value = json[3..].trim_ascii();
    let mut nul = bom.to_vec();
    for line in &lines {
        nul.extend_from_slice(line);
        nul.push(0);
    }
    for split in SPLITS {
        let c = conf(split, MB);
        let (records, body): (Vec<&[u8]>, Vec<u8>) = match split {
            StreamSplit::Nul => (lines.clone(), nul.clone()),
            StreamSplit::JsonConcat => (vec![value], json.clone()),
            StreamSplit::JsonSeq => (vec![value], [bom, b"\x1e", value, b"\n"].concat()),
            StreamSplit::JsonArray => (vec![value], [bom, b"[", value, b"]"].concat()),
            // An octet-counted stream reads lines with no count as LF lines.
            _ => (lines.clone(), csv.clone()),
        };
        let want: Vec<Ev> = records.iter().map(|r| rec(r)).collect();
        let singles: Vec<&[u8]> = body.chunks(1).collect();
        for pieces in [vec![&body[..]], singles] {
            let got = scan(&c, &pieces);
            assert_eq!(got.events, want, "{split:?}");
            assert_eq!(got.consumed_at_end, body.len() as u64, "{split:?}");
        }
        let kept = StreamConfig {
            strip_bom: false,
            ..c
        };
        assert_ne!(
            scan(&kept, &[&body]).events,
            want,
            "{split:?} with the mark kept"
        );
    }
}

#[test]
fn only_a_whole_mark_at_the_stream_start_is_dropped() {
    let kept = StreamConfig {
        strip_bom: false,
        ..conf(StreamSplit::Lf, MB)
    };
    check_events(vec![
        (
            "lf: a mark cut across reads",
            conf(StreamSplit::Lf, MB),
            vec![b"\xef", b"\xbb", b"\xbfa\nb\n"],
            vec![rec(b"a"), rec(b"b")],
        ),
        (
            "lf: a mark after the start is text",
            conf(StreamSplit::Lf, MB),
            vec![b"a\n\xef\xbb\xbfb\n"],
            vec![rec(b"a"), rec(b"\xef\xbb\xbfb")],
        ),
        (
            "lf: the start of a mark and then other bytes is text",
            conf(StreamSplit::Lf, MB),
            vec![b"\xef\xbb", b"x\n"],
            vec![rec(b"\xef\xbbx")],
        ),
        (
            "lf: the start of a mark the end of input cuts is text",
            conf(StreamSplit::Lf, MB),
            vec![b"\xef\xbb"],
            vec![rec(b"\xef\xbb")],
        ),
        (
            "lf: strip_bom off keeps the mark",
            kept,
            vec![b"\xef\xbb\xbfa\n"],
            vec![rec(b"\xef\xbb\xbfa")],
        ),
        (
            "concat: an offset after the mark counts it",
            conf(StreamSplit::JsonConcat, MB),
            vec![b"\xef\xbb\xbf]{}"],
            vec![Ev::Bad(3), rec(b"{}")],
        ),
    ]);
    let mut out = Vec::new();
    assert_eq!(
        Writer::new(&conf(StreamSplit::Lf, MB)).frame(b"\xef\xbb\xbfa", &mut out),
        Err(Refused::ByteOrderMark)
    );
    let mut writer = Writer::new(&conf(StreamSplit::Lf, MB));
    writer.frame(b"a", &mut out).unwrap();
    writer.frame(b"\xef\xbb\xbfb", &mut out).unwrap();
}

#[test]
fn a_run_of_junk_between_two_values_is_one_malformed_however_it_is_read() {
    let junk = vec![b'x'; 10_000];
    let concat = [&b"{\"a\":1}"[..], &junk, b"{\"b\":2}"].concat();
    let array = [&b"[1,"[..], &junk, b",2]"].concat();
    for (name, c, body, want) in [
        (
            "concat",
            conf(StreamSplit::JsonConcat, MB),
            concat,
            vec![rec(b"{\"a\":1}"), Ev::Bad(7), rec(b"{\"b\":2}")],
        ),
        (
            "array",
            conf(StreamSplit::JsonArray, MB),
            array,
            vec![rec(b"1"), Ev::Bad(3), rec(b"2")],
        ),
    ] {
        let singles: Vec<&[u8]> = body.chunks(1).collect();
        let sevens: Vec<&[u8]> = body.chunks(7).collect();
        for pieces in [vec![&body[..]], singles, sevens] {
            assert_eq!(scan(&c, &pieces).events, want, "{name}");
        }
    }
}

#[test]
fn a_writer_frames_each_split_and_refuses_what_would_not_read_back() {
    use StreamSplit::{JsonArray, JsonConcat, JsonSeq, Lf, Nul, OctetCounted};
    let cases: [(StreamConfig, &[&[u8]], &[u8]); 7] = [
        (conf(Lf, MB), &[b"a", b" b\t"], b"a\n b\t\n"),
        (conf_keep(Lf, MB), &[b"a\r"], b"a\r\n"),
        (conf(Nul, MB), &[b"a\nb", b"c\r"], b"a\nb\0c\r\0"),
        (
            conf(OctetCounted, MB),
            &[b"<1>a b", b"<2>\n"],
            b"6 <1>a b4 <2>\n",
        ),
        (
            conf(JsonConcat, MB),
            &[b"{}", b"12", b"\"s\""],
            b"{}\n12\n\"s\"\n",
        ),
        (
            conf(JsonSeq, MB),
            &[b"[1]", b"true"],
            b"\x1e[1]\n\x1etrue\n",
        ),
        (
            conf(JsonArray, MB),
            &[b"{\"a\":[1]}", b"-2.5"],
            b"[{\"a\":[1]},-2.5]",
        ),
    ];
    for (c, records, want) in cases {
        let mut writer = Writer::new(&c);
        let mut out = Vec::new();
        for r in records {
            writer.frame(r, &mut out).unwrap();
        }
        writer.finish(&mut out);
        assert_eq!(out, want, "{:?}", c.split);
        let mut empty = Vec::new();
        Writer::new(&c).finish(&mut empty);
        let none: &[u8] = if c.split == JsonArray { b"[]" } else { b"" };
        assert_eq!(empty, none, "{:?} with no record", c.split);
    }
    for (c, record, want) in [
        (conf(Lf, MB), &b""[..], Refused::Empty),
        (conf(Lf, MB), b"a\nb", Refused::Delimiter),
        (conf(Lf, MB), b"a\r", Refused::CarriageReturn),
        (conf(Lf, 2), b"abc", Refused::TooLong { len: 3, max: 2 }),
        (conf(Nul, MB), b"a\0", Refused::Delimiter),
        (conf(OctetCounted, MB), b"1 x", Refused::NotCounted),
        (conf(JsonConcat, MB), b" 1", Refused::NotOneValue),
        (conf(JsonConcat, MB), b"1 2", Refused::NotOneValue),
        (conf(JsonConcat, MB), b"{\"a\":1", Refused::NotOneValue),
        (conf(JsonSeq, MB), b"[\x1e]", Refused::NotOneValue),
        (conf(JsonArray, MB), b"{}x", Refused::NotOneValue),
    ] {
        let mut out = b"kept".to_vec();
        assert_eq!(
            Writer::new(&c).frame(record, &mut out),
            Err(want),
            "{:?} {record:?}",
            c.split
        );
        assert_eq!(out, b"kept");
    }
}

/// A reader that hands out its bytes `chunk` at a time.
struct Chunked<'a> {
    bytes: &'a [u8],
    chunk: usize,
}

impl std::io::Read for Chunked<'_> {
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        let n = self.chunk.min(out.len()).min(self.bytes.len());
        out[..n].copy_from_slice(&self.bytes[..n]);
        self.bytes = &self.bytes[n..];
        Ok(n)
    }
}

/// What `frames` reads from `bytes` through a buffer of `capacity` filled
/// `chunk` bytes a read.
fn read_frames(c: &StreamConfig, bytes: &[u8], capacity: usize, chunk: usize) -> Vec<Ev> {
    let reader = std::io::BufReader::with_capacity(capacity, Chunked { bytes, chunk });
    frames(reader, c).map(|f| ev(f.unwrap())).collect()
}

/// Real UTF-16 documents, with and without a byte order mark, and the
/// encodings that read each, each with the decoding `encoding_rs` gives the
/// whole file.
fn utf16_samples() -> Vec<(String, Vec<u8>, Vec<StreamEncoding>, String)> {
    use StreamEncoding::{Bom, Utf16Be, Utf16Le};
    let le = encoding_rs::UTF_16LE;
    let be = encoding_rs::UTF_16BE;
    let mut samples = Vec::new();
    for (source, path, encodings, encoding) in [
        (
            "quick-xml-documents",
            "tests/documents/encoding/utf16le-bom.xml",
            vec![Utf16Le, Bom],
            le,
        ),
        (
            "quick-xml-documents",
            "tests/documents/encoding/utf16be-bom.xml",
            vec![Utf16Be, Bom],
            be,
        ),
        (
            "quick-xml-documents",
            "tests/documents/encoding/utf16le.xml",
            vec![Utf16Le],
            le,
        ),
        (
            "quick-xml-documents",
            "tests/documents/encoding/utf16be.xml",
            vec![Utf16Be],
            be,
        ),
        (
            "jsontestsuite",
            "test_parsing/i_string_UTF-16LE_with_BOM.json",
            vec![Utf16Le, Bom],
            le,
        ),
        (
            "jsontestsuite",
            "test_parsing/i_string_utf16BE_no_BOM.json",
            vec![Utf16Be],
            be,
        ),
    ] {
        let bytes = crate::shared_tests::corpus::file_bytes(source, path);
        let text = encoding.decode(&bytes).0.into_owned();
        samples.push((path.to_owned(), bytes, encodings, text));
    }
    samples
}

#[test]
fn a_utf16_stream_frames_as_its_utf8_text_at_any_read_size() {
    for (path, bytes, encodings, text) in utf16_samples() {
        let want = scan(&conf(StreamSplit::Lf, MB), &[text.as_bytes()]).events;
        assert!(!want.is_empty(), "{path}");
        for encoding in encodings {
            let c = StreamConfig {
                encoding,
                ..conf(StreamSplit::Lf, MB)
            };
            for (capacity, chunk) in [(8192, 8192), (1, 1), (64, 7), (16, 3)] {
                assert_eq!(
                    read_frames(&c, &bytes, capacity, chunk),
                    want,
                    "{path} as {encoding:?}, {capacity}/{chunk}"
                );
            }
        }
    }
}

#[test]
fn a_decoder_holds_a_cut_unit_pair_or_mark_and_replaces_a_broken_one() {
    use StreamEncoding::{Bom, Utf8, Utf16Be, Utf16Le};
    // `a`, U+1F600 as a surrogate pair, `b` and LF, in UTF-16LE and UTF-16BE.
    let le: &[u8] = b"a\0\x3d\xd8\x00\xdeb\0\n\0";
    let be: &[u8] = b"\0a\xd8\x3d\xde\x00\0b\0\n";
    let smile = "a\u{1f600}b".as_bytes();
    for (name, encoding, body, want) in [
        ("le, no mark", Utf16Le, le.to_vec(), vec![rec(smile)]),
        ("be, no mark", Utf16Be, be.to_vec(), vec![rec(smile)]),
        (
            "le with its mark",
            Utf16Le,
            [b"\xff\xfe", le].concat(),
            vec![rec(smile)],
        ),
        (
            "bom naming le",
            Bom,
            [b"\xff\xfe", le].concat(),
            vec![rec(smile)],
        ),
        (
            "bom naming be",
            Bom,
            [b"\xfe\xff", be].concat(),
            vec![rec(smile)],
        ),
        (
            "bom naming utf-8",
            Bom,
            b"\xef\xbb\xbfa\nb\n".to_vec(),
            vec![rec(b"a"), rec(b"b")],
        ),
        (
            "bom with no mark reads utf-8",
            Bom,
            b"a\nb".to_vec(),
            vec![rec(b"a"), rec(b"b")],
        ),
        (
            "a utf-8 mark in a utf-16 stream is text",
            Utf16Le,
            b"\xef\xbb\xbf\0\n\0".to_vec(),
            vec![rec("\u{bbef}\u{bf}".as_bytes())],
        ),
        (
            "an odd last byte reads as U+FFFD",
            Utf16Le,
            b"a\0\n\0b".to_vec(),
            vec![rec(b"a"), rec("\u{fffd}".as_bytes())],
        ),
        (
            "a lone high surrogate reads as U+FFFD",
            Utf16Le,
            b"\x3d\xd8".to_vec(),
            vec![rec("\u{fffd}".as_bytes())],
        ),
        (
            "utf-8 is left alone",
            Utf8,
            b"\xff\xfe\n".to_vec(),
            vec![rec(b"\xff\xfe")],
        ),
    ] {
        let c = StreamConfig {
            encoding,
            ..conf(StreamSplit::Lf, MB)
        };
        for (capacity, chunk) in [(64, 64), (1, 1), (2, 2), (3, 3)] {
            assert_eq!(
                read_frames(&c, &body, capacity, chunk),
                want,
                "{name}, {chunk} at a time"
            );
        }
    }
}

/// PowerShell 5.1's own output from the `windows-lab` corpus source, one
/// folder per Windows image.
#[test]
fn powershell_output_frames_in_each_encoding_it_writes() {
    use StreamEncoding::{Bom, Utf16Be, Utf16Le};
    let mut read = 0;
    for (name, encodings) in [
        ("ps_redirect.txt", vec![Utf16Le, Bom]),
        ("ps_outfile_default.txt", vec![Utf16Le, Bom]),
        ("ps_utf16le.txt", vec![Utf16Le, Bom]),
        ("ps_utf16be.txt", vec![Utf16Be, Bom]),
        ("ps_utf8_bom.txt", vec![Bom]),
    ] {
        for (image, bytes) in crate::shared_tests::windows_text::lab(name) {
            read += 1;
            // encoding_rs on the whole file, its mark naming the encoding, is the oracle.
            let text = encoding_rs::UTF_8.decode(&bytes).0.into_owned();
            let want = scan(&conf(StreamSplit::Lf, MB), &[text.as_bytes()]).events;
            assert_eq!(want.first(), Some(&rec(b"alpha line one")), "{name}");
            for &encoding in &encodings {
                let c = StreamConfig {
                    encoding,
                    ..conf(StreamSplit::Lf, MB)
                };
                for (capacity, chunk) in [(8192, 8192), (1, 1), (64, 7)] {
                    let got = read_frames(&c, &bytes, capacity, chunk);
                    let at = format!("{image}/{name} as {encoding:?}, {chunk} at a time");
                    assert_eq!(got, want, "{at}");
                }
            }
        }
    }
    assert!(read > 0, "windows-lab holds no PowerShell samples");
}

#[test]
fn frames_and_write_frames_round_trip_through_any_read_size() {
    let records: Vec<Vec<u8>> = (0..200)
        .map(|n| format!("<{}>{n} message {}", n % 191, "x".repeat(n % 37)).into_bytes())
        .collect();
    let json: Vec<Vec<u8>> = (0..200)
        .map(|n| format!("{{\"n\":{n},\"s\":\"{}\"}}", "y".repeat(n % 41)).into_bytes())
        .collect();
    for split in SPLITS {
        let c = conf(split, MB);
        let body = match split {
            StreamSplit::JsonConcat | StreamSplit::JsonSeq | StreamSplit::JsonArray => &json,
            _ => &records,
        };
        let mut out = Vec::new();
        write_frames(&mut out, &c, body).unwrap();
        let want: Vec<Ev> = body.iter().map(|r| rec(r)).collect();
        for (capacity, chunk) in [(8192, 8192), (1, 1), (64, 7), (16, 1000)] {
            assert_eq!(
                read_frames(&c, &out, capacity, chunk),
                want,
                "{split:?} {capacity}/{chunk}"
            );
        }
        assert_eq!(
            scan(&c, &[&out]).events,
            want,
            "{split:?} through the scanner"
        );
    }
    let refused = write_frames(Vec::new(), &conf(StreamSplit::Lf, MB), [&b"a\nb"[..]]).unwrap_err();
    assert_eq!(refused.kind(), std::io::ErrorKind::InvalidInput);
}

#[test]
fn a_feed_borrows_what_an_input_holds_whole_and_holds_only_a_cut_frame() {
    let mut feed = Feed::new(&conf(StreamSplit::Lf, MB));
    let mut out: Vec<(Vec<u8>, bool)> = Vec::new();
    let mut emit = |f: Frame<Cow<'_, [u8]>>| {
        if let Frame::Record(bytes) = f {
            out.push((bytes.to_vec(), matches!(bytes, Cow::Borrowed(_))));
        }
    };
    feed.push(b"a\r\nb\nc", false, &mut emit);
    assert_eq!(feed.held(), 1);
    feed.push(b"d\ne", false, &mut emit);
    assert_eq!(feed.fed(), 9);
    feed.push(b"", true, &mut emit);
    assert_eq!(
        out,
        [
            (b"a".to_vec(), true),
            (b"b".to_vec(), true),
            (b"cd".to_vec(), false),
            (b"e".to_vec(), false),
        ]
    );
}

/// The read sizes a seeded generator draws: 1 to 97 bytes.
fn random_cuts(body: &[u8], seed: u64) -> Vec<&[u8]> {
    let mut state = seed | 1;
    let mut pieces = Vec::new();
    let mut at = 0;
    while at < body.len() {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        let n = usize::try_from(state % 97).unwrap_or(0) + 1;
        let end = (at + n).min(body.len());
        pieces.push(&body[at..end]);
        at = end;
    }
    pieces
}

/// Every way to cut `body` in two.
fn halves(body: &[u8]) -> impl Iterator<Item = [&[u8]; 2]> {
    (0..=body.len()).map(move |i| [&body[..i], &body[i..]])
}

proptest! {
    /// Records the writer accepts, the stream then cut anywhere, read back as
    /// themselves.
    #[test]
    fn what_the_writer_frames_the_scanner_reads_back(
        lines in prop::collection::vec("[^\n]{0,12}", 0..6),
        values in prop::collection::vec("(-?[1-9][0-9]{0,3}|true|null|\"[a-z\\[\\]{}\\\\\"\n]{0,6}\"|\\[[0-9,]{0,5}\\]|\\{\\})", 0..5),
        keep in any::<bool>(),
        split in prop::sample::select(SPLITS.to_vec()),
    ) {
        let c = StreamConfig {
            carriage_returns: if keep { CarriageReturns::Keep } else { CarriageReturns::Strip },
            ..conf(split, MB)
        };
        let json = matches!(split, StreamSplit::JsonConcat | StreamSplit::JsonSeq | StreamSplit::JsonArray);
        let candidates: Vec<Vec<u8>> = if json {
            values.iter().map(|v| v.clone().into_bytes()).collect()
        } else if split == StreamSplit::OctetCounted {
            lines.iter().map(|l| format!("<{l}").into_bytes()).collect()
        } else {
            lines.iter().map(|l| l.clone().into_bytes()).collect()
        };
        let mut writer = Writer::new(&c);
        let mut body = Vec::new();
        let mut want = Vec::new();
        for r in &candidates {
            if writer.frame(r, &mut body).is_ok() {
                want.push(rec(r));
            }
        }
        writer.finish(&mut body);
        for inputs in halves(&body) {
            prop_assert_eq!(&scan(&c, &inputs).events, &want, "{:?}", inputs);
        }
        let singles: Vec<&[u8]> = body.chunks(1).collect();
        let got = scan(&c, &singles);
        prop_assert_eq!(&got.events, &want);
        prop_assert_eq!(got.consumed, body.len() as u64, "all consumed before the end of input");
        prop_assert!(!got.mid_frame);
    }

    /// Any bytes, read whole, a byte at a time, in threes or in random sizes,
    /// give the same frames and the same state before the end of input, an
    /// oversize frame's length aside.
    #[test]
    fn any_bytes_frame_the_same_at_any_read_size(
        bytes in prop::collection::vec(prop::sample::select(b"<0123 a{}\"\\[],\n\r\0\x1e".to_vec()), 0..48),
        max_bytes in 1_usize..10,
        max_frame_bytes in 1_usize..30,
        keep in any::<bool>(),
        seed in any::<u64>(),
        split in prop::sample::select(SPLITS.to_vec()),
    ) {
        let c = StreamConfig {
            carriage_returns: if keep { CarriageReturns::Keep } else { CarriageReturns::Strip },
            ..conf_cap(split, max_bytes, max_frame_bytes)
        };
        let whole = scan(&c, &[&bytes]);
        let whole_events: Vec<Ev> = whole.events.iter().map(headed).collect();
        let singles: Vec<&[u8]> = bytes.chunks(1).collect();
        let threes: Vec<&[u8]> = bytes.chunks(3).collect();
        for pieces in [singles, threes, random_cuts(&bytes, seed)] {
            let got = scan(&c, &pieces);
            let events: Vec<Ev> = got.events.iter().map(headed).collect();
            prop_assert_eq!(&events, &whole_events, "{:?}", pieces);
            prop_assert_eq!(got.consumed, whole.consumed);
            prop_assert_eq!(got.mid_frame, whole.mid_frame);
        }
        prop_assert_eq!(whole.consumed_at_end, bytes.len() as u64);
    }

    /// Any bytes through a feed, cut anywhere, hold no more than the cap and
    /// a counted header, and give the records the scanner gives.
    #[test]
    fn a_feed_holds_no_more_than_its_cap(
        bytes in prop::collection::vec(prop::sample::select(b"<0123 a{}\"\\[]\n\r\0\x1e".to_vec()), 0..40),
        max_bytes in 1_usize..10,
        split in prop::sample::select(SPLITS.to_vec()),
    ) {
        let c = conf(split, max_bytes);
        let want: Vec<Ev> = scan(&c, &[&bytes]).events.into_iter().filter(|e| matches!(e, Ev::Rec(_))).collect();
        for pieces in [bytes.chunks(3).collect::<Vec<_>>(), bytes.chunks(1).collect()] {
            let mut feed = Feed::new(&c);
            let mut got = Vec::new();
            for piece in pieces {
                feed.push(piece, false, &mut |f: Frame<Cow<'_, [u8]>>| if let Frame::Record(r) = f { got.push(rec(&r)) });
                prop_assert!(feed.held() <= max_bytes + 22, "{}", feed.held());
            }
            feed.push(b"", true, &mut |f: Frame<Cow<'_, [u8]>>| if let Frame::Record(r) = f { got.push(rec(&r)) });
            prop_assert_eq!(&got, &want);
        }
    }

    /// `each` gives the frames `next` gives, a step at a time, with the
    /// buffer drained between batches at any read size.
    #[test]
    fn each_gives_what_next_gives(
        bytes in prop::collection::vec(prop::sample::select(b"<0123 a{}\"\\[],\n\r\0\x1e".to_vec()), 0..48),
        max_bytes in 1_usize..10,
        seed in any::<u64>(),
        split in prop::sample::select(SPLITS.to_vec()),
    ) {
        let c = conf(split, max_bytes);
        let want = scan(&c, &random_cuts(&bytes, seed)).events;
        let mut scanner = Scanner::new(&c);
        let mut buf = Vec::new();
        let mut got = Vec::new();
        for piece in random_cuts(&bytes, seed) {
            buf.extend_from_slice(piece);
            let used = scanner.each(&buf, false, |f| got.push(ev(f.map(<[u8]>::to_vec))));
            buf.drain(..used);
        }
        let used = scanner.each(&buf, true, |f| got.push(ev(f.map(<[u8]>::to_vec))));
        prop_assert_eq!(used, buf.len());
        prop_assert_eq!(got, want);
    }
}

#[cfg(feature = "tokio")]
mod on_tokio {
    use std::future::Future;
    use std::pin::{Pin, pin};
    use std::task::{Context, Poll, Waker};

    use ::tokio::io::{AsyncRead, ReadBuf};
    use bytes::Bytes;
    use futures_core::Stream;

    use super::*;

    /// Run a future to its end. Every reader and writer here is in memory, so
    /// none ever waits.
    fn ready<F: Future>(future: F) -> F::Output {
        let mut future = pin!(future);
        let mut cx = Context::from_waker(Waker::noop());
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(out) => out,
            Poll::Pending => panic!("an in-memory future waited"),
        }
    }

    /// An async reader that hands out its bytes `chunk` at a time.
    struct Chunks<'a> {
        bytes: &'a [u8],
        chunk: usize,
    }

    impl AsyncRead for Chunks<'_> {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _: &mut Context<'_>,
            out: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            let n = self.chunk.min(out.remaining()).min(self.bytes.len());
            out.put_slice(&self.bytes[..n]);
            self.bytes = &self.bytes[n..];
            Poll::Ready(Ok(()))
        }
    }

    /// A stream of the items of an iterator.
    struct Items<I>(I);

    impl<I: Iterator + Unpin> Stream for Items<I> {
        type Item = I::Item;

        fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<I::Item>> {
            Poll::Ready(self.0.next())
        }
    }

    /// What `tokio::frames` reads from `bytes` read `chunk` bytes at a time.
    fn read(c: &StreamConfig, bytes: &[u8], chunk: usize) -> Vec<Ev> {
        let mut stream = pin!(super::super::tokio::frames(Chunks { bytes, chunk }, c));
        let mut cx = Context::from_waker(Waker::noop());
        let mut got = Vec::new();
        loop {
            match stream.as_mut().poll_next(&mut cx) {
                Poll::Ready(Some(frame)) => {
                    got.push(ev(frame.unwrap().map(|b: Bytes| b.to_vec())));
                }
                Poll::Ready(None) => return got,
                Poll::Pending => panic!("an in-memory reader waited"),
            }
        }
    }

    #[test]
    fn a_tokio_stream_reads_and_writes_what_the_sync_helpers_do() {
        let records: Vec<Vec<u8>> = (0..200)
            .map(|n| format!("<{}>{n} message {}", n % 191, "x".repeat(n % 37)).into_bytes())
            .collect();
        let json: Vec<Vec<u8>> = (0..200)
            .map(|n| format!("{{\"n\":{n},\"s\":\"{}\"}}", "y".repeat(n % 41)).into_bytes())
            .collect();
        for split in SPLITS {
            let body = match split {
                StreamSplit::JsonConcat | StreamSplit::JsonSeq | StreamSplit::JsonArray => &json,
                _ => &records,
            };
            for max in [MB, 40] {
                let c = conf(split, MB);
                let mut sync = Vec::new();
                write_frames(&mut sync, &c, body).unwrap();
                let mut written = Vec::new();
                ready(super::super::tokio::write_frames(
                    &mut written,
                    &c,
                    Items(body.iter()),
                ))
                .unwrap();
                assert_eq!(written, sync, "{split:?}");
                let capped = conf(split, max);
                let want: Vec<Ev> = scan(&capped, &[&sync]).events.iter().map(headed).collect();
                for chunk in [1, 7, 4096, sync.len()] {
                    let got: Vec<Ev> = read(&capped, &sync, chunk).iter().map(headed).collect();
                    assert_eq!(
                        got, want,
                        "{split:?} capped at {max}, read {chunk} at a time"
                    );
                }
            }
        }
        let refused = ready(super::super::tokio::write_frames(
            Vec::new(),
            &conf(StreamSplit::Lf, MB),
            Items([&b"a"[..], b"b\nc"].into_iter()),
        ))
        .unwrap_err();
        assert_eq!(refused.kind(), std::io::ErrorKind::InvalidInput);
    }

    #[test]
    fn a_tokio_stream_decodes_utf16_as_the_sync_reader_does() {
        for (path, bytes, encodings, _) in utf16_samples() {
            for encoding in encodings {
                let c = StreamConfig {
                    encoding,
                    ..conf(StreamSplit::Lf, MB)
                };
                let want = read_frames(&c, &bytes, 8192, 8192);
                for chunk in [1, 7, 4096] {
                    assert_eq!(
                        read(&c, &bytes, chunk),
                        want,
                        "{path} as {encoding:?}, {chunk} at a time"
                    );
                }
            }
        }
    }

    /// Real files that open with a byte order mark, and junk, oversize and
    /// cut frames, read through the codec at any read size.
    #[test]
    fn a_tokio_stream_gives_every_frame_kind_the_scanner_does() {
        let csv = crate::shared_tests::corpus::file_bytes(
            "jc",
            "tests/fixtures/generic/csv-utf-8-bom.csv",
        );
        let junk = [&b"{\"a\":1}"[..], &[b'x'; 300], b"{\"b\":2}{\"c\":"].concat();
        for (c, body) in [
            (conf(StreamSplit::Lf, MB), csv.clone()),
            (conf(StreamSplit::Lf, 8), csv),
            (conf(StreamSplit::JsonConcat, MB), junk),
            (
                conf(StreamSplit::JsonArray, 4),
                b"[\"abcdef\",1,[2]".to_vec(),
            ),
            (
                conf(StreamSplit::OctetCounted, 8),
                b"20 <1>aaaaaaaaaaaaaaaaa5 <2>bb9 <1>a".to_vec(),
            ),
        ] {
            let want: Vec<Ev> = scan(&c, &[&body]).events.iter().map(headed).collect();
            for chunk in [1, 3, 64, body.len()] {
                let got: Vec<Ev> = read(&c, &body, chunk).iter().map(headed).collect();
                assert_eq!(got, want, "{:?} read {chunk} at a time", c.split);
            }
        }
    }
}