From a0752073325ac9cb38dab7278a02aac5a41a50b4 Mon Sep 17 00:00:00 2001 From: "orion GONZALEZ (contractor)" Date: Thu, 19 Oct 2023 11:35:35 +0200 Subject: [PATCH] reduce code duplication --- src/replacer.rs | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/replacer.rs b/src/replacer.rs index 8cad1e1..f59a2f9 100644 --- a/src/replacer.rs +++ b/src/replacer.rs @@ -99,32 +99,30 @@ impl Replacer { Ok(()) } + fn generic_replace<'a>( + &self, + content: &'a [u8], + replace: impl Iterator, + ) -> std::borrow::Cow<'a, [u8]> { + let mut content = std::borrow::Cow::Borrowed(content); + for (regex, replace_with) in self.regexes.into_iter().zip(replace) { + content = + regex.replacen(&content, self.max_replacements, replace_with); + } + content + } + pub(crate) fn replace<'a>( &'a self, content: &'a [u8], ) -> std::borrow::Cow<'a, [u8]> { - let mut content = std::borrow::Cow::Borrowed(content); if self.is_literal { - let replace_withs = self.replace_withs.iter().map(|r| regex::bytes::NoExpand(r)); - self.regexes.iter().zip(replace_withs).for_each(|(regex, replace_with)| { - content = regex.replacen( - &content, - self.max_replacements, - replace_with, - ); - }); + let mut rep = + self.replace_withs.iter().map(|r| regex::bytes::NoExpand(r)); + self.generic_replace(content, rep) } else { - for (regex, replace_with) in - self.regexes.iter().zip(&self.replace_withs) - { - content = regex.replacen( - &content, - self.max_replacements, - replace_with, - ); - } + self.generic_replace(content, self.replace_withs.into_iter()) } - content } pub(crate) fn replace_preview<'a>(