use std::fmt::Write;
use std::net::Ipv6Addr;
use std::sync::LazyLock;
use proptest::prelude::*;
use regex_automata::meta::Regex;
use regex_automata::{Anchored, Input};
use super::*;
fn table() -> impl Iterator<Item = &'static Field> {
every()
}
static REGEXES: LazyLock<Vec<Oracle>> = LazyLock::new(|| {
table()
.map(|f| {
let whole = format!("(?:{})", f.regex);
Regex::new(&whole).map_or_else(
|_| {
let relaxed = format!("(?:{})", Edge::relaxed(f.regex));
Oracle::Fancy(
Regex::new(&relaxed).unwrap(),
fancy_regex::Regex::new(&whole).unwrap(),
)
},
Oracle::Linear,
)
})
.collect()
});
enum Oracle {
Linear(Regex),
Fancy(Regex, fancy_regex::Regex),
}
fn regex_end(i: usize, hay: &[u8], at: usize) -> Option<usize> {
match ®EXES[i] {
Oracle::Linear(regex) => {
let input = Input::new(hay).range(at..).anchored(Anchored::Yes);
regex.search(&input).map(|m| m.end())
}
Oracle::Fancy(relaxed, regex) => {
let anchored = Input::new(hay).range(at..).anchored(Anchored::Yes);
relaxed.search_half(&anchored)?;
let input = fancy_regex::RegexInput::new(hay)
.from_pos(at)
.anchored(true);
regex.find_input(input).unwrap().map(|m| m.end())
}
}
}
fn agree(hay: &str, at: usize) -> Result<usize, TestCaseError> {
let mut deferred = 0;
for (i, f) in table().enumerate() {
let want = regex_end(i, hay.as_bytes(), at);
match (f.scan)(hay.as_bytes(), at) {
Scan::Defer => deferred += 1,
Scan::Match(end) => {
prop_assert_eq!(Some(end), want, "{} on {:?} at {}", f.name, hay, at);
}
Scan::NoMatch => prop_assert_eq!(None, want, "{} on {:?} at {}", f.name, hay, at),
}
}
Ok(deferred)
}
#[test]
fn known_lines_match_as_the_regex_does() {
let rows: &[(&str, &str, Option<&str>)] = &[
("IPV4", "10.1.2.3:443", Some("10.1.2.3")),
("IPV4", "175.16.199.1", Some("175.16.199.1")),
("IPV4", "1.2.3.4567", None),
("IPV4", "x1.2.3.4", None),
("IPV4", "10.0.0.1host.example", Some("10.0.0.1")),
("IPV4", "10.0.0.1_x", Some("10.0.0.1")),
("WORD", "error: disk", Some("error")),
("INT", "-42ms", Some("-42")),
("INT", "+x", None),
("INT", "\u{661}\u{662}\u{663}", None),
("INT", "12\u{663}", Some("12")),
("PORT", "\u{661}\u{662}", None),
("NUMBER", "\u{661}.\u{662}", None),
("TIME", "1\u{663}:00", None),
("NUMBER", "3.14.15", Some("3.14")),
("NUMBER", ".5", Some(".5")),
("NUMBER", "7.", Some("7")),
("POSINT", "012", None),
("NONNEGINT", "12ab", None),
("MAC", "00:1a:2b:3c:4d:5e", Some("00:1a:2b:3c:4d:5e")),
("MAC", "001a.2b3c.4d5e", Some("001a.2b3c.4d5e")),
(
"UUID",
"123e4567-e89b-12d3-a456-426614174000",
Some("123e4567-e89b-12d3-a456-426614174000"),
),
(
"QUOTEDSTRING",
r#""a \"b\" c" tail"#,
Some(r#""a \"b\" c""#),
),
("QUOTEDSTRING", "''", Some("''")),
("LOGLEVEL", "ERROR:", Some("ERROR")),
("LOGLEVEL", "Warning", Some("Warning")),
("MONTH", "June", Some("June")),
("MONTH", "Junk", Some("Jun")),
("YEAR", "123", Some("12")),
("HOUR", "24", Some("2")),
("TIME", "9:05:07.123 x", Some("9:05:07.123")),
("TIME", "123:45", None),
("ISO8601_TIMEZONE", "+130", Some("+130")),
(
"TIMESTAMP_ISO8601",
"2026-11-26T11:22:33.456+11:00 x",
Some("2026-11-26T11:22:33.456+11:00"),
),
(
"TIMESTAMP_ISO8601",
"2026-11-26 11:22Z",
Some("2026-11-26 11:22Z"),
),
(
"SYSLOGTIMESTAMP",
"Nov 6 08:01:02 host",
Some("Nov 6 08:01:02"),
),
(
"HTTPDATE",
"26/Nov/2026:11:22:33 +1100]",
Some("26/Nov/2026:11:22:33 +1100"),
),
("BASE10NUM", "-3.25e", Some("-3.25")),
("BASE10NUM", "+.5", Some("+.5")),
("BASE16NUM", "0x1Fz", Some("0x1F")),
("BASE16NUM", "0xg", Some("0")),
("URIPATH", "/a/b.html?q=1", Some("/a/b.html")),
("URIPATH", "a/b", None),
("URIPARAM", "?q=1&r=[2] x", Some("?q=1&r=[2]")),
("UNIXPATH", "/var/log/syslog.1 x", Some("/var/log/syslog.1")),
("WINPATH", r"C:\Windows\x.dll? y", Some(r"C:\Windows\x.dll")),
("WINPATH", r"\\srv\share", Some(r"\\srv\share")),
("WINPATH", r"\srv", None),
(
"JAVACLASS",
"org.example.Main.run()",
Some("org.example.Main.run"),
),
("JAVACLASS", "a..b", Some("a")),
(
"EMAILADDRESS",
"ops+alerts@mail.example.com>",
Some("ops+alerts@mail.example.com"),
),
("EMAILADDRESS", "a@b", None),
];
for (name, hay, want) in rows {
let f = field(name).unwrap();
let got = match (f.scan)(hay.as_bytes(), 0) {
Scan::Match(end) => Some(&hay[..end]),
Scan::NoMatch => None,
Scan::Defer => panic!("{name} deferred on ASCII {hay:?}"),
};
assert_eq!(got, *want, "{name} on {hay:?}");
let i = FIELDS.iter().position(|g| g.name == *name).unwrap();
assert_eq!(
regex_end(i, hay.as_bytes(), 0).map(|e| &hay[..e]),
*want,
"{name} regex on {hay:?}"
);
}
}
#[test]
fn the_ascii_classes_hold_what_their_char_tests_do() {
for byte in 0..=255_u8 {
let ascii = byte.is_ascii().then(|| char::from(byte));
assert_eq!(
NOTSPACE.has(byte),
ascii.is_some_and(|c| !c.is_whitespace()),
"NOTSPACE {byte:#x}"
);
assert_eq!(WORD.has(byte), ascii.is_some_and(is_word), "WORD {byte:#x}");
}
for (line, end) in [("abc\u{b}def", 3), ("abc\u{a0}def", 3), ("ab\u{e9}c d", 5)] {
assert_eq!(notspace(line.as_bytes(), 0), Scan::Match(end), "{line:?}");
}
assert_eq!(word("na\u{ef}ve_1 x".as_bytes(), 0), Scan::Match(8));
for lead in 0..40 {
let line = format!(
"{}{}\u{e9}{} tail",
" ".repeat(lead),
"a".repeat(45),
"b".repeat(37)
);
let end = lead + 45 + 2 + 37;
assert_eq!(notspace(line.as_bytes(), lead), Scan::Match(end), "{lead}");
assert_eq!(word(line.as_bytes(), lead), Scan::Match(end), "{lead}");
}
}
#[test]
fn a_unicode_digit_is_no_digit_and_a_unicode_letter_is_a_word() {
let arabic_three = "\u{0663}";
let int = field("INT").unwrap().scan;
let hay = format!("1{arabic_three}");
assert_eq!(int(hay.as_bytes(), 0), Scan::Match(1));
assert_eq!(int(arabic_three.as_bytes(), 0), Scan::NoMatch);
let hay = "é12";
assert_eq!(
(field("NONNEGINT").unwrap().scan)(hay.as_bytes(), 2),
Scan::NoMatch
);
assert_eq!(field("NOPE").map(|f| f.name), None);
}
#[test]
fn a_wide_zone_runs_to_the_end_of_the_line() {
for (hay, wide, bounded) in [
("fe80::1%eth0 up", Scan::Match(15), Scan::Match(12)),
("fe80::1%a b\nc", Scan::Match(11), Scan::Match(9)),
("fe80::1%eth0/1", Scan::Match(14), Scan::Match(12)),
("fe80::1%", Scan::Match(7), Scan::Match(7)),
("fe80::1%\n", Scan::Match(7), Scan::Match(7)),
("fe80::1", Scan::Match(7), Scan::Match(7)),
("10.0.0.1%x", Scan::NoMatch, Scan::NoMatch),
] {
assert_eq!(ipv6_wide(hay.as_bytes(), 0), wide, "{hay:?} wide");
assert_eq!(ipv6(hay.as_bytes(), 0), bounded, "{hay:?} bounded");
}
assert_eq!(ip_wide(b"10.0.0.1%x", 0), Scan::Match(8));
assert_eq!(ip_wide_checked(b"999.1.1.1", 0), Scan::NoMatch);
assert_eq!(ipv6_checked_wide(b"::ffff:1.2.3.4%a b", 0), Scan::Match(18));
assert_eq!(ipv6_checked_wide(b"fe80::1x%eth0", 0), Scan::NoMatch);
assert_eq!(iporhost_wide_checked(b"999.1.1.1", 0), Scan::Match(9));
assert_eq!(iporhost_wide(b"db-1.example.com", 0), Scan::Match(16));
}
#[test]
fn a_unixpath_segment_past_ascii_defers_to_the_regex() {
let path = field("UNIXPATH").unwrap().scan;
assert_eq!(path(b"/var/log x", 0), Scan::Match(8));
assert_eq!(path(b"x/var", 1), Scan::Match(5));
assert_eq!(path(b"var", 0), Scan::NoMatch);
let i = FIELDS.iter().position(|f| f.name == "UNIXPATH").unwrap();
for (hay, whole) in [
("/caf\u{e9}/app.log", true),
("/var/\u{65e5}\u{672c}", true),
("/a/\u{2192}b", false),
] {
assert_eq!(path(hay.as_bytes(), 0), Scan::Defer, "{hay:?}");
let end = regex_end(i, hay.as_bytes(), 0);
assert_eq!(end == Some(hay.len()), whole, "{hay:?} by the regex");
}
}
fn pieces() -> Vec<&'static str> {
vec![
"0",
"1",
"2",
"3",
"5",
"6",
"9",
"12",
"60",
"255",
"256",
"2026",
"-",
"+",
".",
",",
":",
"/",
"T",
" ",
" ",
"Z",
"a",
"e",
"A",
"_",
"x",
"Jan",
"June",
"Jul",
"Nov",
"Sep",
"err",
"INFO",
"warn",
"\"",
"'",
"`",
"\\",
"\n",
"\t",
"%",
"fe",
"1a",
"é",
"\u{0663}",
"\u{00a0}",
"fe80::1",
"2001:db8::8a2e:370:7334",
"::1",
"::ffff:192.168.1.1",
"1:2:3:4:5:6:7:8",
"%eth0",
"%3",
"::",
"1::",
"abcd:",
"256.1.2.3",
"host.example.com",
"a-b.",
"web01",
"http",
"x+y-z.w",
"10.1.2.3",
"1.2.3.4567",
"255.255.255.255",
"1.2.3.",
"00:1a:2b:3c:4d:5e",
"001a.2b3c.4d5e",
"123e4567-e89b-12d3-a456-426614174000",
"2026-11-26T11:22:33",
"2026-11-26 11:22",
".456",
"+11:00",
"+1100",
"-0530",
"Nov 6 08:01:02",
"26/Nov/2026:11:22:33 +1100",
"23:59",
"9:05",
"\"a\\\"b\"",
"\\\n",
"C:",
"\\",
"\\\\srv\\share",
"?",
"*",
"?a=b&c=[1]",
"/var/log",
"/a(b)",
"@",
"a.B$c_1",
"0x",
"0x1F",
"0X",
"g",
"user+tag@",
"x=y:z",
"64:ff9b::",
"::ffff:",
"1.2.3.4",
"1::2::3",
"dead:beef::",
"%eth0.1-",
"d",
"f",
]
}
fn ascii_pieces() -> Vec<&'static str> {
pieces().into_iter().filter(|p| p.is_ascii()).collect()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn every_field_agrees_with_its_regex(
before in prop::collection::vec(prop::sample::select(pieces()), 0..3),
body in prop::collection::vec(prop::sample::select(pieces()), 0..14),
) {
let before = before.concat();
let hay = format!("{before}{}", body.concat());
agree(&hay, before.len())?;
}
#[test]
fn ascii_input_never_defers(
before in prop::collection::vec(prop::sample::select(ascii_pieces()), 0..3),
body in prop::collection::vec(prop::sample::select(ascii_pieces()), 0..14),
) {
let before = before.concat();
let hay = format!("{before}{}", body.concat());
prop_assert_eq!(agree(&hay, before.len())?, 0);
}
}
const V6_PIECES: &[&str] = &[
"0", "1", "a", "f", "ff", "dead", "12345", "255", "256", "01", ":", ":", "::", ".", "1.2.3.4",
"%", "eth0", "g", "-",
];
static CHECKED_V6_WHOLE: LazyLock<fancy_regex::Regex> = LazyLock::new(|| {
let f = CHECKED.iter().find(|f| f.name == "IPV6").unwrap();
fancy_regex::Regex::new(&format!("^(?:{})$", f.regex)).unwrap()
});
proptest! {
#![proptest_config(ProptestConfig::with_cases(20000))]
#[test]
fn the_checked_ipv6_regex_and_the_validator_read_the_same_tokens(
parts in prop::collection::vec(prop::sample::select(V6_PIECES), 1..13),
) {
let token = parts.concat();
prop_assert_eq!(
CHECKED_V6_WHOLE.is_match(&token).unwrap(),
ipv6_valid(token.as_bytes()),
"{:?}", token
);
let checked = CHECKED.iter().find(|f| f.name == "IPV6").unwrap();
prop_assert_eq!(
matches!((checked.scan)(token.as_bytes(), 0), Scan::Match(e) if e == token.len()),
ipv6_valid(token.as_bytes()),
"scan on {:?}", token
);
}
}
#[test]
fn validation_is_opt_in_and_steps_away_from_the_regex_on_purpose() {
let ipv4 = field("IPV4").unwrap();
assert_eq!(
(ipv4.scan)(b"192.168.1.256", 0),
Scan::NoMatch,
"an octet past 255 is no match"
);
let check = validator("IPV4").unwrap();
for (text, want) in [
("192.168.1.255", true),
("192.168.1.256", false),
("0.0.0.0", true),
("010.1.1.0001", true),
("+1.2.3.4", true),
("1.2.3.999", false),
("1.2..4", false),
("1.2.3.", false),
("1.2.3.+", false),
("1.2.3.-4", false),
("1.2.3.4a", false),
("1.2.3.\u{663}", false),
] {
let parsed = text.split('.').all(|o| o.parse::<u8>().is_ok());
assert_eq!(check(text.as_bytes()), want, "{text}");
assert_eq!(parsed, want, "{text} as str::parse reads it");
}
let port = validator("PORT").unwrap();
for (text, want) in [
("65535", true),
("65536", false),
("0", true),
("00443", true),
("+80", true),
("", false),
("+", false),
("-1", false),
("99999999999", false),
("8o", false),
] {
assert_eq!(port(text.as_bytes()), want, "{text}");
assert_eq!(
text.parse::<u16>().is_ok(),
want,
"{text} as str::parse reads it"
);
}
let ip = validator("IP").unwrap();
assert!(ip(b"fe80::1"));
assert!(!ip(b"999.1.1.1"));
assert!(!ip(b"1::2::3"));
assert!(validator("WORD").is_none());
}
const V6_FORMS: &[(&str, bool)] = &[
("::", true),
("::1", true),
("1::", true),
("2001:db8::1", true),
("2001:DB8::A", true),
("1:2:3:4:5:6:7:8", true),
("1:2:3:4:5:6:7::", true),
("::2:3:4:5:6:7:8", true),
("1::3:4:5:6:7:8", true),
("::ffff:1.2.3.4", true),
("64:ff9b::1.2.3.4", true),
("1:2:3:4:5:6:1.2.3.4", true),
("fe80::1%eth0", true),
("fe80::1%en0.1-x~", true),
("1::2::3", false),
("12345::1", false),
(":::::", false),
("1:2:3:4:5:6:7:8:9", false),
("1:2:3:4:5:6:7", false),
("1::2:3:4:5:6:7:8", false),
("::1.2.3", false),
("::ffff:1.2.3.256", false),
("::ffff:01.2.3.4", false),
("1::g", false),
("2001:db8::1x", false),
("[::1]", false),
("1.2.3.4", false),
("fe80::1%", false),
("fe80::1%a b", false),
("fe80::1%\u{e9}", false),
(":", false),
("", false),
];
#[test]
fn the_ipv6_validator_reads_an_address_as_std_does() {
let v6 = validator("IPV6").unwrap();
let ip = validator("IP").unwrap();
let host = validator("IPORHOST").unwrap();
for &(text, want) in V6_FORMS {
let bare = text.split('%').next().unwrap_or_default();
if !text.contains('%') {
assert_eq!(
bare.parse::<Ipv6Addr>().is_ok(),
want,
"{text:?} as std reads it"
);
}
assert_eq!(v6(text.as_bytes()), want, "IPV6 {text:?}");
if text.contains(':') {
assert_eq!(ip(text.as_bytes()), want, "IP {text:?}");
assert_eq!(host(text.as_bytes()), want, "IPORHOST {text:?}");
}
}
for (text, ip_ok, host_ok) in [
("1.2.3.4", true, true),
("999.1.1.1", false, true),
("web-01.example.com", false, true),
] {
assert_eq!(ip(text.as_bytes()), ip_ok, "IP {text:?}");
assert_eq!(host(text.as_bytes()), host_ok, "IPORHOST {text:?}");
}
}
#[test]
fn the_checked_ipv6_scan_takes_the_address_whole() {
let checked = CHECKED.iter().find(|f| f.name == "IPV6").unwrap();
let default = field("IPV6").unwrap();
let rows: &[(&str, usize, Option<usize>, Option<usize>)] = &[
("2001:db8::1", 0, Some(11), Some(11)),
("fe80::1%eth0", 0, Some(12), Some(12)),
("2001:db8::1x", 0, None, Some(11)),
("abcd:ef01::1g", 0, None, Some(12)),
("12345::1", 1, None, Some(8)),
("x2001:db8::1", 1, None, Some(12)),
("::ffff:1.2.3.4", 0, Some(14), Some(8)),
("64:ff9b::1.2.3.4", 0, Some(16), Some(10)),
("1:2:3:4:5:6:1.2.3.4", 0, Some(19), Some(19)),
("fe80::1%eth0\u{e9}", 0, Some(7), Some(12)),
("1::2::3", 0, None, Some(4)),
("1::2::3", 4, None, Some(7)),
("1:2:3:4:5:6:7:8:9", 0, None, Some(15)),
("2001:db8::1.", 0, Some(11), Some(11)),
("2001:db8::1.5", 0, None, Some(11)),
("fe80::1%eth0:80", 0, Some(12), Some(12)),
("not an address", 0, None, None),
];
for &(text, at, want_checked, want_default) in rows {
let end = |f: &Field| match (f.scan)(text.as_bytes(), at) {
Scan::Match(end) => Some(end),
Scan::NoMatch => None,
Scan::Defer => panic!("{} deferred on {text:?}", f.name),
};
assert_eq!(
end(checked),
want_checked,
"checked IPV6 on {text:?} at {at}"
);
assert_eq!(
end(default),
want_default,
"default IPV6 on {text:?} at {at}"
);
}
}
#[test]
fn the_replacement_list_in_docs_matches_the_table() {
let mut want =
String::from("| Pattern | Dialect | Replaced by | Tier |\n| --- | --- | --- | --- |\n");
for f in FIELDS {
writeln!(want, "| `{0}` | grok | `field(\"{0}\")` | Field |", f.name).unwrap();
}
let doc = include_str!("../../docs/replaces.md");
let table = doc
.split("<!-- replaces:begin -->\n")
.nth(1)
.and_then(|rest| rest.split("<!-- replaces:end -->").next())
.unwrap_or_default();
assert_eq!(table, want, "docs/replaces.md disagrees with field::FIELDS");
}
const PAST_NON_UTF8: &str = " (past a byte that isn't UTF-8)";
#[test]
#[ignore = "bug: GREEDYDATA and QUOTEDSTRING run past a byte that isn't UTF-8, where the regex stops, so own-nginx/error.log:74 scans past it"]
fn a_text_field_stops_at_a_byte_that_is_not_utf8() {
let cases: [(&str, &[u8]); 2] = [("GREEDYDATA", b"x\xfcy"), ("QUOTEDSTRING", b"\"x\xfcy\"")];
for (name, line) in cases {
let i = table()
.position(|f| f.name == name)
.expect("the field is in the table");
let got = table().nth(i).map(|f| (f.scan)(line, 0));
let want = regex_end(i, line, 0);
let agrees = match got {
Some(Scan::Match(end)) => Some(end) == want,
Some(Scan::NoMatch) => want.is_none(),
_ => true,
};
assert!(agrees, "{name}: {got:?}, regex {want:?}");
}
}
#[test]
fn real_lines_scan_as_the_regex_does() {
use crate::shared_tests::corpus::{Join, Tally, for_each_record_of};
let tags = [
"syslog",
"cef",
"leef",
"kv",
"mixed",
"access",
"text",
"tsv",
"cloud-vpc",
"cloud-alb",
];
let mut tally = Tally::default();
tally.known_bug(
PAST_NON_UTF8,
"a field scanner runs past a byte that isn't UTF-8, where the regex stops",
);
for_each_record_of(&tags, |r| {
let starts = (0..r.bytes.len()).filter(|&i| i == 0 || r.bytes[i - 1] == b' ');
let mut hits = vec![false; table().count()];
for at in starts.take(64) {
for (i, f) in table().enumerate() {
let Some((got, want)) = tally.caught("field", r, || {
((f.scan)(r.bytes, at), regex_end(i, r.bytes, at))
}) else {
continue;
};
match got {
Scan::Defer => {}
Scan::Match(end) if Some(end) == want => hits[i] = true,
Scan::NoMatch if want.is_none() => {}
got => {
let mut w = format!("{} at {at}: {got:?}, regex {want:?}", f.name);
if let Scan::Match(end) = got
&& std::str::from_utf8(&r.bytes[at..end]).is_err()
&& want.is_none_or(|stop| {
stop < end && std::str::from_utf8(&r.bytes[at..stop]).is_ok()
})
{
w.push_str(PAST_NON_UTF8);
}
tally.problem("field", r, &w);
}
}
}
}
tally.count("field", r, hits.iter().any(|&h| h));
});
tally.scales_longest("field", Join::SPACE, |line| {
for f in table() {
let _ = (f.scan)(line, 0);
}
});
tally.finish("field");
}
#[test]
fn real_ipv6_candidates_are_validated_as_std_reads_them() {
use crate::shared_tests::corpus::{MANIFEST, for_each_record_of};
let mut tags: Vec<&str> = MANIFEST
.iter()
.flat_map(|s| &s.files)
.flat_map(|f| f.tags.iter().map(String::as_str))
.collect();
tags.sort_unstable();
tags.dedup();
let checked = CHECKED.iter().find(|f| f.name == "IPV6").unwrap();
let v6 = validator("IPV6").unwrap();
let is_run = |b: u8| b.is_ascii_hexdigit() || matches!(b, b':' | b'.');
let (mut accepted, mut rejected, mut whole) = (0, 0, 0);
let mut problems = Vec::new();
for_each_record_of(&tags, |r| {
let h = r.bytes;
let mut i = 0;
while i < h.len() {
if !is_run(h[i]) {
i += 1;
continue;
}
let start = i;
while i < h.len() && is_run(h[i]) {
i += 1;
}
let dots = h[start..i].iter().rev().take_while(|&&b| b == b'.').count();
let run = &h[start..i - dots];
if run.split(|&b| b == b':').count() < 3 {
continue;
}
let end = start + run.len();
let text = std::str::from_utf8(run).unwrap_or_default();
let std_ok = text.parse::<Ipv6Addr>().is_ok();
if v6(run) != std_ok {
problems.push(format!("{}: validator and std differ on {text:?}", r.at()));
}
if std_ok {
accepted += 1;
} else {
rejected += 1;
}
let scan = (checked.scan)(h, start);
let bounded = !word_before(h, start) && !word_at(h, end);
if std_ok && bounded && h.get(end) != Some(&b'%') {
whole += 1;
if scan != Scan::Match(end) {
problems.push(format!("{}: checked scan {scan:?} on {text:?}", r.at()));
}
}
if !std_ok && scan == Scan::Match(end) {
problems.push(format!("{}: checked scan took bad {text:?}", r.at()));
}
}
});
assert!(
problems.is_empty(),
"{} problems: {:#?}",
problems.len(),
&problems[..problems.len().min(20)]
);
println!(
"corpus IPv6 candidates: {accepted} accepted, {rejected} rejected, {whole} scanned whole"
);
assert!(
accepted >= 450 && rejected >= 1000 && whole >= 350,
"the corpus lost its IPv6 data"
);
}
#[test]
fn a_long_line_costs_each_scan_in_proportion_to_its_length() {
use std::time::{Duration, Instant};
const FLOOR: Duration = Duration::from_micros(1);
for unit in ["a", "1", "1.", "a ", ":", "-", "\u{e9}"] {
let short = unit.repeat(1_000 / unit.len());
let long = unit.repeat(32_000 / unit.len());
agree(&short, 0).unwrap();
agree(&long, 0).unwrap();
for f in table() {
let time = |line: &str| {
let t = Instant::now();
let _ = (f.scan)(line.as_bytes(), 0);
t.elapsed()
};
time(&short);
time(&long);
let (mut fast, mut slow) = (Duration::MAX, Duration::MAX);
for _ in 0..5 {
fast = fast.min(time(&short));
slow = slow.min(time(&long));
}
assert!(
slow < fast.max(FLOOR) * 256,
"{} on {unit:?}: 32x the line took {slow:?} against {fast:?}",
f.name
);
}
}
}