use std::collections::HashMap;
use aho_corasick::{AhoCorasick, AhoCorasickKind, MatchKind};
use memchr::memmem::Finder;
use thiserror::Error;
pub type Verify = fn(&[u8], usize) -> bool;
pub const MAX_VERIFY: u8 = 8;
pub const MAX_ALL_OF: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum Specificity {
Generic,
#[default]
Specific,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SignatureError {
#[error("signature: an empty literal matches every position")]
EmptyLiteral,
#[error("signature: {got} all_of literals, at most {max}")]
TooManyAllOf {
got: usize,
max: usize,
},
#[error("signature: a set holds at most {max} signatures")]
TooMany {
max: usize,
},
#[error("signature: the literal automaton does not build: {source}")]
Automaton {
#[source]
source: Box<aho_corasick::BuildError>,
},
}
fn automaton_error(e: aho_corasick::BuildError) -> SignatureError {
SignatureError::Automaton {
source: Box::new(e),
}
}
#[derive(Debug, Clone)]
enum Needle {
Exact(Box<Finder<'static>>),
Folded(Box<[u8]>),
}
impl Needle {
fn new(literal: &[u8], folded: bool) -> Self {
if folded && literal.iter().any(u8::is_ascii_alphabetic) {
Self::Folded(literal.into())
} else {
Self::Exact(Box::new(Finder::new(literal).into_owned()))
}
}
fn find(&self, hay: &[u8]) -> Option<usize> {
match self {
Self::Exact(f) => f.find(hay),
Self::Folded(literal) => {
let first = *literal.first()?;
let starts = hay.get(..=hay.len().checked_sub(literal.len())?)?;
memchr::memchr2_iter(first, first.to_ascii_uppercase(), starts).find(|&at| {
hay.get(at..at + literal.len())
.is_some_and(|here| here.eq_ignore_ascii_case(literal))
})
}
}
}
fn bytes(&self) -> &[u8] {
match self {
Self::Exact(f) => f.needle(),
Self::Folded(literal) => literal,
}
}
}
fn starts_with(span: &[u8], literal: &[u8], folded: bool) -> bool {
if folded {
span.get(..literal.len())
.is_some_and(|head| head.eq_ignore_ascii_case(literal))
} else {
span.starts_with(literal)
}
}
#[derive(Debug, Clone)]
pub struct Signature {
anchored: Vec<Box<[u8]>>,
all_of: Vec<Needle>,
any_of: Vec<Needle>,
verify: Option<Verify>,
within: Option<usize>,
folded: bool,
verify_cap: Option<u8>,
every_hit: bool,
specificity: Specificity,
priority: u8,
}
#[derive(Debug, Clone)]
pub struct SignatureBuilder {
anchored: Vec<Box<[u8]>>,
all_of: Vec<Box<[u8]>>,
any_of: Vec<Box<[u8]>>,
verify: Option<Verify>,
within: Option<usize>,
folded: bool,
verify_cap: Option<u8>,
every_hit: bool,
specificity: Specificity,
priority: u8,
}
impl Default for SignatureBuilder {
fn default() -> Self {
Self {
anchored: Vec::new(),
all_of: Vec::new(),
any_of: Vec::new(),
verify: None,
within: None,
folded: false,
verify_cap: Some(MAX_VERIFY),
every_hit: false,
specificity: Specificity::default(),
priority: 0,
}
}
}
impl SignatureBuilder {
#[must_use]
pub fn anchored<I, L>(mut self, literals: I) -> Self
where
I: IntoIterator<Item = L>,
L: AsRef<[u8]>,
{
self.anchored
.extend(literals.into_iter().map(|l| l.as_ref().into()));
self
}
#[must_use]
pub fn all_of<I, L>(mut self, literals: I) -> Self
where
I: IntoIterator<Item = L>,
L: AsRef<[u8]>,
{
self.all_of
.extend(literals.into_iter().map(|l| l.as_ref().into()));
self
}
#[must_use]
pub fn any_of<I, L>(mut self, literals: I) -> Self
where
I: IntoIterator<Item = L>,
L: AsRef<[u8]>,
{
self.any_of
.extend(literals.into_iter().map(|l| l.as_ref().into()));
self
}
#[must_use]
pub const fn verify(mut self, verify: Verify) -> Self {
self.verify = Some(verify);
self
}
#[must_use]
pub const fn within(mut self, bytes: usize) -> Self {
self.within = Some(bytes);
self
}
#[must_use]
pub const fn ascii_case_insensitive(mut self, enabled: bool) -> Self {
self.folded = enabled;
self
}
#[must_use]
pub const fn verify_cap(mut self, cap: Option<u8>) -> Self {
self.verify_cap = cap;
self
}
#[must_use]
pub const fn every_hit(mut self, enabled: bool) -> Self {
self.every_hit = enabled;
self
}
#[must_use]
pub const fn specificity(mut self, specificity: Specificity) -> Self {
self.specificity = specificity;
self
}
#[must_use]
pub const fn priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
pub fn build(self) -> Result<Signature, SignatureError> {
let all = [&self.anchored, &self.all_of, &self.any_of];
if all.iter().any(|lits| lits.iter().any(|l| l.is_empty())) {
return Err(SignatureError::EmptyLiteral);
}
if self.all_of.len() > MAX_ALL_OF {
return Err(SignatureError::TooManyAllOf {
got: self.all_of.len(),
max: MAX_ALL_OF,
});
}
let folded = self.folded;
let lower = |lits: Vec<Box<[u8]>>| -> Vec<Box<[u8]>> {
if folded {
lits.iter().map(|l| l.to_ascii_lowercase().into()).collect()
} else {
lits
}
};
let needles = |lits: Vec<Box<[u8]>>| -> Vec<Needle> {
lower(lits).iter().map(|l| Needle::new(l, folded)).collect()
};
Ok(Signature {
anchored: lower(self.anchored),
all_of: needles(self.all_of),
any_of: needles(self.any_of),
verify: self.verify,
within: self.within,
folded,
verify_cap: self.verify_cap,
every_hit: self.every_hit,
specificity: self.specificity,
priority: self.priority,
})
}
}
impl Signature {
#[must_use]
pub fn builder() -> SignatureBuilder {
SignatureBuilder::default()
}
#[must_use]
pub const fn is_literal_free(&self) -> bool {
self.anchored.is_empty() && self.all_of.is_empty() && self.any_of.is_empty()
}
#[must_use]
pub const fn specificity(&self) -> Specificity {
self.specificity
}
#[must_use]
pub const fn priority(&self) -> u8 {
self.priority
}
#[must_use]
pub fn cost(&self) -> Option<crate::cost::Cost> {
use crate::cost::{Cost, Line, of};
let (literal, memmem) = (of("literal")?, of("memmem")?);
#[allow(
clippy::cast_precision_loss,
reason = "a signature holds far fewer than 2^24 literals"
)]
let searches = (self.all_of.len() + self.any_of.len()) as f32;
let compares: f32 = if self.anchored.is_empty() { 0.0 } else { 1.0 };
let line = |l: Line, s: Line| Line {
fixed_ns: compares.mul_add(l.fixed_ns, searches * s.fixed_ns),
ns_per_byte: searches * s.ns_per_byte,
};
Some(Cost {
hit: line(literal.hit, memmem.hit),
miss: line(literal.miss, memmem.miss),
})
}
#[must_use]
pub fn may_match(&self, span: &[u8]) -> bool {
(self.anchored.is_empty()
|| self
.anchored
.iter()
.any(|a| starts_with(span, a, self.folded)))
&& self.searched(span).is_some()
}
fn searched(&self, span: &[u8]) -> Option<usize> {
let head = self.within.map_or(span, |n| &span[..span.len().min(n)]);
if !self.all_of.iter().all(|f| f.find(head).is_some()) {
return None;
}
if self.any_of.is_empty() {
return self.verify.is_none_or(|v| v(span, 0)).then_some(0);
}
let Some(verify) = self.verify else {
return self.any_of.iter().find_map(|f| f.find(head));
};
let mut calls = 0_u8;
for f in &self.any_of {
let mut from = 0;
while let Some(at) = f.find(&head[from..]).map(|i| from + i) {
if Some(calls) == self.verify_cap || verify(span, at) {
return Some(at);
}
calls = calls.saturating_add(1);
from = at + 1;
}
}
None
}
const fn searched_len(&self) -> usize {
self.all_of.len() + self.any_of.len()
}
}
const DFA_LITERALS: usize = 1_024;
const DFA_BYTES: usize = 1 << 20;
const DIRECT_LITERALS: usize = 8;
#[derive(Debug, Clone, Copy)]
struct Use {
sig: u32,
need: u8,
slot: u8,
bounded: bool,
anchored: bool,
}
const ANY_OF: u8 = u8::MAX;
#[derive(Debug, Clone, Copy)]
struct Uses {
start: usize,
every: usize,
end: usize,
}
#[derive(Debug, Clone)]
struct Meta {
verify: Option<Verify>,
specificity: Specificity,
priority: u8,
has_any_of: bool,
folded: bool,
verify_cap: Option<u8>,
every_hit: bool,
need: u8,
within: usize,
reach: usize,
}
#[derive(Debug, Clone, Copy, Default)]
struct Live {
epoch: u32,
met: u8,
refused: u8,
triggered: bool,
}
#[derive(Debug, Clone, Copy, Default)]
struct SpanMarks {
anchored: u32,
verified: u32,
refused: u8,
}
#[derive(Debug, Clone)]
pub struct SignatureScratch {
live: Vec<Live>,
trigger: Vec<usize>,
trigger_span: Vec<usize>,
all: Vec<u64>,
marks: Vec<SpanMarks>,
seen: Vec<u32>,
ready: Vec<u32>,
anchored: Vec<u32>,
hits: Vec<(u32, usize, usize)>,
epoch: u32,
span_epoch: u32,
}
impl SignatureScratch {
fn next_epoch(&mut self) -> u32 {
self.epoch = self.epoch.wrapping_add(1);
if self.epoch == 0 {
self.live.fill(Live::default());
self.epoch = 1;
}
self.epoch
}
fn next_span_epoch(&mut self) -> u32 {
self.span_epoch = self.span_epoch.wrapping_add(1);
if self.span_epoch == 0 {
self.seen.fill(0);
self.marks.fill(SpanMarks::default());
self.span_epoch = 1;
}
self.span_epoch
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignatureMatch {
pub index: usize,
pub at: usize,
pub span: usize,
}
#[derive(Debug, Clone)]
pub struct SignatureSet {
automata: [Option<AhoCorasick>; 2],
folded_base: usize,
uses: Vec<Use>,
spans: Vec<Uses>,
metas: Vec<Meta>,
anchors: Vec<Vec<(Box<[u8]>, u32, bool)>>,
free_reach: [usize; 2],
sigs: Vec<Signature>,
free: Vec<u32>,
free_literals: usize,
free_min: usize,
anchored: usize,
every_hit: bool,
}
#[derive(Default)]
struct Literals<'a> {
ids: HashMap<&'a [u8], usize>,
bytes: Vec<&'a [u8]>,
once: Vec<Vec<Use>>,
every: Vec<Vec<Use>>,
}
impl<'a> Literals<'a> {
fn add(&mut self, literal: &'a [u8], each_hit: bool, u: Use) {
let id = *self.ids.entry(literal).or_insert_with(|| {
self.bytes.push(literal);
self.once.push(Vec::new());
self.every.push(Vec::new());
self.bytes.len() - 1
});
if each_hit {
self.every[id].push(u);
} else {
self.once[id].push(u);
}
}
fn automaton(&self, folded: bool) -> Result<Option<AhoCorasick>, SignatureError> {
if self.bytes.is_empty() {
return Ok(None);
}
let build = |kind| {
AhoCorasick::builder()
.match_kind(MatchKind::Standard)
.ascii_case_insensitive(folded)
.kind(kind)
.build(&self.bytes)
.map_err(automaton_error)
};
let dfa = (self.bytes.len() <= DFA_LITERALS)
.then(|| build(Some(AhoCorasickKind::DFA)))
.transpose()?
.filter(|ac| ac.memory_usage() <= DFA_BYTES);
Ok(Some(match dfa {
Some(ac) => ac,
None => build(None)?,
}))
}
}
impl SignatureSet {
pub fn new<'a, I>(signatures: I) -> Result<Self, SignatureError>
where
I: IntoIterator<Item = &'a Signature>,
{
let mut literals: [Literals<'a>; 2] = [Literals::default(), Literals::default()];
let mut metas = Vec::new();
let mut anchors: Vec<Vec<(Box<[u8]>, u32, bool)>> = vec![Vec::new(); 256];
let mut free_reach = [0_usize; 2];
let mut sigs = Vec::new();
let mut free = Vec::new();
let mut free_literals = 0_usize;
let mut free_min = usize::MAX;
let mut anchored = 0_usize;
let mut every_hit = false;
for (i, sig) in signatures.into_iter().enumerate() {
let index = u32::try_from(i).map_err(|_| SignatureError::TooMany {
max: u32::MAX as usize,
})?;
for a in &sig.anchored {
let Some(&first) = a.first() else { continue };
let upper = first.to_ascii_uppercase();
let other = (sig.folded && upper != first).then_some(upper);
for b in std::iter::once(first).chain(other) {
anchors[usize::from(b)].push((a.clone(), index, sig.folded));
}
}
let has_any_of = !sig.any_of.is_empty();
let need = u8::try_from(sig.all_of.len() + usize::from(has_any_of)).map_err(|_| {
SignatureError::TooManyAllOf {
got: sig.all_of.len(),
max: MAX_ALL_OF,
}
})?;
let use_ = |slot| Use {
sig: index,
need,
slot,
bounded: sig.within.is_some(),
anchored: !sig.anchored.is_empty(),
};
let lits = &mut literals[usize::from(sig.folded)];
for (slot, f) in (0_u8..).zip(&sig.all_of) {
lits.add(f.bytes(), false, use_(slot));
}
let every = sig.every_hit && !sig.any_of.is_empty();
every_hit |= every;
for f in &sig.any_of {
lits.add(f.bytes(), sig.verify.is_some() || every, use_(ANY_OF));
}
let within = sig.within.unwrap_or(usize::MAX);
let searched = sig.searched_len() > 0;
let reach = if searched { within } else { 0 };
if sig.anchored.is_empty() {
let k = usize::from(sig.folded);
free_reach[k] = free_reach[k].max(reach);
if searched {
free.push(index);
free_literals += sig.searched_len();
let longest_needed = sig.all_of.iter().map(|f| f.bytes().len()).max();
let shortest_any = sig.any_of.iter().map(|f| f.bytes().len()).min();
let least = longest_needed.unwrap_or(0).max(shortest_any.unwrap_or(0));
free_min = free_min.min(least);
}
} else {
anchored += 1;
}
sigs.push(sig.clone());
metas.push(Meta {
verify: sig.verify,
specificity: sig.specificity,
priority: sig.priority,
has_any_of,
folded: sig.folded,
verify_cap: sig.verify_cap,
every_hit: every,
need,
within,
reach,
});
}
let automata = [literals[0].automaton(false)?, literals[1].automaton(true)?];
let folded_base = literals[0].bytes.len();
let mut uses = Vec::new();
let mut spans = Vec::new();
for lits in literals {
for (once, every) in lits.once.into_iter().zip(lits.every) {
let start = uses.len();
uses.extend(once);
let split = uses.len();
uses.extend(every);
spans.push(Uses {
start,
every: split,
end: uses.len(),
});
}
}
Ok(Self {
automata,
folded_base,
uses,
spans,
metas,
anchors,
free_reach,
sigs,
free,
free_literals,
free_min,
anchored,
every_hit,
})
}
#[must_use]
pub fn could_fire(&self, span: &[u8]) -> bool {
span.len() >= self.free_min
|| span.first().is_some_and(|&first| {
self.anchors[usize::from(first)]
.iter()
.any(|(literal, _, folded)| starts_with(span, literal, *folded))
})
}
#[must_use]
pub const fn len(&self) -> usize {
self.metas.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.metas.is_empty()
}
#[must_use]
pub fn scratch(&self) -> SignatureScratch {
let n = self.metas.len();
SignatureScratch {
live: vec![Live::default(); n],
trigger: vec![0; n],
trigger_span: vec![0; n],
all: vec![0; n],
marks: vec![SpanMarks::default(); n],
seen: vec![0; self.spans.len()],
ready: Vec::with_capacity(n),
anchored: Vec::with_capacity(self.anchored),
hits: Vec::new(),
epoch: 0,
span_epoch: 0,
}
}
const fn fits(&self, scratch: &SignatureScratch) -> bool {
scratch.live.len() == self.metas.len()
&& scratch.marks.len() == self.metas.len()
&& scratch.seen.len() == self.spans.len()
}
pub fn for_each_match(
&self,
span: &[u8],
scratch: &mut SignatureScratch,
mut f: impl FnMut(SignatureMatch),
) {
if !self.fits(scratch) {
*scratch = self.scratch();
}
scratch.ready.clear();
scratch.anchored.clear();
scratch.hits.clear();
let epoch = scratch.next_epoch();
let span_epoch = scratch.next_span_epoch();
let mut reach = self.free_reach;
let mut literals = self.free_literals;
if let Some(&first) = span.first() {
for (literal, sig, folded) in &self.anchors[usize::from(first)] {
let i = *sig as usize;
let live = &mut scratch.live[i];
if live.epoch == epoch || !starts_with(span, literal, *folded) {
continue;
}
*live = Live {
epoch,
..Live::default()
};
scratch.anchored.push(*sig);
literals += self.sigs[i].searched_len();
let m = &self.metas[i];
let k = usize::from(m.folded);
reach[k] = reach[k].max(m.reach);
}
}
let direct = literals <= DIRECT_LITERALS && !self.every_hit;
if direct {
for &sig in scratch.anchored.iter().chain(&self.free) {
let i = sig as usize;
if let Some(at) = self.sigs[i].searched(span) {
scratch.trigger[i] = at;
scratch.ready.push(sig);
}
}
} else {
for &sig in &scratch.anchored {
if self.metas[sig as usize].need == 0 {
scratch.ready.push(sig);
}
}
let bases = [0, self.folded_base];
for (k, ac) in self.automata.iter().enumerate() {
let Some(ac) = ac else { continue };
if reach[k] == 0 {
continue;
}
let head = &span[..span.len().min(reach[k])];
for hit in ac.find_overlapping_iter(head) {
let id = bases[k] + hit.pattern().as_usize();
let hit = (id, hit.start(), hit.end());
self.visit::<false>(span, 0, hit, (epoch, span_epoch), scratch);
}
}
}
scratch.ready.sort_unstable();
prepare_hits(&mut scratch.hits);
let mut hits = 0;
for &sig in &scratch.ready {
let i = sig as usize;
let m = &self.metas[i];
if m.every_hit {
report_hits(&scratch.hits, &mut hits, sig, &mut f);
continue;
}
let at = if direct || m.has_any_of {
Some(scratch.trigger[i])
} else {
m.verify.is_none_or(|v| v(span, 0)).then_some(0)
};
if let Some(at) = at {
f(SignatureMatch {
index: i,
at,
span: 0,
});
}
}
scratch.ready.clear();
scratch.anchored.clear();
scratch.hits.clear();
}
pub fn for_each_match_spans(
&self,
spans: &[&[u8]],
scratch: &mut SignatureScratch,
mut f: impl FnMut(SignatureMatch),
) {
if let [span] = spans {
return self.for_each_match(span, scratch, f);
}
if !self.fits(scratch) {
*scratch = self.scratch();
}
scratch.ready.clear();
scratch.hits.clear();
let epoch = scratch.next_epoch();
let bases = [0, self.folded_base];
for (s, span) in spans.iter().enumerate() {
let span_epoch = scratch.next_span_epoch();
let mut reach = self.free_reach;
if let Some(&first) = span.first() {
for (literal, sig, folded) in &self.anchors[usize::from(first)] {
let i = *sig as usize;
let marks = &mut scratch.marks[i];
if marks.anchored == span_epoch || !starts_with(span, literal, *folded) {
continue;
}
marks.anchored = span_epoch;
let m = &self.metas[i];
let k = usize::from(m.folded);
reach[k] = reach[k].max(m.reach);
let live = &mut scratch.live[i];
if live.epoch != epoch {
*live = Live {
epoch,
..Live::default()
};
scratch.all[i] = 0;
if m.need == 0 {
scratch.ready.push(*sig);
}
}
}
}
for (k, ac) in self.automata.iter().enumerate() {
let Some(ac) = ac else { continue };
if reach[k] == 0 {
continue;
}
let head = &span[..span.len().min(reach[k])];
for hit in ac.find_overlapping_iter(head) {
let id = bases[k] + hit.pattern().as_usize();
let hit = (id, hit.start(), hit.end());
self.visit::<true>(span, s, hit, (epoch, span_epoch), scratch);
}
}
}
scratch.ready.sort_unstable();
prepare_hits(&mut scratch.hits);
let mut hits = 0;
for &sig in &scratch.ready {
let i = sig as usize;
let m = &self.metas[i];
if m.every_hit {
report_hits(&scratch.hits, &mut hits, sig, &mut f);
continue;
}
let fired = if m.has_any_of {
Some((scratch.trigger_span[i], scratch.trigger[i]))
} else {
let sig = &self.sigs[i];
spans
.iter()
.position(|span| {
(sig.anchored.is_empty()
|| sig.anchored.iter().any(|a| starts_with(span, a, m.folded)))
&& m.verify.is_none_or(|v| v(span, 0))
})
.map(|s| (s, 0))
};
if let Some((span, at)) = fired {
f(SignatureMatch { index: i, at, span });
}
}
scratch.ready.clear();
scratch.hits.clear();
}
fn visit<const POOLED: bool>(
&self,
span: &[u8],
s: usize,
(id, start, end): (usize, usize, usize),
(epoch, span_epoch): (u32, u32),
scratch: &mut SignatureScratch,
) {
let run = self.spans[id];
let from = if scratch.seen[id] == span_epoch {
run.every
} else {
scratch.seen[id] = span_epoch;
run.start
};
for (k, u) in self.uses[from..run.end].iter().enumerate() {
let i = u.sig as usize;
if u.bounded && end > self.metas[i].within {
continue;
}
if POOLED && u.anchored && scratch.marks[i].anchored != span_epoch {
continue;
}
let live = &mut scratch.live[i];
if live.epoch != epoch {
if u.anchored {
continue;
}
*live = Live {
epoch,
..Live::default()
};
if POOLED {
scratch.all[i] = 0;
}
}
if u.slot == ANY_OF {
let m = &self.metas[i];
if live.triggered && !m.every_hit {
continue;
}
if from + k >= run.every {
let refused = if POOLED {
let marks = &mut scratch.marks[i];
if marks.verified != span_epoch {
marks.verified = span_epoch;
marks.refused = 0;
}
&mut marks.refused
} else {
&mut live.refused
};
let asks = m.verify_cap.is_none_or(|cap| *refused < cap);
if asks && !m.verify.is_none_or(|v| v(span, start)) {
*refused = refused.saturating_add(1);
continue;
}
}
if m.every_hit {
scratch.hits.push((u.sig, s, start));
if live.triggered {
continue;
}
}
live.triggered = true;
scratch.trigger[i] = start;
if POOLED {
scratch.trigger_span[i] = s;
}
} else if POOLED {
let bit = 1_u64 << u.slot;
if scratch.all[i] & bit != 0 {
continue;
}
scratch.all[i] |= bit;
}
live.met += 1;
if live.met == u.need {
scratch.ready.push(u.sig);
}
}
}
fn keep_best(&self, best: &mut Option<SignatureMatch>, m: SignatureMatch) {
let key = |m: SignatureMatch| {
(
self.metas[m.index].specificity,
self.metas[m.index].priority,
)
};
if best.is_none_or(|b| key(m) > key(b)) {
*best = Some(m);
}
}
#[must_use]
pub fn best(&self, span: &[u8], scratch: &mut SignatureScratch) -> Option<SignatureMatch> {
let mut best: Option<SignatureMatch> = None;
self.for_each_match(span, scratch, |m| self.keep_best(&mut best, m));
best
}
#[must_use]
pub fn best_spans(
&self,
spans: &[&[u8]],
scratch: &mut SignatureScratch,
) -> Option<SignatureMatch> {
let mut best: Option<SignatureMatch> = None;
self.for_each_match_spans(spans, scratch, |m| self.keep_best(&mut best, m));
best
}
}
fn prepare_hits(hits: &mut Vec<(u32, usize, usize)>) {
hits.sort_unstable();
hits.dedup();
}
fn report_hits(
hits: &[(u32, usize, usize)],
next: &mut usize,
sig: u32,
f: &mut impl FnMut(SignatureMatch),
) {
*next += hits[*next..].partition_point(|h| h.0 < sig);
for &(_, span, at) in hits[*next..].iter().take_while(|h| h.0 == sig) {
*next += 1;
f(SignatureMatch {
index: sig as usize,
at,
span,
});
}
}
#[cfg(test)]
mod tests;