Skip to main content

xsd_schema/document/
serialize.rs

1//! Writing a navigable XML tree back out as XML text.
2//!
3//! [`BufferDocument`](super::BufferDocument) and the read-only roxmltree adapter
4//! can both be navigated, but neither could be *written*. This module closes that
5//! gap for every backend at once: it is generic over
6//! [`DomNavigator`] and uses nothing but
7//! navigation plus the node's name and string value, so the same code serializes
8//! a `BufferDocNavigator`, a `RoXmlNavigator`, and any navigator a host embedding
9//! the engine supplies of its own.
10//!
11//! ```
12//! use bumpalo::Bump;
13//! use xsd_schema::document::{serialize, BufferDocument};
14//! use xsd_schema::namespace::NameTable;
15//!
16//! let arena = Bump::new();
17//! let names = NameTable::new();
18//! let doc = BufferDocument::from_reader_default(
19//!     r#"<p:a xmlns:p="urn:x"><p:b k="1">t</p:b><!--c--></p:a>"#.as_bytes(),
20//!     &arena,
21//!     &names,
22//! )?;
23//!
24//! let xml = serialize::to_string(&doc.create_navigator(), &Default::default())?;
25//! assert_eq!(xml, r#"<p:a xmlns:p="urn:x"><p:b k="1">t</p:b><!--c--></p:a>"#);
26//! # Ok::<(), Box<dyn std::error::Error>>(())
27//! ```
28//!
29//! # What the output looks like
30//!
31//! Output is UTF-8 bytes. By default nothing is added: the serializer writes
32//! exactly the nodes of the tree, so `parse → serialize → parse` yields the same
33//! tree again. Empty elements are always collapsed to `<a/>`.
34//!
35//! Escaping follows the rules of *Canonical XML 1.0* §2.3 ("Processing Model",
36//! its *Text Nodes* and *Attribute Nodes* items), because those are the rules
37//! designed so that a re-parse cannot change the value back: without them XML
38//! 1.0's end-of-line handling (§2.11) and attribute-value normalization (§3.3.3)
39//! would silently rewrite literal carriage returns and attribute whitespace.
40//!
41//! | Context | Character | Written as |
42//! |---|---|---|
43//! | text | `&` `<` `>` | `&amp;` `&lt;` `&gt;` (`>` always, which covers the `]]>` rule of XML 1.0 §2.4 without scanning) |
44//! | text | U+000D | `&#xD;` |
45//! | attribute value (always `"`-quoted) | `&` `<` `"` | `&amp;` `&lt;` `&quot;` |
46//! | attribute value | U+0009 U+000A U+000D | `&#x9;` `&#xA;` `&#xD;` |
47//! | comment, PI target, PI data, names | nothing | — |
48//!
49//! This is an escaping policy, not an implementation of Canonical XML: nothing
50//! here sorts attributes, normalizes namespace declarations or expands empty
51//! elements.
52//!
53//! # What is refused
54//!
55//! A tree parsed from XML cannot hold content that XML cannot express, but a
56//! tree built programmatically can. Such content is never dropped or mangled —
57//! it is an error:
58//!
59//! * a character outside the XML 1.0 `Char` production (C0 controls other than
60//!   tab, LF and CR; U+FFFE; U+FFFF) anywhere, including in names
61//!   ([`SerializeError::InvalidChar`]);
62//! * a comment containing `--` or ending in `-`, XML 1.0 §2.5
63//!   ([`SerializeError::InvalidComment`]);
64//! * a processing instruction whose target is `xml` in any case, or whose data
65//!   contains `?>`, XML 1.0 §2.6 ([`SerializeError::InvalidPi`]);
66//! * an element or attribute whose prefix is not bound to its namespace URI in
67//!   the scope the output creates ([`SerializeError::UnboundName`]).
68//!
69//! Out of scope for this module: other encodings, CDATA sections and a doctype
70//! declaration.
71//!
72//! # Compact and formatted output
73//!
74//! [`SerializeOptions::indent`] chooses between the two modes. `None`, the
75//! default, is *compact*: no layout whitespace is added — and none is removed,
76//! so it is the mode for an exact text round trip. `Some(n)` is *formatted*: a
77//! line break plus `n` spaces per level wherever the contract below permits one
78//! (`Some(0)` gives the breaks without the spaces).
79//!
80//! ```
81//! use bumpalo::Bump;
82//! use xsd_schema::document::{serialize, BufferDocument, SerializeOptions};
83//! use xsd_schema::namespace::NameTable;
84//!
85//! let arena = Bump::new();
86//! let names = NameTable::new();
87//! let doc = BufferDocument::from_reader_default(
88//!     "<catalog><book id=\"b1\"><title>One</title></book></catalog>".as_bytes(),
89//!     &arena,
90//!     &names,
91//! )?;
92//! let nav = doc.create_navigator();
93//!
94//! let formatted = SerializeOptions { indent: Some(2), ..Default::default() };
95//! assert_eq!(
96//!     serialize::to_string(&nav, &formatted)?,
97//!     "<catalog>\n  <book id=\"b1\">\n    <title>One</title>\n  </book>\n</catalog>",
98//! );
99//!
100//! // The same tree, no layout added, nothing rebuilt.
101//! assert_eq!(
102//!     serialize::to_string(&nav, &Default::default())?,
103//!     "<catalog><book id=\"b1\"><title>One</title></book></catalog>",
104//! );
105//! # Ok::<(), Box<dyn std::error::Error>>(())
106//! ```
107//!
108//! Line breaks are LF on every platform, the outermost element sits at depth 0
109//! (a subtree written on its own included), attributes stay on the start-tag
110//! line, an empty element stays `<a/>`, and no trailing newline is written.
111//! Whether a declaration is written is independent of the mode.
112//!
113//! ## Whitespace contract
114//!
115//! Formatted output must not change what the document says, so layout is added
116//! conservatively:
117//!
118//! 1. **Every existing text character survives, in both modes**, whitespace-only
119//!    text included. Before formatting a container, *all* of its direct children
120//!    are inspected: any text child suppresses added layout throughout that
121//!    container's subtree. So `<p>Hello <b>world</b>!</p>` and
122//!    `<p><b>world</b>!</p>` both stay on one line, and existing indentation is
123//!    kept rather than rewritten.
124//! 2. **A break goes only at a child boundary next to an element**: before an
125//!    element child at the child's depth, before the closing tag at the
126//!    container's depth when the last child is an element, and between siblings
127//!    when either one is an element. A run of comments and processing
128//!    instructions is never split internally, and nothing is ever added inside
129//!    text, a comment, PI data, an attribute value or an empty element.
130//! 3. **`xml:space` is honoured** (XML 1.0 §2.10, read by its expanded
131//!    XML-namespace name): `preserve` turns added layout off for that element and
132//!    is inherited; a descendant `default` turns it back on for its own content,
133//!    unless rule 1 still suppresses it. A subtree serialized on its own consults
134//!    its ancestors for the inherited value without inventing an attribute.
135//! 4. **At document level** the same rules apply at depth 0. A declaration
136//!    immediately followed by the document element gets a break between them; a
137//!    declaration followed by a comment or PI does not. No leading blank line and
138//!    no final newline are invented, and a standalone text, comment or PI node
139//!    gets no layout at all.
140//!
141//! Formatted output therefore adds whitespace *text nodes* to a reparsed
142//! document, which can change string values and text-node counts: compact mode
143//! is the contract for exact round trips, formatted mode is a presentation
144//! choice. Tabs, other line endings and line wrapping are out of scope.
145//!
146//! # Namespace declarations
147//!
148//! Declarations are written where they are *introduced*, computed by comparing
149//! each element's in-scope bindings (the `namespace::` axis, minus `xml`) with
150//! the scope the output has already established — see [`serialize_node`] for
151//! what that means for a subtree. A declaration that only repeats what is
152//! already in scope is dropped; an element that leaves an inherited default
153//! namespace gets `xmlns=""`. On one element the declarations come out in
154//! prefix order, the default namespace first, because the axis itself has no
155//! order to preserve.
156
157use std::io::Write;
158
159use crate::namespace::XML_NAMESPACE;
160use crate::navigator::{DomNavigator, DomNodeType, NamespaceAxisScope};
161
162/// Options controlling XML output.
163///
164/// The default writes no XML declaration, which is what a host wants when the
165/// result is embedded in something larger; turn it on for a standalone file.
166///
167/// ```
168/// use xsd_schema::document::SerializeOptions;
169///
170/// let embedded = SerializeOptions::default();
171/// assert!(!embedded.xml_declaration);
172///
173/// let file = SerializeOptions {
174///     xml_declaration: true,
175///     standalone: Some(true),
176///     indent: Some(2),
177/// };
178/// assert_eq!(file.standalone, Some(true));
179/// ```
180#[derive(Clone, Debug, Default)]
181pub struct SerializeOptions {
182    /// Write `<?xml version="1.0" encoding="UTF-8"?>` before a document.
183    ///
184    /// The declaration is written by [`serialize_document`], and by
185    /// [`serialize_node`] on a document (`Root`) node; a node written on its own
186    /// is a fragment and never gets one.
187    pub xml_declaration: bool,
188    /// Adds ` standalone="yes"` / ` standalone="no"` to that declaration.
189    ///
190    /// Ignored when `xml_declaration` is `false`.
191    pub standalone: Option<bool>,
192    /// `None` — the default — writes no layout whitespace. `Some(n)` writes a
193    /// line break plus `n` spaces per level where the whitespace contract
194    /// allows one; `Some(0)` writes the line breaks alone.
195    ///
196    /// `None` is not a minifier: it adds no whitespace and removes none, which
197    /// is what makes it the mode for an exact text round trip. Breaks are LF on
198    /// every platform, the outermost element sits at depth 0 (a subtree
199    /// included), and no trailing newline is written. See the module docs for
200    /// the rules on where a break may go.
201    pub indent: Option<usize>,
202}
203
204/// Why a tree could not be written as XML.
205///
206/// Every variant but [`Io`](SerializeError::Io) reports content that no
207/// well-formed XML document can hold, so it is reported rather than silently
208/// repaired; repairing names is the job of the code that builds the tree.
209///
210/// ```
211/// use xsd_schema::document::{serialize, SerializeError};
212/// use xsd_schema::navigator::{DomNavigator, RoXmlNavigator};
213///
214/// // An attribute is not a tree, so it cannot be written on its own.
215/// let doc = roxmltree::Document::parse(r#"<a k="v"/>"#)?;
216/// let mut attr = RoXmlNavigator::new(&doc);
217/// attr.move_to_first_child();
218/// attr.move_to_first_attribute();
219/// match serialize::to_string(&attr, &Default::default()) {
220///     Err(SerializeError::NotSerializable(kind)) => println!("refused {kind:?}"),
221///     other => panic!("expected a refusal, got {other:?}"),
222/// }
223/// # Ok::<(), Box<dyn std::error::Error>>(())
224/// ```
225#[derive(Debug, thiserror::Error)]
226pub enum SerializeError {
227    /// The writer failed.
228    #[error("failed to write XML: {0}")]
229    Io(#[from] std::io::Error),
230
231    /// A character that the XML 1.0 `Char` production does not allow, in a
232    /// place where no escape can express it either.
233    ///
234    /// `context` is one of `"text"`, `"attribute value"`, `"comment"`,
235    /// `"processing instruction"` or `"name"`.
236    #[error("U+{code_point:04X} is not an XML 1.0 Char and cannot appear in {context}")]
237    InvalidChar {
238        /// The offending Unicode scalar value.
239        code_point: u32,
240        /// Where it was found.
241        context: &'static str,
242    },
243
244    /// Comment content containing `--`, or ending in `-` (XML 1.0 §2.5).
245    #[error("comment content is not well-formed (XML 1.0 \u{a7}2.5): {0:?}")]
246    InvalidComment(String),
247
248    /// A processing instruction that XML 1.0 §2.6 does not allow.
249    #[error("processing instruction {target:?} is not well-formed (XML 1.0 \u{a7}2.6): {reason}")]
250    InvalidPi {
251        /// The PI target as found in the tree.
252        target: String,
253        /// What is wrong with it.
254        reason: &'static str,
255    },
256
257    /// An element or attribute name whose prefix is not bound to its namespace
258    /// URI in the scope the output establishes, so the written name would not
259    /// re-parse to the same expanded name.
260    #[error("prefix {prefix:?} is not bound to namespace {uri:?} in the output scope")]
261    UnboundName {
262        /// The name's prefix (empty for an unprefixed name).
263        prefix: String,
264        /// The namespace URI the node claims.
265        uri: String,
266    },
267
268    /// An attribute or namespace node was asked to serialize itself. Both are
269    /// properties of an element, not subtrees, so there is nothing to write.
270    #[error("a {0:?} node cannot be serialized on its own")]
271    NotSerializable(DomNodeType),
272}
273
274/// Writes the document containing `root`, optionally preceded by an XML
275/// declaration.
276///
277/// `root` may be positioned anywhere in the document: the serializer starts from
278/// its document root, writing every top-level node — comments and processing
279/// instructions around the document element included — in document order.
280///
281/// ```
282/// use bumpalo::Bump;
283/// use xsd_schema::document::{serialize, BufferDocument, SerializeOptions};
284/// use xsd_schema::namespace::NameTable;
285///
286/// let arena = Bump::new();
287/// let names = NameTable::new();
288/// let doc = BufferDocument::from_reader_default(
289///     "<?work now?><a/><!--after-->".as_bytes(),
290///     &arena,
291///     &names,
292/// )?;
293///
294/// let mut out = Vec::new();
295/// let opts = SerializeOptions { xml_declaration: true, ..Default::default() };
296/// serialize::serialize_document(&doc.create_navigator(), &mut out, &opts)?;
297/// assert_eq!(
298///     String::from_utf8(out)?,
299///     r#"<?xml version="1.0" encoding="UTF-8"?><?work now?><a/><!--after-->"#,
300/// );
301///
302/// // Formatted: a break lands next to the element and nowhere else.
303/// let mut out = Vec::new();
304/// let opts = SerializeOptions { xml_declaration: true, indent: Some(2), ..Default::default() };
305/// serialize::serialize_document(&doc.create_navigator(), &mut out, &opts)?;
306/// assert_eq!(
307///     String::from_utf8(out)?,
308///     "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?work now?>\n<a/>\n<!--after-->",
309/// );
310/// # Ok::<(), Box<dyn std::error::Error>>(())
311/// ```
312pub 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
324/// Writes the node at the cursor.
325///
326/// * On a document (`Root`) node this is [`serialize_document`].
327/// * On an element it writes that subtree. The element receives the namespace
328///   declarations it needs, inherited ones included, so the fragment stands on
329///   its own.
330/// * On a text, comment or processing-instruction node it writes that one node,
331///   with no layout around it even in formatted mode.
332/// * On an attribute or namespace node it is
333///   [`SerializeError::NotSerializable`].
334///
335/// ```
336/// use bumpalo::Bump;
337/// use xsd_schema::document::{serialize, BufferDocument};
338/// use xsd_schema::namespace::NameTable;
339/// use xsd_schema::navigator::DomNavigator;
340///
341/// let arena = Bump::new();
342/// let names = NameTable::new();
343/// let doc = BufferDocument::from_reader_default(
344///     r#"<a xmlns:p="urn:x"><p:b/></a>"#.as_bytes(),
345///     &arena,
346///     &names,
347/// )?;
348///
349/// let mut inner = doc.create_navigator();
350/// inner.move_to_first_child(); // <a>
351/// inner.move_to_first_child(); // <p:b>
352///
353/// // `xmlns:p` is declared on <a>, and travels with the subtree.
354/// let mut out = Vec::new();
355/// serialize::serialize_node(&inner, &mut out, &Default::default())?;
356/// assert_eq!(String::from_utf8(out)?, r#"<p:b xmlns:p="urn:x"/>"#);
357/// # Ok::<(), Box<dyn std::error::Error>>(())
358/// ```
359pub 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
375/// [`serialize_node`] into a `String`.
376///
377/// ```
378/// use xsd_schema::document::serialize;
379/// use xsd_schema::navigator::{DomNavigator, RoXmlNavigator};
380///
381/// let doc = roxmltree::Document::parse("<a>1 &lt; 2</a>")?;
382/// let mut nav = RoXmlNavigator::new(&doc);
383/// nav.move_to_first_child();
384///
385/// assert_eq!(
386///     serialize::to_string(&nav, &Default::default())?,
387///     "<a>1 &lt; 2</a>",
388/// );
389/// # Ok::<(), Box<dyn std::error::Error>>(())
390/// ```
391pub 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    // Every byte written came from a `&str`, so the buffer is valid UTF-8.
398    Ok(String::from_utf8(buf).expect("serializer writes UTF-8"))
399}
400
401// ── Implementation ───────────────────────────────────────────────────────
402
403/// The `xml` prefix, which is bound implicitly everywhere and is therefore
404/// never declared in the output.
405const XML_PREFIX: &str = "xml";
406
407/// True for a Unicode scalar the XML 1.0 (Fifth Edition) `Char` production
408/// excludes: `Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
409/// [#x10000-#x10FFFF]`. Surrogates cannot occur in a Rust `str`, so what is
410/// left is the C0 controls other than tab/LF/CR plus U+FFFE and U+FFFF.
411fn 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
420/// Spaces to write an indent from, so a break costs no allocation.
421const SPACES: [u8; 64] = [b' '; 64];
422
423/// What a container's content is allowed to receive in the way of layout, and
424/// what its children inherit.
425#[derive(Clone, Copy, Debug, Default)]
426struct Layout {
427    /// Add breaks at this container's child boundaries.
428    enabled: bool,
429    /// A text child of this container or of an ancestor. Rule 1 of the
430    /// whitespace contract: it suppresses layout for the whole subtree and
431    /// cannot be switched back on.
432    suppressed: bool,
433    /// The effective `xml:space="preserve"`, inherited until a descendant says
434    /// `default` (XML 1.0 §2.10).
435    preserve: bool,
436}
437
438/// One open element: what to unwind when its end tag is written.
439struct Frame {
440    ns_watermark: usize,
441    layout: Layout,
442    /// The kind of the last child written in this container; `None` before the
443    /// first one, which is what distinguishes the opening boundary.
444    prev_child: Option<DomNodeType>,
445}
446
447/// The in-scope namespace stack, the layout state and the writer.
448struct Serializer<'o, W: Write> {
449    out: W,
450    opts: &'o SerializeOptions,
451    /// In-scope `(prefix, uri)` bindings, innermost last. An entry with an
452    /// empty prefix *and* an empty URI is an undeclared default namespace.
453    /// This is the serializer's only per-node allocation.
454    ns_stack: Vec<(String, String)>,
455    /// The layout state the requested node inherits from its ancestors. Only
456    /// `suppressed` and `preserve` are read; `enabled` is always recomputed.
457    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    /// Seeds the inherited `xml:space` from the node's ancestors, so an
471    /// attached subtree honours a `preserve` it sits inside without the
472    /// serializer inventing an attribute for it (XML 1.0 §2.10).
473    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    // ── Layout ───────────────────────────────────────────────────────
490
491    /// The layout state for an element's content: rule 1's child scan (skipped
492    /// when a break could not be written anyway) over rule 3's `xml:space`.
493    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        // `||` short-circuits: an already-suppressed subtree is never scanned,
502        // and neither is anything in compact mode.
503        let suppressed = inherited.suppressed || (indented && has_text_child(nav));
504        Layout {
505            enabled: indented && !suppressed && !preserve,
506            suppressed,
507            preserve,
508        }
509    }
510
511    /// A line break plus `depth` levels of indentation.
512    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    // ── Namespace scope ──────────────────────────────────────────────
524
525    /// The namespace URI `prefix` resolves to in the scope written so far, or
526    /// `None` when the prefix is not usable there.
527    ///
528    /// The empty prefix always resolves (to the empty URI when no default
529    /// namespace is in scope); `xml` resolves without a declaration.
530    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            // A prefixed binding to the empty URI is an XML 1.1 undeclaration;
542            // it is never written, so the prefix is not usable here.
543            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    /// Whether a non-empty default namespace is in scope, i.e. whether an
555    /// element with no default namespace needs `xmlns=""`.
556    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    // ── Node dispatch ────────────────────────────────────────────────
565
566    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            // A fragment tree whose visible root is an element (an assertion
580            // fragment, say) has no document node to walk into.
581            if declaration && self.opts.indent.is_some() {
582                self.write_break(0)?;
583            }
584            return self.write_subtree(node);
585        }
586        // The document node is a container too, at depth 0, under the same
587        // rules; a declaration stands in for its opening boundary.
588        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                    // No leading break is invented; a declaration is what
596                    // there is to separate the document element from.
597                    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        // No final newline either.
611        Ok(())
612    }
613
614    /// Writes the subtree at the cursor, iteratively: `frames` holds one entry
615    /// per open element — its `ns_stack` watermark and its layout state — so
616    /// descending never recurses and a deep document cannot overflow the Rust
617    /// stack. `frames.len()` is the depth of the node at the cursor, which is
618    /// also its indentation level; the node the caller asked for is at depth 0.
619    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            // The boundary before this child, inside its container. A standalone
625            // node has no container, hence no layout around it.
626            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                        // An empty element stays `<a/>`; nothing goes inside it.
659                        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            // Advance to the next sibling, closing elements on the way up.
669            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                // The closing boundary, at the container's own depth.
679                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    // ── Elements ─────────────────────────────────────────────────────
739
740    /// Writes `<qname` plus the declarations this element introduces and all of
741    /// its attributes, leaving the caller to add `>` or `/>`.
742    ///
743    /// Returns the element's `xml:space` if it carries one, read off the
744    /// attributes as they are written rather than in a second walk.
745    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        // Invariant, not fixup: the name we just wrote must read back the same.
754        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                // An unprefixed attribute is in no namespace: the default
772                // namespace does not apply to it (Namespaces in XML §6.2).
773                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    /// Emits exactly the declarations that change the scope: the element's
798    /// in-scope bindings minus what is already bound identically, plus
799    /// `xmlns=""` when the element leaves an inherited default namespace.
800    ///
801    /// The declarations are collected onto the in-scope stack first and written
802    /// from there in prefix order (the default namespace first). The
803    /// `namespace::` axis has no defined order and the backends disagree on the
804    /// one they use, so sorting is what makes the output a function of the tree
805    /// rather than of the navigator behind it. It needs no allocation of its
806    /// own: the entries are sorted in place, above this element's watermark.
807    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                // `ExcludeXml` already drops it; belt and braces, because the
819                // `xml` prefix must never be declared.
820                if prefix != XML_PREFIX {
821                    if prefix.is_empty() {
822                        if uri.is_empty() {
823                            // An undeclared default namespace, recorded by the
824                            // tree; handled below, where the inherited scope is
825                            // known.
826                        } 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                    // A prefixed binding to the empty URI is an XML 1.1
836                    // undeclaration, which is never written.
837                }
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        // Disjoint field borrows: the writer and the stack are independent.
849        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
876// ── Layout helpers, independent of the writer ────────────────────────────
877
878fn is_element(kind: DomNodeType) -> bool {
879    kind == DomNodeType::Element
880}
881
882/// Whether any direct child of this element is a text node — rule 1 of the
883/// whitespace contract, which looks at *all* the children: text after an
884/// element suppresses layout just as text before one does.
885fn 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
900/// `xml:space` on this element, by its expanded XML-namespace name.
901fn 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
916/// `Some(true)` for `preserve`, `Some(false)` for `default`; any other value is
917/// not one XML 1.0 §2.10 defines, so it changes nothing.
918fn xml_space_value(value: &str) -> Option<bool> {
919    match value {
920        "preserve" => Some(true),
921        "default" => Some(false),
922        _ => None,
923    }
924}
925
926// ── Writing, independent of the cursor ───────────────────────────────────
927
928fn 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            '&' => "&amp;",
958            '<' => "&lt;",
959            // Always escaped, which covers the `]]>` prohibition of XML 1.0
960            // §2.4 without scanning for it.
961            '>' => "&gt;",
962            // A literal CR would be turned into LF by the end-of-line handling
963            // of XML 1.0 §2.11 on re-parse.
964            '\r' => "&#xD;",
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            '&' => "&amp;",
986            '<' => "&lt;",
987            // The quote character, because values are always `"`-quoted.
988            '"' => "&quot;",
989            // Whitespace would be collapsed to a space by the attribute-value
990            // normalization of XML 1.0 §3.3.3 on re-parse.
991            '\t' => "&#x9;",
992            '\n' => "&#xA;",
993            '\r' => "&#xD;",
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
1010/// Rejects content that cannot be written at all, for the contexts that are
1011/// copied out verbatim (comments, PI targets and data, names).
1012fn 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    /// Parses `xml` into a `BufferDocument` and returns its serialization.
1031    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    /// Serializes `xml` through the roxmltree backend instead.
1040    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    /// Just the indentation width, everything else default.
1046    fn indented(width: usize) -> SerializeOptions {
1047        SerializeOptions {
1048            indent: Some(width),
1049            ..SerializeOptions::default()
1050        }
1051    }
1052
1053    /// Parses `xml` and serializes it with the given options.
1054    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    /// The same through the roxmltree backend.
1063    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    /// Serializes the element reached by `descend` steps of `move_to_first_child`
1069    /// from the document root — a subtree, still attached to its tree.
1070    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    /// Builds a tree by hand, so that content XML cannot express can be tested.
1083    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    // ── Escaping matrix (§4.2) ───────────────────────────────────────
1098
1099    #[test]
1100    fn text_escapes_ampersand_lt_and_gt() {
1101        // `>` is escaped unconditionally, which is what makes the `]]>`
1102        // prohibition of XML 1.0 §2.4 impossible to hit.
1103        assert_eq!(
1104            round("<a>&amp; &lt; &gt; ]]&gt; ' \"</a>"),
1105            "<a>&amp; &lt; &gt; ]]&gt; ' \"</a>"
1106        );
1107    }
1108
1109    #[test]
1110    fn text_escapes_carriage_return_only() {
1111        // CR must become a reference (XML 1.0 §2.11 would fold it to LF);
1112        // tab and LF survive as themselves in text.
1113        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&#xD;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="&amp; &lt; &gt; &quot; '"/>"#),
1127            r#"<a k="&amp; &lt; > &quot; '"/>"#
1128        );
1129    }
1130
1131    #[test]
1132    fn attribute_escapes_all_three_whitespace_characters() {
1133        // Written as references because XML 1.0 §3.3.3 would otherwise
1134        // normalize them to plain spaces on re-parse.
1135        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&#x9;y&#xA;z&#xD;w"/>"#);
1143        // And the round trip holds: a re-parse gives the value back.
1144        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        // One fixture, both contexts: `>` in text vs `>` in an attribute.
1151        assert_eq!(round(r#"<a k="&gt;">&gt;</a>"#), r#"<a k=">">&gt;</a>"#);
1152    }
1153
1154    // ── Refused content ──────────────────────────────────────────────
1155
1156    #[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        // A name the output scope cannot express: refused, never repaired.
1289        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        // An unprefixed attribute name always re-parses to no namespace
1314        // (Namespaces in XML §6.2), so this name cannot be written.
1315        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        // `xml` is bound everywhere and is never written, but names using it
1329        // still pass the scope check.
1330        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    // ── Namespace declarations (§4.3) ────────────────────────────────
1360
1361    #[test]
1362    fn redundant_redeclaration_is_dropped() {
1363        // The child re-declares what it already inherits; the output declares
1364        // it once, where it is introduced.
1365        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        // Every binding in scope at <p:b> is re-established on it: the two
1415        // prefixes it uses and the default namespace it sits in.
1416        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        // Source order is not preserved — the axis does not have it to give —
1429        // but the order is a function of the tree, so both backends agree.
1430        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        // `q` is introduced on the first child only, so the second child must
1439        // not carry it.
1440        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    // ── Node kinds (§4.4) ────────────────────────────────────────────
1447
1448    #[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    // ── The XML declaration ──────────────────────────────────────────
1505
1506    #[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    // ── Backend independence ─────────────────────────────────────────
1572
1573    #[test]
1574    fn both_backends_produce_identical_output() {
1575        // The serializer talks to `DomNavigator` only, so the store behind it
1576        // cannot change the bytes.
1577        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">&amp;&lt;&gt;</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        // 50_000 levels: an implementation that descended by recursion would
1595        // overflow the stack here.
1596        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        // The innermost element is childless, so it collapses.
1605        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        // Both navigators report a PI's data as its string value, so the data
1616        // survives on either backend.
1617        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        // Trailing whitespace is part of the data (XML 1.0 §2.6).
1620        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    // ── Formatted output (§4.7) ──────────────────────────────────────
1625
1626    #[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        // It adds no whitespace and removes none.
1635        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        // §4.7's example, built through the builder API.
1642        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        // A declaration in front of the document element gets a break.
1718        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        // In front of a comment it gets none.
1723        assert_eq!(
1724            round_with("<!--c--><a/>", &with_declaration),
1725            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!--c-->\n<a/>"
1726        );
1727        // And no leading break is invented without a declaration.
1728        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        // Layout only lands next to an element; a run of comments and PIs is
1734        // never split internally. No final newline.
1735        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        // A container of comments alone gets no layout at all.
1748        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        // Both of these stay on one line; inspecting only the first child would
1784        // get the second one wrong.
1785        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        // Suppression reaches the whole subtree, not just the mixed container.
1793        assert_eq!(
1794            round_with("<p>t<b><c/></b></p>", &indented(2)),
1795            "<p>t<b><c/></b></p>"
1796        );
1797        // A sibling with text does not suppress its neighbours.
1798        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        // An already-indented document has whitespace text children, so its
1812        // layout is kept exactly as it is rather than rewritten.
1813        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        // And it is inherited by descendants.
1822        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        // The ancestors are consulted for the inherited value; no attribute is
1840        // invented on the subtree's top element.
1841        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        // The nearest ancestor wins, so a `default` in between restores layout.
1850        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        // Without an ancestor setting, the same subtree is formatted.
1859        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        // The added whitespace is exactly one break plus one level, and one
1913        // break before the closing tag.
1914        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        // Existing text is untouched: no break went inside <title>.
1935        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}