nmbrs_workload/
op_text.rs1use std::borrow::Cow;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Piece<'a> {
39 Text(&'a str),
41 Brace(char),
43 Inline { raw: &'a str, body: &'a str },
45 Group { raw: &'a str, body: &'a str },
47}
48
49impl Piece<'_> {
50 pub fn as_written(&self, out: &mut String) {
52 match self {
53 Piece::Text(text) => out.push_str(text),
54 Piece::Brace(brace) => {
55 out.push('\\');
56 out.push(*brace);
57 }
58 Piece::Inline { raw, .. } | Piece::Group { raw, .. } => out.push_str(raw),
59 }
60 }
61}
62
63fn is_escape(bytes: &[u8], at: usize) -> bool {
65 bytes[at] == b'\\' && matches!(bytes.get(at + 1), Some(b'{') | Some(b'}'))
66}
67
68fn closing_brace(bytes: &[u8], open: usize) -> Option<usize> {
71 let mut depth = 1u32;
72 let mut at = open + 1;
73 while at < bytes.len() {
74 if is_escape(bytes, at) {
75 at += 2;
76 continue;
77 }
78 match bytes[at] {
79 b'{' => depth += 1,
80 b'}' => {
81 depth -= 1;
82 if depth == 0 {
83 return Some(at);
84 }
85 }
86 _ => {}
87 }
88 at += 1;
89 }
90 None
91}
92
93pub fn pieces(text: &str) -> Vec<Piece<'_>> {
97 let bytes = text.as_bytes();
98 let end = bytes.len();
99 let mut out = Vec::new();
100 let mut literal = 0;
102 let mut at = 0;
103 while at < end {
104 if is_escape(bytes, at) {
105 if literal < at {
106 out.push(Piece::Text(&text[literal..at]));
107 }
108 out.push(Piece::Brace(bytes[at + 1] as char));
109 at += 2;
110 literal = at;
111 continue;
112 }
113 if bytes[at] != b'{' {
114 at += 1;
115 continue;
116 }
117 if bytes.get(at + 1) == Some(&b'{') {
118 let Some(close) = text[at + 2..].find("}}").map(|offset| at + 2 + offset) else {
119 break;
121 };
122 if literal < at {
123 out.push(Piece::Text(&text[literal..at]));
124 }
125 out.push(Piece::Inline {
126 raw: &text[at..close + 2],
127 body: text[at + 2..close].trim(),
128 });
129 at = close + 2;
130 literal = at;
131 continue;
132 }
133 let next = text[at + 1..].chars().find(|c| !c.is_whitespace());
134 if matches!(next, Some('\'') | Some('"')) {
135 at += 1;
136 continue;
137 }
138 let Some(close) = closing_brace(bytes, at) else {
139 at += 1;
140 continue;
141 };
142 let body = text[at + 1..close].trim();
143 if body.is_empty() {
144 at = close + 1;
145 continue;
146 }
147 if literal < at {
148 out.push(Piece::Text(&text[literal..at]));
149 }
150 out.push(Piece::Group {
151 raw: &text[at..=close],
152 body,
153 });
154 at = close + 1;
155 literal = at;
156 }
157 if literal < end {
158 out.push(Piece::Text(&text[literal..]));
159 }
160 out
161}
162
163pub fn unescape(text: &str) -> Cow<'_, str> {
170 if !text.contains('\\') {
171 return Cow::Borrowed(text);
172 }
173 let pieces = pieces(text);
174 if !pieces.iter().any(|piece| matches!(piece, Piece::Brace(_))) {
175 return Cow::Borrowed(text);
176 }
177 let mut out = String::with_capacity(text.len());
178 for piece in &pieces {
179 match piece {
180 Piece::Brace(brace) => out.push(*brace),
181 other => other.as_written(&mut out),
182 }
183 }
184 Cow::Owned(out)
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190
191 fn written(text: &str) -> String {
192 let mut out = String::new();
193 for piece in pieces(text) {
194 piece.as_written(&mut out);
195 }
196 out
197 }
198
199 #[test]
200 fn the_pieces_written_back_are_the_text() {
201 for text in [
202 "",
203 "plain",
204 "a {name} b {{hash(cycle)}} c",
205 r"^\d\{8\}-{node}\.log$",
206 "WITH compaction = {\n 'class': '{strategy}'\n}",
207 "open { and {} and { } and {{ unclosed",
208 "{k_{k}_limits}",
209 r"C:\dir\file and \\{name}",
210 ] {
211 assert_eq!(written(text), text);
212 }
213 }
214
215 #[test]
216 fn an_escaped_brace_is_a_brace_and_not_a_group() {
217 assert_eq!(
218 pieces(r"\d\{8\} {node}"),
219 vec![
220 Piece::Text(r"\d"),
221 Piece::Brace('{'),
222 Piece::Text("8"),
223 Piece::Brace('}'),
224 Piece::Text(" "),
225 Piece::Group {
226 raw: "{node}",
227 body: "node"
228 },
229 ]
230 );
231 }
232
233 #[test]
234 fn a_backslash_before_anything_else_is_text() {
235 assert_eq!(pieces(r"a\nb\\c"), vec![Piece::Text(r"a\nb\\c")]);
236 }
237
238 #[test]
239 fn an_escaped_brace_inside_a_group_does_not_close_it() {
240 assert_eq!(
241 pieces(r#"{f("\}")}"#),
242 vec![Piece::Group {
243 raw: r#"{f("\}")}"#,
244 body: r#"f("\}")"#
245 }]
246 );
247 }
248
249 #[test]
250 fn a_brace_before_a_quote_is_literal_and_the_map_is_still_scanned() {
251 assert_eq!(
252 pieces("{ 'class': '{strategy}' }"),
253 vec![
254 Piece::Text("{ 'class': '"),
255 Piece::Group {
256 raw: "{strategy}",
257 body: "strategy"
258 },
259 Piece::Text("' }"),
260 ]
261 );
262 }
263
264 #[test]
265 fn an_inline_expression_keeps_its_body() {
266 assert_eq!(
267 pieces("v={{ mod(cycle, 10) }}"),
268 vec![
269 Piece::Text("v="),
270 Piece::Inline {
271 raw: "{{ mod(cycle, 10) }}",
272 body: "mod(cycle, 10)"
273 },
274 ]
275 );
276 }
277
278 #[test]
279 fn unescape_writes_braces_alone_and_keeps_bind_points() {
280 assert_eq!(unescape(r"^\d\{2,3\}$"), r"^\d{2,3}$");
281 assert_eq!(unescape(r"\{{name}\}"), "{{name}}");
282 assert!(matches!(unescape(r"a\nb"), Cow::Borrowed(_)));
283 }
284}