grippo 0.2.2

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/cost.rs
// Purpose:   The measured cost each primitive is labelled with
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! What a primitive costs, beside the [`MatcherTier`](crate::MatcherTier) it
//! runs on.
//!
//! The tier is a guarantee: the worst case a hostile line can force. The cost
//! is a price: nanoseconds on the reference host, an `x86_64` desktop, for an
//! ordinary line. `benches/costs.rs` measures each primitive on a hit and a
//! miss of 64, 256 and 1,024 bytes and writes the table this module reads.
//! The data moves the figures, so compare costs in 2x [bands], not to the
//! nanosecond.
//!
//! [bands]: Cost::band

use std::collections::HashMap;
use std::sync::LazyLock;

/// The line length a cost label is quoted for.
pub const REFERENCE_BYTES: usize = 256;

/// A cost that grows with the input: ns fixed, and ns per byte.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Line {
    /// Paid whatever the length.
    pub fixed_ns: f32,
    /// Paid per byte of input.
    pub ns_per_byte: f32,
}

impl Line {
    /// The cost of an input `bytes` long, in ns.
    #[must_use]
    #[allow(clippy::cast_precision_loss, reason = "a line length far below 2^24")]
    pub const fn ns(self, bytes: usize) -> f32 {
        self.ns_per_byte.mul_add(bytes as f32, self.fixed_ns)
    }
}

/// What a primitive costs on an input it matches and on one it doesn't.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cost {
    /// On an input it matches.
    pub hit: Line,
    /// On an input it doesn't.
    pub miss: Line,
}

impl Cost {
    /// The label: ns for a [`REFERENCE_BYTES`] line that matches.
    #[must_use]
    pub const fn label(self) -> f32 {
        self.hit.ns(REFERENCE_BYTES)
    }

    /// The cost in ns of a `bytes` line when `hit_rate` of lines match, from
    /// 0.0 to 1.0.
    #[must_use]
    pub fn ns(self, bytes: usize, hit_rate: f32) -> f32 {
        let rate = hit_rate.clamp(0.0, 1.0);
        rate.mul_add(self.hit.ns(bytes), (1.0 - rate) * self.miss.ns(bytes))
    }

    /// The label's 2x band: 0 under 2 ns, 1 from 2 ns, 2 from 4 ns, and so on.
    /// Two costs in one band are too close to rank.
    #[must_use]
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "the log2 of a positive ns figure is a small non-negative number"
    )]
    pub fn band(self) -> u8 {
        self.label().max(1.0).log2() as u8
    }
}

/// The table `benches/costs.rs` wrote on the reference host.
static TABLE: LazyLock<HashMap<&'static str, Cost>> = LazyLock::new(|| {
    include_str!("cost/x86_64.tsv")
        .lines()
        .skip(1)
        .filter_map(|row| {
            let mut cells = row.split('\t');
            let name = cells.next()?;
            // The second cell is the arch the row was measured on.
            cells.next()?;
            let mut number = || cells.next()?.parse::<f32>().ok();
            let hit = Line {
                fixed_ns: number()?,
                ns_per_byte: number()?,
            };
            let miss = Line {
                fixed_ns: number()?,
                ns_per_byte: number()?,
            };
            Some((name, Cost { hit, miss }))
        })
        .collect()
});

/// The measured cost of the primitive `name`: an engine such as `memchr` or
/// `lazy_dfa_find`, a field scanner as `field.IPV4`, a stock parser as
/// `parser.syslog`. `None` for a name the table doesn't hold.
#[must_use]
pub fn of(name: &str) -> Option<Cost> {
    TABLE.get(name).copied()
}

/// Every primitive the table holds, in no order.
pub fn primitives() -> impl Iterator<Item = &'static str> {
    TABLE.keys().copied()
}

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

    /// The engines `benches/costs.rs` measures beside the fields and parsers.
    const ENGINES: [&str; 8] = [
        "memchr",
        "memmem",
        "aho_corasick",
        "lazy_dfa_find",
        "onepass_captures",
        "pikevm_captures",
        "meta_captures",
        "grok_native",
    ];

    #[test]
    #[cfg_attr(
        not(feature = "parse"),
        allow(unused_mut, reason = "the names it adds come with the parse feature")
    )]
    fn every_primitive_has_a_measured_cost() {
        let mut names: Vec<String> = ENGINES.iter().map(|e| (*e).to_owned()).collect();
        #[cfg(feature = "parse")]
        names.extend(
            crate::field::FIELDS
                .iter()
                .map(|f| format!("field.{}", f.name)),
        );
        #[cfg(feature = "parse")]
        names.extend(
            crate::format::stock()
                .iter()
                .filter(|p| !p.decodes())
                .map(|p| format!("parser.{}", p.name())),
        );
        for name in &names {
            let cost = of(name).unwrap_or_else(|| panic!("no cost row for {name}"));
            for line in [cost.hit, cost.miss] {
                assert!(line.fixed_ns >= 0.0 && line.ns_per_byte >= 0.0, "{name}");
            }
        }
        // Every row parsed: the header and nothing else was left out.
        let rows = include_str!("cost/x86_64.tsv").lines().count() - 1;
        assert_eq!(primitives().count(), rows);
    }

    #[cfg(feature = "strmatch")]
    #[test]
    fn stock_parsers_and_matchers_report_their_measured_cost() {
        #[cfg(feature = "parse")]
        // A decoder's work follows what it decodes to, which a line cost can't
        // price, so it has no row and its signature always runs first.
        for p in crate::format::stock().iter().filter(|p| !p.decodes()) {
            assert!(p.cost().is_some(), "{} has no cost", p.name());
        }
        let m = crate::strmatch::StrMatcher::new("needle").unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(m.cost(), of("memmem"));
        let r = crate::strmatch::StrMatcher::new(r"a\d+b").unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(r.cost(), of("lazy_dfa_find"));
    }

    #[test]
    fn a_cost_reads_as_a_label_and_a_band() {
        let cost = Cost {
            hit: Line {
                fixed_ns: 62.0,
                ns_per_byte: 0.5,
            },
            miss: Line {
                fixed_ns: 10.0,
                ns_per_byte: 0.0,
            },
        };
        assert!((cost.label() - 190.0).abs() < 0.01);
        assert_eq!(cost.band(), 7);
        assert!((cost.ns(256, 0.5) - 100.0).abs() < 0.01);
        assert!((cost.ns(256, 2.0) - 190.0).abs() < 0.01);
    }
}