Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(snap): Simplify the applying of substitutions #314

Merged
merged 1 commit into from
May 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions crates/snapbox/src/filter/redactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,30 +85,42 @@ impl Redactions {
normalize(input, pattern, self)
}

fn substitute<'v>(&self, value: &'v str) -> Cow<'v, str> {
let mut value = Cow::Borrowed(value);
for (var, replace) in self.vars.iter() {
for replace in replace {
debug_assert!(!replace.is_empty());
value = Cow::Owned(value.replace(replace.as_ref(), var));
}
}
value
fn substitute<'v>(&self, input: &'v str) -> Cow<'v, str> {
let mut input = input.to_owned();
replace_many(
&mut input,
self.vars.iter().flat_map(|(var, replaces)| {
replaces.iter().map(|replace| (replace.as_ref(), *var))
}),
);
Cow::Owned(input)
}

fn clear<'v>(&self, pattern: &'v str) -> Cow<'v, str> {
if !self.unused.is_empty() && pattern.contains('[') {
let mut pattern = pattern.to_owned();
for var in self.unused.iter() {
pattern = pattern.replace(var, "");
}
replace_many(&mut pattern, self.unused.iter().map(|var| (*var, "")));
Cow::Owned(pattern)
} else {
Cow::Borrowed(pattern)
}
}
}

fn replace_many<'a>(
buffer: &mut String,
replacements: impl IntoIterator<Item = (&'a str, &'a str)>,
) {
for (var, replace) in replacements {
let mut index = 0;
while let Some(offset) = buffer[index..].find(var) {
let old_range = (index + offset)..(index + offset + var.len());
buffer.replace_range(old_range, replace);
index += offset + replace.len();
}
}
}

fn validate_placeholder(placeholder: &'static str) -> crate::assert::Result<&'static str> {
if !placeholder.starts_with('[') || !placeholder.ends_with(']') {
return Err(format!("Key `{}` is not enclosed in []", placeholder).into());
Expand Down
Loading