use fancy_regex::{Captures, Regex, RegexBuilder};
use super::Capture;
#[cfg(feature = "parse-backtracking")]
use super::Expanded;
use crate::parse::{FieldSink, ParseError};
#[cfg(test)]
thread_local! {
pub(super) static SEARCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(feature = "parse-backtracking")]
pub(super) struct Backtracking {
patterns: Vec<Pattern>,
}
pub(super) struct Pattern {
index: usize,
regex: Regex,
groups: Vec<Option<Capture>>,
}
pub(super) struct Hit<'p, 'a> {
pub(super) start: usize,
pub(super) index: usize,
captures: Captures<'a, [u8]>,
groups: &'p [Option<Capture>],
}
impl Pattern {
pub(super) fn new(
index: usize,
regex: &str,
captures: &[Capture],
limit: usize,
) -> Result<Self, Box<fancy_regex::Error>> {
let regex = RegexBuilder::new(regex)
.backtrack_limit(limit)
.build()
.map_err(Box::new)?;
let groups = regex
.capture_names()
.map(|name| {
let i: usize = name?.strip_prefix('g')?.parse().ok()?;
captures.get(i).cloned()
})
.collect();
Ok(Self {
index,
regex,
groups,
})
}
pub(super) fn search_from<'p, 'a>(
&'p self,
input: &'a [u8],
from: usize,
) -> Result<Option<Hit<'p, 'a>>, ParseError> {
#[cfg(test)]
SEARCHES.with(|n| n.set(n.get() + 1));
let found = self
.regex
.captures_from_pos(input, from)
.map_err(|_| ParseError::Limit {
what: "the backtracking budget",
})?;
Ok(found.map(|captures| Hit {
start: captures.get(0).map_or(from, |m| m.start()),
index: self.index,
captures,
groups: &self.groups,
}))
}
}
#[cfg(feature = "parse-backtracking")]
impl Backtracking {
pub(super) fn new(
slow: &[usize],
rendered: &[Option<Expanded>],
limit: usize,
) -> Result<Option<Self>, Box<fancy_regex::Error>> {
let patterns = slow
.iter()
.filter_map(|&i| Some((i, rendered.get(i)?.as_ref()?)))
.map(|(i, e)| Pattern::new(i, &e.regex, &e.captures, limit))
.collect::<Result<Vec<Pattern>, Box<fancy_regex::Error>>>()?;
Ok((!patterns.is_empty()).then_some(Self { patterns }))
}
pub(super) fn holds(&self, index: usize) -> bool {
self.patterns.iter().any(|p| p.index == index)
}
pub(super) fn search<'p, 'a>(
&'p self,
input: &'a [u8],
rival: Option<(usize, usize)>,
) -> Result<Option<Hit<'p, 'a>>, ParseError> {
let mut best: Option<Hit<'p, 'a>> = None;
for p in &self.patterns {
let bound = best.as_ref().map(|b| (b.start, b.index)).or(rival);
if bound.is_some_and(|(start, index)| start == 0 && index < p.index) {
continue;
}
let Some(hit) = p.search_from(input, 0)? else {
continue;
};
if bound.is_none_or(|first| (hit.start, hit.index) < first) {
best = Some(hit);
}
}
Ok(best)
}
}
impl<'a> Hit<'_, 'a> {
pub(super) fn write(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>) {
for (i, capture) in self.groups.iter().enumerate() {
if let (Some(c), Some(m)) = (capture, self.captures.get(i))
&& let Some(v) = c.value(&input[m.range()])
{
out.field(&c.field, v);
}
}
}
}