oxml 0.0.11

A pure Rust XML toolkit with zero unsafe code: parsing, an ergonomic tree, and XPath
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 oxml. All rights reserved.

//! Changing a [`Document`] after it is built.
//!
//! Every operation here goes through three gates before it touches
//! the arena: the identifiers resolve (or [`NodeError::Stale`]), the
//! node kinds fit the operation (a child goes under a container, an
//! attribute on an element), and the content is XML the serialiser
//! can write. The first mutation API checked only the first, so a
//! caller could build a document that serialised to something the
//! parser refused and find out on the round trip. See
//! `doc/adr/0008-generational-slots-and-block-relocation.md`.

use alloc::vec::Vec;

use super::blocks::BlockEdit;
use super::names::{check_comment, check_pi, check_text};
use super::{Document, NodeData, NodeError, NodeId};

/// Which of the three block arenas an edit addresses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Arena {
    Children,
    Attributes,
    Namespaces,
}

impl Document {
    /// An empty document, with a root and nothing under it.
    ///
    /// The counterpart to parsing. Until now a `Document` could only
    /// come from a parser, so building one meant writing XML to a
    /// string and parsing it back -- which is both slower and unable
    /// to express anything the serialiser would have escaped.
    #[must_use]
    pub fn empty() -> Self {
        Self::with_capacity(0)
    }

    // --- gates ---------------------------------------------------------

    /// `Ok` for a live element.
    pub(super) fn element(&self, id: NodeId) -> Result<(), NodeError> {
        match self.resolve(id).map(|n| &n.data) {
            None => Err(NodeError::Stale),
            Some(NodeData::Element { .. }) => Ok(()),
            Some(_) => Err(NodeError::NotAnElement),
        }
    }

    /// `Ok` for a live node that can hold children.
    pub(super) fn container(&self, id: NodeId) -> Result<(), NodeError> {
        match self.resolve(id).map(|n| &n.data) {
            None => Err(NodeError::Stale),
            Some(NodeData::Root | NodeData::Element { .. }) => Ok(()),
            Some(_) => Err(NodeError::NotAContainer),
        }
    }

    /// `Ok` for a live node that lives in a child list.
    pub(super) fn child_kind(&self, id: NodeId) -> Result<(), NodeError> {
        match self.resolve(id).map(|n| &n.data) {
            None => Err(NodeError::Stale),
            Some(NodeData::Root) => Err(NodeError::NotRemovable),
            Some(NodeData::Attr { .. } | NodeData::Namespace { .. }) => {
                Err(NodeError::NotAChild)
            }
            Some(_) => Ok(()),
        }
    }

    /// XML has exactly one root element. Allowing a second would
    /// build a document that serialises and then fails to reparse
    /// with `TrailingContent` -- a fault the caller meets long after
    /// the call that caused it. `except` is the element being moved,
    /// which may already be the root element.
    pub(super) fn refuse_second_root(
        &self,
        parent: NodeId,
        is_element: bool,
        except: Option<NodeId>,
    ) -> Result<(), NodeError> {
        let taken = parent == self.root()
            && is_element
            && self.root_element().is_some_and(|r| Some(r) != except);
        if taken {
            Err(NodeError::RootElementExists)
        } else {
            Ok(())
        }
    }

    /// Walk up from the destination: if `id` is on that path, the
    /// move would put a node inside its own subtree.
    pub(super) fn check_no_cycle(
        &self,
        id: NodeId,
        new_parent: NodeId,
    ) -> Result<(), NodeError> {
        let mut cursor = Some(new_parent);
        while let Some(node) = cursor {
            if node == id {
                return Err(NodeError::WouldCycle);
            }
            cursor = self.parent(node);
        }
        Ok(())
    }

    // --- appending -----------------------------------------------------

    /// Root-level character data must remain literal XML whitespace.
    /// A carriage return would be escaped by the writer, which is not
    /// legal in the document's `Misc` production.
    fn check_text_at(
        &self,
        parent: Option<NodeId>,
        text: &str,
    ) -> Result<(), NodeError> {
        check_text(text)?;
        if parent == Some(self.root())
            && text.chars().any(|c| !matches!(c, ' ' | '\t' | '\n'))
        {
            return Err(NodeError::InvalidText);
        }
        Ok(())
    }

    /// Add an element as the last child of `parent`.
    ///
    /// A `namespace` is the namespace *name* (the URI). No prefix is
    /// chosen here: the serialiser reuses one in scope for that
    /// namespace, or declares one on the element.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`] if `parent` has been removed,
    /// [`NodeError::NotAContainer`] if it is not the root or an element,
    /// [`NodeError::RootElementExists`] if `parent` is the root and
    /// already has one, or [`NodeError::InvalidName`] if `local` is
    /// not an `NCName`.
    pub fn append_element(
        &mut self,
        parent: NodeId,
        namespace: Option<&str>,
        local: &str,
    ) -> Result<NodeId, NodeError> {
        self.container(parent)?;
        self.refuse_second_root(parent, true, None)?;
        let name = self.intern(namespace, local)?;
        let data = NodeData::Element {
            name,
            attributes: (0, 0),
            namespaces: (0, 0),
        };
        Ok(self.append_node(parent, data))
    }

    /// Add a text node as the last child of `parent`.
    ///
    /// The text is stored verbatim. Escaping happens at serialisation,
    /// so a caller passes the characters it means rather than the
    /// markup that spells them.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`] if `parent` has been removed,
    /// [`NodeError::NotAContainer`] if it cannot hold children, or
    /// [`NodeError::InvalidText`] if the text contains a character no
    /// XML version can write.
    pub fn append_text(
        &mut self,
        parent: NodeId,
        text: &str,
    ) -> Result<NodeId, NodeError> {
        self.container(parent)?;
        self.check_text_at(Some(parent), text)?;
        let chars = self.store_text(text);
        Ok(self.append_node(parent, NodeData::Text(chars)))
    }

    /// Add a comment as the last child of `parent`.
    ///
    /// # Errors
    ///
    /// As [`Document::append_text`]; a comment also may not contain
    /// `--` or end with `-`, and is written verbatim so it may not
    /// contain a control character or a carriage return.
    pub fn append_comment(
        &mut self,
        parent: NodeId,
        text: &str,
    ) -> Result<NodeId, NodeError> {
        self.container(parent)?;
        check_comment(text)?;
        let chars = self.store_text(text);
        Ok(self.append_node(parent, NodeData::Comment(chars)))
    }

    /// Add a processing instruction as the last child of `parent`.
    ///
    /// # Errors
    ///
    /// As [`Document::append_text`]; [`NodeError::InvalidName`] if the
    /// target is not an `NCName` or is `xml` in any case, and
    /// [`NodeError::InvalidText`] if the data contains `?>`, a control
    /// character or a carriage return.
    pub fn append_pi(
        &mut self,
        parent: NodeId,
        target: &str,
        data: &str,
    ) -> Result<NodeId, NodeError> {
        self.container(parent)?;
        check_pi(target, data)?;
        let target = self.store_text(target);
        let data = self.store_text(data);
        Ok(self.append_node(
            parent,
            NodeData::ProcessingInstruction { target, data },
        ))
    }

    /// Replace the content of a text node.
    ///
    /// Overwrites the stored text in place, so repeated replacement
    /// retains only the latest value.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`], [`NodeError::NotText`] for any other kind
    /// of node, or [`NodeError::InvalidText`].
    pub fn set_text(
        &mut self,
        id: NodeId,
        text: &str,
    ) -> Result<(), NodeError> {
        let old = match self.resolve(id).map(|n| &n.data) {
            None => return Err(NodeError::Stale),
            Some(NodeData::Text(c)) => *c,
            Some(_) => return Err(NodeError::NotText),
        };
        self.check_text_at(self.parent(id), text)?;
        let chars = self.replace_text(old, text);
        if let Some(n) = self.resolve_mut(id) {
            n.data = NodeData::Text(chars);
        }
        Ok(())
    }

    // --- removing and moving -------------------------------------------

    /// Free one arena slot, once.
    ///
    /// Bumping an even generation to odd is what makes every
    /// identifier minted for the slot stop resolving. A slot already
    /// odd is left alone: freeing it again would make it even -- live
    /// -- and list it twice, so the next two allocations would share
    /// it. That is how `remove(attr)` followed by `remove(element)`
    /// once made a node vanish.
    pub(super) fn free_slot(&mut self, id: NodeId) {
        let index = id.index as usize;
        let Some(g) = self.generations.get_mut(index) else {
            return;
        };
        if *g % 2 == 1 {
            return;
        }
        *g = g.wrapping_add(1);
        self.free_slots.push(id.index);
        self.order_dirty = true;
        self.release_node_text(index);
    }

    /// Free `id` and everything it owns: children, attributes and
    /// namespace nodes, to any depth.
    pub(super) fn free_subtree(&mut self, id: NodeId) {
        let mut stack = Vec::from([id]);
        while let Some(current) = stack.pop() {
            // Attribute and namespace nodes have no children, so they
            // can ride the same stack as the subtree.
            stack.extend_from_slice(self.children(current));
            stack.extend_from_slice(self.attribute_nodes(current));
            stack.extend_from_slice(self.namespace_nodes(current));
            self.free_slot(current);
        }
    }

    /// Remove a node and everything under it.
    ///
    /// An attribute or namespace node is taken off its element; any
    /// other node is unlinked from its parent and freed with its
    /// subtree. The slots are recycled for future allocations once
    /// their generations are bumped, so every identifier minted for
    /// them beforehand stops resolving. That is the whole reason
    /// [`NodeId`] carries a generation: without it a caller holding an
    /// identifier across this call would address whatever occupied the
    /// slot next, and get a wrong answer nothing reports.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`] if `id` has already been removed, or
    /// [`NodeError::NotRemovable`] for the document root.
    pub fn remove(&mut self, id: NodeId) -> Result<(), NodeError> {
        let owned_by = match self.resolve(id).map(|n| &n.data) {
            None => return Err(NodeError::Stale),
            Some(NodeData::Root) => return Err(NodeError::NotRemovable),
            Some(NodeData::Attr { .. }) => Some(Arena::Attributes),
            Some(NodeData::Namespace { .. }) => Some(Arena::Namespaces),
            Some(_) => None,
        };
        // Unlink first, so the tree is never walkable into a removed
        // subtree even briefly.
        match (owned_by, self.parent(id)) {
            (Some(arena), Some(owner)) => {
                let _ = self.edit_block(owner, arena, BlockEdit::Without(id));
            }
            (None, _) => self.unlink_from_parent(id),
            (Some(_), None) => {}
        }
        self.free_subtree(id);
        Ok(())
    }

    /// Unlink a node from its parent without freeing it.
    ///
    /// The subtree stays live and can be put back with
    /// [`Document::reparent`] or [`Document::insert_at`]. Until then it
    /// is not written and has no document position.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`], [`NodeError::NotRemovable`] for the root,
    /// or [`NodeError::NotAChild`] for an attribute or namespace node.
    pub fn detach(&mut self, id: NodeId) -> Result<(), NodeError> {
        self.child_kind(id)?;
        self.unlink_from_parent(id);
        if let Some(n) = self.resolve_mut(id) {
            n.parent = None;
        }
        self.order_dirty = true;
        Ok(())
    }

    /// Move a subtree to a new parent, appending it there.
    ///
    /// # Errors
    ///
    /// [`NodeError::Stale`] if either identifier has been removed,
    /// [`NodeError::NotAContainer`] if `new_parent` cannot hold
    /// children, [`NodeError::NotAChild`] for an attribute or namespace
    /// node, [`NodeError::NotRemovable`] for the root,
    /// [`NodeError::RootElementExists`] if the move would put a second
    /// element under the root, or [`NodeError::WouldCycle`] if `id` is
    /// `new_parent` or an ancestor of it. That last check is not
    /// optional: the result would be a "tree" containing a loop, and
    /// every walker in this crate -- `descendants_of`, `text`, the
    /// serialiser, `XPath` -- follows children until they run out. None
    /// of them would ever run out.
    pub fn reparent(
        &mut self,
        id: NodeId,
        new_parent: NodeId,
    ) -> Result<(), NodeError> {
        self.move_node(id, new_parent, None)
    }

    /// Put `child` at position `index` among `parent`'s children.
    ///
    /// `child` is unlinked from wherever it was first, so the index
    /// counts the children that remain; an index past the end appends.
    ///
    /// # Errors
    ///
    /// As [`Document::reparent`].
    pub fn insert_at(
        &mut self,
        parent: NodeId,
        index: usize,
        child: NodeId,
    ) -> Result<(), NodeError> {
        self.move_node(child, parent, Some(index))
    }

    pub(super) fn move_node(
        &mut self,
        id: NodeId,
        new_parent: NodeId,
        at: Option<usize>,
    ) -> Result<(), NodeError> {
        self.child_kind(id)?;
        self.container(new_parent)?;
        self.check_no_cycle(id, new_parent)?;
        self.refuse_second_root(new_parent, self.is_element(id), Some(id))?;
        if let Some(super::NodeKind::Text(text)) = self.kind(id) {
            self.check_text_at(Some(new_parent), text)?;
        }
        self.unlink_from_parent(id);
        if let Some(n) = self.resolve_mut(id) {
            n.parent = Some(new_parent);
        }
        let edit =
            at.map_or(BlockEdit::Append(id), |i| BlockEdit::InsertAt(i, id));
        let _ = self.edit_block(new_parent, Arena::Children, edit);
        Ok(())
    }
}