git_editor/utils/
sanitize.rs1use std::borrow::Cow;
8
9pub fn safe(text: &str) -> Cow<'_, str> {
11 if !text.chars().any(is_unsafe) {
12 return Cow::Borrowed(text);
13 }
14 let mut out = String::with_capacity(text.len() + 8);
15 for c in text.chars() {
16 if is_unsafe(c) {
17 out.extend(c.escape_default());
18 } else {
19 out.push(c);
20 }
21 }
22 Cow::Owned(out)
23}
24
25fn is_unsafe(c: char) -> bool {
26 c.is_control() && c != '\n' && c != '\t'
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn escapes_terminal_sequences() {
35 assert_eq!(safe("a\u{1b}]0;title\u{7}b"), "a\\u{1b}]0;title\\u{7}b");
36 assert_eq!(safe("red\u{1b}[31m"), "red\\u{1b}[31m");
37 assert_eq!(safe("del\u{7f}"), "del\\u{7f}");
38 }
39
40 #[test]
41 fn leaves_normal_text_alone() {
42 assert!(matches!(safe("张三 <a@b.c>\tok\n"), Cow::Borrowed(_)));
43 }
44}