1#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Kind {
37 #[default]
39 Element,
40 Text,
42 Cdata,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub struct Node {
49 pub kind: Kind,
51 pub name: String,
53 pub value: String,
55 pub attrs: Vec<(String, String)>,
61 pub children: Vec<Node>,
63}
64
65const NEWLINE: u8 = 1;
67const INDENT: u8 = 2;
69
70impl Node {
71 pub fn element(name: &str) -> Node {
73 Node {
74 kind: Kind::Element,
75 name: name.to_string(),
76 ..Default::default()
77 }
78 }
79
80 pub fn text(value: &str) -> Node {
82 Node {
83 kind: Kind::Text,
84 value: value.to_string(),
85 ..Default::default()
86 }
87 }
88
89 pub fn cdata(value: &str) -> Node {
91 Node {
92 kind: Kind::Cdata,
93 value: value.to_string(),
94 ..Default::default()
95 }
96 }
97
98 pub fn append_child(&mut self, name: &str) -> &mut Node {
100 self.children.push(Node::element(name));
101 self.children.last_mut().unwrap()
102 }
103
104 pub fn append_child_value(&mut self, name: &str, value: &str) -> &mut Node {
109 let mut e = Node::element(name);
110 e.children.push(Node::text(value));
111 self.children.push(e);
112 self.children.last_mut().unwrap()
113 }
114
115 pub fn child(&self, name: &str) -> Option<&Node> {
117 self.children.iter().find(|c| c.name == name)
118 }
119
120 pub fn child_mut(&mut self, name: &str) -> Option<&mut Node> {
122 self.children.iter_mut().find(|c| c.name == name)
123 }
124
125 pub fn child_value(&self) -> &str {
127 for c in &self.children {
128 if c.kind != Kind::Element {
129 return &c.value;
130 }
131 }
132 ""
133 }
134
135 pub fn child_value_of(&self, name: &str) -> &str {
137 match self.child(name) {
138 Some(c) => c.child_value(),
139 None => "",
140 }
141 }
142
143 pub fn is_empty(&self) -> bool {
145 self.name.is_empty()
146 && self.value.is_empty()
147 && self.children.is_empty()
148 && self.attrs.is_empty()
149 }
150
151 pub fn write(&self, out: &mut String, depth: usize) {
155 self.emit(out, depth, INDENT);
156 out.push('\n');
157 }
158
159 fn emit(&self, out: &mut String, depth: usize, flags: u8) -> u8 {
166 if self.kind == Kind::Text {
167 escape_text_into(&self.value, out);
168 return 0;
169 }
170 if self.kind == Kind::Cdata {
171 out.push_str("<![CDATA[");
172 out.push_str(&self.value);
173 out.push_str("]]>");
174 return 0;
175 }
176 if flags & NEWLINE != 0 {
177 out.push('\n');
178 }
179 if flags & INDENT != 0 {
180 for _ in 0..depth {
181 out.push('\t');
182 }
183 }
184 out.push('<');
185 out.push_str(&self.name);
186 for (k, v) in &self.attrs {
187 out.push(' ');
188 out.push_str(k);
189 out.push_str("=\"");
190 escape_attr_into(v, out);
191 out.push('"');
192 }
193 if self.children.is_empty() {
194 out.push_str(" />");
195 return NEWLINE | INDENT;
196 }
197 out.push('>');
198 let mut f = NEWLINE | INDENT;
199 for c in &self.children {
200 f = c.emit(out, depth + 1, f);
201 }
202 if f & NEWLINE != 0 {
203 out.push('\n');
204 }
205 if f & INDENT != 0 {
206 for _ in 0..depth {
207 out.push('\t');
208 }
209 }
210 out.push_str("</");
211 out.push_str(&self.name);
212 out.push('>');
213 NEWLINE | INDENT
214 }
215}
216
217fn escape_text_into(s: &str, out: &mut String) {
223 for c in s.chars() {
224 match c {
225 '&' => out.push_str("&"),
226 '<' => out.push_str("<"),
227 '>' => out.push_str(">"),
228 other => out.push(other),
229 }
230 }
231}
232
233fn escape_attr_into(s: &str, out: &mut String) {
242 for c in s.chars() {
243 match c {
244 '&' => out.push_str("&"),
245 '<' => out.push_str("<"),
246 '"' => out.push_str("""),
247 '\n' => out.push_str(" "),
248 '\r' => out.push_str(" "),
249 '\t' => out.push_str("	"),
250 other => out.push(other),
251 }
252 }
253}
254
255pub fn parse(xml: &str) -> Option<Node> {
273 let b = xml.as_bytes();
274 let mut i = 0usize;
275 let mut stack: Vec<Node> = Vec::new();
276 let mut root: Option<Node> = None;
277
278 while i < b.len() {
279 if b[i] != b'<' {
280 let start = i;
281 while i < b.len() && b[i] != b'<' {
282 i += 1;
283 }
284 let raw = &xml[start..i];
285 if !raw.trim().is_empty() {
286 if let Some(top) = stack.last_mut() {
287 top.children.push(Node::text(&decode(raw)));
288 }
289 }
290 continue;
291 }
292 if xml[i..].starts_with("<?") {
293 i = find(b, i, b"?>")? + 2;
294 continue;
295 }
296 if xml[i..].starts_with("<!--") {
297 i = find(b, i, b"-->")? + 3;
298 continue;
299 }
300 if xml[i..].starts_with("<![CDATA[") {
301 let end = find(b, i, b"]]>")?;
302 let raw = normalize_eol(&xml[i + 9..end]);
305 if let Some(top) = stack.last_mut() {
306 top.children.push(Node::cdata(&raw));
307 }
308 i = end + 3;
309 continue;
310 }
311 if xml[i..].starts_with("<!") {
312 i = find(b, i, b">")? + 1;
313 continue;
314 }
315 if xml[i..].starts_with("</") {
316 let end = find(b, i, b">")?;
317 let done = stack.pop()?;
318 if stack.is_empty() {
319 root = Some(done);
320 } else {
321 stack.last_mut()?.children.push(done);
322 }
323 i = end + 1;
324 continue;
325 }
326
327 let end = tag_end(b, i)?;
329 let inner = &xml[i + 1..end];
330 let selfclose = inner.trim_end().ends_with('/');
331 let inner = match inner.trim_end().strip_suffix('/') {
332 Some(x) => x,
333 None => inner,
334 };
335 let (name, rest) = split_name(inner);
336 if name.is_empty() {
337 return None;
338 }
339 let mut node = Node::element(name);
340 node.attrs = read_attrs(rest);
341 if selfclose {
342 if let Some(top) = stack.last_mut() {
343 top.children.push(node);
344 } else {
345 root = Some(node);
346 }
347 } else {
348 stack.push(node);
349 }
350 i = end + 1;
351 }
352
353 if !stack.is_empty() {
354 return None;
355 }
356 root
357}
358
359fn tag_end(b: &[u8], from: usize) -> Option<usize> {
361 let mut quote = 0u8;
362 for (k, &c) in b.iter().enumerate().skip(from) {
363 if quote != 0 {
364 if c == quote {
365 quote = 0;
366 }
367 } else if c == b'"' || c == b'\'' {
368 quote = c;
369 } else if c == b'>' {
370 return Some(k);
371 }
372 }
373 None
374}
375
376fn split_name(inner: &str) -> (&str, &str) {
377 match inner.find(|c: char| c.is_ascii_whitespace()) {
378 Some(k) => (&inner[..k], &inner[k..]),
379 None => (inner, ""),
380 }
381}
382
383fn read_attrs(rest: &str) -> Vec<(String, String)> {
385 let mut out = Vec::new();
386 let chars: Vec<char> = rest.chars().collect();
387 let mut i = 0;
388 while i < chars.len() {
389 if chars[i].is_ascii_whitespace() {
390 i += 1;
391 continue;
392 }
393 let start = i;
394 while i < chars.len() && chars[i] != '=' && !chars[i].is_ascii_whitespace() {
395 i += 1;
396 }
397 let name: String = chars[start..i].iter().collect();
398 while i < chars.len() && chars[i].is_ascii_whitespace() {
399 i += 1;
400 }
401 if i >= chars.len() || chars[i] != '=' {
402 continue;
403 }
404 i += 1;
405 while i < chars.len() && chars[i].is_ascii_whitespace() {
406 i += 1;
407 }
408 if i >= chars.len() {
409 break;
410 }
411 let quote = chars[i];
412 if quote != '"' && quote != '\'' {
413 break;
414 }
415 i += 1;
416 let vstart = i;
417 while i < chars.len() && chars[i] != quote {
418 i += 1;
419 }
420 let value: String = chars[vstart..i].iter().collect();
421 i += 1;
422 if !name.is_empty() {
423 out.push((name, decode(&value)));
424 }
425 }
426 out
427}
428
429fn find(b: &[u8], from: usize, pat: &[u8]) -> Option<usize> {
430 (from..=b.len().checked_sub(pat.len())?).find(|&k| &b[k..k + pat.len()] == pat)
431}
432
433fn normalize_eol(s: &str) -> String {
435 let mut out = String::with_capacity(s.len());
436 let mut it = s.chars().peekable();
437 while let Some(c) = it.next() {
438 if c == '\r' {
439 if it.peek() == Some(&'\n') {
440 it.next();
441 }
442 out.push('\n');
443 } else {
444 out.push(c);
445 }
446 }
447 out
448}
449
450fn decode(s: &str) -> String {
452 let mut out = String::with_capacity(s.len());
453 let b = s.as_bytes();
454 let mut i = 0;
455 while i < b.len() {
456 if b[i] != b'&' {
457 let start = i;
458 while i < b.len() && b[i] != b'&' {
459 i += 1;
460 }
461 out.push_str(&s[start..i]);
462 continue;
463 }
464 let end = match find(b, i, b";") {
465 Some(e) if e - i <= 10 => e,
466 _ => {
468 out.push('&');
469 i += 1;
470 continue;
471 }
472 };
473 let name = &s[i + 1..end];
474 let decoded = match name {
475 "amp" => Some('&'),
476 "lt" => Some('<'),
477 "gt" => Some('>'),
478 "quot" => Some('"'),
479 "apos" => Some('\''),
480 _ => numeric_entity(name),
481 };
482 match decoded {
483 Some(c) => {
484 out.push(c);
485 i = end + 1;
486 }
487 None => {
488 out.push('&');
489 i += 1;
490 }
491 }
492 }
493 normalize_eol(&out)
494}
495
496fn numeric_entity(name: &str) -> Option<char> {
497 let digits = name.strip_prefix('#')?;
498 let code = match digits
499 .strip_prefix('x')
500 .or_else(|| digits.strip_prefix('X'))
501 {
502 Some(hex) => u32::from_str_radix(hex, 16).ok()?,
503 None => digits.parse::<u32>().ok()?,
504 };
505 char::from_u32(code)
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 fn render(n: &Node) -> String {
513 let mut s = String::new();
514 n.write(&mut s, 0);
515 s
516 }
517
518 fn round(desc: &str) -> String {
522 let n = parse(desc).expect("a tree");
523 let mut s = String::new();
524 n.emit(&mut s, 1, INDENT);
525 s
526 }
527
528 #[test]
529 fn an_element_with_no_children_prints_as_an_empty_tag() {
530 assert_eq!(render(&Node::element("desc")), "<desc />\n");
531 }
532
533 #[test]
534 fn an_empty_text_child_prints_as_a_pair_of_tags() {
535 let mut d = Node::element("desc");
538 d.append_child_value("blank", "");
539 d.append_child("hollow");
540 assert_eq!(
541 render(&d),
542 "<desc>\n\t<blank></blank>\n\t<hollow />\n</desc>\n"
543 );
544 }
545
546 #[test]
547 fn text_beside_an_element_keeps_the_whole_element_on_one_line() {
548 assert_eq!(
550 round("<desc><v>a<b />c</v></desc>"),
551 "\t<desc>\n\t\t<v>a<b />c</v>\n\t</desc>"
552 );
553 }
554
555 #[test]
556 fn only_three_characters_are_escaped_in_text() {
557 let mut d = Node::element("d");
558 d.append_child_value("v", "a & b <x> \" ' \t");
559 assert_eq!(
560 render(&d),
561 "<d>\n\t<v>a & b <x> \" ' \t</v>\n</d>\n"
562 );
563 }
564
565 #[test]
566 fn an_attribute_survives_a_round_trip() {
567 assert_eq!(
570 round("<desc><v id=\"1\" unit='mV'>x</v></desc>"),
571 "\t<desc>\n\t\t<v id=\"1\" unit=\"mV\">x</v>\n\t</desc>"
572 );
573 }
574
575 #[test]
576 fn an_attribute_escapes_the_characters_that_the_oracle_escapes() {
577 assert_eq!(
579 round("<desc><v a=\"x&y"z w	t<u>\" b='s'q'>1</v></desc>"),
580 "\t<desc>\n\t\t<v a=\"x&y"z w	t<u>\" b=\"s'q\">1</v>\n\t</desc>"
581 );
582 }
583
584 #[test]
585 fn a_section_of_character_data_stays_one() {
586 assert_eq!(
588 round("<desc><v><![CDATA[a & <b>]]></v></desc>"),
589 "\t<desc>\n\t\t<v><![CDATA[a & <b>]]></v>\n\t</desc>"
590 );
591 assert_eq!(
592 round("<desc><v>a<![CDATA[<b>]]>c</v></desc>"),
593 "\t<desc>\n\t\t<v>a<![CDATA[<b>]]>c</v>\n\t</desc>"
594 );
595 }
596
597 #[test]
598 fn a_comment_is_dropped() {
599 assert_eq!(
601 round("<desc><!-- gone --><v>x</v></desc>"),
602 "\t<desc>\n\t\t<v>x</v>\n\t</desc>"
603 );
604 }
605
606 #[test]
607 fn text_that_holds_only_spaces_is_dropped() {
608 assert_eq!(
610 round("<desc><v> </v></desc>"),
611 "\t<desc>\n\t\t<v />\n\t</desc>"
612 );
613 }
614
615 #[test]
616 fn a_reference_with_no_semicolon_stays_as_it_is() {
617 let n = parse("<desc><v>100% & fine</v></desc>").expect("a tree");
620 assert_eq!(n.child_value_of("v"), "100% & fine");
621 assert_eq!(
622 round("<desc><v>100% & fine</v></desc>"),
623 "\t<desc>\n\t\t<v>100% &amp fine</v>\n\t</desc>"
624 );
625 }
626
627 #[test]
628 fn a_numeric_reference_is_decoded() {
629 let n = parse("<desc><v>AB </v></desc>").expect("a tree");
631 assert_eq!(n.child_value_of("v"), "AB\n");
632 }
633
634 #[test]
635 fn a_carriage_return_does_not_survive_the_reader() {
636 let n = parse("<a><lines>one\ntwo\rthree\tfour</lines></a>").expect("a tree");
639 assert_eq!(n.child_value_of("lines"), "one\ntwo\nthree\tfour");
640 }
641
642 #[test]
643 fn a_tag_that_never_closes_is_rejected() {
644 assert!(parse("<a><b></a>").is_none());
645 assert!(parse("<a>").is_none());
646 }
647
648 #[test]
649 fn text_reads_back_as_a_child_node() {
650 let n = parse("<a><b>v</b></a>").expect("a tree");
652 let b = n.child("b").expect("b");
653 assert_eq!(b.kind, Kind::Element);
654 assert_eq!(b.value, "");
655 assert_eq!(b.children.len(), 1);
656 assert_eq!(b.children[0].kind, Kind::Text);
657 assert_eq!(b.children[0].value, "v");
658 }
659
660 #[test]
661 fn a_greater_than_sign_inside_an_attribute_does_not_end_the_tag() {
662 let n = parse("<a><b x=\"1>2\">v</b></a>").expect("a tree");
663 assert_eq!(
664 n.child("b").expect("b").attrs,
665 vec![("x".into(), "1>2".into())]
666 );
667 }
668}