use aho_corasick::AhoCorasick;
use regex_automata::util::captures::GroupInfo;
use regex_automata::util::iter::Searcher;
use regex_automata::util::primitives::PatternID;
use regex_automata::{Input, meta};
use super::Match;
use super::dialect::final_terminator;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Anchor {
Anywhere,
AtStart,
AtEnd,
Exact,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct SmallByteSet {
bytes: [u8; 3],
n: u8,
}
impl SmallByteSet {
pub(super) fn new(src: &[u8]) -> Option<Self> {
let n = match src.len() {
1 => 1,
2 => 2,
3 => 3,
_ => return None,
};
let mut bytes = [0_u8; 3];
bytes[..src.len()].copy_from_slice(src);
Some(Self { bytes, n })
}
#[inline]
pub(super) fn contains_any_in(self, hay: &[u8]) -> Option<usize> {
match self.n {
1 => memchr::memchr(self.bytes[0], hay),
2 => memchr::memchr2(self.bytes[0], self.bytes[1], hay),
3 => memchr::memchr3(self.bytes[0], self.bytes[1], self.bytes[2], hay),
_ => None,
}
}
#[inline]
pub(super) const fn n(self) -> u8 {
self.n
}
#[inline]
pub(super) const fn byte(self, i: usize) -> u8 {
self.bytes[i]
}
}
#[derive(Debug, Clone)]
pub(super) enum ShapeOp {
ContainsByte(u8),
ByteSet(SmallByteSet),
Contains(Box<memchr::memmem::Finder<'static>>),
StartsWith(Box<[u8]>),
EndsWith(Box<[u8]>),
ExactMatch(Box<[u8]>),
}
pub(super) enum Plan {
LiteralOnly {
ac: Box<AhoCorasick>,
anchor: Anchor,
literals: Box<[Box<[u8]>]>,
case_insensitive: bool,
},
Shape(ShapeOp),
Meta(Box<meta::Regex>),
#[cfg(feature = "strmatch-backtracking")]
Backtrack(Box<fancy_regex::Regex>),
LineEnd(Box<LineEnd>),
}
pub(super) struct LineEnd {
pub(super) inner: Plan,
pub(super) java: JavaEnd,
}
pub(super) enum JavaEnd {
Literals {
literals: Box<[Box<[u8]>]>,
case_insensitive: bool,
exact: bool,
},
Regex {
find: meta::Regex,
groups: Option<meta::Regex>,
layout: GroupInfo,
},
}
impl Plan {
#[inline]
pub(super) fn is_match(&self, hay: &[u8]) -> bool {
match self {
Self::LiteralOnly {
ac,
anchor,
literals,
case_insensitive,
} => match_set_is(ac, *anchor, literals, *case_insensitive, hay),
Self::Shape(op) => match_shape_is(op, hay),
Self::Meta(r) => r.is_match(hay),
#[cfg(feature = "strmatch-backtracking")]
Self::Backtrack(r) => r.is_match(hay).unwrap_or(false),
Self::LineEnd(le) => le.is_match(hay),
}
}
#[inline]
pub(super) fn find(&self, hay: &[u8]) -> Option<Match> {
match self {
Self::LiteralOnly {
ac,
anchor,
literals,
case_insensitive,
} => match_set_find(ac, *anchor, literals, *case_insensitive, hay),
Self::Shape(op) => match_shape_find(op, hay),
Self::Meta(r) => r.find(hay).map(|m| Match {
start: m.start(),
end: m.end(),
}),
#[cfg(feature = "strmatch-backtracking")]
Self::Backtrack(r) => r.find(hay).ok().flatten().map(|m| Match {
start: m.start(),
end: m.end(),
}),
Self::LineEnd(le) => {
final_terminator(hay).map_or_else(|| le.inner.find(hay), |t| le.find_at(hay, t, 0))
}
}
}
pub(super) fn find_from(&self, hay: &[u8], from: usize) -> Result<Option<Match>, Limit> {
if from > hay.len() {
return Ok(None);
}
let found = match self {
Self::LiteralOnly {
ac,
anchor,
literals,
case_insensitive,
} => match anchor {
Anchor::Anywhere => ac
.find(aho_corasick::Input::new(hay).span(from..hay.len()))
.map(|m| Match {
start: m.start(),
end: m.end(),
}),
Anchor::AtStart => (from == 0)
.then(|| match_set_find(ac, *anchor, literals, *case_insensitive, hay))
.flatten(),
Anchor::AtEnd | Anchor::Exact => {
match_set_end(literals, *case_insensitive, *anchor, hay, from)
}
},
Self::Shape(op) => match op {
ShapeOp::StartsWith(_) | ShapeOp::ExactMatch(_) if from > 0 => None,
ShapeOp::StartsWith(_) | ShapeOp::ExactMatch(_) | ShapeOp::EndsWith(_) => {
match_shape_find(op, hay).filter(|m| m.start >= from)
}
ShapeOp::ContainsByte(_) | ShapeOp::ByteSet(_) | ShapeOp::Contains(_) => {
match_shape_find(op, &hay[from..]).map(|m| Match {
start: m.start + from,
end: m.end + from,
})
}
},
Self::Meta(r) => r
.search(&Input::new(hay).span(from..hay.len()))
.map(|m| Match {
start: m.start(),
end: m.end(),
}),
#[cfg(feature = "strmatch-backtracking")]
Self::Backtrack(r) => r
.find_from_pos(hay, from)
.map_err(|_| Limit)?
.map(|m| Match {
start: m.start(),
end: m.end(),
}),
Self::LineEnd(le) => match final_terminator(hay) {
None => le.inner.find_from(hay, from)?,
Some(t) => le.find_at(hay, t, from),
},
};
Ok(found)
}
pub(super) fn for_each_match_java(&self, hay: &[u8], mut f: impl FnMut(Match) -> bool) -> bool {
let mut at = 0;
while at <= hay.len() {
let Ok(found) = self.find_from(hay, at) else {
return false;
};
let Some(m) = found else { break };
if !f(m) {
break;
}
at = resume(hay, m);
}
true
}
pub(super) fn for_each_match(&self, hay: &[u8], mut f: impl FnMut(Match) -> bool) -> bool {
match self {
Self::LiteralOnly {
ac,
anchor,
literals,
case_insensitive,
} => {
if *anchor == Anchor::Anywhere {
each_set(ac, hay, &mut f);
} else if let Some(m) =
match_set_find(ac, *anchor, literals, *case_insensitive, hay)
{
f(m);
}
}
Self::Shape(op) => each_shape(op, hay, &mut f),
Self::Meta(r) => {
for m in r.find_iter(hay) {
if !f(Match {
start: m.start(),
end: m.end(),
}) {
break;
}
}
}
#[cfg(feature = "strmatch-backtracking")]
Self::Backtrack(r) => {
for m in r.find_iter(hay) {
let Ok(m) = m else { return false };
if !f(Match {
start: m.start(),
end: m.end(),
}) {
break;
}
}
}
Self::LineEnd(le) => match final_terminator(hay) {
None => return le.inner.for_each_match(hay, f),
Some(t) => le.each_at(hay, t, &mut f),
},
}
true
}
pub(super) fn merge_literals(&self) -> Option<(Vec<Vec<u8>>, bool)> {
match self {
Self::LiteralOnly {
anchor: Anchor::Anywhere,
literals,
case_insensitive,
..
} => Some((
literals.iter().map(|l| l.to_vec()).collect(),
*case_insensitive,
)),
Self::Shape(ShapeOp::ContainsByte(b)) => Some((vec![vec![*b]], false)),
Self::Shape(ShapeOp::ByteSet(s)) => {
let n = s.n() as usize;
Some(((0..n).map(|i| vec![s.byte(i)]).collect(), false))
}
Self::Shape(ShapeOp::Contains(f)) => Some((vec![f.needle().to_vec()], false)),
Self::LiteralOnly { .. } | Self::Shape(_) | Self::Meta(_) | Self::LineEnd(_) => None,
#[cfg(feature = "strmatch-backtracking")]
Self::Backtrack(_) => None,
}
}
pub(super) fn end_literals(&self) -> Option<(Box<[Box<[u8]>]>, bool, bool)> {
match self {
Self::Shape(ShapeOp::EndsWith(lit)) => Some((Box::new([lit.clone()]), false, false)),
Self::Shape(ShapeOp::ExactMatch(lit)) => Some((Box::new([lit.clone()]), false, true)),
Self::LiteralOnly {
anchor: anchor @ (Anchor::AtEnd | Anchor::Exact),
literals,
case_insensitive,
..
} => Some((
literals.clone(),
*case_insensitive,
*anchor == Anchor::Exact,
)),
_ => None,
}
}
pub(super) fn layout(&self) -> Option<&GroupInfo> {
match self {
Self::LineEnd(le) => match &le.java {
JavaEnd::Regex { layout, .. } => Some(layout),
JavaEnd::Literals { .. } => None,
},
_ => None,
}
}
}
impl LineEnd {
fn is_match(&self, hay: &[u8]) -> bool {
match (final_terminator(hay), &self.java) {
(None, _) => self.inner.is_match(hay),
(Some(_), JavaEnd::Regex { find, .. }) => find.is_match(hay),
(Some(t), JavaEnd::Literals { .. }) => self.find_at(hay, t, 0).is_some(),
}
}
pub(super) fn find_at(&self, hay: &[u8], t: usize, from: usize) -> Option<Match> {
match &self.java {
JavaEnd::Literals {
literals,
case_insensitive,
exact,
} => end_literal(literals, *case_insensitive, *exact, hay, t, from),
JavaEnd::Regex { find, .. } => {
let mut slots = [None; 4];
find.search_slots(&Input::new(hay).span(from..hay.len()), &mut slots)?;
let [Some(start), Some(end), marker, _] = slots else {
return None;
};
Some(Match {
start: start.get(),
end: marker.unwrap_or(end).get(),
})
}
}
}
pub(super) fn each_at(&self, hay: &[u8], t: usize, f: &mut impl FnMut(Match) -> bool) {
let mut it = Searcher::new(Input::new(hay));
while let Some(m) = it.advance(|input| {
Ok(self
.find_at(hay, t, input.start())
.map(|m| regex_automata::Match::new(PatternID::ZERO, m.start..m.end)))
}) {
if !f(Match {
start: m.start(),
end: m.end(),
}) {
break;
}
}
}
}
pub(super) struct Limit;
pub(super) fn resume(hay: &[u8], m: Match) -> usize {
if m.start < m.end {
return m.end;
}
let tail = match hay.get(m.end) {
Some(0xC2..=0xDF) => 1,
Some(0xE0..=0xEF) => 2,
Some(0xF0..=0xF4) => 3,
_ => 0,
};
let rest = hay.get(m.end + 1..).unwrap_or_default();
let tail = rest
.iter()
.take(tail)
.take_while(|b| (0x80..=0xBF).contains(*b))
.count();
m.end + 1 + tail
}
fn end_literal(
literals: &[Box<[u8]>],
case_insensitive: bool,
exact: bool,
hay: &[u8],
t: usize,
from: usize,
) -> Option<Match> {
literals
.iter()
.enumerate()
.flat_map(|(i, lit)| [t, hay.len()].map(|end| (i, lit, end)))
.filter_map(|(i, lit, end)| {
let start = end.checked_sub(lit.len())?;
let tail = &hay[start..end];
let hit = if case_insensitive {
tail.eq_ignore_ascii_case(lit)
} else {
tail == lit.as_ref()
};
(hit && start >= from && (!exact || start == 0)).then_some((start, i, end))
})
.min()
.map(|(start, _, end)| Match { start, end })
}
#[inline]
fn match_set_is(
ac: &AhoCorasick,
anchor: Anchor,
literals: &[Box<[u8]>],
case_insensitive: bool,
hay: &[u8],
) -> bool {
match anchor {
Anchor::Anywhere => ac.find(hay).is_some(),
Anchor::AtStart => ac.find(hay).is_some_and(|m| m.start() == 0),
Anchor::AtEnd | Anchor::Exact => {
match_set_end(literals, case_insensitive, anchor, hay, 0).is_some()
}
}
}
#[inline]
fn match_set_find(
ac: &AhoCorasick,
anchor: Anchor,
literals: &[Box<[u8]>],
case_insensitive: bool,
hay: &[u8],
) -> Option<Match> {
match anchor {
Anchor::Anywhere => ac.find(hay).map(|m| Match {
start: m.start(),
end: m.end(),
}),
Anchor::AtStart => ac.find(hay).filter(|m| m.start() == 0).map(|m| Match {
start: m.start(),
end: m.end(),
}),
Anchor::AtEnd | Anchor::Exact => match_set_end(literals, case_insensitive, anchor, hay, 0),
}
}
fn match_set_end(
literals: &[Box<[u8]>],
case_insensitive: bool,
anchor: Anchor,
hay: &[u8],
from: usize,
) -> Option<Match> {
let room = hay.len().checked_sub(from)?;
let longest = literals
.iter()
.filter(|l| {
if anchor == Anchor::Exact {
l.len() == hay.len() && from == 0
} else {
l.len() <= room
}
})
.filter(|l| {
let tail = &hay[hay.len() - l.len()..];
if case_insensitive {
tail.eq_ignore_ascii_case(l)
} else {
tail == l.as_ref()
}
})
.map(|l| l.len())
.max()?;
Some(Match {
start: hay.len() - longest,
end: hay.len(),
})
}
#[inline]
fn match_shape_is(op: &ShapeOp, hay: &[u8]) -> bool {
match op {
ShapeOp::ContainsByte(b) => memchr::memchr(*b, hay).is_some(),
ShapeOp::ByteSet(s) => s.contains_any_in(hay).is_some(),
ShapeOp::Contains(f) => f.find(hay).is_some(),
ShapeOp::StartsWith(lit) => hay.starts_with(lit),
ShapeOp::EndsWith(lit) => hay.ends_with(lit),
ShapeOp::ExactMatch(lit) => hay == lit.as_ref(),
}
}
#[inline]
fn match_shape_find(op: &ShapeOp, hay: &[u8]) -> Option<Match> {
match op {
ShapeOp::ContainsByte(b) => memchr::memchr(*b, hay).map(|i| Match {
start: i,
end: i + 1,
}),
ShapeOp::ByteSet(s) => s.contains_any_in(hay).map(|i| Match {
start: i,
end: i + 1,
}),
ShapeOp::Contains(f) => f.find(hay).map(|i| Match {
start: i,
end: i + f.needle().len(),
}),
ShapeOp::StartsWith(lit) => hay.starts_with(lit).then_some(Match {
start: 0,
end: lit.len(),
}),
ShapeOp::EndsWith(lit) => hay.ends_with(lit).then(|| Match {
start: hay.len() - lit.len(),
end: hay.len(),
}),
ShapeOp::ExactMatch(lit) => (hay == lit.as_ref()).then_some(Match {
start: 0,
end: hay.len(),
}),
}
}
fn each_set(ac: &AhoCorasick, hay: &[u8], f: &mut impl FnMut(Match) -> bool) {
for m in ac.find_iter(hay) {
if !f(Match {
start: m.start(),
end: m.end(),
}) {
break;
}
}
}
fn each_byte(hits: impl Iterator<Item = usize>, f: &mut impl FnMut(Match) -> bool) {
for i in hits {
if !f(Match {
start: i,
end: i + 1,
}) {
break;
}
}
}
fn each_shape(op: &ShapeOp, hay: &[u8], f: &mut impl FnMut(Match) -> bool) {
match op {
ShapeOp::ContainsByte(b) => each_byte(memchr::memchr_iter(*b, hay), f),
ShapeOp::ByteSet(s) => match s.n() {
1 => each_byte(memchr::memchr_iter(s.byte(0), hay), f),
2 => each_byte(memchr::memchr2_iter(s.byte(0), s.byte(1), hay), f),
3 => each_byte(
memchr::memchr3_iter(s.byte(0), s.byte(1), s.byte(2), hay),
f,
),
_ => {}
},
ShapeOp::Contains(finder) => {
for i in finder.find_iter(hay) {
if !f(Match {
start: i,
end: i + finder.needle().len(),
}) {
break;
}
}
}
ShapeOp::StartsWith(_) | ShapeOp::EndsWith(_) | ShapeOp::ExactMatch(_) => {
if let Some(m) = match_shape_find(op, hay) {
f(m);
}
}
}
}