use std::borrow::Cow;
#[cfg(feature = "dfa")]
use aho_corasick::{
AhoCorasick as AcEngine, AhoCorasickBuilder as AcBuilder, AhoCorasickKind as AcKind,
MatchKind as AcMatchKind,
};
use daachorse::{
DoubleArrayAhoCorasick as BytewiseDAACEngine,
DoubleArrayAhoCorasickBuilder as BytewiseDAACBuilder, MatchKind as DAACMatchKind,
charwise::{
CharwiseDoubleArrayAhoCorasick as CharwiseDAACEngine,
CharwiseDoubleArrayAhoCorasickBuilder as CharwiseDAACBuilder,
},
};
use super::pattern::{PatternEntry, PatternIndex};
use crate::MatcherError;
pub(super) const CHARWISE_DENSITY_THRESHOLD: f32 = 0.67;
#[inline(always)]
pub(super) fn text_non_ascii_density(text: &str) -> f32 {
let bytes = text.as_bytes();
let len = bytes.len();
if len == 0 {
return 0.0;
}
super::simd::count_non_ascii_simd(bytes) as f32 / len as f32
}
trait ScanEngine {
fn is_match(&self, text: &str) -> bool;
fn for_each_match_value(
&self,
text: &str,
on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool;
fn for_each_match_value_from_iter(
&self,
iter: impl Iterator<Item = u8>,
on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool;
fn heap_bytes(&self) -> usize;
}
#[derive(Clone)]
struct BytewiseMatcher {
daac: BytewiseDAACEngine<u32>,
#[cfg(feature = "dfa")]
dfa: AcEngine,
#[cfg(feature = "dfa")]
dfa_to_value: Vec<u32>,
}
impl ScanEngine for BytewiseMatcher {
#[inline(always)]
fn is_match(&self, text: &str) -> bool {
#[cfg(feature = "dfa")]
{
self.dfa.is_match(text)
}
#[cfg(not(feature = "dfa"))]
{
self.daac.find_iter(text).next().is_some()
}
}
#[inline(always)]
fn for_each_match_value(
&self,
text: &str,
mut on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
#[cfg(feature = "dfa")]
{
for m in self.dfa.find_overlapping_iter(text) {
let pid = m.pattern().as_usize();
unsafe { core::hint::assert_unchecked(pid < self.dfa_to_value.len()) };
let value = self.dfa_to_value[pid];
if on_value(value, m.start(), m.end()) {
return true;
}
}
false
}
#[cfg(not(feature = "dfa"))]
{
for hit in self.daac.find_overlapping_iter(text) {
if on_value(hit.value(), hit.start(), hit.end()) {
return true;
}
}
false
}
}
#[inline(always)]
fn for_each_match_value_from_iter(
&self,
iter: impl Iterator<Item = u8>,
mut on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
for hit in self.daac.find_overlapping_iter_from_iter(iter) {
if on_value(hit.value(), hit.start(), hit.end()) {
return true;
}
}
false
}
fn heap_bytes(&self) -> usize {
let daac = self.daac.heap_bytes();
#[cfg(feature = "dfa")]
{
daac + self.dfa.memory_usage() + self.dfa_to_value.capacity() * size_of::<u32>()
}
#[cfg(not(feature = "dfa"))]
daac
}
}
type CharwiseMatcher = CharwiseDAACEngine<u32>;
impl ScanEngine for CharwiseMatcher {
fn is_match(&self, text: &str) -> bool {
self.find_iter(text).next().is_some()
}
#[inline(always)]
fn for_each_match_value(
&self,
text: &str,
mut on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
for hit in self.find_overlapping_iter(text) {
if on_value(hit.value(), hit.start(), hit.end()) {
return true;
}
}
false
}
#[inline(always)]
fn for_each_match_value_from_iter(
&self,
iter: impl Iterator<Item = u8>,
mut on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
for hit in unsafe { self.find_overlapping_iter_from_iter(iter) } {
if on_value(hit.value(), hit.start(), hit.end()) {
return true;
}
}
false
}
fn heap_bytes(&self) -> usize {
CharwiseDAACEngine::heap_bytes(self)
}
}
#[derive(Clone)]
struct Engines {
bytewise: BytewiseMatcher,
charwise: CharwiseMatcher,
}
macro_rules! dispatch {
($engines:expr, $density:expr, $method:ident ($($arg:expr),*)) => {
if $density <= CHARWISE_DENSITY_THRESHOLD {
ScanEngine::$method(&$engines.bytewise, $($arg),*)
} else {
ScanEngine::$method(&$engines.charwise, $($arg),*)
}
};
}
#[derive(Clone)]
pub(super) struct ScanPlan {
engines: Engines,
all_patterns_ascii: bool,
patterns: PatternIndex,
}
impl ScanPlan {
pub(super) fn compile(
dedup_patterns: &[Cow<'_, str>],
dedup_entries: Vec<Vec<PatternEntry>>,
rule_info: &[super::rule::RuleInfo],
) -> Result<Self, MatcherError> {
debug_assert!(
!dedup_patterns.is_empty(),
"ScanPlan::compile called with zero patterns"
);
let patterns = PatternIndex::new(dedup_entries);
let value_map = patterns.build_value_map(rule_info);
let engines = compile_automata(dedup_patterns, &value_map)?;
let all_patterns_ascii = dedup_patterns.iter().all(|p| p.is_ascii());
Ok(Self {
engines,
all_patterns_ascii,
patterns,
})
}
pub(super) fn patterns(&self) -> &PatternIndex {
&self.patterns
}
pub(super) fn heap_bytes(&self) -> usize {
self.engines.bytewise.heap_bytes()
+ self.engines.charwise.heap_bytes()
+ self.patterns.heap_bytes()
}
#[inline(always)]
pub(super) fn is_match(&self, text: &str) -> bool {
let density = text_non_ascii_density(text);
if self.all_patterns_ascii && density >= 1.0 {
return false;
}
dispatch!(self.engines, density, is_match(text))
}
#[inline(always)]
pub(super) fn for_each_match_value(
&self,
text: &str,
density: f32,
on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
if self.all_patterns_ascii && density >= 1.0 {
return false;
}
dispatch!(self.engines, density, for_each_match_value(text, on_value))
}
#[inline(always)]
pub(super) fn for_each_match_value_from_iter(
&self,
iter: impl Iterator<Item = u8>,
density: f32,
on_value: impl FnMut(u32, usize, usize) -> bool,
) -> bool {
dispatch!(
self.engines,
density,
for_each_match_value_from_iter(iter, on_value)
)
}
}
#[optimize(speed)]
fn compile_automata(
dedup_patterns: &[Cow<'_, str>],
value_map: &[u32],
) -> Result<Engines, MatcherError> {
let all_patvals: Vec<(&str, u32)> = dedup_patterns
.iter()
.enumerate()
.map(|(i, p)| (p.as_ref(), value_map[i]))
.collect();
let all_patvals_clone = all_patvals.clone();
let build_bytewise = move || -> Result<BytewiseMatcher, MatcherError> {
build_current_bytewise(all_patvals_clone)
};
let build_charwise = |source: Vec<(&str, u32)>| -> Result<CharwiseMatcher, MatcherError> {
CharwiseDAACBuilder::new()
.match_kind(DAACMatchKind::Standard)
.build_with_values(source)
.map_err(MatcherError::automaton_build)
};
std::thread::scope(|s| {
let bytewise_handle = s.spawn(build_bytewise);
let charwise = build_charwise(all_patvals)?;
let bytewise = bytewise_handle
.join()
.expect("bytewise automaton build panicked")?;
Ok(Engines { bytewise, charwise })
})
}
fn build_current_bytewise(all_patvals: Vec<(&str, u32)>) -> Result<BytewiseMatcher, MatcherError> {
#[cfg(feature = "dfa")]
let dfa_to_value: Vec<u32> = all_patvals.iter().map(|&(_, v)| v).collect();
#[cfg(feature = "dfa")]
let dfa = AcBuilder::new()
.kind(Some(AcKind::DFA))
.match_kind(AcMatchKind::Standard)
.build(all_patvals.iter().map(|(p, _)| p))
.map_err(MatcherError::automaton_build)?;
let daac = BytewiseDAACBuilder::new()
.match_kind(DAACMatchKind::Standard)
.build_with_values(all_patvals)
.map_err(MatcherError::automaton_build)?;
Ok(BytewiseMatcher {
daac,
#[cfg(feature = "dfa")]
dfa,
#[cfg(feature = "dfa")]
dfa_to_value,
})
}