grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/field/edge.rs
// Purpose:   The lookarounds of the upstream grok fields, as checks on the bytes beside a match
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The upstream grok library writes some fields with a lookaround on the byte
//! or two beside a match. A field regex here writes the same lookaround, and
//! each one the linear engine can't run is an [`Edge`]: the scans make the
//! check, and grok's expansion marks where it sits.

#![cfg_attr(
    not(feature = "parse-grok"),
    allow(dead_code, reason = "grok's planner and expansion read the checks")
)]

use std::borrow::Cow;

/// A zero-width check on the bytes beside a position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Edge {
    /// `(?<![0-9])`.
    NoDigitBefore,
    /// `(?![0-9])`.
    NoDigitAfter,
    /// `(?<![0-9.+-])`.
    NoNumberBefore,
    /// No `:` before with a hex digit or `:` before that, and no `.` before
    /// with a hex digit before that: nothing that would extend an IPv6 address.
    Ipv6Before,
    /// [`Edge::Ipv6Before`] on the bytes after.
    Ipv6After,
}

/// Every check.
const ALL: [Edge; 5] = [
    Edge::NoDigitBefore,
    Edge::NoDigitAfter,
    Edge::NoNumberBefore,
    Edge::Ipv6Before,
    Edge::Ipv6After,
];

impl Edge {
    /// Whether the check holds at `at` in `h`.
    #[must_use]
    pub fn holds(self, h: &[u8], at: usize) -> bool {
        let before = |back: usize| at.checked_sub(back).and_then(|i| h.get(i)).copied();
        let after = |ahead: usize| h.get(at + ahead).copied();
        let extends = |side: Option<u8>, far: Option<u8>| match side {
            Some(b':') => far.is_some_and(|b| b.is_ascii_hexdigit() || b == b':'),
            Some(b'.') => far.is_some_and(|b| b.is_ascii_hexdigit()),
            _ => false,
        };
        match self {
            Self::NoDigitBefore => !before(1).is_some_and(|b| b.is_ascii_digit()),
            Self::NoDigitAfter => !after(0).is_some_and(|b| b.is_ascii_digit()),
            Self::NoNumberBefore => {
                !before(1).is_some_and(|b| b.is_ascii_digit() || matches!(b, b'.' | b'+' | b'-'))
            }
            Self::Ipv6Before => !extends(before(1), before(2)),
            Self::Ipv6After => !extends(after(0), after(1)),
        }
    }

    /// Whether the check reads the bytes before its position.
    #[must_use]
    pub const fn looks_back(self) -> bool {
        matches!(
            self,
            Self::NoDigitBefore | Self::NoNumberBefore | Self::Ipv6Before
        )
    }

    /// The lookaround, as a field regex writes it.
    #[must_use]
    pub const fn lookaround(self) -> &'static str {
        match self {
            Self::NoDigitBefore => no_digit_before!(),
            Self::NoDigitAfter => no_digit_after!(),
            Self::NoNumberBefore => no_number_before!(),
            Self::Ipv6Before => ipv6_before!(),
            Self::Ipv6After => ipv6_after!(),
        }
    }

    /// The check whose lookaround starts `text`, and the lookaround's length.
    #[must_use]
    pub fn at_start(text: &str) -> Option<(Self, usize)> {
        ALL.into_iter()
            .find(|e| text.starts_with(e.lookaround()))
            .map(|e| (e, e.lookaround().len()))
    }

    /// `regex` with every check's lookaround taken out: a regex the linear
    /// engine and its DFAs build, which matches wherever `regex` does and more.
    #[must_use]
    pub fn relaxed(regex: &str) -> Cow<'_, str> {
        if !regex.contains("(?<!") && !regex.contains("(?!") {
            return Cow::Borrowed(regex);
        }
        let mut out = String::with_capacity(regex.len());
        let mut rest = regex;
        while let Some(i) = rest.find("(?") {
            out.push_str(&rest[..i]);
            rest = &rest[i..];
            if let Some((_, len)) = Self::at_start(rest) {
                rest = &rest[len..];
            } else {
                out.push_str("(?");
                rest = &rest[2..];
            }
        }
        out.push_str(rest);
        Cow::Owned(out)
    }
}

/// A field regex's checks, by where they sit: at its start, at its end, or
/// inside one branch.
#[derive(Debug, Clone, Default)]
pub struct Edges {
    /// Checks every match makes at its start.
    pub start: Vec<Edge>,
    /// Checks every match makes at its end.
    pub end: Vec<Edge>,
    /// Checks only some branches make. A branch's check sits where the field
    /// starts or ends.
    pub inner: Vec<Edge>,
}

impl Edges {
    /// The checks in `regex`, a field's.
    pub fn of(regex: &str) -> Self {
        let mut edges = Self::default();
        let mut at = 0;
        while let Some(i) = regex[at..].find("(?") {
            let from = at + i;
            let Some((edge, len)) = Edge::at_start(&regex[from..]) else {
                at = from + 2;
                continue;
            };
            let whole = if edge.looks_back() {
                from == 0
            } else {
                from + len == regex.len()
            };
            match (whole, edge.looks_back()) {
                (true, true) => edges.start.push(edge),
                (true, false) => edges.end.push(edge),
                (false, _) => edges.inner.push(edge),
            }
            at = from + len;
        }
        edges
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_lookaround_reads_back_as_its_check() {
        for edge in ALL {
            let text = format!("{}x", edge.lookaround());
            assert_eq!(Edge::at_start(&text), Some((edge, text.len() - 1)));
        }
        assert_eq!(Edge::at_start("(?<![a-z])"), None);
        assert_eq!(
            Edge::relaxed("(?<![0-9])a(?<![a-z])b(?![0-9])"),
            "a(?<![a-z])b"
        );
    }

    #[test]
    fn the_ipv6_checks_read_both_bytes_beside() {
        let h = b"1::2::3 a.b 2001:db8::1. x";
        assert!(!Edge::Ipv6After.holds(h, 4));
        assert!(!Edge::Ipv6Before.holds(h, 6));
        assert!(Edge::Ipv6After.holds(h, 23));
        assert!(Edge::Ipv6Before.holds(h, 0));
        assert!(Edge::Ipv6Before.holds(h, 1));
    }

    #[test]
    fn a_field_regex_says_where_its_checks_sit() {
        let edges = Edges::of(super::super::field("IPV4").unwrap().regex);
        assert_eq!(edges.start, [Edge::NoDigitBefore]);
        assert_eq!(edges.end, [Edge::NoDigitAfter]);
        assert_eq!(edges.inner, []);
        let ip = Edges::of(super::super::field("IP").unwrap().regex);
        assert_eq!(ip.inner, [Edge::NoDigitBefore, Edge::NoDigitAfter]);
    }
}