Skip to content

Commit

Permalink
refactor(snap): Simplify the applying of substitutions
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Apr 19, 2024
1 parent 06d6a0f commit 06236b8
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions crates/snapbox/src/substitutions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,30 +84,42 @@ impl Substitutions {
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) -> String {

Check failure

Code scanning / clippy

the following explicit lifetimes could be elided: 'v Error

the following explicit lifetimes could be elided: 'v

Check failure

Code scanning / clippy

the following explicit lifetimes could be elided: 'v Error

the following explicit lifetimes could be elided: 'v
let mut input = input.to_owned();
replace_many(
&mut input,
self.vars.iter().flat_map(|(var, replaces)| {
replaces.iter().map(|replace| (*var, replace.as_ref()))
}),
);
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_key(key: &'static str) -> Result<&'static str, crate::Error> {
if !key.starts_with('[') || !key.ends_with(']') {
return Err(format!("Key `{}` is not enclosed in []", key).into());
Expand Down

0 comments on commit 06236b8

Please sign in to comment.