// 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 in
//! a `UNIXPATH` segment is the one case it can't settle without the Unicode
//! letter, mark and digit 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. Digits
//! are `[0-9]` in every numeric field, so a Unicode digit is never one. Word
//! boundaries and `\w` use the regex engine's own Unicode word table, and `\s`
//! is the Unicode `White_Space` property, so neither defers.
//!
//! A field's regex keeps the lookarounds the upstream library writes, such as
//! `IPV4`'s `(?<![0-9])`. The linear engine can't run one, so each is an
//! [`Edge`]: the scan makes the check, and grok's expansion marks where it sits.
#![allow(
clippy::many_single_char_names,
reason = "byte scanners read h[i] at positions i, j, k the way the regex reads its positions"
)]
/// The lookaround of [`Edge::NoDigitBefore`].
macro_rules! no_digit_before {
() => {
"(?<![0-9])"
};
}
/// The lookaround of [`Edge::NoDigitAfter`].
macro_rules! no_digit_after {
() => {
"(?![0-9])"
};
}
/// The lookaround of [`Edge::NoNumberBefore`].
macro_rules! no_number_before {
() => {
"(?<![0-9.+-])"
};
}
/// The lookarounds of [`Edge::Ipv6Before`].
macro_rules! ipv6_before {
() => {
r"(?<![0-9A-Fa-f:]:)(?<![0-9A-Fa-f]\.)"
};
}
/// The lookahead of [`Edge::Ipv6After`].
macro_rules! ipv6_after {
() => {
r"(?!:[0-9A-Fa-f:]|\.[0-9A-Fa-f])"
};
}
mod edge;
#[cfg(test)]
mod tests;
use std::net::Ipv6Addr;
pub use edge::Edge;
#[cfg_attr(
not(feature = "parse-grok"),
allow(unused_imports, reason = "grok's planner reads the checks")
)]
pub(crate) use edge::Edges;
#[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 in a `UNIXPATH` segment.
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, lookarounds and all.
pub regex: &'static str,
/// How a captured value reads.
pub hint: Hint,
/// Scan `hay` from `at`. Bytes before `at` are context for `\b` and an
/// [`Edge`].
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),
"IPV6" => Some(ipv6_valid),
"IP" => Some(|v| {
if v.contains(&b':') {
ipv6_valid(v)
} else {
ipv4_in_range(v)
}
}),
"IPORHOST" => Some(|v| !v.contains(&b':') || ipv6_valid(v)),
"PORT" => Some(|v| at_most(v, u32::from(u16::MAX))),
_ => None,
}
}
/// `v` is an address `std::net::Ipv6Addr` reads, then an optional `%zone` of
/// the regex's zone characters.
pub(crate) fn ipv6_valid(v: &[u8]) -> bool {
let (addr, zone) = v
.iter()
.position(|&b| b == b'%')
.map_or((v, None), |i| (&v[..i], Some(&v[i + 1..])));
zone.is_none_or(|z| {
!z.is_empty()
&& z.iter()
.all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'~' | b'-'))
}) && std::str::from_utf8(addr).is_ok_and(|a| a.parse::<Ipv6Addr>().is_ok())
}
/// The checked field with this `name`, which grok's `validate` option reads in
/// place of [`field`].
///
/// `None` where `validate` changes nothing, as for `IPV4`, whose octets are
/// always range-checked. An IPv6 address from `IPV6`, `IP` or `IPORHOST` has
/// nothing beside it that would extend it, as [`Edge::Ipv6Before`] and
/// [`Edge::Ipv6After`] read: `1::2::3` holds no address that stands alone.
#[must_use]
pub fn checked(name: &str) -> Option<&'static Field> {
CHECKED.iter().find(|f| f.name == name)
}
/// 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 eight forms of an IPv6 address, as the upstream grok library's newer
/// `IPV6` writes them, without the zone id.
macro_rules! ipv6_body_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}))|:)))"
};
}
/// `IPV6` with the zone id bounded to RFC 6874's unreserved characters, so it
/// can't run past a space.
macro_rules! ipv6_re {
() => {
concat!(ipv6_body_re!(), r"(%[0-9A-Za-z_.~-]+)?")
};
}
/// `IPV6` with a zone id that runs from the `%` to the end of the line.
macro_rules! ipv6_wide_re {
() => {
concat!(ipv6_body_re!(), r"(%.+)?")
};
}
/// 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})"
};
}
/// `IPV4`, each octet 0 to 255, with no digit beside it.
macro_rules! ipv4_re {
() => {
concat!(
no_digit_before!(),
octet_re!(),
r"(?:\.",
octet_re!(),
r"){3}",
no_digit_after!()
)
};
}
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)"
};
}
macro_rules! hex_group_re {
() => {
r"[0-9A-Fa-f]{1,4}"
};
}
/// The dotted quad IPv6 embeds, each octet without a leading zero.
macro_rules! embedded_v4_re {
() => {
concat!(
r"(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])",
r"(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}"
)
};
}
/// One `IPV6` address taken whole, without the zone: the longest form of each
/// shape, so an embedded dotted quad isn't cut at its first group, with no word
/// character beside it. `\b` and `\B` can't test for `:` or `.`, so those can
/// still sit beside a match.
macro_rules! ipv6_checked_body_re {
() => {
concat!(
r"(?:\b(?:",
r"(?:",
hex_group_re!(),
r":){7}(?:",
hex_group_re!(),
r"\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){6}(?:",
embedded_v4_re!(),
r"\b|:",
hex_group_re!(),
r"\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){5}(?::",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,2}\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){4}(?:(?::",
hex_group_re!(),
r")?:",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,3}\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){3}(?:(?::",
hex_group_re!(),
r"){0,2}:",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,4}\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){2}(?:(?::",
hex_group_re!(),
r"){0,3}:",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,5}\b|:\B)",
r"|(?:",
hex_group_re!(),
r":){1}(?:(?::",
hex_group_re!(),
r"){0,4}:",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,6}\b|:\B)",
r")|\B:(?:(?::",
hex_group_re!(),
r"){0,5}:",
embedded_v4_re!(),
r"\b|(?::",
hex_group_re!(),
r"){1,7}\b|:\B))"
)
};
}
/// `ipv6_checked_body_re` with a zone that ends on a non-word character, and
/// nothing beside the address that would extend it. A zone ends the address,
/// so the side after it isn't tested.
macro_rules! ipv6_checked_re {
() => {
concat!(
ipv6_before!(),
ipv6_checked_body_re!(),
r"(?:%[0-9A-Za-z_.~-]*(?:[0-9A-Za-z_]\b|[.~-]\B)|",
ipv6_after!(),
")"
)
};
}
/// [`ipv6_checked_re`] with a zone that runs to the end of the line.
macro_rules! ipv6_checked_wide_re {
() => {
concat!(
ipv6_before!(),
ipv6_checked_body_re!(),
r"(?:%.+|",
ipv6_after!(),
")"
)
};
}
/// `IPV6`, `IP` and `IPORHOST` with an IPv6 address taken whole and standing
/// alone, 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; 3] = [
Field {
name: "IPV6",
regex: ipv6_checked_re!(),
hint: Hint::Ip,
scan: ipv6_checked,
},
Field {
name: "IP",
regex: concat!("(?:", ipv6_checked_re!(), "|", ipv4_re!(), ")"),
hint: Hint::Ip,
scan: ip_checked,
},
Field {
name: "IPORHOST",
regex: concat!(
"(?:",
ipv6_checked_re!(),
"|",
ipv4_re!(),
"|",
hostname_re!(),
")"
),
hint: Hint::Text,
scan: iporhost_checked,
},
];
/// `IPV6`, `IP` and `IPORHOST` with a zone id that runs from the `%` to the end
/// of the line, which grok's `wide_ipv6_zone` option puts in place of the
/// entries in [`FIELDS`].
#[cfg_attr(
not(feature = "parse-grok"),
allow(dead_code, reason = "grok's wide_ipv6_zone option reads it")
)]
pub(crate) static WIDE_ZONE: [Field; 3] = [
Field {
name: "IPV6",
regex: ipv6_wide_re!(),
hint: Hint::Ip,
scan: ipv6_wide,
},
Field {
name: "IP",
regex: concat!("(?:", ipv6_wide_re!(), "|", ipv4_re!(), ")"),
hint: Hint::Ip,
scan: ip_wide,
},
Field {
name: "IPORHOST",
regex: concat!(
"(?:",
ipv6_wide_re!(),
"|",
ipv4_re!(),
"|",
hostname_re!(),
")"
),
hint: Hint::Text,
scan: iporhost_wide,
},
];
/// [`CHECKED`]'s `IPV6`, `IP` and `IPORHOST` with a zone that runs to the end
/// of the line, for grok's `validate` and `wide_ipv6_zone` options together.
#[cfg_attr(
not(feature = "parse-grok"),
allow(dead_code, reason = "grok's wide_ipv6_zone option reads it")
)]
pub(crate) static WIDE_ZONE_CHECKED: [Field; 3] = [
Field {
name: "IPV6",
regex: ipv6_checked_wide_re!(),
hint: Hint::Ip,
scan: ipv6_checked_wide,
},
Field {
name: "IP",
regex: concat!("(?:", ipv6_checked_wide_re!(), "|", ipv4_re!(), ")"),
hint: Hint::Ip,
scan: ip_wide_checked,
},
Field {
name: "IPORHOST",
regex: concat!(
"(?:",
ipv6_checked_wide_re!(),
"|",
ipv4_re!(),
"|",
hostname_re!(),
")"
),
hint: Hint::Text,
scan: iporhost_wide_checked,
},
];
/// Every field a grok library can hold: [`FIELDS`] and the entries its options
/// put in their place.
#[cfg_attr(
not(feature = "parse-grok"),
allow(dead_code, reason = "grok's planner reads it")
)]
pub(crate) fn every() -> impl Iterator<Item = &'static Field> {
FIELDS
.iter()
.chain(&CHECKED)
.chain(&WIDE_ZONE)
.chain(&WIDE_ZONE_CHECKED)
}
/// `+-=` 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 that
/// `INT`, `BASE16NUM` and the timestamps drop their lookbehinds, and
/// `WINPATH`'s 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"[+-]?[0-9]+",
hint: Hint::Int,
scan: int,
},
Field {
name: "NUMBER",
regex: concat!(
no_number_before!(),
r"[+-]?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)"
),
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"[0-9]+",
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"[0-9]{1,2}",
hint: Hint::Int,
scan: monthday,
},
Field {
name: "YEAR",
regex: r"(?:[0-9][0-9]){1,2}",
hint: Hint::Int,
scan: year,
},
Field {
name: "HOUR",
regex: r"(?:2[0-3]|[01]?[0-9])",
hint: Hint::Int,
scan: hour,
},
Field {
name: "MINUTE",
regex: r"[0-5][0-9]",
hint: Hint::Int,
scan: minute,
},
Field {
name: "SECOND",
regex: r"(?:[0-5]?[0-9]|60)(?:[:.,][0-9]+)?",
hint: Hint::Text,
scan: second,
},
Field {
name: "TIME",
regex: r"[0-9]{1,2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]+)?)?",
hint: Hint::Text,
scan: time,
},
Field {
name: "ISO8601_TIMEZONE",
regex: r"(?:Z|[+-](?:2[0-3]|[01]?[0-9])(?::?[0-5][0-9]))",
hint: Hint::Text,
scan: iso_tz,
},
Field {
name: "TIMESTAMP_ISO8601",
regex: r"[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}(?::?(?:[0-5]?[0-9]|60)(?:[:.,][0-9]+)?)?(?:Z|[+-][0-9]{2}:?[0-9]{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" +[0-9]{1,2} [0-9]{1,2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]+)?)?"
),
hint: Hint::Timestamp,
scan: syslog_timestamp,
},
Field {
name: "HTTPDATE",
regex: concat!(
r"[0-9]{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"/[0-9]{4}:[0-9]{1,2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]+)?)? [+-]?[0-9]+"
),
hint: Hint::Timestamp,
scan: httpdate,
},
Field {
name: "BASE10NUM",
regex: concat!(
no_number_before!(),
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"(/[\p{L}\p{M}\p{Nd}_%!$@:.,+~-]*)+",
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,
},
];
fn byte(h: &[u8], i: usize) -> Option<u8> {
h.get(i).copied()
}
/// Greedy count of `[0-9]` from `i`, at most `max` digits.
fn digits(h: &[u8], i: usize, max: usize) -> usize {
h.get(i..).map_or(0, |rest| {
rest.iter()
.take(max)
.take_while(|b| b.is_ascii_digit())
.count()
})
}
/// `[0-9]` at `i`.
fn digit(h: &[u8], i: usize) -> bool {
digits(h, i, 1) == 1
}
/// Exactly `n` digits at `i`.
fn exact(h: &[u8], i: usize, n: usize) -> bool {
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 = digits(h, s, usize::MAX);
some_if(n > 0, s + n)
}
fn number(h: &[u8], at: usize) -> Scan {
if !Edge::NoNumberBefore.holds(h, at) {
return Scan::NoMatch;
}
let s = at + usize::from(sign(h, at));
let n = digits(h, s, usize::MAX);
if n > 0 {
let e = s + n;
if byte(h, e) == Some(b'.') {
let f = 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 = 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 = 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)
}
/// Its octets are whole digit runs, as the checks on either side leave them,
/// so the range check is the octet regex's whole answer.
fn ipv4(h: &[u8], at: usize) -> Scan {
if !Edge::NoDigitBefore.holds(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) && ipv4_in_range(&h[at..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 `:`. With `LONGEST` the dotted quad comes
/// first, as the checked regex orders it.
fn compressed_tail<const LONGEST: bool>(
h: &[u8],
i: usize,
n: usize,
k: Kont<'_>,
) -> Option<usize> {
let hexes = |k: Kont<'_>| rep(h, i, 1, 7 - n, colon_hex, k);
let quad = |k: Kont<'_>| rep(h, i, 0, 5 - n, colon_hex, &mut |j| colon_v4(h, j, k));
if LONGEST {
quad(k).or_else(|| hexes(k))
} else {
hexes(k).or_else(|| quad(k))
}
.or_else(|| lit(h, i, b':', k))
}
/// IPV6's eight alternatives, in the regex's order, without the zone. With
/// `LONGEST` each tries its dotted quad before its hex groups.
fn ipv6_body<const LONGEST: bool>(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| {
if LONGEST {
v4(h, j, k).or_else(|| colon_hex(h, j, k))
} else {
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| {
if LONGEST {
colon_v4(h, j, k).or_else(|| rep(h, j, 1, 2, colon_hex, k))
} else {
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::<LONGEST>(h, j, n, k)
})
};
let a8 = |k: Kont<'_>| {
lit(h, at, b':', &mut |j| {
let hexes = |k: Kont<'_>| rep(h, j, 1, 7, colon_hex, k);
let quad = |k: Kont<'_>| rep(h, j, 0, 5, colon_hex, &mut |m| colon_v4(h, m, k));
if LONGEST {
quad(k).or_else(|| hexes(k))
} else {
hexes(k).or_else(|| quad(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::<false>(h, at, &mut |e| Some(zone(h, e))).map_or(Scan::NoMatch, Scan::Match)
}
/// The zone of [`ipv6_checked`]: the longest `%` run of zone characters that
/// a non-word character follows, or none.
fn zone_checked(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'-')
});
(e + 2..=e + 1 + n)
.rev()
.find(|&end| !word_at(h, end))
.unwrap_or(e)
}
/// The longest form of the address, with no word character before or after
/// it, then the zone `zone` reads. Without a zone nothing after the address
/// may extend it, and nothing before it ever may.
fn ipv6_whole(h: &[u8], at: usize, zone: fn(&[u8], usize) -> usize) -> Scan {
if word_before(h, at) || !Edge::Ipv6Before.holds(h, at) {
return Scan::NoMatch;
}
ipv6_body::<true>(h, at, &mut |e| {
if word_at(h, e) {
return None;
}
let end = zone(h, e);
(end > e || Edge::Ipv6After.holds(h, e)).then_some(end)
})
.map_or(Scan::NoMatch, Scan::Match)
}
/// [`ipv6`] for the checked regex.
fn ipv6_checked(h: &[u8], at: usize) -> Scan {
ipv6_whole(h, at, zone_checked)
}
fn ip(h: &[u8], at: usize) -> Scan {
match ipv6(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4(h, at),
}
}
fn ip_checked(h: &[u8], at: usize) -> Scan {
match ipv6_checked(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4(h, at),
}
}
/// The zone id that runs to the end of the line, `(%.+)?`, greedy.
fn zone_wide(h: &[u8], e: usize) -> usize {
if byte(h, e) != Some(b'%') {
return e;
}
let rest = h.get(e + 1..).unwrap_or_default();
let n = memchr::memchr(b'\n', rest).unwrap_or(rest.len());
if n > 0 { e + 1 + n } else { e }
}
fn ipv6_wide(h: &[u8], at: usize) -> Scan {
ipv6_body::<false>(h, at, &mut |e| Some(zone_wide(h, e))).map_or(Scan::NoMatch, Scan::Match)
}
fn ip_wide(h: &[u8], at: usize) -> Scan {
match ipv6_wide(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4(h, at),
}
}
/// [`ipv6_checked`] with the zone of [`ipv6_wide`].
fn ipv6_checked_wide(h: &[u8], at: usize) -> Scan {
ipv6_whole(h, at, zone_wide)
}
fn ip_wide_checked(h: &[u8], at: usize) -> Scan {
match ipv6_checked_wide(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => ipv4(h, at),
}
}
/// [`iporhost_checked`] with the zone of [`ipv6_wide`].
fn iporhost_wide_checked(h: &[u8], at: usize) -> Scan {
match ipv6_checked_wide(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => match ipv4(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => hostname(h, at),
},
}
}
fn iporhost_wide(h: &[u8], at: usize) -> Scan {
match ip_wide(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => hostname(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),
}
}
/// [`iporhost`] with its IPv6 half read by [`ipv6_checked`].
fn iporhost_checked(h: &[u8], at: usize) -> Scan {
match ipv6_checked(h, at) {
Scan::Match(e) => Scan::Match(e),
_ => match ipv4(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 = digits(h, at, 2);
some_if(n > 0, at + n)
}
fn year(h: &[u8], at: usize) -> Scan {
match 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) -> Vec<usize> {
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);
}
ends
}
fn hour(h: &[u8], at: usize) -> Scan {
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')) && digit(h, at + 1);
some_if(ok, at + 2)
}
/// The first end of `(?:[0-5]?[0-9]|60)` from `i`.
fn second_whole(h: &[u8], i: usize) -> Option<usize> {
if matches!(byte(h, i), Some(b'0'..=b'5')) {
return Some(if digit(h, i + 1) { i + 2 } else { i + 1 });
}
digit(h, i).then_some(i + 1)
}
/// Greedy optional `[seps][0-9]+` after `e`.
fn fraction(h: &[u8], e: usize, seps: &[u8]) -> usize {
if byte(h, e).is_some_and(|b| seps.contains(&b)) {
let n = digits(h, e + 1, usize::MAX);
if n > 0 {
return e + 1 + n;
}
}
e
}
fn second(h: &[u8], at: usize) -> Scan {
second_whole(h, at).map_or(Scan::NoMatch, |e| Scan::Match(fraction(h, e, b":.,")))
}
/// `[0-9]{1,2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]+)?)?` from `i`.
fn time_end(h: &[u8], i: usize) -> Option<usize> {
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 None,
};
if !exact(h, j, 2) {
return None;
}
let k = j + 2;
if byte(h, k) == Some(b':') && exact(h, k + 1, 2) {
return Some(fraction(h, k + 3, b".,"));
}
Some(k)
}
fn time(h: &[u8], at: usize) -> Scan {
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 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')) && digit(h, p + 1) {
return Scan::Match(p + 2);
}
}
}
Scan::NoMatch
}
fn timestamp_iso8601(h: &[u8], at: usize) -> Scan {
let date = exact(h, at, 4)
&& byte(h, at + 4) == Some(b'-')
&& exact(h, at + 5, 2)
&& byte(h, at + 7) == Some(b'-')
&& exact(h, at + 8, 2)
&& matches!(byte(h, at + 10), Some(b'T' | b' '))
&& exact(h, at + 11, 2)
&& byte(h, at + 13) == Some(b':')
&& 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 = second_whole(h, sec_at).map_or(k, |e| fraction(h, e, b":.,"));
if byte(h, m) == Some(b'Z') {
m += 1;
} else if sign(h, m) && exact(h, m + 1, 2) {
let p = m + 3;
if byte(h, p) == Some(b':') && exact(h, p + 1, 2) {
m = p + 3;
} else if 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 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) = time_end(h, q) {
return Scan::Match(end);
}
}
Scan::NoMatch
}
fn httpdate(h: &[u8], at: usize) -> Scan {
let p = match 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'/') || !exact(h, m + 1, 4) || byte(h, m + 5) != Some(b':') {
continue;
}
let Some(t) = 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 = digits(h, s, usize::MAX);
if n > 0 {
return Scan::Match(s + n);
}
}
Scan::NoMatch
}
fn base10num(h: &[u8], at: usize) -> Scan {
if !Edge::NoNumberBefore.holds(h, at) {
return Scan::NoMatch;
}
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 {
let keep = |b: u8| b.is_ascii_alphanumeric() || b"_%!$@:.,+~-".contains(&b);
let mut i = at;
while byte(h, i) == Some(b'/') {
i += 1 + run(h, i + 1, keep);
// Whether a character past ASCII is a letter, mark or digit is the
// regex's table to read.
if byte(h, i).is_some_and(|b| b >= 0x80) {
return Scan::Defer;
}
}
some_if(i > at, i)
}
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,
}
}