grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/grok/ends.rs
// Purpose:   Every place a field's regex can end, read from its lazy DFA
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use regex_automata::dfa::{Automaton, StartKind, dense};
use regex_automata::hybrid::dfa::{Cache, DFA};
use regex_automata::util::pool::Pool;
use regex_automata::{Anchored, Input, MatchKind};

use std::sync::{LazyLock, OnceLock};

use crate::field::{FIELDS, Field};

type CachePool = Pool<Cache, Box<dyn Fn() -> Cache + Send + Sync>>;

/// A field regex as a DFA that reports every end, not only the one the
/// regex prefers.
pub(super) struct Ends {
    /// Fully built ahead, for a field regex small enough: a table lookup a
    /// byte, with no cache to borrow.
    table: Option<dense::DFA<Vec<u32>>>,
    dfa: DFA,
    pool: CachePool,
}

/// The most memory a field's ahead-built DFA may take.
const TABLE_LIMIT: usize = 1 << 20;

impl std::fmt::Debug for Ends {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ends").finish_non_exhaustive()
    }
}

/// Where a field ends, given where the next step can start.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum End {
    /// Only here.
    At(usize),
    /// Nowhere the next step can start.
    Nowhere,
    /// At two or more such places, or the DFA gave up.
    Unsure,
    /// The budget ran out.
    Spent,
}

/// The ends of `field`, built once per process and shared by every pattern
/// that holds it. `None` when the DFA doesn't build.
pub(super) fn of(field: &'static Field) -> Option<&'static Ends> {
    static ENDS: LazyLock<Vec<OnceLock<Option<Ends>>>> =
        LazyLock::new(|| FIELDS.iter().map(|_| OnceLock::new()).collect());
    let i = FIELDS.iter().position(|f| std::ptr::eq(f, field))?;
    ENDS[i].get_or_init(|| Ends::new(field.regex)).as_ref()
}

impl Ends {
    fn new(regex: &str) -> Option<Self> {
        let dfa = DFA::builder()
            .configure(
                DFA::config()
                    .match_kind(MatchKind::All)
                    .unicode_word_boundary(true),
            )
            .build(regex)
            .ok()?;
        let make = dfa.clone();
        let pool = Pool::new(
            Box::new(move || make.create_cache()) as Box<dyn Fn() -> Cache + Send + Sync>
        );
        let table = dense::DFA::builder()
            .configure(
                dense::Config::new()
                    .match_kind(MatchKind::All)
                    .start_kind(StartKind::Anchored)
                    .unicode_word_boundary(true)
                    .dfa_size_limit(Some(TABLE_LIMIT))
                    .determinize_size_limit(Some(TABLE_LIMIT)),
            )
            .build(regex)
            .ok();
        Some(Self { table, dfa, pool })
    }

    /// The one end from `at`, the field's start, where `viable` holds. Each
    /// byte read comes off `budget`.
    pub(super) fn only(
        &self,
        h: &[u8],
        at: usize,
        budget: &mut usize,
        viable: impl Fn(usize) -> bool,
    ) -> End {
        if let Some(table) = &self.table {
            return only_in(table, h, at, budget, viable);
        }
        let mut cache = self.pool.get();
        let input = Input::new(h).range(at..).anchored(Anchored::Yes);
        let Ok(mut sid) = self.dfa.start_state_forward(&mut cache, &input) else {
            return End::Unsure;
        };
        let mut found = None;
        // A match state is reached one byte past the end it reports.
        for p in at..=h.len() {
            let Some(left) = budget.checked_sub(1) else {
                return End::Spent;
            };
            *budget = left;
            let next = if p == h.len() {
                self.dfa.next_eoi_state(&mut cache, sid)
            } else {
                self.dfa.next_state(&mut cache, sid, h[p])
            };
            let Ok(next) = next else { return End::Unsure };
            sid = next;
            if sid.is_quit() {
                return End::Unsure;
            }
            if sid.is_match() && viable(p) {
                if found.is_some() {
                    return End::Unsure;
                }
                found = Some(p);
            }
            if sid.is_dead() {
                break;
            }
        }
        found.map_or(End::Nowhere, End::At)
    }
}

/// [`Ends::only`] on the ahead-built DFA.
fn only_in(
    table: &dense::DFA<Vec<u32>>,
    h: &[u8],
    at: usize,
    budget: &mut usize,
    viable: impl Fn(usize) -> bool,
) -> End {
    let input = Input::new(h).range(at..).anchored(Anchored::Yes);
    let Ok(mut sid) = table.start_state_forward(&input) else {
        return End::Unsure;
    };
    let mut found = None;
    // A match state is reached one byte past the end it reports.
    for p in at..=h.len() {
        let Some(left) = budget.checked_sub(1) else {
            return End::Spent;
        };
        *budget = left;
        sid = if p == h.len() {
            table.next_eoi_state(sid)
        } else {
            table.next_state(sid, h[p])
        };
        if table.is_quit_state(sid) {
            return End::Unsure;
        }
        if table.is_match_state(sid) && viable(p) {
            if found.is_some() {
                return End::Unsure;
            }
            found = Some(p);
        }
        if table.is_dead_state(sid) {
            break;
        }
    }
    found.map_or(End::Nowhere, End::At)
}

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

    #[test]
    fn a_common_overlapping_field_walks_a_table_built_ahead() {
        let field = crate::field::field("TIMESTAMP_ISO8601").unwrap_or_else(|| unreachable!());
        let ends = of(field).unwrap_or_else(|| panic!("no ends DFA"));
        let built = dense::DFA::builder()
            .configure(
                dense::Config::new()
                    .match_kind(MatchKind::All)
                    .start_kind(StartKind::Anchored)
                    .unicode_word_boundary(true),
            )
            .build(field.regex)
            .map(|d| d.memory_usage());
        assert!(ends.table.is_some(), "no table: {built:?}");
    }
}