1use fancy_regex::Regex;
2use std::sync::LazyLock;
3
4static NEEDS_QUOTING_REGEX: LazyLock<Regex> = LazyLock::new(|| {
10 Regex::new(r#"[\[\]:`\{\}#'";\(\)\|\$,\.\d\s!?=]|(?i)^[+\-]?(inf(inity)?|nan)$"#)
11 .expect("internal error: NEEDS_QUOTING_REGEX didn't compile")
12});
13
14pub fn needs_quoting(string: &str) -> bool {
15 if string.is_empty() {
16 return true;
17 }
18 match string {
20 "true" | "false" | "null" | "&&" => return true,
24 _ => (),
25 };
26 NEEDS_QUOTING_REGEX.is_match(string).unwrap_or(false)
28}
29
30pub fn escape_quote_string(string: &str) -> String {
31 let mut output = String::with_capacity(string.len() + 2);
32 output.push('"');
33
34 for c in string.chars() {
35 if c == '"' || c == '\\' {
36 output.push('\\');
37 }
38 output.push(c);
39 }
40
41 output.push('"');
42 output
43}