1use std::io::Write;
158
159use crate::namespace::XML_NAMESPACE;
160use crate::navigator::{DomNavigator, DomNodeType, NamespaceAxisScope};
161
162#[derive(Clone, Debug, Default)]
181pub struct SerializeOptions {
182 pub xml_declaration: bool,
188 pub standalone: Option<bool>,
192 pub indent: Option<usize>,
202}
203
204#[derive(Debug, thiserror::Error)]
226pub enum SerializeError {
227 #[error("failed to write XML: {0}")]
229 Io(#[from] std::io::Error),
230
231 #[error("U+{code_point:04X} is not an XML 1.0 Char and cannot appear in {context}")]
237 InvalidChar {
238 code_point: u32,
240 context: &'static str,
242 },
243
244 #[error("comment content is not well-formed (XML 1.0 \u{a7}2.5): {0:?}")]
246 InvalidComment(String),
247
248 #[error("processing instruction {target:?} is not well-formed (XML 1.0 \u{a7}2.6): {reason}")]
250 InvalidPi {
251 target: String,
253 reason: &'static str,
255 },
256
257 #[error("prefix {prefix:?} is not bound to namespace {uri:?} in the output scope")]
261 UnboundName {
262 prefix: String,
264 uri: String,
266 },
267
268 #[error("a {0:?} node cannot be serialized on its own")]
271 NotSerializable(DomNodeType),
272}
273
274pub fn serialize_document<N: DomNavigator, W: Write>(
313 root: &N,
314 out: W,
315 opts: &SerializeOptions,
316) -> Result<(), SerializeError> {
317 let mut nav = root.clone();
318 nav.move_to_root();
319 Serializer::new(out, opts)
320 .with_ancestor_layout(&nav)
321 .write_document(&nav)
322}
323
324pub fn serialize_node<N: DomNavigator, W: Write>(
360 node: &N,
361 out: W,
362 opts: &SerializeOptions,
363) -> Result<(), SerializeError> {
364 let kind = node.node_type();
365 let mut ser = Serializer::new(out, opts).with_ancestor_layout(node);
366 match kind {
367 DomNodeType::Root => ser.write_document(node),
368 DomNodeType::Attribute | DomNodeType::Namespace | DomNodeType::All => {
369 Err(SerializeError::NotSerializable(kind))
370 }
371 _ => ser.write_subtree(node),
372 }
373}
374
375pub fn to_string<N: DomNavigator>(
392 node: &N,
393 opts: &SerializeOptions,
394) -> Result<String, SerializeError> {
395 let mut buf: Vec<u8> = Vec::new();
396 serialize_node(node, &mut buf, opts)?;
397 Ok(String::from_utf8(buf).expect("serializer writes UTF-8"))
399}
400
401const XML_PREFIX: &str = "xml";
406
407fn is_forbidden_char(ch: char) -> bool {
412 match ch {
413 '\t' | '\n' | '\r' => false,
414 c if (c as u32) < 0x20 => true,
415 '\u{FFFE}' | '\u{FFFF}' => true,
416 _ => false,
417 }
418}
419
420const SPACES: [u8; 64] = [b' '; 64];
422
423#[derive(Clone, Copy, Debug, Default)]
426struct Layout {
427 enabled: bool,
429 suppressed: bool,
433 preserve: bool,
436}
437
438struct Frame {
440 ns_watermark: usize,
441 layout: Layout,
442 prev_child: Option<DomNodeType>,
445}
446
447struct Serializer<'o, W: Write> {
449 out: W,
450 opts: &'o SerializeOptions,
451 ns_stack: Vec<(String, String)>,
455 seed: Layout,
458}
459
460impl<'o, W: Write> Serializer<'o, W> {
461 fn new(out: W, opts: &'o SerializeOptions) -> Self {
462 Self {
463 out,
464 opts,
465 ns_stack: Vec::new(),
466 seed: Layout::default(),
467 }
468 }
469
470 fn with_ancestor_layout<N: DomNavigator>(mut self, node: &N) -> Self {
474 if self.opts.indent.is_none() {
475 return self;
476 }
477 let mut ancestor = node.clone();
478 while ancestor.move_to_parent() {
479 if ancestor.node_type() == DomNodeType::Element {
480 if let Some(preserve) = xml_space(&ancestor) {
481 self.seed.preserve = preserve;
482 break;
483 }
484 }
485 }
486 self
487 }
488
489 fn content_layout<N: DomNavigator>(
494 &self,
495 nav: &N,
496 inherited: Layout,
497 space: Option<bool>,
498 ) -> Layout {
499 let indented = self.opts.indent.is_some();
500 let preserve = space.unwrap_or(inherited.preserve);
501 let suppressed = inherited.suppressed || (indented && has_text_child(nav));
504 Layout {
505 enabled: indented && !suppressed && !preserve,
506 suppressed,
507 preserve,
508 }
509 }
510
511 fn write_break(&mut self, depth: usize) -> Result<(), SerializeError> {
513 self.out.write_all(b"\n")?;
514 let mut remaining = self.opts.indent.unwrap_or(0) * depth;
515 while remaining > 0 {
516 let take = remaining.min(SPACES.len());
517 self.out.write_all(&SPACES[..take])?;
518 remaining -= take;
519 }
520 Ok(())
521 }
522
523 fn in_scope(&self, prefix: &str) -> Option<&str> {
531 if prefix == XML_PREFIX {
532 return Some(XML_NAMESPACE);
533 }
534 match self
535 .ns_stack
536 .iter()
537 .rev()
538 .find(|(p, _)| p == prefix)
539 .map(|(_, u)| u.as_str())
540 {
541 Some("") if !prefix.is_empty() => None,
544 Some(uri) => Some(uri),
545 None if prefix.is_empty() => Some(""),
546 None => None,
547 }
548 }
549
550 fn is_bound(&self, prefix: &str, uri: &str) -> bool {
551 self.in_scope(prefix) == Some(uri)
552 }
553
554 fn has_default_namespace(&self) -> bool {
557 matches!(self.in_scope(""), Some(uri) if !uri.is_empty())
558 }
559
560 fn push_binding(&mut self, prefix: &str, uri: &str) {
561 self.ns_stack.push((prefix.to_string(), uri.to_string()));
562 }
563
564 fn write_document<N: DomNavigator>(&mut self, node: &N) -> Result<(), SerializeError> {
567 let declaration = self.opts.xml_declaration;
568 if declaration {
569 self.out
570 .write_all(br#"<?xml version="1.0" encoding="UTF-8""#)?;
571 match self.opts.standalone {
572 Some(true) => self.out.write_all(br#" standalone="yes""#)?,
573 Some(false) => self.out.write_all(br#" standalone="no""#)?,
574 None => {}
575 }
576 self.out.write_all(b"?>")?;
577 }
578 if node.node_type() != DomNodeType::Root {
579 if declaration && self.opts.indent.is_some() {
582 self.write_break(0)?;
583 }
584 return self.write_subtree(node);
585 }
586 let layout = self.content_layout(node, self.seed, None);
589 let mut prev_child: Option<DomNodeType> = None;
590 let mut child = node.clone();
591 if child.move_to_first_child() {
592 loop {
593 let kind = child.node_type();
594 let boundary = match prev_child {
595 None => declaration && kind == DomNodeType::Element,
598 Some(prev) => is_element(prev) || is_element(kind),
599 };
600 if layout.enabled && boundary {
601 self.write_break(0)?;
602 }
603 prev_child = Some(kind);
604 self.write_subtree(&child)?;
605 if !child.move_to_next_sibling() {
606 break;
607 }
608 }
609 }
610 Ok(())
612 }
613
614 fn write_subtree<N: DomNavigator>(&mut self, start: &N) -> Result<(), SerializeError> {
620 let mut nav = start.clone();
621 let mut frames: Vec<Frame> = Vec::new();
622 loop {
623 let kind = nav.node_type();
624 let boundary = frames.last().is_some_and(|frame| {
627 frame.layout.enabled
628 && match frame.prev_child {
629 None => is_element(kind),
630 Some(prev) => is_element(prev) || is_element(kind),
631 }
632 });
633 if boundary {
634 self.write_break(frames.len())?;
635 }
636 if let Some(frame) = frames.last_mut() {
637 frame.prev_child = Some(kind);
638 }
639
640 let mut descended = false;
641 match kind {
642 DomNodeType::Element => {
643 let ns_watermark = self.ns_stack.len();
644 let space = self.write_start_tag(&nav)?;
645 let mut child = nav.clone();
646 if child.move_to_first_child() {
647 self.out.write_all(b">")?;
648 let inherited = frames.last().map_or(self.seed, |frame| frame.layout);
649 let layout = self.content_layout(&nav, inherited, space);
650 frames.push(Frame {
651 ns_watermark,
652 layout,
653 prev_child: None,
654 });
655 nav = child;
656 descended = true;
657 } else {
658 self.out.write_all(b"/>")?;
660 self.ns_stack.truncate(ns_watermark);
661 }
662 }
663 kind => self.write_leaf(&nav, kind)?,
664 }
665 if descended {
666 continue;
667 }
668 loop {
670 if frames.is_empty() {
671 return Ok(());
672 }
673 if nav.move_to_next_sibling() {
674 break;
675 }
676 nav.move_to_parent();
677 let frame = frames.pop().expect("checked non-empty");
678 if frame.layout.enabled && frame.prev_child.is_some_and(is_element) {
680 self.write_break(frames.len())?;
681 }
682 self.write_end_tag(&nav)?;
683 self.ns_stack.truncate(frame.ns_watermark);
684 }
685 }
686 }
687
688 fn write_leaf<N: DomNavigator>(
689 &mut self,
690 nav: &N,
691 kind: DomNodeType,
692 ) -> Result<(), SerializeError> {
693 match kind {
694 DomNodeType::Text | DomNodeType::Whitespace | DomNodeType::SignificantWhitespace => {
695 self.write_text(&nav.value_ref())
696 }
697 DomNodeType::Comment => {
698 let value = nav.value_ref();
699 check_chars(&value, "comment")?;
700 if value.contains("--") || value.ends_with('-') {
701 return Err(SerializeError::InvalidComment(value.into_owned()));
702 }
703 self.out.write_all(b"<!--")?;
704 self.out.write_all(value.as_bytes())?;
705 self.out.write_all(b"-->")?;
706 Ok(())
707 }
708 DomNodeType::ProcessingInstruction => {
709 let target = nav.local_name();
710 check_chars(target, "name")?;
711 if target.eq_ignore_ascii_case(XML_PREFIX) {
712 return Err(SerializeError::InvalidPi {
713 target: target.to_string(),
714 reason: "the target `xml` is reserved",
715 });
716 }
717 let data = nav.value_ref();
718 check_chars(&data, "processing instruction")?;
719 if data.contains("?>") {
720 return Err(SerializeError::InvalidPi {
721 target: target.to_string(),
722 reason: "the data contains `?>`",
723 });
724 }
725 self.out.write_all(b"<?")?;
726 self.out.write_all(target.as_bytes())?;
727 if !data.is_empty() {
728 self.out.write_all(b" ")?;
729 self.out.write_all(data.as_bytes())?;
730 }
731 self.out.write_all(b"?>")?;
732 Ok(())
733 }
734 other => Err(SerializeError::NotSerializable(other)),
735 }
736 }
737
738 fn write_start_tag<N: DomNavigator>(
746 &mut self,
747 nav: &N,
748 ) -> Result<Option<bool>, SerializeError> {
749 self.out.write_all(b"<")?;
750 self.write_qname(nav.prefix(), nav.local_name())?;
751 self.write_namespace_declarations(nav)?;
752
753 let (prefix, uri) = (nav.prefix(), nav.namespace_uri());
755 if !self.is_bound(prefix, uri) {
756 return Err(SerializeError::UnboundName {
757 prefix: prefix.to_string(),
758 uri: uri.to_string(),
759 });
760 }
761
762 let watch_space = self.opts.indent.is_some();
763 let mut space = None;
764 let mut attr = nav.clone();
765 if attr.move_to_first_attribute() {
766 loop {
767 let (prefix, uri) = (attr.prefix(), attr.namespace_uri());
768 if watch_space && uri == XML_NAMESPACE && attr.local_name() == "space" {
769 space = xml_space_value(&attr.value_ref());
770 }
771 let bound = if prefix.is_empty() {
774 uri.is_empty()
775 } else {
776 self.is_bound(prefix, uri)
777 };
778 if !bound {
779 return Err(SerializeError::UnboundName {
780 prefix: prefix.to_string(),
781 uri: uri.to_string(),
782 });
783 }
784 self.out.write_all(b" ")?;
785 self.write_qname(prefix, attr.local_name())?;
786 self.out.write_all(b"=\"")?;
787 self.write_attribute_value(&attr.value_ref())?;
788 self.out.write_all(b"\"")?;
789 if !attr.move_to_next_attribute() {
790 break;
791 }
792 }
793 }
794 Ok(space)
795 }
796
797 fn write_namespace_declarations<N: DomNavigator>(
808 &mut self,
809 nav: &N,
810 ) -> Result<(), SerializeError> {
811 let watermark = self.ns_stack.len();
812 let mut axis_has_default = false;
813 let mut ns = nav.clone();
814 if ns.move_to_first_namespace(NamespaceAxisScope::ExcludeXml) {
815 loop {
816 let prefix = ns.local_name();
817 let uri = ns.value_ref();
818 if prefix != XML_PREFIX {
821 if prefix.is_empty() {
822 if uri.is_empty() {
823 } else {
827 axis_has_default = true;
828 if !self.is_bound("", &uri) {
829 self.push_binding("", &uri);
830 }
831 }
832 } else if !uri.is_empty() && !self.is_bound(prefix, &uri) {
833 self.push_binding(prefix, &uri);
834 }
835 }
838 if !ns.move_to_next_namespace(NamespaceAxisScope::ExcludeXml) {
839 break;
840 }
841 }
842 }
843 if !axis_has_default && self.has_default_namespace() {
844 self.push_binding("", "");
845 }
846
847 self.ns_stack[watermark..].sort_by(|(a, _), (b, _)| a.cmp(b));
848 let out = &mut self.out;
850 for (prefix, uri) in &self.ns_stack[watermark..] {
851 write_declaration(out, prefix, uri)?;
852 }
853 Ok(())
854 }
855
856 fn write_end_tag<N: DomNavigator>(&mut self, nav: &N) -> Result<(), SerializeError> {
857 self.out.write_all(b"</")?;
858 self.write_qname(nav.prefix(), nav.local_name())?;
859 self.out.write_all(b">")?;
860 Ok(())
861 }
862
863 fn write_qname(&mut self, prefix: &str, local: &str) -> Result<(), SerializeError> {
864 write_qname(&mut self.out, prefix, local)
865 }
866
867 fn write_text(&mut self, text: &str) -> Result<(), SerializeError> {
868 write_text(&mut self.out, text)
869 }
870
871 fn write_attribute_value(&mut self, value: &str) -> Result<(), SerializeError> {
872 write_attribute_value(&mut self.out, value)
873 }
874}
875
876fn is_element(kind: DomNodeType) -> bool {
879 kind == DomNodeType::Element
880}
881
882fn has_text_child<N: DomNavigator>(nav: &N) -> bool {
886 let mut child = nav.clone();
887 if !child.move_to_first_child() {
888 return false;
889 }
890 loop {
891 if child.node_type().is_text_like() {
892 return true;
893 }
894 if !child.move_to_next_sibling() {
895 return false;
896 }
897 }
898}
899
900fn xml_space<N: DomNavigator>(nav: &N) -> Option<bool> {
902 let mut attr = nav.clone();
903 if attr.move_to_first_attribute() {
904 loop {
905 if attr.namespace_uri() == XML_NAMESPACE && attr.local_name() == "space" {
906 return xml_space_value(&attr.value_ref());
907 }
908 if !attr.move_to_next_attribute() {
909 break;
910 }
911 }
912 }
913 None
914}
915
916fn xml_space_value(value: &str) -> Option<bool> {
919 match value {
920 "preserve" => Some(true),
921 "default" => Some(false),
922 _ => None,
923 }
924}
925
926fn write_declaration<W: Write>(out: &mut W, prefix: &str, uri: &str) -> Result<(), SerializeError> {
929 check_chars(prefix, "name")?;
930 if prefix.is_empty() {
931 out.write_all(b" xmlns=\"")?;
932 } else {
933 out.write_all(b" xmlns:")?;
934 out.write_all(prefix.as_bytes())?;
935 out.write_all(b"=\"")?;
936 }
937 write_attribute_value(out, uri)?;
938 out.write_all(b"\"")?;
939 Ok(())
940}
941
942fn write_qname<W: Write>(out: &mut W, prefix: &str, local: &str) -> Result<(), SerializeError> {
943 check_chars(prefix, "name")?;
944 check_chars(local, "name")?;
945 if !prefix.is_empty() {
946 out.write_all(prefix.as_bytes())?;
947 out.write_all(b":")?;
948 }
949 out.write_all(local.as_bytes())?;
950 Ok(())
951}
952
953fn write_text<W: Write>(out: &mut W, text: &str) -> Result<(), SerializeError> {
954 let mut written = 0;
955 for (offset, ch) in text.char_indices() {
956 let escape = match ch {
957 '&' => "&",
958 '<' => "<",
959 '>' => ">",
962 '\r' => "
",
965 c if is_forbidden_char(c) => {
966 return Err(SerializeError::InvalidChar {
967 code_point: c as u32,
968 context: "text",
969 })
970 }
971 _ => continue,
972 };
973 out.write_all(&text.as_bytes()[written..offset])?;
974 out.write_all(escape.as_bytes())?;
975 written = offset + ch.len_utf8();
976 }
977 out.write_all(&text.as_bytes()[written..])?;
978 Ok(())
979}
980
981fn write_attribute_value<W: Write>(out: &mut W, value: &str) -> Result<(), SerializeError> {
982 let mut written = 0;
983 for (offset, ch) in value.char_indices() {
984 let escape = match ch {
985 '&' => "&",
986 '<' => "<",
987 '"' => """,
989 '\t' => "	",
992 '\n' => "
",
993 '\r' => "
",
994 c if is_forbidden_char(c) => {
995 return Err(SerializeError::InvalidChar {
996 code_point: c as u32,
997 context: "attribute value",
998 })
999 }
1000 _ => continue,
1001 };
1002 out.write_all(&value.as_bytes()[written..offset])?;
1003 out.write_all(escape.as_bytes())?;
1004 written = offset + ch.len_utf8();
1005 }
1006 out.write_all(&value.as_bytes()[written..])?;
1007 Ok(())
1008}
1009
1010fn check_chars(text: &str, context: &'static str) -> Result<(), SerializeError> {
1013 match text.chars().find(|&c| is_forbidden_char(c)) {
1014 Some(c) => Err(SerializeError::InvalidChar {
1015 code_point: c as u32,
1016 context,
1017 }),
1018 None => Ok(()),
1019 }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024 use super::*;
1025 use crate::document::{BufferDocument, BufferDocumentBuilder, BufferDocumentOptions};
1026 use crate::namespace::NameTable;
1027 use crate::navigator::RoXmlNavigator;
1028 use bumpalo::Bump;
1029
1030 fn round(xml: &str) -> String {
1032 let arena = Bump::new();
1033 let names = NameTable::new();
1034 let doc = BufferDocument::from_reader_default(xml.as_bytes(), &arena, &names)
1035 .expect("the fixture parses");
1036 to_string(&doc.create_navigator(), &SerializeOptions::default()).expect("serializes")
1037 }
1038
1039 fn round_roxml(xml: &str) -> String {
1041 let doc = roxmltree::Document::parse(xml).expect("the fixture parses");
1042 to_string(&RoXmlNavigator::new(&doc), &SerializeOptions::default()).expect("serializes")
1043 }
1044
1045 fn indented(width: usize) -> SerializeOptions {
1047 SerializeOptions {
1048 indent: Some(width),
1049 ..SerializeOptions::default()
1050 }
1051 }
1052
1053 fn round_with(xml: &str, opts: &SerializeOptions) -> String {
1055 let arena = Bump::new();
1056 let names = NameTable::new();
1057 let doc = BufferDocument::from_reader_default(xml.as_bytes(), &arena, &names)
1058 .expect("the fixture parses");
1059 to_string(&doc.create_navigator(), opts).expect("serializes")
1060 }
1061
1062 fn round_roxml_with(xml: &str, opts: &SerializeOptions) -> String {
1064 let doc = roxmltree::Document::parse(xml).expect("the fixture parses");
1065 to_string(&RoXmlNavigator::new(&doc), opts).expect("serializes")
1066 }
1067
1068 fn round_subtree(xml: &str, descend: usize, opts: &SerializeOptions) -> String {
1071 let arena = Bump::new();
1072 let names = NameTable::new();
1073 let doc = BufferDocument::from_reader_default(xml.as_bytes(), &arena, &names)
1074 .expect("the fixture parses");
1075 let mut nav = doc.create_navigator();
1076 for _ in 0..descend {
1077 assert!(nav.move_to_first_child(), "not that deep");
1078 }
1079 to_string(&nav, opts).expect("serializes")
1080 }
1081
1082 fn built<F>(f: F) -> Result<String, SerializeError>
1084 where
1085 F: FnOnce(&mut BufferDocumentBuilder<'_>),
1086 {
1087 let arena = Bump::new();
1088 let names = NameTable::new();
1089 let mut builder =
1090 BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())
1091 .expect("builder");
1092 f(&mut builder);
1093 let doc = builder.finalize().expect("finalize");
1094 to_string(&doc.create_navigator(), &SerializeOptions::default())
1095 }
1096
1097 #[test]
1100 fn text_escapes_ampersand_lt_and_gt() {
1101 assert_eq!(
1104 round("<a>& < > ]]> ' \"</a>"),
1105 "<a>& < > ]]> ' \"</a>"
1106 );
1107 }
1108
1109 #[test]
1110 fn text_escapes_carriage_return_only() {
1111 let out = built(|b| {
1114 b.start_element("a", "", "", &[]).unwrap();
1115 b.end_of_attributes();
1116 b.text("x\ry\tz\nw");
1117 b.end_element().unwrap();
1118 })
1119 .expect("serializes");
1120 assert_eq!(out, "<a>x
y\tz\nw</a>");
1121 }
1122
1123 #[test]
1124 fn attribute_escapes_quote_lt_and_ampersand_but_not_gt() {
1125 assert_eq!(
1126 round(r#"<a k="& < > " '"/>"#),
1127 r#"<a k="& < > " '"/>"#
1128 );
1129 }
1130
1131 #[test]
1132 fn attribute_escapes_all_three_whitespace_characters() {
1133 let out = built(|b| {
1136 b.start_element("a", "", "", &[]).unwrap();
1137 b.attribute("k", "", "", "x\ty\nz\rw").unwrap();
1138 b.end_of_attributes();
1139 b.end_element().unwrap();
1140 })
1141 .expect("serializes");
1142 assert_eq!(out, r#"<a k="x	y
z
w"/>"#);
1143 let doc = roxmltree::Document::parse(&out).expect("output parses");
1145 assert_eq!(doc.root_element().attribute("k"), Some("x\ty\nz\rw"));
1146 }
1147
1148 #[test]
1149 fn text_and_attribute_escaping_differ_only_where_specified() {
1150 assert_eq!(round(r#"<a k=">">></a>"#), r#"<a k=">">></a>"#);
1152 }
1153
1154 #[test]
1157 fn forbidden_character_in_text_is_an_error() {
1158 let err = built(|b| {
1159 b.start_element("a", "", "", &[]).unwrap();
1160 b.end_of_attributes();
1161 b.text("x\u{1}y");
1162 b.end_element().unwrap();
1163 })
1164 .expect_err("U+0001 is not an XML 1.0 Char");
1165 assert!(matches!(
1166 err,
1167 SerializeError::InvalidChar {
1168 code_point: 1,
1169 context: "text"
1170 }
1171 ));
1172 }
1173
1174 #[test]
1175 fn forbidden_character_in_attribute_value_is_an_error() {
1176 let err = built(|b| {
1177 b.start_element("a", "", "", &[]).unwrap();
1178 b.attribute("k", "", "", "\u{FFFF}").unwrap();
1179 b.end_of_attributes();
1180 b.end_element().unwrap();
1181 })
1182 .expect_err("U+FFFF is not an XML 1.0 Char");
1183 assert!(matches!(
1184 err,
1185 SerializeError::InvalidChar {
1186 code_point: 0xFFFF,
1187 context: "attribute value"
1188 }
1189 ));
1190 }
1191
1192 #[test]
1193 fn forbidden_character_in_name_is_an_error() {
1194 let err = built(|b| {
1195 b.start_element("a\u{b}b", "", "", &[]).unwrap();
1196 b.end_of_attributes();
1197 b.end_element().unwrap();
1198 })
1199 .expect_err("U+000B is not an XML 1.0 Char");
1200 assert!(matches!(
1201 err,
1202 SerializeError::InvalidChar {
1203 code_point: 0xB,
1204 context: "name"
1205 }
1206 ));
1207 }
1208
1209 #[test]
1210 fn comment_with_double_hyphen_is_an_error() {
1211 let err = built(|b| {
1212 b.start_element("a", "", "", &[]).unwrap();
1213 b.end_of_attributes();
1214 b.comment("x--y").unwrap();
1215 b.end_element().unwrap();
1216 })
1217 .expect_err("XML 1.0 §2.5 forbids `--` inside a comment");
1218 assert!(matches!(err, SerializeError::InvalidComment(s) if s == "x--y"));
1219 }
1220
1221 #[test]
1222 fn comment_ending_in_hyphen_is_an_error() {
1223 let err = built(|b| {
1224 b.start_element("a", "", "", &[]).unwrap();
1225 b.end_of_attributes();
1226 b.comment("x-").unwrap();
1227 b.end_element().unwrap();
1228 })
1229 .expect_err("XML 1.0 §2.5 forbids a comment ending in `-`");
1230 assert!(matches!(err, SerializeError::InvalidComment(s) if s == "x-"));
1231 }
1232
1233 #[test]
1234 fn forbidden_character_in_comment_is_an_error() {
1235 let err = built(|b| {
1236 b.start_element("a", "", "", &[]).unwrap();
1237 b.end_of_attributes();
1238 b.comment("x\u{0}y").unwrap();
1239 b.end_element().unwrap();
1240 })
1241 .expect_err("NUL is not an XML 1.0 Char");
1242 assert!(matches!(
1243 err,
1244 SerializeError::InvalidChar {
1245 code_point: 0,
1246 context: "comment"
1247 }
1248 ));
1249 }
1250
1251 #[test]
1252 fn reserved_pi_target_is_an_error() {
1253 for target in ["xml", "XML", "xMl"] {
1254 let err = built(|b| {
1255 b.start_element("a", "", "", &[]).unwrap();
1256 b.end_of_attributes();
1257 b.processing_instruction(target, "x").unwrap();
1258 b.end_element().unwrap();
1259 })
1260 .expect_err("XML 1.0 §2.6 reserves the target `xml`");
1261 assert!(
1262 matches!(&err, SerializeError::InvalidPi { target: t, .. } if t == target),
1263 "{err:?}"
1264 );
1265 }
1266 }
1267
1268 #[test]
1269 fn pi_data_containing_the_close_delimiter_is_an_error() {
1270 let err = built(|b| {
1271 b.start_element("a", "", "", &[]).unwrap();
1272 b.end_of_attributes();
1273 b.processing_instruction("go", "x?>y").unwrap();
1274 b.end_element().unwrap();
1275 })
1276 .expect_err("PI data cannot contain `?>`");
1277 assert!(matches!(
1278 err,
1279 SerializeError::InvalidPi {
1280 reason: "the data contains `?>`",
1281 ..
1282 }
1283 ));
1284 }
1285
1286 #[test]
1287 fn unbound_element_prefix_is_an_error() {
1288 let err = built(|b| {
1290 b.start_element("x", "urn:x", "p", &[]).unwrap();
1291 b.end_of_attributes();
1292 b.end_element().unwrap();
1293 })
1294 .expect_err("prefix `p` is not declared anywhere");
1295 assert!(matches!(err, SerializeError::UnboundName { prefix, uri }
1296 if prefix == "p" && uri == "urn:x"));
1297 }
1298
1299 #[test]
1300 fn unbound_attribute_prefix_is_an_error() {
1301 let err = built(|b| {
1302 b.start_element("a", "", "", &[]).unwrap();
1303 b.attribute("k", "urn:x", "p", "v").unwrap();
1304 b.end_of_attributes();
1305 b.end_element().unwrap();
1306 })
1307 .expect_err("prefix `p` is not declared anywhere");
1308 assert!(matches!(err, SerializeError::UnboundName { prefix, .. } if prefix == "p"));
1309 }
1310
1311 #[test]
1312 fn unprefixed_attribute_in_a_namespace_is_an_error() {
1313 let err = built(|b| {
1316 b.start_element("a", "urn:d", "", &[("", "urn:d")]).unwrap();
1317 b.attribute("k", "urn:d", "", "v").unwrap();
1318 b.end_of_attributes();
1319 b.end_element().unwrap();
1320 })
1321 .expect_err("an unprefixed attribute cannot be in a namespace");
1322 assert!(matches!(err, SerializeError::UnboundName { prefix, uri }
1323 if prefix.is_empty() && uri == "urn:d"));
1324 }
1325
1326 #[test]
1327 fn the_xml_prefix_needs_no_declaration() {
1328 assert_eq!(round(r#"<a xml:lang="en"/>"#), r#"<a xml:lang="en"/>"#);
1331 }
1332
1333 #[test]
1334 fn attribute_node_is_not_serializable() {
1335 let doc = roxmltree::Document::parse(r#"<a k="v"/>"#).expect("parses");
1336 let mut nav = RoXmlNavigator::new(&doc);
1337 assert!(nav.move_to_first_child());
1338 assert!(nav.move_to_first_attribute());
1339 let err = to_string(&nav, &SerializeOptions::default()).expect_err("attribute is refused");
1340 assert!(matches!(
1341 err,
1342 SerializeError::NotSerializable(DomNodeType::Attribute)
1343 ));
1344 }
1345
1346 #[test]
1347 fn namespace_node_is_not_serializable() {
1348 let doc = roxmltree::Document::parse(r#"<a xmlns:p="urn:x"/>"#).expect("parses");
1349 let mut nav = RoXmlNavigator::new(&doc);
1350 assert!(nav.move_to_first_child());
1351 assert!(nav.move_to_first_namespace(NamespaceAxisScope::ExcludeXml));
1352 let err = to_string(&nav, &SerializeOptions::default()).expect_err("namespace is refused");
1353 assert!(matches!(
1354 err,
1355 SerializeError::NotSerializable(DomNodeType::Namespace)
1356 ));
1357 }
1358
1359 #[test]
1362 fn redundant_redeclaration_is_dropped() {
1363 assert_eq!(
1366 round(r#"<p:a xmlns:p="urn:x"><p:b xmlns:p="urn:x"/></p:a>"#),
1367 r#"<p:a xmlns:p="urn:x"><p:b/></p:a>"#
1368 );
1369 }
1370
1371 #[test]
1372 fn shadowing_redeclaration_is_kept() {
1373 assert_eq!(
1374 round(r#"<p:a xmlns:p="urn:x"><p:b xmlns:p="urn:y"/></p:a>"#),
1375 r#"<p:a xmlns:p="urn:x"><p:b xmlns:p="urn:y"/></p:a>"#
1376 );
1377 }
1378
1379 #[test]
1380 fn default_namespace_undeclaration_is_written() {
1381 assert_eq!(
1382 round(r#"<a xmlns="urn:d"><b xmlns=""><c/></b></a>"#),
1383 r#"<a xmlns="urn:d"><b xmlns=""><c/></b></a>"#
1384 );
1385 }
1386
1387 #[test]
1388 fn undeclaration_is_not_repeated_on_descendants() {
1389 let out = round(r#"<a xmlns="urn:d"><b xmlns=""><c><d/></c></b></a>"#);
1390 assert_eq!(out, r#"<a xmlns="urn:d"><b xmlns=""><c><d/></c></b></a>"#);
1391 assert_eq!(out.matches(r#"xmlns="""#).count(), 1);
1392 }
1393
1394 #[test]
1395 fn undeclaration_is_not_written_without_a_default_namespace() {
1396 assert_eq!(round("<a><b/></a>"), "<a><b/></a>");
1397 }
1398
1399 #[test]
1400 fn subtree_gains_the_declarations_it_inherits() {
1401 let arena = Bump::new();
1402 let names = NameTable::new();
1403 let doc = BufferDocument::from_reader_default(
1404 r#"<a xmlns:p="urn:x" xmlns:q="urn:y" xmlns="urn:d"><p:b q:k="v"/></a>"#.as_bytes(),
1405 &arena,
1406 &names,
1407 )
1408 .expect("parses");
1409 let mut inner = doc.create_navigator();
1410 assert!(inner.move_to_first_child());
1411 assert!(inner.move_to_first_child());
1412
1413 let out = to_string(&inner, &SerializeOptions::default()).expect("serializes");
1414 let reparsed = roxmltree::Document::parse(&out).expect("output parses");
1417 let elem = reparsed.root_element();
1418 assert_eq!(elem.tag_name().namespace(), Some("urn:x"));
1419 assert_eq!(elem.tag_name().name(), "b");
1420 assert_eq!(elem.attribute(("urn:y", "k")), Some("v"));
1421 assert!(out.contains(r#"xmlns:p="urn:x""#), "{out}");
1422 assert!(out.contains(r#"xmlns:q="urn:y""#), "{out}");
1423 assert!(out.contains(r#"xmlns="urn:d""#), "{out}");
1424 }
1425
1426 #[test]
1427 fn declarations_come_out_in_prefix_order() {
1428 let xml = r#"<a xmlns:z="urn:z" xmlns:b="urn:b" xmlns="urn:d"/>"#;
1431 let expected = r#"<a xmlns="urn:d" xmlns:b="urn:b" xmlns:z="urn:z"/>"#;
1432 assert_eq!(round(xml), expected);
1433 assert_eq!(round_roxml(xml), expected);
1434 }
1435
1436 #[test]
1437 fn declarations_are_scoped_to_their_element() {
1438 assert_eq!(
1441 round(r#"<a><b xmlns:q="urn:y"/><c/></a>"#),
1442 r#"<a><b xmlns:q="urn:y"/><c/></a>"#
1443 );
1444 }
1445
1446 #[test]
1449 fn empty_element_is_collapsed() {
1450 assert_eq!(round("<a><b></b></a>"), "<a><b/></a>");
1451 }
1452
1453 #[test]
1454 fn pi_with_empty_data_omits_the_space() {
1455 assert_eq!(round("<a><?go?></a>"), "<a><?go?></a>");
1456 assert_eq!(round("<a><?go now?></a>"), "<a><?go now?></a>");
1457 }
1458
1459 #[test]
1460 fn comments_and_pis_around_the_document_element_are_kept() {
1461 assert_eq!(
1462 round("<!--before--><?go?><a/><?stop?><!--after-->"),
1463 "<!--before--><?go?><a/><?stop?><!--after-->"
1464 );
1465 }
1466
1467 #[test]
1468 fn mixed_content_keeps_node_order() {
1469 assert_eq!(
1470 round("<a>t1<b/>t2<!--c-->t3<?pi d?>t4</a>"),
1471 "<a>t1<b/>t2<!--c-->t3<?pi d?>t4</a>"
1472 );
1473 }
1474
1475 #[test]
1476 fn attribute_order_is_document_order() {
1477 assert_eq!(
1478 round(r#"<a z="1" m="2" a="3"/>"#),
1479 r#"<a z="1" m="2" a="3"/>"#
1480 );
1481 }
1482
1483 #[test]
1484 fn a_single_leaf_node_serializes_on_its_own() {
1485 let arena = Bump::new();
1486 let names = NameTable::new();
1487 let doc =
1488 BufferDocument::from_reader_default("<a>text<!--c--></a>".as_bytes(), &arena, &names)
1489 .expect("parses");
1490 let mut nav = doc.create_navigator();
1491 assert!(nav.move_to_first_child());
1492 assert!(nav.move_to_first_child());
1493 assert_eq!(
1494 to_string(&nav, &SerializeOptions::default()).expect("serializes"),
1495 "text"
1496 );
1497 assert!(nav.move_to_next_sibling());
1498 assert_eq!(
1499 to_string(&nav, &SerializeOptions::default()).expect("serializes"),
1500 "<!--c-->"
1501 );
1502 }
1503
1504 #[test]
1507 fn xml_declaration_is_written_on_request() {
1508 let arena = Bump::new();
1509 let names = NameTable::new();
1510 let doc =
1511 BufferDocument::from_reader_default("<a/>".as_bytes(), &arena, &names).expect("parses");
1512 let nav = doc.create_navigator();
1513
1514 let mut out = Vec::new();
1515 let opts = SerializeOptions {
1516 xml_declaration: true,
1517 standalone: None,
1518 indent: None,
1519 };
1520 serialize_document(&nav, &mut out, &opts).expect("serializes");
1521 assert_eq!(
1522 String::from_utf8(out).unwrap(),
1523 r#"<?xml version="1.0" encoding="UTF-8"?><a/>"#
1524 );
1525
1526 for (standalone, expected) in [(true, "yes"), (false, "no")] {
1527 let mut out = Vec::new();
1528 let opts = SerializeOptions {
1529 xml_declaration: true,
1530 standalone: Some(standalone),
1531 indent: None,
1532 };
1533 serialize_document(&nav, &mut out, &opts).expect("serializes");
1534 assert_eq!(
1535 String::from_utf8(out).unwrap(),
1536 format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="{expected}"?><a/>"#)
1537 );
1538 }
1539 }
1540
1541 #[test]
1542 fn no_xml_declaration_by_default() {
1543 assert_eq!(round("<a/>"), "<a/>");
1544 }
1545
1546 #[test]
1547 fn serialize_document_starts_from_the_document_root() {
1548 let arena = Bump::new();
1549 let names = NameTable::new();
1550 let doc = BufferDocument::from_reader_default("<a><b/></a>".as_bytes(), &arena, &names)
1551 .expect("parses");
1552 let mut inner = doc.create_navigator();
1553 assert!(inner.move_to_first_child());
1554 assert!(inner.move_to_first_child());
1555
1556 let mut out = Vec::new();
1557 serialize_document(&inner, &mut out, &SerializeOptions::default()).expect("serializes");
1558 assert_eq!(String::from_utf8(out).unwrap(), "<a><b/></a>");
1559 }
1560
1561 #[test]
1562 fn serialize_node_on_the_root_writes_the_document() {
1563 let arena = Bump::new();
1564 let names = NameTable::new();
1565 let doc = BufferDocument::from_reader_default("<a/><!--x-->".as_bytes(), &arena, &names)
1566 .expect("parses");
1567 assert_eq!(round("<a/><!--x-->"), "<a/><!--x-->");
1568 assert_eq!(doc.create_navigator().node_type(), DomNodeType::Root);
1569 }
1570
1571 #[test]
1574 fn both_backends_produce_identical_output() {
1575 for xml in [
1578 "<a/>",
1579 "<a>t1<b/>t2<!--c--><?pi d?></a>",
1580 r#"<a z="1" m="2"/>"#,
1581 r#"<p:a xmlns:p="urn:x" xmlns="urn:d"><p:b p:k="v"><c/></p:b></a>"#
1582 .replace("</a>", "</p:a>")
1583 .as_str(),
1584 r#"<a xmlns="urn:d"><b xmlns=""/></a>"#,
1585 r#"<a xml:lang="en">&<></a>"#,
1586 "<!--before--><a/><!--after-->",
1587 ] {
1588 assert_eq!(round(xml), round_roxml(xml), "backends differ on {xml}");
1589 }
1590 }
1591
1592 #[test]
1593 fn deep_nesting_does_not_recurse() {
1594 let depth = 50_000;
1597 let mut xml = String::new();
1598 for _ in 0..depth {
1599 xml.push_str("<a>");
1600 }
1601 for _ in 0..depth {
1602 xml.push_str("</a>");
1603 }
1604 let expected = format!(
1606 "{}<a/>{}",
1607 "<a>".repeat(depth - 1),
1608 "</a>".repeat(depth - 1)
1609 );
1610 assert_eq!(round(&xml), expected);
1611 }
1612
1613 #[test]
1614 fn both_backends_report_pi_data() {
1615 assert_eq!(round("<a><?pi d?></a>"), "<a><?pi d?></a>");
1618 assert_eq!(round_roxml("<a><?pi d?></a>"), "<a><?pi d?></a>");
1619 assert_eq!(round("<a><?pi d ?></a>"), "<a><?pi d ?></a>");
1621 assert_eq!(round_roxml("<a><?pi d ?></a>"), "<a><?pi d ?></a>");
1622 }
1623
1624 #[test]
1627 fn compact_is_the_default_and_adds_nothing() {
1628 assert_eq!(SerializeOptions::default().indent, None);
1629 assert_eq!(round("<a><b><c/></b></a>"), "<a><b><c/></b></a>");
1630 }
1631
1632 #[test]
1633 fn compact_mode_is_not_a_minifier() {
1634 assert_eq!(round("<a> <b/> </a>"), "<a> <b/> </a>");
1636 assert_eq!(round("<a>\n <b/>\n</a>"), "<a>\n <b/>\n</a>");
1637 }
1638
1639 #[test]
1640 fn the_catalog_example_writes_both_ways() {
1641 let arena = Bump::new();
1643 let names = NameTable::new();
1644 let mut builder =
1645 BufferDocumentBuilder::new(&arena, &names, None, BufferDocumentOptions::default())
1646 .expect("builder");
1647 builder.start_element("catalog", "", "", &[]).unwrap();
1648 builder.end_of_attributes();
1649 for (id, title) in [("b1", "One"), ("b2", "Two")] {
1650 builder.start_element("book", "", "", &[]).unwrap();
1651 builder.attribute("id", "", "", id).unwrap();
1652 builder.end_of_attributes();
1653 builder.start_element("title", "", "", &[]).unwrap();
1654 builder.end_of_attributes();
1655 builder.text(title);
1656 builder.end_element().unwrap();
1657 builder.end_element().unwrap();
1658 }
1659 builder.end_element().unwrap();
1660 let doc = builder.finalize().expect("finalize");
1661 let nav = doc.create_navigator();
1662
1663 assert_eq!(
1664 to_string(&nav, &SerializeOptions::default()).expect("serializes"),
1665 "<catalog><book id=\"b1\"><title>One</title></book>\
1666 <book id=\"b2\"><title>Two</title></book></catalog>"
1667 );
1668 assert_eq!(
1669 to_string(&nav, &indented(2)).expect("serializes"),
1670 "<catalog>\n \
1671 <book id=\"b1\">\n \
1672 <title>One</title>\n \
1673 </book>\n \
1674 <book id=\"b2\">\n \
1675 <title>Two</title>\n \
1676 </book>\n\
1677 </catalog>"
1678 );
1679 }
1680
1681 #[test]
1682 fn indentation_width_zero_writes_breaks_only() {
1683 assert_eq!(
1684 round_with("<a><b><c/></b></a>", &indented(0)),
1685 "<a>\n<b>\n<c/>\n</b>\n</a>"
1686 );
1687 }
1688
1689 #[test]
1690 fn indentation_width_two_and_four_nest_per_depth() {
1691 assert_eq!(
1692 round_with("<a><b><c/></b></a>", &indented(2)),
1693 "<a>\n <b>\n <c/>\n </b>\n</a>"
1694 );
1695 assert_eq!(
1696 round_with("<a><b><c/></b></a>", &indented(4)),
1697 "<a>\n <b>\n <c/>\n </b>\n</a>"
1698 );
1699 }
1700
1701 #[test]
1702 fn empty_elements_stay_collapsed_when_formatted() {
1703 assert_eq!(
1704 round_with("<a><b/><c></c></a>", &indented(2)),
1705 "<a>\n <b/>\n <c/>\n</a>"
1706 );
1707 assert_eq!(round_with("<a/>", &indented(2)), "<a/>");
1708 }
1709
1710 #[test]
1711 fn formatted_output_with_and_without_the_declaration() {
1712 let with_declaration = SerializeOptions {
1713 xml_declaration: true,
1714 standalone: None,
1715 indent: Some(2),
1716 };
1717 assert_eq!(
1719 round_with("<a><b/></a>", &with_declaration),
1720 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a>\n <b/>\n</a>"
1721 );
1722 assert_eq!(
1724 round_with("<!--c--><a/>", &with_declaration),
1725 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!--c-->\n<a/>"
1726 );
1727 assert_eq!(round_with("<a><b/></a>", &indented(2)), "<a>\n <b/>\n</a>");
1729 }
1730
1731 #[test]
1732 fn document_level_comments_and_pis_when_formatted() {
1733 assert_eq!(
1736 round_with("<!--before--><?go?><a/><?stop?><!--after-->", &indented(2)),
1737 "<!--before--><?go?>\n<a/>\n<?stop?><!--after-->"
1738 );
1739 }
1740
1741 #[test]
1742 fn comments_and_pis_inside_an_element_when_formatted() {
1743 assert_eq!(
1744 round_with("<a><!--c--><b/><?pi d?></a>", &indented(2)),
1745 "<a><!--c-->\n <b/>\n <?pi d?></a>"
1746 );
1747 assert_eq!(
1749 round_with("<a><!--c--><!--d--></a>", &indented(2)),
1750 "<a><!--c--><!--d--></a>"
1751 );
1752 }
1753
1754 #[test]
1755 fn standalone_nodes_get_no_layout() {
1756 let arena = Bump::new();
1757 let names = NameTable::new();
1758 let doc = BufferDocument::from_reader_default(
1759 "<a>text<!--c--><?go d?></a>".as_bytes(),
1760 &arena,
1761 &names,
1762 )
1763 .expect("parses");
1764 let mut nav = doc.create_navigator();
1765 assert!(nav.move_to_first_child());
1766 assert!(nav.move_to_first_child());
1767 for expected in ["text", "<!--c-->", "<?go d?>"] {
1768 assert_eq!(to_string(&nav, &indented(2)).expect("serializes"), expected);
1769 nav.move_to_next_sibling();
1770 }
1771 }
1772
1773 #[test]
1774 fn a_subtree_is_formatted_from_depth_zero() {
1775 assert_eq!(
1776 round_subtree("<r><box><a/></box></r>", 2, &indented(2)),
1777 "<box>\n <a/>\n</box>"
1778 );
1779 }
1780
1781 #[test]
1782 fn text_anywhere_in_a_container_suppresses_layout() {
1783 for xml in [
1786 "<p>Hello <b>world</b>!</p>",
1787 "<p><b>world</b>!</p>",
1788 "<p><b/>tail</p>",
1789 ] {
1790 assert_eq!(round_with(xml, &indented(2)), xml, "{xml}");
1791 }
1792 assert_eq!(
1794 round_with("<p>t<b><c/></b></p>", &indented(2)),
1795 "<p>t<b><c/></b></p>"
1796 );
1797 assert_eq!(
1799 round_with("<r><p>t</p><q><c/></q></r>", &indented(2)),
1800 "<r>\n <p>t</p>\n <q>\n <c/>\n </q>\n</r>"
1801 );
1802 }
1803
1804 #[test]
1805 fn whitespace_only_text_is_preserved_and_suppresses_layout() {
1806 assert_eq!(round_with("<p> <b/> </p>", &indented(2)), "<p> <b/> </p>");
1807 }
1808
1809 #[test]
1810 fn formatting_does_not_reindent_existing_layout() {
1811 let xml = "<a>\n <b/>\n</a>";
1814 assert_eq!(round_with(xml, &indented(2)), xml);
1815 }
1816
1817 #[test]
1818 fn xml_space_preserve_disables_added_layout() {
1819 let xml = "<pre xml:space=\"preserve\"><a/><b/></pre>";
1820 assert_eq!(round_with(xml, &indented(2)), xml);
1821 let xml = "<pre xml:space=\"preserve\"><a><b/></a></pre>";
1823 assert_eq!(round_with(xml, &indented(2)), xml);
1824 }
1825
1826 #[test]
1827 fn a_descendant_xml_space_default_restores_layout() {
1828 assert_eq!(
1829 round_with(
1830 "<r xml:space=\"preserve\"><a><b xml:space=\"default\"><c/></b></a></r>",
1831 &indented(2)
1832 ),
1833 "<r xml:space=\"preserve\"><a><b xml:space=\"default\">\n <c/>\n </b></a></r>"
1834 );
1835 }
1836
1837 #[test]
1838 fn an_attached_subtree_inherits_xml_space_from_its_ancestors() {
1839 assert_eq!(
1842 round_subtree(
1843 "<r xml:space=\"preserve\"><box><a/><b/></box></r>",
1844 2,
1845 &indented(2)
1846 ),
1847 "<box><a/><b/></box>"
1848 );
1849 assert_eq!(
1851 round_subtree(
1852 "<r xml:space=\"preserve\"><m xml:space=\"default\"><box><a/></box></m></r>",
1853 3,
1854 &indented(2)
1855 ),
1856 "<box>\n <a/>\n</box>"
1857 );
1858 assert_eq!(
1860 round_subtree("<r><box><a/><b/></box></r>", 2, &indented(2)),
1861 "<box>\n <a/>\n <b/>\n</box>"
1862 );
1863 }
1864
1865 #[test]
1866 fn string_and_writer_output_are_the_same_bytes() {
1867 let arena = Bump::new();
1868 let names = NameTable::new();
1869 let doc = BufferDocument::from_reader_default(
1870 "<a><b k=\"v\"><c/></b><!--x--></a>".as_bytes(),
1871 &arena,
1872 &names,
1873 )
1874 .expect("parses");
1875 let nav = doc.create_navigator();
1876 for opts in [SerializeOptions::default(), indented(0), indented(3)] {
1877 let string = to_string(&nav, &opts).expect("serializes");
1878 let mut bytes = Vec::new();
1879 serialize_node(&nav, &mut bytes, &opts).expect("serializes");
1880 assert_eq!(string.as_bytes(), bytes.as_slice());
1881 let mut document_bytes = Vec::new();
1882 serialize_document(&nav, &mut document_bytes, &opts).expect("serializes");
1883 assert_eq!(string.as_bytes(), document_bytes.as_slice());
1884 }
1885 }
1886
1887 #[test]
1888 fn serializing_leaves_the_source_tree_unchanged() {
1889 let arena = Bump::new();
1890 let names = NameTable::new();
1891 let doc =
1892 BufferDocument::from_reader_default("<a><b>t</b><c/></a>".as_bytes(), &arena, &names)
1893 .expect("parses");
1894 let nav = doc.create_navigator();
1895 let before = to_string(&nav, &SerializeOptions::default()).expect("serializes");
1896 let _ = to_string(&nav, &indented(4)).expect("serializes");
1897 let after = to_string(&nav, &SerializeOptions::default()).expect("serializes");
1898 assert_eq!(before, after);
1899 assert_eq!(after, "<a><b>t</b><c/></a>");
1900 }
1901
1902 #[test]
1903 fn formatted_output_reparses_with_its_content_intact() {
1904 let formatted = round_with(
1905 "<catalog><book id=\"b1\"><title>One</title></book></catalog>",
1906 &indented(2),
1907 );
1908 let doc = roxmltree::Document::parse(&formatted).expect("output parses");
1909 let catalog = doc.root_element();
1910 assert_eq!(catalog.tag_name().name(), "catalog");
1911
1912 let catalog_text: Vec<&str> = catalog
1915 .children()
1916 .filter(|n| n.is_text())
1917 .map(|n| n.text().unwrap_or(""))
1918 .collect();
1919 assert_eq!(catalog_text, vec!["\n ", "\n"]);
1920
1921 let book = catalog
1922 .children()
1923 .find(|n| n.is_element())
1924 .expect("the book survived");
1925 assert_eq!(book.tag_name().name(), "book");
1926 assert_eq!(book.attribute("id"), Some("b1"));
1927 let book_text: Vec<&str> = book
1928 .children()
1929 .filter(|n| n.is_text())
1930 .map(|n| n.text().unwrap_or(""))
1931 .collect();
1932 assert_eq!(book_text, vec!["\n ", "\n "]);
1933
1934 let title = book
1936 .children()
1937 .find(|n| n.is_element())
1938 .expect("the title survived");
1939 assert_eq!(title.text(), Some("One"));
1940 assert_eq!(title.children().count(), 1);
1941 }
1942
1943 #[test]
1944 fn both_backends_format_identically() {
1945 for xml in [
1946 "<a><b><c/></b></a>",
1947 "<a><!--c--><b/><?pi d?></a>",
1948 "<p>Hello <b>world</b>!</p>",
1949 "<pre xml:space=\"preserve\"><a/><b/></pre>",
1950 "<r xml:space=\"preserve\"><a><b xml:space=\"default\"><c/></b></a></r>",
1951 "<!--before--><a><b/></a><!--after-->",
1952 ] {
1953 assert_eq!(
1954 round_with(xml, &indented(2)),
1955 round_roxml_with(xml, &indented(2)),
1956 "backends differ on {xml}"
1957 );
1958 }
1959 }
1960}