grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/tier.rs
// Purpose:   The cost tier every matcher and parser reports
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One tier enum for matching and parsing, ranked by worst-case complexity
//! class rather than by a nanosecond figure.

/// The engine class a matcher or parser runs on.
///
/// Variants are ordered fastest first. [`Self::class`] groups them by
/// worst-case complexity, and [`Self::rank`] orders them for `min_tier`
/// gates.
///
/// | Variant | Class | Worst case |
/// |---|---|---|
/// | `Fixed` | 0 | O(1) per field: fixed offsets, length-prefixed frames |
/// | `Byte`, `Literal`, `LiteralSet` | 1 | O(n) scan: memchr, memmem, aho-corasick |
/// | `Field` | 2 | O(field): anchored field parsers that never backtrack |
/// | `Regex` | 3 | O(n * pattern): the linear-time regex engine |
/// | `Backtracking` | 4 | exponential: lookaround and backreferences |
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MatcherTier {
    /// Fixed offsets or a length-prefixed frame.
    Fixed,
    /// Up to 30 ns on a ~200-byte haystack: `memchr` / `memchr2/3` /
    /// single-byte `starts_with` / `ends_with` / `==`.
    Byte,
    /// Up to 200 ns on a ~200-byte haystack: one multi-byte literal through
    /// `memmem::Finder` / `starts_with` / `ends_with` / `==`.
    Literal,
    /// Up to 500 ns on a ~200-byte haystack: `aho-corasick` over two or more
    /// literals, with an optional uniform anchor checked after the scan.
    LiteralSet,
    /// An anchored field parser: an address, a number, a timestamp.
    Field,
    /// The linear-time `regex-automata` meta engine.
    Regex,
    /// A backtracking engine. Has no worst-case bound.
    Backtracking,
}

impl MatcherTier {
    /// Every tier, fastest first. [`Self::index`] is the position in this array.
    pub const ALL: [Self; 7] = [
        Self::Fixed,
        Self::Byte,
        Self::Literal,
        Self::LiteralSet,
        Self::Field,
        Self::Regex,
        Self::Backtracking,
    ];

    /// Position in [`Self::ALL`], for per-tier count arrays.
    #[must_use]
    pub const fn index(self) -> usize {
        match self {
            Self::Fixed => 0,
            Self::Byte => 1,
            Self::Literal => 2,
            Self::LiteralSet => 3,
            Self::Field => 4,
            Self::Regex => 5,
            Self::Backtracking => 6,
        }
    }

    /// Worst-case complexity class, 0 to 4. See the table on [`MatcherTier`].
    #[must_use]
    pub const fn class(self) -> u8 {
        match self {
            Self::Fixed => 0,
            Self::Byte | Self::Literal | Self::LiteralSet => 1,
            Self::Field => 2,
            Self::Regex => 3,
            Self::Backtracking => 4,
        }
    }

    /// Cost rank, higher is faster: `Fixed` 7 down to `Backtracking` 1.
    ///
    /// Compare ranks, never the numbers themselves: a later tier can shift them.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Fixed => 7,
            Self::Byte => 6,
            Self::Literal => 5,
            Self::LiteralSet => 4,
            Self::Field => 3,
            Self::Regex => 2,
            Self::Backtracking => 1,
        }
    }

    /// Indicative ns budget per call on a ~200-byte haystack, for the scan
    /// tiers that have one. `None` where cost depends on the input or pattern.
    ///
    /// The figures come from `benches/strmatch.rs` on a modern x86 server.
    #[must_use]
    pub const fn typical_budget_ns(self) -> Option<u64> {
        match self {
            Self::Byte => Some(30),
            Self::Literal => Some(200),
            Self::LiteralSet => Some(500),
            Self::Fixed | Self::Field | Self::Regex | Self::Backtracking => None,
        }
    }
}

impl std::fmt::Display for MatcherTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Fixed => "Fixed",
            Self::Byte => "Byte",
            Self::Literal => "Literal",
            Self::LiteralSet => "LiteralSet",
            Self::Field => "Field",
            Self::Regex => "Regex",
            Self::Backtracking => "Backtracking",
        })
    }
}

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

    #[test]
    fn all_is_in_index_order_and_ranks_fall() {
        for (i, tier) in MatcherTier::ALL.iter().enumerate() {
            assert_eq!(tier.index(), i, "{tier}");
        }
        for pair in MatcherTier::ALL.windows(2) {
            assert!(
                pair[0].rank() > pair[1].rank(),
                "{} vs {}",
                pair[0],
                pair[1]
            );
            assert!(
                pair[0].class() <= pair[1].class(),
                "{} vs {}",
                pair[0],
                pair[1]
            );
        }
        assert_eq!(MatcherTier::Fixed.rank(), 7);
        assert_eq!(MatcherTier::Backtracking.rank(), 1);
    }

    #[test]
    fn classes_match_the_design_table() {
        let classes: Vec<u8> = MatcherTier::ALL.iter().map(|t| t.class()).collect();
        assert_eq!(classes, [0, 1, 1, 1, 2, 3, 4]);
    }
}