use std::borrow::Cow;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct MappingQueue<'a> {
queue: Vec<(&'a str, &'a str)>,
}
impl<'a> MappingQueue<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn push(mut self, from: &'a str, to: &'a str) -> Self {
self.queue.push((from, to));
self
}
pub fn extend<I: Iterator<Item = (&'a str, &'a str)>>(mut self, it: I) -> Self {
self.queue.extend(it);
self
}
pub fn apply(&self, input: &str) -> String {
let mut output = Cow::Borrowed(input);
for (from, to) in self.queue.iter() {
output = Cow::Owned(output.replace(from, to));
}
output.into_owned()
}
}
fn char_slices(s: &str) -> impl Iterator<Item = &str> {
s.char_indices().map(|(i, c)| &s[i..i + c.len_utf8()])
}
pub fn char_mappings<'a>(from: &'a str, to: &'a str) -> impl Iterator<Item = (&'a str, &'a str)> {
assert_eq!(
from.len(),
to.len(),
"There must be as many pattern characters as replacement characters"
);
char_slices(from).zip(char_slices(to))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "There must be as many pattern characters as replacement characters")]
fn char_mappings_unequal_len() {
let _ = char_mappings("", "a");
}
}