use std::borrow::Cow;
#[cfg(feature = "dfa")]
use aho_corasick::{
Anchored, Input, MatchKind as AhoCorasickMatchKind, automaton::Automaton,
dfa::DFA as AcDfaEngine,
};
use daachorse::{
DoubleArrayAhoCorasick, DoubleArrayAhoCorasickBuilder,
MatchKind as DoubleArrayAhoCorasickMatchKind,
charwise::{CharwiseDoubleArrayAhoCorasick, CharwiseDoubleArrayAhoCorasickBuilder},
};
use crate::MatcherError;
use crate::process::transform::simd::multibyte_density;
use super::rule::{PatternEntry, PatternIndex};
#[cfg(feature = "dfa")]
const AC_DFA_PATTERN_THRESHOLD: usize = 7_000;
pub(super) const CHARWISE_DENSITY_THRESHOLD: f32 = 0.1;
#[derive(Clone)]
pub(super) struct ScanPlan {
bytewise_matcher: Option<BytewiseMatcher>,
charwise_matcher: Option<CharwiseMatcher>,
patterns: PatternIndex,
charwise_density_threshold: f32,
}
#[derive(Clone)]
enum BytewiseMatcher {
#[cfg(feature = "dfa")]
AcDfa {
matcher: Box<AcDfaEngine>,
to_value: Vec<u32>,
},
DaacBytewise(DoubleArrayAhoCorasick<u32>),
}
#[derive(Clone)]
enum CharwiseMatcher {
DaacCharwise(CharwiseDoubleArrayAhoCorasick<u32>),
}
impl ScanPlan {
pub(super) fn compile(
dedup_patterns: &[Cow<'_, str>],
dedup_entries: Vec<Vec<PatternEntry>>,
) -> Result<Self, MatcherError> {
let patterns = PatternIndex::new(dedup_entries);
let value_map = patterns.build_value_map();
let (bytewise_matcher, charwise_matcher) = compile_automata(dedup_patterns, &value_map)?;
let charwise_density_threshold = match &bytewise_matcher {
#[cfg(feature = "dfa")]
Some(BytewiseMatcher::AcDfa { .. }) => f32::MAX,
_ => CHARWISE_DENSITY_THRESHOLD,
};
Ok(Self {
bytewise_matcher,
charwise_matcher,
patterns,
charwise_density_threshold,
})
}
#[inline(always)]
pub(super) fn patterns(&self) -> &PatternIndex {
&self.patterns
}
#[inline(always)]
pub(super) fn charwise_density_threshold(&self) -> f32 {
self.charwise_density_threshold
}
#[inline(always)]
pub(super) fn is_match(&self, text: &str) -> bool {
let use_bytewise = multibyte_density(text.as_bytes()) < self.charwise_density_threshold;
if use_bytewise {
self.bytewise_matcher
.as_ref()
.is_some_and(|m| m.is_match(text))
} else {
self.charwise_matcher
.as_ref()
.is_some_and(|m| m.is_match(text))
}
}
#[inline(always)]
pub(super) fn for_each_match_value(
&self,
text: &str,
use_bytewise: bool,
on_value: impl FnMut(u32) -> bool,
) -> bool {
if use_bytewise {
if let Some(ref matcher) = self.bytewise_matcher {
return matcher.for_each_match_value(text, on_value);
}
} else if let Some(ref matcher) = self.charwise_matcher {
return matcher.for_each_match_value(text, on_value);
}
false
}
#[inline(always)]
pub(super) fn for_each_match_value_from_iter<I: Iterator<Item = u8>>(
&self,
iter: I,
use_bytewise: bool,
on_value: impl FnMut(u32) -> bool,
) -> bool {
if use_bytewise {
if let Some(ref matcher) = self.bytewise_matcher {
return matcher.for_each_match_value_from_iter(iter, on_value);
}
} else if let Some(ref matcher) = self.charwise_matcher {
return matcher.for_each_match_value_from_iter(iter, on_value);
}
false
}
}
impl BytewiseMatcher {
#[inline(always)]
fn is_match(&self, text: &str) -> bool {
match self {
#[cfg(feature = "dfa")]
Self::AcDfa { matcher, .. } => matcher.try_find(&Input::new(text)).unwrap().is_some(),
Self::DaacBytewise(matcher) => matcher.find_iter(text).next().is_some(),
}
}
#[inline(always)]
fn for_each_match_value(&self, text: &str, mut on_value: impl FnMut(u32) -> bool) -> bool {
match self {
#[cfg(feature = "dfa")]
Self::AcDfa { matcher, to_value } => {
for hit in matcher.try_find_overlapping_iter(Input::new(text)).unwrap() {
let value = unsafe { *to_value.get_unchecked(hit.pattern().as_usize()) };
if on_value(value) {
return true;
}
}
false
}
Self::DaacBytewise(matcher) => {
for hit in matcher.find_overlapping_iter(text) {
if on_value(hit.value()) {
return true;
}
}
false
}
}
}
#[inline(always)]
fn for_each_match_value_from_iter<I: Iterator<Item = u8>>(
&self,
iter: I,
mut on_value: impl FnMut(u32) -> bool,
) -> bool {
match self {
#[cfg(feature = "dfa")]
Self::AcDfa { matcher, to_value } => {
let mut sid = matcher.start_state(Anchored::No).unwrap();
for byte in iter {
sid = matcher.next_state(Anchored::No, sid, byte);
if matcher.is_special(sid) && matcher.is_match(sid) {
for i in 0..matcher.match_len(sid) {
let pid = matcher.match_pattern(sid, i);
let value = unsafe { *to_value.get_unchecked(pid.as_usize()) };
if on_value(value) {
return true;
}
}
}
}
false
}
Self::DaacBytewise(matcher) => {
for hit in matcher.find_overlapping_iter_from_iter(iter) {
if on_value(hit.value()) {
return true;
}
}
false
}
}
}
}
impl CharwiseMatcher {
#[inline(always)]
fn is_match(&self, text: &str) -> bool {
match self {
Self::DaacCharwise(matcher) => matcher.find_iter(text).next().is_some(),
}
}
#[inline(always)]
fn for_each_match_value(&self, text: &str, mut on_value: impl FnMut(u32) -> bool) -> bool {
match self {
Self::DaacCharwise(matcher) => {
for hit in matcher.find_overlapping_iter(text) {
if on_value(hit.value()) {
return true;
}
}
false
}
}
}
#[inline(always)]
fn for_each_match_value_from_iter<I: Iterator<Item = u8>>(
&self,
iter: I,
mut on_value: impl FnMut(u32) -> bool,
) -> bool {
match self {
Self::DaacCharwise(matcher) => {
for hit in unsafe { matcher.find_overlapping_iter_from_iter(iter) } {
if on_value(hit.value()) {
return true;
}
}
false
}
}
}
}
fn compile_automata(
dedup_patterns: &[Cow<'_, str>],
value_map: &[u32],
) -> Result<(Option<BytewiseMatcher>, Option<CharwiseMatcher>), MatcherError> {
if dedup_patterns.is_empty() {
return Ok((None, None));
}
let all_patvals: Vec<(&str, u32)> = dedup_patterns
.iter()
.enumerate()
.map(|(i, p)| (p.as_ref(), value_map[i]))
.collect();
#[cfg(feature = "dfa")]
let all_ascii = dedup_patterns.iter().all(|p| p.is_ascii());
#[cfg(feature = "dfa")]
let ac_to_value: Vec<u32> = value_map.to_vec();
let build_bytewise = || -> Result<BytewiseMatcher, MatcherError> {
#[cfg(feature = "dfa")]
if all_ascii && all_patvals.len() <= AC_DFA_PATTERN_THRESHOLD {
return Ok(BytewiseMatcher::AcDfa {
matcher: Box::new(
AcDfaEngine::builder()
.match_kind(AhoCorasickMatchKind::Standard)
.build(all_patvals.iter().map(|(p, _)| p))
.map_err(MatcherError::automaton_build)?,
),
to_value: ac_to_value,
});
}
Ok(BytewiseMatcher::DaacBytewise(
DoubleArrayAhoCorasickBuilder::new()
.match_kind(DoubleArrayAhoCorasickMatchKind::Standard)
.build_with_values(all_patvals.iter().copied())
.map_err(MatcherError::automaton_build)?,
))
};
let build_charwise = || -> Result<CharwiseMatcher, MatcherError> {
Ok(CharwiseMatcher::DaacCharwise(
CharwiseDoubleArrayAhoCorasickBuilder::new()
.match_kind(DoubleArrayAhoCorasickMatchKind::Standard)
.build_with_values(all_patvals.iter().copied())
.map_err(MatcherError::automaton_build)?,
))
};
std::thread::scope(|s| {
let bytewise_handle = s.spawn(build_bytewise);
let charwise = build_charwise()?;
let bytewise = bytewise_handle
.join()
.expect("bytewise automaton build panicked")?;
Ok((Some(bytewise), Some(charwise)))
})
}