chatgpt_functions/
escape_json.rs

1/// Escape a string for JSON.
2///
3/// This is useful to escape the content of a message, for example.
4/// Withouht escaping, the JSON would be invalid and the API would return an error.
5pub trait EscapeJson {
6    fn escape_json(&self) -> String;
7}
8
9impl EscapeJson for str {
10    fn escape_json(&self) -> String {
11        let mut escaped_string = String::new();
12        for c in self.chars() {
13            match c {
14                '\\' => escaped_string.push_str("\\\\"),
15                '\"' => escaped_string.push_str("\\\""),
16                '\n' => escaped_string.push_str("\\n"),
17                '\r' => escaped_string.push_str("\\r"),
18                '\t' => escaped_string.push_str("\\t"),
19                '\x08' => escaped_string.push_str("\\b"),
20                '\x0C' => escaped_string.push_str("\\f"),
21                _ => escaped_string.push(c),
22            }
23        }
24        escaped_string
25    }
26}
27
28impl EscapeJson for String {
29    fn escape_json(&self) -> String {
30        self.as_str().escape_json()
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_escape_json() {
40        assert_eq!("\"".escape_json(), "\\\"");
41        assert_eq!("\\".escape_json(), "\\\\");
42        assert_eq!("\n".escape_json(), "\\n");
43        assert_eq!("\r".escape_json(), "\\r");
44        assert_eq!("\t".escape_json(), "\\t");
45        assert_eq!("\x08".escape_json(), "\\b");
46        assert_eq!("\x0C".escape_json(), "\\f");
47        assert_eq!(
48            "\"\\n\\r\\t\x08\x0C".escape_json(),
49            "\\\"\\\\n\\\\r\\\\t\\b\\f"
50        );
51    }
52
53    #[test]
54    fn test_escape_json_string() {
55        assert_eq!("\"".to_string().escape_json(), "\\\"");
56        assert_eq!("\\".to_string().escape_json(), "\\\\");
57        assert_eq!("\n".to_string().escape_json(), "\\n");
58        assert_eq!("\r".to_string().escape_json(), "\\r");
59        assert_eq!("\t".to_string().escape_json(), "\\t");
60        assert_eq!("\x08".to_string().escape_json(), "\\b");
61        assert_eq!("\x0C".to_string().escape_json(), "\\f");
62        assert_eq!(
63            "\"\\n\\r\\t\x08\x0C".to_string().escape_json(),
64            "\\\"\\\\n\\\\r\\\\t\\b\\f"
65        );
66    }
67
68    #[test]
69    fn test_escape_json_string_with_quotes() {
70        assert_eq!("\"\"\"".to_string().escape_json(), "\\\"\\\"\\\"");
71        assert_eq!(
72            "\"\"\"\"\"".to_string().escape_json(),
73            "\\\"\\\"\\\"\\\"\\\""
74        );
75    }
76
77    #[test]
78    fn test_escape_json_string_with_text() {
79        let text = "text with \"quotes\" and a \nnewline";
80        assert_eq!(
81            text.to_string().escape_json(),
82            "text with \\\"quotes\\\" and a \\nnewline"
83        );
84    }
85}