// Project: grippo
// File: src/field/mod.rs
// Purpose: Field parsers, each exact to the grok regex it stands for
// Language: Rust
//
// License: Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED
//! Field parsers for the common grok patterns.
//!
//! Each [`Field`] names a grok pattern, carries the regex it stands for, and
//! scans at an anchored position with that regex's leftmost-first answer. It
//! answers only where its answer is provably the regex's. A non-ASCII byte
//! where `\d` decides is the one case it can't settle without Unicode tables,
//! so it returns [`Scan::Defer`] and the caller runs the regex for that span.
//!
//! The input must be valid UTF-8, which grok checks once per record. Word
//! boundaries and `\w` use the regex engine's own Unicode word table, and `\s`
//! is the Unicode `White_Space` property, so neither defers.
#![allow(
clippy::many_single_char_names,
reason = "byte scanners read h[i] at positions i, j, k the way the regex reads its positions"
)]
#[cfg(test)]
mod tests;
#[doc(hidden)]
pub use crate::kernel::ByteClass;
use crate::parse::Hint;
/// One anchored scan's answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scan {
/// The regex matches from the start position up to this end.
Match(usize),
/// The regex does not match at the start position.
NoMatch,
/// Only the regex can say: a non-ASCII byte sits where `\d` decides.
Defer,
}
/// A grok pattern with a native scan.
#[derive(Debug, Clone, Copy)]
pub struct Field {
/// The grok pattern name, such as `IPV4`.
pub name: &'static str,
/// The regex the scan is exact to.
pub regex: &'static str,
/// How a captured value reads.
pub hint: Hint,
/// Scan `hay` from `at`. Bytes before `at` are context for `\b`.
pub scan: fn(&[u8], usize) -> Scan,
}
/// The field named `name`.
#[must_use]
pub fn field(name: &str) -> Option<&'static Field> {
FIELDS.iter().find(|f| f.name == name)
}
/// A stricter check on a value the field matched, for `validate: true`.
///
/// A value that fails it counts as no match, a deliberate step away from the
/// regex. `None` where the regex is the whole rule.
#[must_use]
pub fn validator(name: &str) -> Option<fn(&[u8]) -> bool> {
match name {
"IPV4" => Some(ipv4_in_range),
"IP" => Some(|v| v.contains(&b':') || ipv4_in_range(v)),
"PORT" => Some(|v| at_most(v, u32::from(u16::MAX))),
_ => None,
}
}
/// Every octet of a dotted quad reads as a `u8`, as [`at_most`] reads one.
fn ipv4_in_range(v: &[u8]) -> bool {
let (mut octet, mut digits, mut start) = (0u32, false, true);
for &b in v {
match b {
b'.' if digits => (octet, digits, start) = (0, false, true),
b'+' if start => start = false,
b'0'..=b'9' => {
octet = octet * 10 + u32::from(b - b'0');
if octet > 255 {
return false;
}
(digits, start) = (true, false);
}
_ => return false,
}
}
digits
}
/// `text` reads as an unsigned integer of `max` or less, as `str::parse`
/// reads one: an optional `+`, then decimal digits, leading zeros allowed.
fn at_most(text: &[u8], max: u32) -> bool {
let digits = text.strip_prefix(b"+").unwrap_or(text);
!digits.is_empty()
&& digits
.iter()
.try_fold(0u32, |n, &b| {
let n = n * 10 + u32::from(b.wrapping_sub(b'0'));
(b.is_ascii_digit() && n <= max).then_some(n)
})
.is_some()
}
/// the upstream grok library's newer `IPV6`, with the zone id bounded to RFC 6874's
/// unreserved characters so it can't run past a space.
macro_rules! ipv6_re {
() => {
r"((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(%[0-9A-Za-z_.~-]+)?"
};
}
macro_rules! ipv4_re {
() => {
r"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b"
};
}
/// One octet, 0 to 255 in up to three digits, as the upstream grok library reads it.
macro_rules! octet_re {
() => {
r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})"
};
}
macro_rules! ipv4_checked_re {
() => {
concat!(r"\b", octet_re!(), r"(?:\.", octet_re!(), r"){3}\b")
};
}
/// `IPV4` and `IP` with each octet range-checked, which grok's `validate`
/// option puts in place of the entries in [`FIELDS`].
#[cfg_attr(
not(feature = "parse-grok"),
allow(dead_code, reason = "grok's validate option reads it")
)]
pub(crate) static CHECKED: [Field; 2] = [
Field {
name: "IPV4",
regex: ipv4_checked_re!(),
hint: Hint::Ip,
scan: ipv4_checked,
},
Field {
name: "IP",
regex: concat!("(?:", ipv6_re!(), "|", ipv4_checked_re!(), ")"),
hint: Hint::Ip,
scan: ip_checked,
},
];
macro_rules! hostname_re {
() => {
r"\b(?:[0-9A-Za-z][0-9A-Za-z-]{0,62})(?:\.(?:[0-9A-Za-z][0-9A-Za-z-]{0,62}))*(?:\.?|\b)"
};
}
/// `+-=` is the range `+` to `=`: `+,-./0-9:;<=`.
macro_rules! emaillocalpart_re {
() => {
r"[a-zA-Z][a-zA-Z0-9_.+-=:]+"
};
}
const MONTH_RE: &str = concat!(
r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?",
r"|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)"
);
/// Every field, by grok name.
///
/// Definitions are the upstream grok library's (see NOTICE), except `IPV4` (`\b` guards for its lookarounds, no octet range check),
/// `INT`, `NUMBER`, `BASE10NUM`, `BASE16NUM` and the timestamps, which drop
/// lookbehinds the linear engine can't run, and `WINPATH`, whose atomic group
/// is decided by its first byte.
pub static FIELDS: &[Field] = &[
Field {
name: "GREEDYDATA",
regex: r".*",
hint: Hint::Text,
scan: greedydata,
},
Field {
name: "NOTSPACE",
regex: r"\S+",
hint: Hint::Text,
scan: notspace,
},
Field {
name: "SPACE",
regex: r"\s*",
hint: Hint::Text,
scan: space,
},
Field {
name: "WORD",
regex: r"\b\w+\b",
hint: Hint::Text,
scan: word,
},
Field {
name: "INT",
regex: r"[+-]?\d+",
hint: Hint::Int,
scan: int,
},
Field {
name: "NUMBER",
regex: r"[+-]?(?:\d+(?:\.\d+)?|\.\d+)",
hint: Hint::Float,
scan: number,
},
Field {
name: "POSINT",
regex: r"\b(?:[1-9][0-9]*)\b",
hint: Hint::Int,
scan: posint,
},
Field {
name: "NONNEGINT",
regex: r"\b(?:[0-9]+)\b",
hint: Hint::Int,
scan: nonnegint,
},
Field {
name: "PORT",
regex: r"\d+",
hint: Hint::Int,
scan: port,
},
Field {
name: "USERNAME",
regex: r"[a-zA-Z0-9._-]+",
hint: Hint::Text,
scan: username,
},
Field {
name: "IPV4",
regex: ipv4_re!(),
hint: Hint::Ip,
scan: ipv4,
},
Field {
name: "IPV6",
regex: ipv6_re!(),
hint: Hint::Ip,
scan: ipv6,
},
Field {
name: "IP",
regex: concat!("(?:", ipv6_re!(), "|", ipv4_re!(), ")"),
hint: Hint::Ip,
scan: ip,
},
Field {
name: "HOSTNAME",
regex: hostname_re!(),
hint: Hint::Text,
scan: hostname,
},
Field {
name: "IPORHOST",
regex: concat!("(?:", ipv6_re!(), "|", ipv4_re!(), "|", hostname_re!(), ")"),
hint: Hint::Text,
scan: iporhost,
},
Field {
name: "URIPROTO",
regex: r"[A-Za-z][A-Za-z0-9+\-.]+",
hint: Hint::Text,
scan: uriproto,
},
Field {
name: "MAC",
regex: r"(?:(?:[A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4}|(?:[0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2})",
hint: Hint::Text,
scan: mac,
},
Field {
name: "UUID",
regex: r"[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}",
hint: Hint::Text,
scan: uuid,
},
Field {
name: "QUOTEDSTRING",
regex: r#"(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)"#,
hint: Hint::Text,
scan: quoted,
},
Field {
name: "LOGLEVEL",
regex: r"(?i:emerg|alert|crit|err|warn|notice|info|debug|trace)\w*",
hint: Hint::Text,
scan: loglevel,
},
Field {
name: "MONTH",
regex: MONTH_RE,
hint: Hint::Text,
scan: month,
},
Field {
name: "MONTHDAY",
regex: r"\d{1,2}",
hint: Hint::Int,
scan: monthday,
},
Field {
name: "YEAR",
regex: r"(?:\d\d){1,2}",
hint: Hint::Int,
scan: year,
},
Field {
name: "HOUR",
regex: r"(?:2[0-3]|[01]?\d)",
hint: Hint::Int,
scan: hour,
},
Field {
name: "MINUTE",
regex: r"[0-5]\d",
hint: Hint::Int,
scan: minute,
},
Field {
name: "SECOND",
regex: r"(?:[0-5]?\d|60)(?:[:.,]\d+)?",
hint: Hint::Text,
scan: second,
},
Field {
name: "TIME",
regex: r"\d{1,2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?",
hint: Hint::Text,
scan: time,
},
Field {
name: "ISO8601_TIMEZONE",
regex: r"(?:Z|[+-](?:2[0-3]|[01]?\d)(?::?[0-5]\d))",
hint: Hint::Text,
scan: iso_tz,
},
Field {
name: "TIMESTAMP_ISO8601",
regex: r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::?(?:[0-5]?\d|60)(?:[:.,]\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?",
hint: Hint::Timestamp,
scan: timestamp_iso8601,
},
Field {
name: "SYSLOGTIMESTAMP",
regex: concat!(
r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?",
r"|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)",
r" +\d{1,2} \d{1,2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?"
),
hint: Hint::Timestamp,
scan: syslog_timestamp,
},
Field {
name: "HTTPDATE",
regex: concat!(
r"\d{1,2}/",
r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?",
r"|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)",
r"/\d{4}:\d{1,2}:\d{2}(?::\d{2}(?:[.,]\d+)?)? [+-]?\d+"
),
hint: Hint::Timestamp,
scan: httpdate,
},
Field {
name: "BASE10NUM",
regex: r"[+-]?(?:(?:[0-9]+(?:\.[0-9]+)?)|(?:\.[0-9]+))",
hint: Hint::Float,
scan: base10num,
},
Field {
name: "BASE16NUM",
regex: r"[+-]?(?:0x)?(?:[0-9A-Fa-f]+)",
hint: Hint::Text,
scan: base16num,
},
Field {
name: "URIPATH",
regex: r"(?:/[A-Za-z0-9$.+!*'(){},~:;=@#%&_\-]*)+",
hint: Hint::Text,
scan: uripath,
},
Field {
name: "URIPARAM",
regex: r"\?[A-Za-z0-9$.+!*'|(){},~@#%&/=:;_?\-\[\]<>]*",
hint: Hint::Text,
scan: uriparam,
},
Field {
name: "UNIXPATH",
regex: r"(/[[[:alnum:]]_%!$@:.,+~-]*)+",
hint: Hint::Text,
scan: unixpath,
},
Field {
name: "WINPATH",
regex: r"(?:[A-Za-z]+:|\\)(?:\\[^\\?*]*)+",
hint: Hint::Text,
scan: winpath,
},
Field {
name: "JAVACLASS",
regex: r"(?:[a-zA-Z$_][a-zA-Z$_0-9]*\.)*[a-zA-Z$_][a-zA-Z$_0-9]*",
hint: Hint::Text,
scan: javaclass,
},
Field {
name: "EMAILLOCALPART",
regex: emaillocalpart_re!(),
hint: Hint::Text,
scan: emaillocalpart,
},
Field {
name: "EMAILADDRESS",
regex: concat!(emaillocalpart_re!(), "@", hostname_re!()),
hint: Hint::Text,
scan: emailaddress,
},
];
/// A `\d` decision that needs the Unicode digit table.
#[derive(Debug, Clone, Copy)]
struct Defer;
impl From<Defer> for Scan {
fn from(_: Defer) -> Self {
Self::Defer
}
}
/// Unwrap a step, returning `Scan::Defer` from the scan on a deferral.
macro_rules! step {
($e:expr) => {
match $e {
Ok(v) => v,
Err(Defer) => return Scan::Defer,
}
};
}
fn byte(h: &[u8], i: usize) -> Option<u8> {
h.get(i).copied()
}
/// Greedy count of `\d` from `i`, at most `max` digits.
fn digits(h: &[u8], i: usize, max: usize) -> Result<usize, Defer> {
let mut n = 0;
while n < max {
match byte(h, i + n) {
Some(b) if b.is_ascii_digit() => n += 1,
Some(b) if b >= 0x80 => return Err(Defer),
_ => break,
}
}
Ok(n)
}
/// `\d` at `i`.
fn digit(h: &[u8], i: usize) -> Result<bool, Defer> {
Ok(digits(h, i, 1)? == 1)
}
/// Exactly `n` digits at `i`.
fn exact(h: &[u8], i: usize, n: usize) -> Result<bool, Defer> {
Ok(digits(h, i, n)? == n)
}
/// Run of ASCII bytes from `i` that satisfy `keep`.
fn run(h: &[u8], i: usize, keep: impl Fn(u8) -> bool) -> usize {
h.get(i..)
.map_or(0, |rest| rest.iter().take_while(|&&b| keep(b)).count())
}
/// The char starting at `i` and its width.
fn char_at(h: &[u8], i: usize) -> Option<(char, usize)> {
let rest = h.get(i..)?;
let width = match *rest.first()? {
b if b < 0x80 => return Some((char::from(b), 1)),
b if b >= 0xF0 => 4,
b if b >= 0xE0 => 3,
_ => 2,
};
let c = std::str::from_utf8(rest.get(..width)?)
.ok()?
.chars()
.next()?;
Some((c, width))
}
/// The char ending at `i`.
fn char_before(h: &[u8], i: usize) -> Option<char> {
if let Some(&b) = i.checked_sub(1).and_then(|at| h.get(at))
&& b < 0x80
{
return Some(char::from(b));
}
let start = (i.saturating_sub(4)..i)
.rev()
.find(|&s| h.get(s).is_some_and(|&b| (b & 0xC0) != 0x80))?;
std::str::from_utf8(h.get(start..i)?)
.ok()?
.chars()
.next_back()
}
fn is_word(c: char) -> bool {
if c.is_ascii() {
c.is_ascii_alphanumeric() || c == '_'
} else {
regex_syntax::is_word_character(c)
}
}
fn word_at(h: &[u8], i: usize) -> bool {
char_at(h, i).is_some_and(|(c, _)| is_word(c))
}
fn word_before(h: &[u8], i: usize) -> bool {
char_before(h, i).is_some_and(is_word)
}
/// ASCII bytes that aren't whitespace, as `char::is_whitespace` has it.
static NOTSPACE: ByteClass = ByteClass::new({
let mut bits = 0_u128;
let mut byte = 0_u8;
while byte < 128 {
if !matches!(byte, 9..=13 | b' ') {
bits |= 1 << byte;
}
byte += 1;
}
bits
});
/// ASCII word bytes: letters, digits and `_`.
static WORD: ByteClass = ByteClass::new({
let mut bits = 0_u128;
let mut byte = 0_u8;
while byte < 128 {
if byte.is_ascii_alphanumeric() || byte == b'_' {
bits |= 1 << byte;
}
byte += 1;
}
bits
});
/// End of a greedy run of chars that satisfy `keep`. `ascii` is the run of
/// its ASCII members at the start of a slice.
fn class_while(
h: &[u8],
mut i: usize,
ascii: impl Fn(&[u8]) -> usize,
keep: impl Fn(char) -> bool,
) -> usize {
loop {
i += ascii(h.get(i..).unwrap_or_default());
// The run stops at a byte past ASCII as well as at a non-member.
match char_at(h, i) {
Some((c, w)) if !c.is_ascii() && keep(c) => i += w,
_ => return i,
}
}
}
/// End of a greedy run of chars that satisfy `keep`.
fn chars_while(h: &[u8], mut i: usize, keep: impl Fn(char) -> bool) -> usize {
while let Some((c, w)) = char_at(h, i) {
if !keep(c) {
break;
}
i += w;
}
i
}
const fn some_if(ok: bool, end: usize) -> Scan {
if ok { Scan::Match(end) } else { Scan::NoMatch }
}
fn greedydata(h: &[u8], at: usize) -> Scan {
let rest = h.get(at..).unwrap_or_default();
Scan::Match(at + memchr::memchr(b'\n', rest).unwrap_or(rest.len()))
}
fn notspace(h: &[u8], at: usize) -> Scan {
let end = class_while(h, at, |rest| NOTSPACE.run(rest), |c| !c.is_whitespace());
some_if(end > at, end)
}
fn space(h: &[u8], at: usize) -> Scan {
Scan::Match(chars_while(h, at, char::is_whitespace))
}
fn word(h: &[u8], at: usize) -> Scan {
if word_before(h, at) {
return Scan::NoMatch;
}
// A word is a few bytes, so the table alone is quicker than a vector step.
let end = class_while(h, at, |rest| WORD.run_by_table(rest), is_word);
some_if(end > at, end)
}
fn sign(h: &[u8], i: usize) -> bool {
matches!(byte(h, i), Some(b'+' | b'-'))
}
fn int(h: &[u8], at: usize) -> Scan {
let s = at + usize::from(sign(h, at));
let n = step!(digits(h, s, usize::MAX));
some_if(n > 0, s + n)
}
fn number(h: &[u8], at: usize) -> Scan {
let s = at + usize::from(sign(h, at));
let n = step!(digits(h, s, usize::MAX));
if n > 0 {
let e = s + n;
if byte(h, e) == Some(b'.') {
let f = step!(digits(h, e + 1, usize::MAX));
if f > 0 {
return Scan::Match(e + 1 + f);
}
}
return Scan::Match(e);
}
if byte(h, s) == Some(b'.') {
let f = step!(digits(h, s + 1, usize::MAX));
if f > 0 {
return Scan::Match(s + 1 + f);
}
}
Scan::NoMatch
}
fn bounded_digits(h: &[u8], at: usize, first: impl Fn(u8) -> bool) -> Scan {
if word_before(h, at) || !byte(h, at).is_some_and(first) {
return Scan::NoMatch;
}
let end = at + 1 + run(h, at + 1, |b| b.is_ascii_digit());
some_if(!word_at(h, end), end)
}
fn posint(h: &[u8], at: usize) -> Scan {
bounded_digits(h, at, |b| (b'1'..=b'9').contains(&b))
}
fn nonnegint(h: &[u8], at: usize) -> Scan {
bounded_digits(h, at, |b| b.is_ascii_digit())
}
fn port(h: &[u8], at: usize) -> Scan {
let n = step!(digits(h, at, usize::MAX));
some_if(n > 0, at + n)
}
fn username(h: &[u8], at: usize) -> Scan {
let n = run(h, at, |b| {
b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')
});
some_if(n > 0, at + n)
}
fn ipv4(h: &[u8], at: usize) -> Scan {
if word_before(h, at) {
return Scan::NoMatch;
}
let mut i = at;
for _ in 0..3 {
let n = run(h, i, |b| b.is_ascii_digit());
if !(1..=3).contains(&n) || byte(h, i + n) != Some(b'.') {
return Scan::NoMatch;
}
i += n + 1;
}
let n = run(h, i, |b| b.is_ascii_digit());
some_if((1..=3).contains(&n) && !word_at(h, i + n), i + n)
}
/// A continuation: given where a piece ended, the end of the whole match.
type Kont<'k> = &'k mut dyn FnMut(usize) -> Option<usize>;
/// `[0-9A-Fa-f]{1,4}`, greedy, longest first.
fn hex4(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
let r = run(h, i, |b| b.is_ascii_hexdigit()).min(4);
(1..=r).rev().find_map(|n| k(i + n))
}
fn lit(h: &[u8], i: usize, c: u8, k: Kont<'_>) -> Option<usize> {
if byte(h, i) == Some(c) {
k(i + 1)
} else {
None
}
}
/// `h:`.
fn hex_colon(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
hex4(h, i, &mut |j| lit(h, j, b':', k))
}
/// `:h`.
fn colon_hex(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
lit(h, i, b':', &mut |j| hex4(h, j, k))
}
/// `item{min,max}`, greedy.
fn rep(
h: &[u8],
i: usize,
min: usize,
max: usize,
item: fn(&[u8], usize, Kont<'_>) -> Option<usize>,
k: Kont<'_>,
) -> Option<usize> {
if max > 0
&& let Some(end) = item(h, i, &mut |j| {
rep(h, j, min.saturating_sub(1), max - 1, item, k)
})
{
return Some(end);
}
if min == 0 { k(i) } else { None }
}
/// `(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`, in that order.
fn octet(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
let d = |j: usize| byte(h, j).is_some_and(|b| b.is_ascii_digit());
let at = |j: usize, lo: u8, hi: u8| byte(h, j).is_some_and(|b| (lo..=hi).contains(&b));
let mut ends = [None; 4];
if byte(h, i) == Some(b'2') && byte(h, i + 1) == Some(b'5') && at(i + 2, b'0', b'5') {
ends[0] = Some(i + 3);
}
if byte(h, i) == Some(b'2') && at(i + 1, b'0', b'4') && d(i + 2) {
ends[1] = Some(i + 3);
}
if byte(h, i) == Some(b'1') && d(i + 1) && d(i + 2) {
ends[2] = Some(i + 3);
}
if at(i, b'1', b'9') && d(i + 1) {
ends[3] = Some(i + 2);
}
for e in ends.into_iter().flatten() {
if let Some(end) = k(e) {
return Some(end);
}
}
if d(i) { k(i + 1) } else { None }
}
/// The range-checked dotted quad IPV6 embeds.
fn v4(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
octet(h, i, &mut |a| {
lit(h, a, b'.', &mut |a| {
octet(h, a, &mut |b| {
lit(h, b, b'.', &mut |b| {
octet(h, b, &mut |c| lit(h, c, b'.', &mut |c| octet(h, c, k)))
})
})
})
})
}
/// `:` then the dotted quad.
fn colon_v4(h: &[u8], i: usize, k: Kont<'_>) -> Option<usize> {
lit(h, i, b':', &mut |j| v4(h, j, k))
}
/// The tail after `n` leading `h:` groups, for `n` of 1 to 5: `(:h){1,7-n}`,
/// then `(:h){0,5-n}:IPv4`, then `:`.
fn compressed_tail(h: &[u8], i: usize, n: usize, k: Kont<'_>) -> Option<usize> {
rep(h, i, 1, 7 - n, colon_hex, k)
.or_else(|| rep(h, i, 0, 5 - n, colon_hex, &mut |j| colon_v4(h, j, k)))
.or_else(|| lit(h, i, b':', k))
}
/// IPV6's eight alternatives, in the regex's order, without the zone.
fn ipv6_body(h: &[u8], at: usize, k: Kont<'_>) -> Option<usize> {
let a1 = |k: Kont<'_>| {
rep(h, at, 7, 7, hex_colon, &mut |j| {
hex4(h, j, k).or_else(|| lit(h, j, b':', k))
})
};
let a2 = |k: Kont<'_>| {
rep(h, at, 6, 6, hex_colon, &mut |j| {
colon_hex(h, j, k)
.or_else(|| v4(h, j, k))
.or_else(|| lit(h, j, b':', k))
})
};
let a3 = |k: Kont<'_>| {
rep(h, at, 5, 5, hex_colon, &mut |j| {
rep(h, j, 1, 2, colon_hex, k)
.or_else(|| colon_v4(h, j, k))
.or_else(|| lit(h, j, b':', k))
})
};
let middle =
|n: usize, k: Kont<'_>| rep(h, at, n, n, hex_colon, &mut |j| compressed_tail(h, j, n, k));
let a8 = |k: Kont<'_>| {
lit(h, at, b':', &mut |j| {
rep(h, j, 1, 7, colon_hex, k)
.or_else(|| rep(h, j, 0, 5, colon_hex, &mut |m| colon_v4(h, m, k)))
.or_else(|| lit(h, j, b':', k))
})
};
a1(k)
.or_else(|| a2(k))
.or_else(|| a3(k))
.or_else(|| middle(4, k))
.or_else(|| middle(3, k))
.or_else(|| middle(2, k))
.or_else(|| middle(1, k))
.or_else(|| a8(k))
}
/// The bounded zone id, `(%[0-9A-Za-z_.~-]+)?`, greedy.
fn zone(h: &[u8], e: usize) -> usize {
if byte(h, e) != Some(b'%') {
return e;
}
let n = run(h, e + 1, |b| {
b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'~' | b'-')
});
if n > 0 { e + 1 + n } else { e }
}
fn ipv6(h: &[u8], at: usize) -> Scan {
ipv6_body(h, at, &mut |e| Some(zone(h, e))).map_or(Scan::NoMatch, Scan::Match)
}
fn ip(h: &[u8], at: usize) -> Scan {
match ipv6(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4(h, at),
}
}
/// [`ipv4`], with an octet past 255 no match. Its octets are whole digit
/// runs, so the range check is all the checked regex adds.
fn ipv4_checked(h: &[u8], at: usize) -> Scan {
match ipv4(h, at) {
Scan::Match(end) if !ipv4_in_range(&h[at..end]) => Scan::NoMatch,
scan => scan,
}
}
fn ip_checked(h: &[u8], at: usize) -> Scan {
match ipv6(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4_checked(h, at),
}
}
fn hostname(h: &[u8], at: usize) -> Scan {
if word_before(h, at) || !byte(h, at).is_some_and(|b| b.is_ascii_alphanumeric()) {
return Scan::NoMatch;
}
let label =
|i: usize| i + 1 + run(h, i + 1, |b| b.is_ascii_alphanumeric() || b == b'-').min(62);
let mut i = label(at);
while byte(h, i) == Some(b'.') && byte(h, i + 1).is_some_and(|b| b.is_ascii_alphanumeric()) {
i = label(i + 1);
}
if byte(h, i) == Some(b'.') {
i += 1;
}
Scan::Match(i)
}
fn iporhost(h: &[u8], at: usize) -> Scan {
match ip(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => hostname(h, at),
}
}
fn uriproto(h: &[u8], at: usize) -> Scan {
if !byte(h, at).is_some_and(|b| b.is_ascii_alphabetic()) {
return Scan::NoMatch;
}
let n = run(h, at + 1, |b| {
b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')
});
some_if(n > 0, at + 1 + n)
}
fn hex(h: &[u8], i: usize, n: usize) -> bool {
run(h, i, |b| b.is_ascii_hexdigit()) >= n
}
fn mac(h: &[u8], at: usize) -> Scan {
let cisco =
(0..3).all(|g| hex(h, at + g * 5, 4) && (g == 2 || byte(h, at + g * 5 + 4) == Some(b'.')));
if cisco {
return Scan::Match(at + 14);
}
let plain = (0..6).all(|g| {
hex(h, at + g * 3, 2) && (g == 5 || matches!(byte(h, at + g * 3 + 2), Some(b':' | b'-')))
});
some_if(plain, at + 17)
}
fn uuid(h: &[u8], at: usize) -> Scan {
let groups = [8, 4, 4, 4, 12];
let mut i = at;
for (k, n) in groups.iter().enumerate() {
if !hex(h, i, *n) {
return Scan::NoMatch;
}
i += n;
if k < 4 {
if byte(h, i) != Some(b'-') {
return Scan::NoMatch;
}
i += 1;
}
}
Scan::Match(i)
}
fn quoted(h: &[u8], at: usize) -> Scan {
let Some(q @ (b'"' | b'\'' | b'`')) = byte(h, at) else {
return Scan::NoMatch;
};
let mut i = at + 1;
// Only the closing quote or a backslash can end a run of plain bytes.
loop {
let Some(j) = memchr::memchr2(q, b'\\', &h[i..]) else {
return Scan::NoMatch;
};
let stop = i + j;
if h[stop] == q {
return Scan::Match(stop + 1);
}
match char_at(h, stop + 1) {
Some((c, w)) if c != '\n' => i = stop + 1 + w,
_ => return Scan::NoMatch,
}
}
}
fn loglevel(h: &[u8], at: usize) -> Scan {
const LEVELS: [&str; 9] = [
"emerg", "alert", "crit", "err", "warn", "notice", "info", "debug", "trace",
];
let rest = h.get(at..).unwrap_or_default();
for level in LEVELS {
if rest.len() >= level.len() && rest[..level.len()].eq_ignore_ascii_case(level.as_bytes()) {
return Scan::Match(chars_while(h, at + level.len(), is_word));
}
}
Scan::NoMatch
}
/// MONTH's ends from `i`, in the regex's order: the full name, then the
/// abbreviation.
fn month_ends(h: &[u8], i: usize) -> Option<(usize, Option<usize>)> {
const MONTHS: [(&str, &str); 12] = [
("Jan", "uary"),
("Feb", "ruary"),
("Mar", "ch"),
("Apr", "il"),
("May", ""),
("Jun", "e"),
("Jul", "y"),
("Aug", "ust"),
("Sep", "tember"),
("Oct", "ober"),
("Nov", "ember"),
("Dec", "ember"),
];
let rest = h.get(i..)?;
let (abbr, tail) = MONTHS
.iter()
.find(|(a, _)| rest.starts_with(a.as_bytes()))?;
let short = i + abbr.len();
let long = !tail.is_empty() && rest[abbr.len()..].starts_with(tail.as_bytes());
Some(if long {
(short + tail.len(), Some(short))
} else {
(short, None)
})
}
fn month(h: &[u8], at: usize) -> Scan {
month_ends(h, at).map_or(Scan::NoMatch, |(end, _)| Scan::Match(end))
}
fn monthday(h: &[u8], at: usize) -> Scan {
let n = step!(digits(h, at, 2));
some_if(n > 0, at + n)
}
fn year(h: &[u8], at: usize) -> Scan {
match step!(digits(h, at, 4)) {
4 => Scan::Match(at + 4),
2 | 3 => Scan::Match(at + 2),
_ => Scan::NoMatch,
}
}
/// HOUR's ends from `i`, in the regex's order. At most two.
fn hour_ends(h: &[u8], i: usize) -> Result<Vec<usize>, Defer> {
let mut ends = Vec::with_capacity(2);
if byte(h, i) == Some(b'2') && matches!(byte(h, i + 1), Some(b'0'..=b'3')) {
ends.push(i + 2);
}
if matches!(byte(h, i), Some(b'0' | b'1')) {
if digit(h, i + 1)? {
ends.push(i + 2);
}
ends.push(i + 1);
} else if digit(h, i)? {
ends.push(i + 1);
}
Ok(ends)
}
fn hour(h: &[u8], at: usize) -> Scan {
step!(hour_ends(h, at))
.first()
.map_or(Scan::NoMatch, |&e| Scan::Match(e))
}
fn minute(h: &[u8], at: usize) -> Scan {
let ok = matches!(byte(h, at), Some(b'0'..=b'5')) && step!(digit(h, at + 1));
some_if(ok, at + 2)
}
/// The first end of `(?:[0-5]?\d|60)` from `i`.
fn second_whole(h: &[u8], i: usize) -> Result<Option<usize>, Defer> {
if matches!(byte(h, i), Some(b'0'..=b'5')) {
return Ok(Some(if digit(h, i + 1)? { i + 2 } else { i + 1 }));
}
if digit(h, i)? {
return Ok(Some(i + 1));
}
Ok(None)
}
/// Greedy optional `[seps]\d+` after `e`.
fn fraction(h: &[u8], e: usize, seps: &[u8]) -> Result<usize, Defer> {
if byte(h, e).is_some_and(|b| seps.contains(&b)) {
let n = digits(h, e + 1, usize::MAX)?;
if n > 0 {
return Ok(e + 1 + n);
}
}
Ok(e)
}
fn second(h: &[u8], at: usize) -> Scan {
match step!(second_whole(h, at)) {
Some(e) => Scan::Match(step!(fraction(h, e, b":.,"))),
None => Scan::NoMatch,
}
}
/// `\d{1,2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?` from `i`.
fn time_end(h: &[u8], i: usize) -> Result<Option<usize>, Defer> {
let j = match digits(h, i, 2)? {
2 if byte(h, i + 2) == Some(b':') => i + 3,
1 if byte(h, i + 1) == Some(b':') => i + 2,
_ => return Ok(None),
};
if !exact(h, j, 2)? {
return Ok(None);
}
let k = j + 2;
if byte(h, k) == Some(b':') && exact(h, k + 1, 2)? {
return Ok(Some(fraction(h, k + 3, b".,")?));
}
Ok(Some(k))
}
fn time(h: &[u8], at: usize) -> Scan {
step!(time_end(h, at)).map_or(Scan::NoMatch, Scan::Match)
}
fn iso_tz(h: &[u8], at: usize) -> Scan {
if byte(h, at) == Some(b'Z') {
return Scan::Match(at + 1);
}
if !sign(h, at) {
return Scan::NoMatch;
}
for e in step!(hour_ends(h, at + 1)) {
let starts = if byte(h, e) == Some(b':') {
vec![e + 1, e]
} else {
vec![e]
};
for p in starts {
if matches!(byte(h, p), Some(b'0'..=b'5')) && step!(digit(h, p + 1)) {
return Scan::Match(p + 2);
}
}
}
Scan::NoMatch
}
fn timestamp_iso8601(h: &[u8], at: usize) -> Scan {
let date = step!(exact(h, at, 4))
&& byte(h, at + 4) == Some(b'-')
&& step!(exact(h, at + 5, 2))
&& byte(h, at + 7) == Some(b'-')
&& step!(exact(h, at + 8, 2))
&& matches!(byte(h, at + 10), Some(b'T' | b' '))
&& step!(exact(h, at + 11, 2))
&& byte(h, at + 13) == Some(b':')
&& step!(exact(h, at + 14, 2));
if !date {
return Scan::NoMatch;
}
let k = at + 16;
let sec_at = if byte(h, k) == Some(b':') { k + 1 } else { k };
let mut m = match step!(second_whole(h, sec_at)) {
Some(e) => step!(fraction(h, e, b":.,")),
None => k,
};
if byte(h, m) == Some(b'Z') {
m += 1;
} else if sign(h, m) && step!(exact(h, m + 1, 2)) {
let p = m + 3;
if byte(h, p) == Some(b':') && step!(exact(h, p + 1, 2)) {
m = p + 3;
} else if step!(exact(h, p, 2)) {
m = p + 2;
}
}
Scan::Match(m)
}
fn syslog_timestamp(h: &[u8], at: usize) -> Scan {
let Some((long, short)) = month_ends(h, at) else {
return Scan::NoMatch;
};
for m in std::iter::once(long).chain(short) {
let spaces = run(h, m, |b| b == b' ');
if spaces == 0 {
continue;
}
let p = m + spaces;
let q = match step!(digits(h, p, 2)) {
2 if byte(h, p + 2) == Some(b' ') => p + 3,
1 if byte(h, p + 1) == Some(b' ') => p + 2,
_ => continue,
};
if let Some(end) = step!(time_end(h, q)) {
return Scan::Match(end);
}
}
Scan::NoMatch
}
fn httpdate(h: &[u8], at: usize) -> Scan {
let p = match step!(digits(h, at, 2)) {
2 if byte(h, at + 2) == Some(b'/') => at + 3,
1 if byte(h, at + 1) == Some(b'/') => at + 2,
_ => return Scan::NoMatch,
};
let Some((long, short)) = month_ends(h, p) else {
return Scan::NoMatch;
};
for m in std::iter::once(long).chain(short) {
if byte(h, m) != Some(b'/') || !step!(exact(h, m + 1, 4)) || byte(h, m + 5) != Some(b':') {
continue;
}
let Some(t) = step!(time_end(h, m + 6)) else {
continue;
};
if byte(h, t) != Some(b' ') {
continue;
}
let s = t + 1 + usize::from(sign(h, t + 1));
let n = step!(digits(h, s, usize::MAX));
if n > 0 {
return Scan::Match(s + n);
}
}
Scan::NoMatch
}
fn base10num(h: &[u8], at: usize) -> Scan {
let s = at + usize::from(sign(h, at));
let fraction = |dot: usize| {
let f = run(h, dot + 1, |b| b.is_ascii_digit());
(byte(h, dot) == Some(b'.') && f > 0).then_some(dot + 1 + f)
};
let n = run(h, s, |b| b.is_ascii_digit());
if n > 0 {
return Scan::Match(fraction(s + n).unwrap_or(s + n));
}
fraction(s).map_or(Scan::NoMatch, Scan::Match)
}
fn base16num(h: &[u8], at: usize) -> Scan {
let s = at + usize::from(sign(h, at));
let hex = |i| run(h, i, |b| b.is_ascii_hexdigit());
if h.get(s..s + 2) == Some(b"0x") && hex(s + 2) > 0 {
return Scan::Match(s + 2 + hex(s + 2));
}
some_if(hex(s) > 0, s + hex(s))
}
/// One or more `/` segments, each followed by a run of `keep`.
fn segments(h: &[u8], at: usize, sep: u8, keep: impl Fn(u8) -> bool) -> Option<usize> {
let mut i = at;
while byte(h, i) == Some(sep) {
i += 1 + run(h, i + 1, &keep);
}
(i > at).then_some(i)
}
fn uripath(h: &[u8], at: usize) -> Scan {
segments(h, at, b'/', |b| {
b.is_ascii_alphanumeric() || b"$.+!*'(){},~:;=@#%&_-".contains(&b)
})
.map_or(Scan::NoMatch, Scan::Match)
}
fn uriparam(h: &[u8], at: usize) -> Scan {
if byte(h, at) != Some(b'?') {
return Scan::NoMatch;
}
Scan::Match(
at + 1
+ run(h, at + 1, |b| {
b.is_ascii_alphanumeric() || b"$.+!*'|(){},~@#%&/=:;_?-[]<>".contains(&b)
}),
)
}
fn unixpath(h: &[u8], at: usize) -> Scan {
segments(h, at, b'/', |b| {
b.is_ascii_alphanumeric() || b"_%!$@:.,+~-".contains(&b)
})
.map_or(Scan::NoMatch, Scan::Match)
}
fn winpath(h: &[u8], at: usize) -> Scan {
let letters = run(h, at, |b| b.is_ascii_alphabetic());
let i = if letters > 0 && byte(h, at + letters) == Some(b':') {
at + letters + 1
} else if byte(h, at) == Some(b'\\') {
at + 1
} else {
return Scan::NoMatch;
};
// One or more `\` segments, each running to the next `\`, `?` or `*`.
// Bytes of a multi-byte char are never one of the three.
let mut end = i;
while byte(h, end) == Some(b'\\') {
let rest = h.get(end + 1..).unwrap_or_default();
end += 1 + memchr::memchr3(b'\\', b'?', b'*', rest).unwrap_or(rest.len());
}
some_if(end > i, end)
}
fn javaclass(h: &[u8], at: usize) -> Scan {
let start = |b: u8| b.is_ascii_alphabetic() || matches!(b, b'$' | b'_');
let ident = |i| run(h, i, |b| start(b) || b.is_ascii_digit());
if !byte(h, at).is_some_and(start) {
return Scan::NoMatch;
}
let mut end = at + ident(at);
while byte(h, end) == Some(b'.') && byte(h, end + 1).is_some_and(start) {
end += 1 + ident(end + 1);
}
Scan::Match(end)
}
fn emaillocalpart(h: &[u8], at: usize) -> Scan {
if !byte(h, at).is_some_and(|b| b.is_ascii_alphabetic()) {
return Scan::NoMatch;
}
let n = run(h, at + 1, |b| {
b.is_ascii_alphanumeric() || b == b'_' || (b'+'..=b'=').contains(&b)
});
some_if(n > 0, at + 1 + n)
}
fn emailaddress(h: &[u8], at: usize) -> Scan {
match emaillocalpart(h, at) {
Scan::Match(end) if byte(h, end) == Some(b'@') => hostname(h, end + 1),
_ => Scan::NoMatch,
}
}