use std::collections::HashMap;
use std::sync::LazyLock;
pub const REFERENCE_BYTES: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Line {
pub fixed_ns: f32,
pub ns_per_byte: f32,
}
impl Line {
#[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)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cost {
pub hit: Line,
pub miss: Line,
}
impl Cost {
#[must_use]
pub const fn label(self) -> f32 {
self.hit.ns(REFERENCE_BYTES)
}
#[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))
}
#[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
}
}
static TABLE: LazyLock<HashMap<&'static str, Cost>> = LazyLock::new(|| {
if !cfg!(target_arch = "x86_64") {
return HashMap::new();
}
include_str!("cost/x86_64.tsv")
.lines()
.skip(1)
.filter_map(|row| {
let mut cells = row.split('\t');
let name = cells.next()?;
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()
});
#[must_use]
pub fn of(name: &str) -> Option<Cost> {
TABLE.get(name).copied()
}
pub fn primitives() -> impl Iterator<Item = &'static str> {
TABLE.keys().copied()
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_arch = "x86_64")]
const ENGINES: [&str; 8] = [
"memchr",
"memmem",
"aho_corasick",
"lazy_dfa_find",
"onepass_captures",
"pikevm_captures",
"meta_captures",
"grok_native",
];
#[cfg(not(target_arch = "x86_64"))]
#[test]
fn a_target_off_x86_64_holds_no_price() {
assert!(of("memchr").is_none());
assert_eq!(primitives().count(), 0);
}
#[cfg(target_arch = "x86_64")]
#[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}");
}
}
let rows = include_str!("cost/x86_64.tsv").lines().count() - 1;
assert_eq!(primitives().count(), rows);
}
#[cfg(all(feature = "strmatch", target_arch = "x86_64"))]
#[test]
fn stock_parsers_and_matchers_report_their_measured_cost() {
#[cfg(feature = "parse")]
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);
}
}