fn escape(string: &str) -> Cow<str> {
lazy_static! {
static ref RE_BACKSLASH: Regex = Regex::new(r#"\\"#).unwrap();
static ref RE_QUOTE: Regex = Regex::new(r#"""#).unwrap();
}
let string1 = RE_BACKSLASH.replace_all(&string, r#"\\"#);
let string2 = RE_QUOTE.replace_all(&string, r#"\""#);
string2
}
I understand that this won't compile, since it will return a reference to the stack in case of string1
being Cow::Owned
. However, is there any way to make this work, so that no copying will happen if there is nothing to replace?
I did found a semi-solution:
fn escape(string: &str) -> Cow<str> {
lazy_static! {
static ref RE_BACKSLASH: Regex = Regex::new(r#"\\"#).unwrap();
static ref RE_QUOTE: Regex = Regex::new(r#"""#).unwrap();
}
let string = RE_BACKSLASH.replace_all(&string, r#"\\"#);
let string = match string {
Cow::Borrowed(borrowed) => RE_QUOTE.replace_all(borrowed, r#"\""#),
Cow::Owned(owned) => RE_QUOTE.replace_all(&owned, r#"\""#).into_owned().into()
};
string
}
However, this would be very verbose to write if there are more replacements.