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)
}
}
#[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),
}
}
fn headed(event: &Ev) -> Ev {
match event {
Ev::Over(head, _) => Ev::Over(head.clone(), 0),
other => other.clone(),
}
}
#[derive(Debug)]
struct Scanned {
events: Vec<Ev>,
consumed: u64,
mid_frame: bool,
consumed_at_end: u64,
}
fn drain(scanner: &mut Scanner, buf: &mut Vec<u8>, eof: bool, events: &mut Vec<Ev>) {
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]}]"#),
],
),
]);
}
#[test]
fn a_scanner_says_what_it_consumed_holds_and_discards() {
use StreamSplit::{JsonConcat, Lf, OctetCounted};
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");
}
}
#[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()),
_ => (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");
}
}
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)
}
}
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()
}
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};
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"
);
}
}
}
#[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;
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),
]
);
}
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
}
fn halves(body: &[u8]) -> impl Iterator<Item = [&[u8]; 2]> {
(0..=body.len()).map(move |i| [&body[..i], &body[i..]])
}
proptest! {
#[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);
}
#[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);
}
#[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);
}
}
#[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::*;
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"),
}
}
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(()))
}
}
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())
}
}
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"
);
}
}
}
}
#[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);
}
}
}
}