#[derive(Default)]
pub(crate) struct AdjacentEmptyFilter {
prev_nonempty_end: Option<usize>,
}
impl AdjacentEmptyFilter {
pub(crate) fn should_suppress(&mut self, start: usize, end: usize) -> bool {
let is_empty = start == end;
if is_empty && self.prev_nonempty_end == Some(start) {
self.prev_nonempty_end = None;
return true;
}
self.prev_nonempty_end = if is_empty { None } else { Some(end) };
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match {
pub start: usize,
pub end: usize,
}
impl Match {
pub fn len(&self) -> usize {
self.end - self.start
}
pub fn is_empty(&self) -> bool {
self.start == self.end
}
pub fn as_str<'a>(&self, text: &'a str) -> &'a str {
&text[self.start..self.end]
}
}
#[derive(Debug, Clone)]
pub struct Captures {
pub full_match: Match,
pub groups: Vec<Option<Match>>,
pub named: std::collections::HashMap<String, Match>,
}
impl Captures {
pub fn get(&self, index: usize) -> Option<&Match> {
if index == 0 {
Some(&self.full_match)
} else {
self.groups.get(index - 1).and_then(|g| g.as_ref())
}
}
pub fn get_named(&self, name: &str) -> Option<&Match> {
self.named.get(name)
}
pub fn as_str<'a>(&self, text: &'a str, index: usize) -> Option<&'a str> {
self.get(index).map(|m| m.as_str(text))
}
pub fn as_str_named<'a>(&self, text: &'a str, name: &str) -> Option<&'a str> {
self.get_named(name).map(|m| m.as_str(text))
}
}
pub fn expand_replacement(caps: &Captures, replacement: &str, text: &str) -> String {
fn push_group(result: &mut String, caps: &Captures, name: &str, text: &str) {
let m = match name.parse::<usize>() {
Ok(idx) => caps.get(idx),
Err(_) => caps.get_named(name),
};
if let Some(m) = m {
result.push_str(m.as_str(text));
}
}
let mut result = String::with_capacity(replacement.len());
let bytes = replacement.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'$' {
let start = i;
while i < bytes.len() && bytes[i] != b'$' {
i += 1;
}
result.push_str(&replacement[start..i]);
continue;
}
if i + 1 >= bytes.len() {
result.push('$');
i += 1;
continue;
}
match bytes[i + 1] {
b'$' => {
result.push('$');
i += 2;
}
b'{' => {
if let Some(close) = replacement[i + 2..].find('}') {
let name = &replacement[i + 2..i + 2 + close];
push_group(&mut result, caps, name, text);
i = i + 2 + close + 1;
} else {
result.push('$');
i += 1;
}
}
c if c.is_ascii_digit() => {
let start = i + 1;
let mut j = start;
while j < bytes.len() && bytes[j].is_ascii_digit() {
j += 1;
}
push_group(&mut result, caps, &replacement[start..j], text);
i = j;
}
c if c == b'_' || c.is_ascii_alphabetic() => {
let start = i + 1;
let mut j = start;
while j < bytes.len() && (bytes[j] == b'_' || bytes[j].is_ascii_alphanumeric()) {
j += 1;
}
push_group(&mut result, caps, &replacement[start..j], text);
i = j;
}
_ => {
result.push('$');
i += 1;
}
}
}
result
}