1use fancy_regex::Regex;
2use std::sync::LazyLock;
3
4static NEEDS_QUOTING_REGEX: LazyLock<Regex> = LazyLock::new(|| {
11 Regex::new(r#"[\[\]:`\{\}#'";\(\)\|\$,\.\d\s\x00!?=]|(?i)^[+\-]?(inf(inity)?|nan)$"#)
12 .expect("internal error: NEEDS_QUOTING_REGEX didn't compile")
13});
14
15pub fn needs_quoting(string: &str) -> bool {
16 if string.is_empty() {
17 return true;
18 }
19 match string {
21 "true" | "false" | "null" | "&&" => return true,
25 _ => (),
26 };
27 NEEDS_QUOTING_REGEX.is_match(string).unwrap_or(false)
29}
30
31pub fn escape_quote_string(string: &str) -> String {
32 let mut output = String::with_capacity(string.len() + 2);
33 output.push('"');
34
35 for c in string.chars() {
36 match c {
37 '"' | '\\' => {
38 output.push('\\');
39 output.push(c);
40 }
41 '\0' => output.push_str("\\0"),
44 _ => output.push(c),
45 }
46 }
47
48 output.push('"');
49 output
50}
51
52pub fn as_raw_string(s: &str) -> Option<String> {
64 if s.contains('\0') || !s.contains(['"', '\\']) {
68 return None;
69 }
70
71 let mut hash_count = 1;
78 loop {
79 let hashes = "#".repeat(hash_count);
80 let closing = format!("'{}", hashes);
81
82 if !s.starts_with(&hashes) && !s.contains(&closing) {
83 return Some(format!("r{hashes}'{s}'{hashes}"));
84 }
85
86 hash_count += 1;
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::{as_raw_string, escape_quote_string, needs_quoting};
93
94 #[test]
95 fn escape_quote_string_escapes_nul_as_backslash_zero() {
96 assert_eq!(escape_quote_string("a\0b"), r#""a\0b""#);
98 assert_eq!(escape_quote_string("\0"), r#""\0""#);
99 assert!(
100 !escape_quote_string("\0").contains('\0'),
101 "the escaped form must not contain a raw NUL"
102 );
103 }
104
105 #[test]
106 fn escape_quote_string_still_escapes_quotes_and_backslashes() {
107 assert_eq!(escape_quote_string(r#"a"b"#), r#""a\"b""#);
109 assert_eq!(escape_quote_string(r"a\b"), r#""a\\b""#);
110 assert_eq!(escape_quote_string("a\0b\"c"), r#""a\0b\"c""#);
111 }
112
113 #[test]
114 fn needs_quoting_forces_a_nul_to_be_quoted() {
115 assert!(needs_quoting("a\0b"));
118 assert!(needs_quoting("\0"));
119 assert!(!needs_quoting("hello"));
121 assert!(!needs_quoting("plain_name"));
122 }
123
124 #[test]
125 fn raw_string_uses_single_hash_when_safe() {
126 assert_eq!(
127 as_raw_string(r#"hello \"world\""#),
128 Some(r#"r#'hello \"world\"'#"#.to_string())
129 );
130 }
131
132 #[test]
133 fn raw_string_is_refused_when_the_value_has_a_nul() {
134 for value in ["a\0\"b", "\0\"", "a\\b\0"] {
137 assert_eq!(
138 as_raw_string(value),
139 None,
140 "a NUL-bearing value must not take the raw form: {value:?}"
141 );
142 }
143
144 assert_eq!(
146 as_raw_string(r#"hello \"world\""#),
147 Some(r#"r#'hello \"world\"'#"#.to_string())
148 );
149 }
150
151 #[test]
152 fn raw_string_uses_more_hashes_for_quote_hash_sequence() {
153 assert_eq!(
154 as_raw_string(r#"contains '# and "quote""#),
155 Some(r##"r##'contains '# and "quote"'##"##.to_string())
156 );
157 }
158
159 #[test]
160 fn raw_string_uses_more_hashes_when_content_starts_with_hash() {
161 let input = "# example.toml\nname = \"my-app\"\nversion = \"1.0.0\"\n";
162
163 assert_eq!(
164 as_raw_string(input),
165 Some(
166 r##"r##'# example.toml
167name = "my-app"
168version = "1.0.0"
169'##"##
170 .to_string()
171 )
172 );
173 }
174
175 #[test]
176 fn raw_string_scales_hash_count_for_longer_sequences() {
177 assert_eq!(
178 as_raw_string(r#"contains '## and "quote""#),
179 Some(r###"r###'contains '## and "quote"'###"###.to_string())
180 );
181 }
182}