use crate::value::Wtf8;
pub(crate) struct Substitution<'a> {
pub input: &'a [u16],
pub position: usize,
pub match_len: usize,
pub matched: &'a [u16],
pub captures: &'a [Option<Vec<u16>>],
pub names: Option<&'a [(String, Vec<u16>)]>,
}
pub(crate) fn get_substitution(out: &mut Vec<u16>, template: &Wtf8, sub: &Substitution<'_>) {
const DOLLAR: u16 = b'$' as u16;
const AMP: u16 = b'&' as u16;
const BACKTICK: u16 = b'`' as u16;
const QUOTE: u16 = b'\'' as u16;
const OPEN: u16 = b'<' as u16;
const CLOSE: u16 = b'>' as u16;
const ZERO: u16 = b'0' as u16;
const NINE: u16 = b'9' as u16;
let points = template.to_units();
let group_count = sub.captures.len().saturating_sub(1);
let end_of_match = sub.position + sub.match_len;
let mut at = 0usize;
let mut occurrence = 0usize;
while at < points.len() {
if points[at] != DOLLAR {
out.push(points[at]);
at += 1;
continue;
}
let Some(next) = points.get(at + 1).copied() else {
out.push(DOLLAR);
break;
};
match next {
v if v == DOLLAR => {
out.push(DOLLAR);
at += 2;
}
v if v == AMP => {
out.extend_from_slice(sub.matched);
at += 2;
}
v if v == BACKTICK => {
out.extend_from_slice(sub.input.get(..sub.position).unwrap_or_default());
at += 2;
}
v if v == QUOTE => {
out.extend_from_slice(sub.input.get(end_of_match..).unwrap_or_default());
at += 2;
}
v if (ZERO..=NINE).contains(&v) => {
let first = usize::from(v - ZERO);
let second = points
.get(at + 2)
.copied()
.filter(|digit| (ZERO..=NINE).contains(digit))
.map(|digit| usize::from(digit - ZERO));
let (group, digits) = match second {
Some(second) if first * 10 + second <= group_count => (first * 10 + second, 2),
_ => (first, 1),
};
if group >= 1 && group <= group_count {
if let Some(Some(units)) = sub.captures.get(group) {
out.extend_from_slice(units);
}
at += 1 + digits;
} else {
out.push(DOLLAR);
at += 1;
}
}
v if v == OPEN => {
let close = sub.names.and_then(|_| {
points[at + 2..]
.iter()
.position(|&unit| unit == CLOSE)
.map(|offset| at + 2 + offset)
});
let Some(close) = close else {
out.push(DOLLAR);
at += 1;
continue;
};
if let Some((_, units)) = sub.names.and_then(|names| names.get(occurrence)) {
out.extend_from_slice(units);
}
occurrence += 1;
at = close + 1;
}
_ => {
out.push(DOLLAR);
at += 1;
}
}
}
}
pub(crate) fn template_group_names(template: &Wtf8) -> Vec<String> {
const DOLLAR: u16 = b'$' as u16;
const OPEN: u16 = b'<' as u16;
const CLOSE: u16 = b'>' as u16;
let units = template.to_units();
let mut names = Vec::new();
let mut at = 0usize;
while at < units.len() {
if units[at] != DOLLAR {
at += 1;
continue;
}
let Some(next) = units.get(at + 1).copied() else {
break;
};
if next == DOLLAR {
at += 2;
continue;
}
if next != OPEN {
at += 1;
continue;
}
let Some(offset) = units[at + 2..].iter().position(|&unit| unit == CLOSE) else {
at += 1;
continue;
};
let close = at + 2 + offset;
if let Some(name) = Wtf8::from_units(&units[at + 2..close]).as_str() {
names.push(name.to_string());
}
at = close + 1;
}
names
}