use crate::value::Wtf8;
pub(crate) struct Substitution<'a> {
pub input: &'a [u16],
pub position: usize,
pub match_len: usize,
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;
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.input
.get(sub.position..end_of_match)
.unwrap_or_default(),
);
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;
};
let name: Option<String> = Wtf8::from_units(&points[at + 2..close])
.as_str()
.map(str::to_string);
let value = name.and_then(|name| {
sub.names
.and_then(|names| names.iter().find(|(n, _)| *n == name))
.map(|(_, units)| units)
});
if let Some(units) = value {
out.extend_from_slice(units);
}
at = close + 1;
}
_ => {
out.push(DOLLAR);
at += 1;
}
}
}
}