Skip to main content

rust_web_server/core/
json.rs

1//! The JSON string escaper every module uses (18.24.0; before, several
2//! modules had their own, some of which left control characters raw).
3
4/// `s` as the inside of a JSON string literal (RFC 8259 §7): quote,
5/// backslash and every control character escaped.
6pub fn escape(s: &str) -> String {
7    let mut out = String::with_capacity(s.len() + 4);
8    for ch in s.chars() {
9        match ch {
10            '"' => out.push_str("\\\""),
11            '\\' => out.push_str("\\\\"),
12            '\n' => out.push_str("\\n"),
13            '\r' => out.push_str("\\r"),
14            '\t' => out.push_str("\\t"),
15            c if (c as u32) < 0x20 => {
16                let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32));
17            }
18            c => out.push(c),
19        }
20    }
21    out
22}
23
24#[cfg(test)]
25mod tests {
26    #[test]
27    fn escapes_quotes_backslashes_and_controls() {
28        assert_eq!(super::escape("a\"b\\c\n\u{1}é"), "a\\\"b\\\\c\\n\\u0001é");
29    }
30}