1use alloc::string::String;
4
5pub fn escape_like_literal(input: &str) -> String {
8 let mut out = String::with_capacity(input.len());
9 for c in input.chars() {
10 if matches!(c, '\\' | '%' | '_') {
11 out.push('\\');
12 }
13 out.push(c);
14 }
15 out
16}
17
18#[cfg(test)]
19mod tests {
20 use super::escape_like_literal;
21
22 #[test]
23 fn escapes_only_like_wildcards_and_the_escape_character() {
24 for (input, expected) in [
25 ("", ""),
26 ("plain text", "plain text"),
27 ("%", "\\%"),
28 ("_", "\\_"),
29 ("\\", "\\\\"),
30 ("name%_\\tail", "name\\%\\_\\\\tail"),
31 ("中文_é%\\", "中文\\_é\\%\\\\"),
32 ("quote' and \"double\"", "quote' and \"double\""),
33 ] {
34 assert_eq!(escape_like_literal(input), expected, "input={input:?}");
35 }
36 }
37}