Skip to main content

ephemeris_documents/json/cst/
quote.rs

1//! Quoted string spellings.
2
3use std::fmt::Write as _;
4
5/// The quote character of a string literal.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub(super) enum Quote {
8    Single,
9    Double,
10}
11
12impl Quote {
13    const fn mark(self) -> char {
14        match self {
15            Self::Single => '\'',
16            Self::Double => '"',
17        }
18    }
19
20    pub(super) fn wrap(self, text: &str) -> String {
21        let quote = self.mark();
22        let mut out = String::from(quote);
23        for character in text.chars() {
24            match character {
25                '\\' => out.push_str("\\\\"),
26                character if character == quote => {
27                    out.push('\\');
28                    out.push(quote);
29                }
30                '\n' => out.push_str("\\n"),
31                '\r' => out.push_str("\\r"),
32                '\t' => out.push_str("\\t"),
33                character if u32::from(character) < 0x20 => {
34                    let _infallible = write!(out, "\\u{:04x}", u32::from(character));
35                }
36                character => out.push(character),
37            }
38        }
39        out.push(quote);
40        out
41    }
42}