grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/grok/backtrack.rs
// Purpose:   Grok patterns the linear engine refuses, on fancy-regex
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use fancy_regex::{Captures, Regex};

use super::Capture;
use crate::parse::{FieldSink, ParseError};

/// The patterns a list opted into backtracking, each searched on its own.
pub(super) struct Backtracking {
    patterns: Vec<Pattern>,
}

struct Pattern {
    /// Its place in the list, which breaks a tie between equal starts.
    index: usize,
    regex: Regex,
    /// The capture behind each group index, `None` for one that names no field.
    groups: Vec<Option<Capture>>,
}

/// The earliest match among the backtracking patterns.
pub(super) struct Hit<'p, 'a> {
    pub(super) start: usize,
    pub(super) index: usize,
    captures: Captures<'a, [u8]>,
    groups: &'p [Option<Capture>],
}

impl Backtracking {
    /// `patterns` as `(index, expanded regex, captures)`.
    pub(super) fn new(
        patterns: Vec<(usize, &str, &[Capture])>,
    ) -> Result<Self, Box<fancy_regex::Error>> {
        let patterns = patterns
            .into_iter()
            .map(|(index, regex, captures)| {
                let regex = Regex::new(regex).map_err(Box::new)?;
                let groups = regex
                    .capture_names()
                    .map(|name| {
                        let i: usize = name?.strip_prefix('g')?.parse().ok()?;
                        captures.get(i).cloned()
                    })
                    .collect();
                Ok(Pattern {
                    index,
                    regex,
                    groups,
                })
            })
            .collect::<Result<Vec<Pattern>, Box<fancy_regex::Error>>>()?;
        Ok(Self { patterns })
    }

    /// Whether the pattern at `index` in the list runs here.
    pub(super) fn holds(&self, index: usize) -> bool {
        self.patterns.iter().any(|p| p.index == index)
    }

    /// The match that starts earliest, a tie going to the pattern listed
    /// first.
    ///
    /// # Errors
    ///
    /// [`ParseError::Limit`] when a search passes fancy-regex's backtracking
    /// limit.
    pub(super) fn search<'p, 'a>(
        &'p self,
        input: &'a [u8],
    ) -> Result<Option<Hit<'p, 'a>>, ParseError> {
        let mut best: Option<Hit<'p, 'a>> = None;
        for p in &self.patterns {
            let found = p.regex.captures(input).map_err(|_| ParseError::Limit {
                what: "the backtracking budget",
            })?;
            let Some(captures) = found else { continue };
            let start = captures.get(0).map_or(0, |m| m.start());
            if best.as_ref().is_none_or(|b| start < b.start) {
                best = Some(Hit {
                    start,
                    index: p.index,
                    captures,
                    groups: &p.groups,
                });
            }
        }
        Ok(best)
    }
}

impl<'a> Hit<'_, 'a> {
    /// Write the match's fields to `out`.
    pub(super) fn write(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>) {
        for (i, capture) in self.groups.iter().enumerate() {
            if let (Some(c), Some(m)) = (capture, self.captures.get(i))
                && let Some(v) = c.value(&input[m.range()])
            {
                out.field(&c.field, v);
            }
        }
    }
}