use fancy_regex::{Captures, Regex};
use super::Capture;
use crate::parse::{FieldSink, ParseError};
pub(super) struct Backtracking {
patterns: Vec<Pattern>,
}
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 Backtracking {
pub(super) fn new(
patterns: Vec<(usize, &str, &[Capture])>,
) -> Result<Self, Box<fancy_regex::Error>> {
let patterns = patterns
.into_iter()
.map(|(index, regex, captures)| {
let regex = Regex::new(regex).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(Pattern {
index,
regex,
groups,
})
})
.collect::<Result<Vec<Pattern>, Box<fancy_regex::Error>>>()?;
Ok(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],
) -> Result<Option<Hit<'p, 'a>>, ParseError> {
let mut best: Option<Hit<'p, 'a>> = None;
for p in &self.patterns {
let found = p.regex.captures(input).map_err(|_| ParseError::Limit {
what: "the backtracking budget",
})?;
let Some(captures) = found else { continue };
let start = captures.get(0).map_or(0, |m| m.start());
if best.as_ref().is_none_or(|b| start < b.start) {
best = Some(Hit {
start,
index: p.index,
captures,
groups: &p.groups,
});
}
}
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);
}
}
}
}