1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
const KNOWN_TAGS: &[&str] = &[
"info",
"comment",
"error",
"question",
"highlight",
"warning",
];
#[derive(Debug, Clone, PartialEq)]
pub enum Segment {
Plain(String),
Tagged { tag: String, content: String },
}
pub fn parse_format_string(input: &str) -> Result<Vec<Segment>, String> {
let mut segments: Vec<Segment> = Vec::new();
let mut chars = input.char_indices().peekable();
let mut plain_buf = String::new();
while let Some(&(i, ch)) = chars.peek() {
if ch == '<' {
// Try to match an opening tag
if let Some((tag, after_tag)) = try_parse_open_tag(input, i) {
// Flush plain buffer
if !plain_buf.is_empty() {
segments.push(Segment::Plain(std::mem::take(&mut plain_buf)));
}
// Advance past the opening tag
while chars.peek().is_some_and(|&(j, _)| j < after_tag) {
chars.next();
}
// Collect content until closing tag
let closing = format!("</{tag}>");
let content_start = after_tag;
let Some(close_pos) = input[content_start..].find(&closing) else {
return Err(format!("unclosed <{tag}> tag"));
};
let content_end = content_start + close_pos;
let content = &input[content_start..content_end];
// Check for nested tags
if contains_known_tag(content) {
return Err(format!("nested tags are not supported inside <{tag}>"));
}
segments.push(Segment::Tagged {
tag: tag.to_string(),
content: content.to_string(),
});
// Advance past the closing tag
let after_close = content_end + closing.len();
while chars.peek().is_some_and(|&(j, _)| j < after_close) {
chars.next();
}
} else {
// Not a known tag, treat as literal
plain_buf.push(ch);
chars.next();
}
} else {
plain_buf.push(ch);
chars.next();
}
}
if !plain_buf.is_empty() {
segments.push(Segment::Plain(plain_buf));
}
Ok(segments)
}
/// Try to parse an opening tag like `<info>` at position `pos`.
/// Returns `(tag_name, byte_index_after_closing_angle)` on success.
fn try_parse_open_tag(input: &str, pos: usize) -> Option<(&str, usize)> {
let rest = &input[pos + 1..]; // skip '<'
// Must not start with '/'
if rest.starts_with('/') {
return None;
}
let end = rest.find('>')?;
let tag_name = &rest[..end];
if KNOWN_TAGS.contains(&tag_name) {
Some((tag_name, pos + 1 + end + 1))
} else {
None
}
}
/// Check if a string contains any known opening tag (for nesting detection).
fn contains_known_tag(s: &str) -> bool {
for tag in KNOWN_TAGS {
if s.contains(&format!("<{tag}>")) {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_text_only() {
let result = parse_format_string("hello world").unwrap();
assert_eq!(result, vec![Segment::Plain("hello world".into())]);
}
#[test]
fn single_tag() {
let result = parse_format_string("<info>hello</info>").unwrap();
assert_eq!(
result,
vec![Segment::Tagged {
tag: "info".into(),
content: "hello".into()
}]
);
}
#[test]
fn tag_with_placeholder() {
let result = parse_format_string("<info>Removing {name}</info>").unwrap();
assert_eq!(
result,
vec![Segment::Tagged {
tag: "info".into(),
content: "Removing {name}".into()
}]
);
}
#[test]
fn multiple_tags() {
let result = parse_format_string("<info>{}</info> : <comment>{}</comment>").unwrap();
assert_eq!(
result,
vec![
Segment::Tagged {
tag: "info".into(),
content: "{}".into()
},
Segment::Plain(" : ".into()),
Segment::Tagged {
tag: "comment".into(),
content: "{}".into()
},
]
);
}
#[test]
fn all_tag_types() {
for tag in KNOWN_TAGS {
let input = format!("<{tag}>text</{tag}>");
let result = parse_format_string(&input).unwrap();
assert_eq!(
result,
vec![Segment::Tagged {
tag: tag.to_string(),
content: "text".into()
}]
);
}
}
#[test]
fn unknown_tag_treated_as_literal() {
let result = parse_format_string("<bold>text</bold>").unwrap();
assert_eq!(result, vec![Segment::Plain("<bold>text</bold>".into())]);
}
#[test]
fn unclosed_tag_error() {
let result = parse_format_string("<info>text");
assert!(result.is_err());
assert!(result.unwrap_err().contains("unclosed"));
}
#[test]
fn nested_tag_error() {
let result = parse_format_string("<info><comment>text</comment></info>");
assert!(result.is_err());
assert!(result.unwrap_err().contains("nested"));
}
#[test]
fn escaped_braces() {
let result = parse_format_string("<info>{{literal}}</info>").unwrap();
assert_eq!(
result,
vec![Segment::Tagged {
tag: "info".into(),
content: "{{literal}}".into()
}]
);
}
#[test]
fn adjacent_tags() {
let result = parse_format_string("<info>a</info><comment>b</comment>").unwrap();
assert_eq!(
result,
vec![
Segment::Tagged {
tag: "info".into(),
content: "a".into()
},
Segment::Tagged {
tag: "comment".into(),
content: "b".into()
},
]
);
}
#[test]
fn plain_before_and_after_tag() {
let result = parse_format_string("before <info>middle</info> after").unwrap();
assert_eq!(
result,
vec![
Segment::Plain("before ".into()),
Segment::Tagged {
tag: "info".into(),
content: "middle".into()
},
Segment::Plain(" after".into()),
]
);
}
#[test]
fn empty_content_tag() {
let result = parse_format_string("<info></info>").unwrap();
assert_eq!(
result,
vec![Segment::Tagged {
tag: "info".into(),
content: String::new()
}]
);
}
}
|