grippo 0.3.0

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
// Project:   grippo
// File:      src/field/tests.rs
// Purpose:   Every field against its own regex, both ways
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

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::*;

/// Every field, the ones grok's options put in the library included.
fn table() -> impl Iterator<Item = &'static Field> {
    every()
}

/// Each field's regex: the linear engine's where it has no lookaround, else a
/// backtracking engine's, which runs the lookarounds as written, behind the
/// linear engine's reading with them taken out.
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),
    /// The relaxed regex, which matches wherever the exact one does, and the
    /// exact one.
    Fancy(Regex, fancy_regex::Regex),
}

/// The regex's answer: the end of its anchored match at `at`.
fn regex_end(i: usize, hay: &[u8], at: usize) -> Option<usize> {
    match &REGEXES[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())
        }
    }
}

/// Every field's native answer equals the regex's, except a deferral.
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}");
    }
    // A vertical tab ends a run, and so does a space past ASCII.
    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));
    // Runs long enough for whole vector steps on either side of a char past
    // ASCII, at every offset into a step.
    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);
}

/// A wide zone runs from the `%` to the end of the line, where the bounded one
/// stops at the first character RFC 6874 leaves reserved.
#[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));
}

/// `UNIXPATH` takes a Unicode letter, mark or digit, and only the regex has
/// the table, so a segment with a byte past ASCII defers.
#[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}",
        // Near-valid tokens, so the structured fields get exercised at their edges.
        "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);
    }
}

/// The pieces of an IPv6 token, in orders no address has too.
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))]

    /// A whole token is in the checked regex's language exactly when
    /// `Ipv6Addr` and the zone rule read it, and the scan ends where the regex does.
    #[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());
}

/// IPv6 forms as `std::net::Ipv6Addr` reads them, with a zone as the
/// regex bounds it.
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:?}");
    }
}

/// The checked `IPV6` takes a whole address: its longest form, no word
/// character beside it, and nothing beside it that would extend it. Rows are
/// (text, start, checked end, default end).
#[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");
}

/// Marks a problem where the native end is past a byte that isn't UTF-8, where
/// the regex stops or finds no match.
const PAST_NON_UTF8: &str = " (past a byte that isn't UTF-8)";

/// A field that reads text stops at a byte that isn't UTF-8, as the regex does.
/// The real line is own-nginx/error.log:74, a TLS handshake sent to the HTTP port.
#[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:?}");
    }
}

/// Every field scanned at the start of every token of every real line: the
/// native end is the regex's, or a deferral. Counted per field, a hit when
/// the field matched.
#[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");
}

/// Every maximal run of hex digits, `:` and `.` in the corpus with two colons
/// is read as `Ipv6Addr` reads it by the validator, and the checked scan
/// takes exactly the ones it accepts, whole.
#[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"
    );
}

/// A line 32 times longer is read as the regex reads it, and each scan takes
/// at most 256 times as long: one that reread the line from every position
/// would take 1024 times. Short and long runs alternate and each keeps its
/// fastest of five, so a stall on a shared host slows neither.
#[test]
fn a_long_line_costs_each_scan_in_proportion_to_its_length() {
    use std::time::{Duration, Instant};
    // Below this a scan is too quick for the clock to tell apart.
    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
            );
        }
    }
}