mangolib/common/format/
strings.rs

1/// Convert a normal string to a double-quoted one that would result in the original
2/// string when parsed by a typical language.
3pub fn to_double_quoted_str(txt: &str) -> String {
4    // todo: performance? mostly I'd like to add the quotes as part of the stream, but it seems difficult
5    let esc: String = txt
6        .chars()
7        .map(|c| match c {
8            '\\' => r"\\".to_string(),
9            '\"' => "\\\"".to_string(),
10            '\n' => "\\n".to_string(),
11            '\0' => panic!("Found null byte in to_double_quoted_str"),
12            c => c.to_string(),
13        })
14        .collect();
15    "\"".to_string() + &esc + "\""
16}
17
18#[cfg(test)]
19mod tests {
20    use super::to_double_quoted_str;
21
22    #[test]
23    fn test_to_double_quoted_str() {
24        assert_eq!("\"hello world\"", to_double_quoted_str("hello world"));
25        assert_eq!("\"hello world\"", to_double_quoted_str("hello world"));
26        assert_eq!("\"hello\\nworld\"", to_double_quoted_str("hello\nworld"));
27        assert_eq!("\"hello\\\\ world\"", to_double_quoted_str("hello\\ world"));
28        assert_eq!("\"hello\\\"world\"", to_double_quoted_str("hello\"world"));
29        assert_eq!("\"\\\"\\\"\\\"\\n\\\\\"", to_double_quoted_str("\"\"\"\n\\"));
30        assert_eq!("\"\\\\n\"", to_double_quoted_str("\\n"));
31        assert_eq!("\"\\\\\\n\"", to_double_quoted_str("\\\n"));
32    }
33}