f-office-xml 0.3.0

Minimal read-only XML tree for Office Open XML and SVG parts.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
//! XML tree for Office Open XML parts.
//!
//! The tree keeps every element, attribute, namespace prefix and comment, and the markup that
//! no format crate reads, including `mc:AlternateContent`, so that a format crate reads what it
//! knows and passes over the rest. It is not lossless, and nothing writes it back: text takes
//! XML's normalization of line ends, with its character and entity references resolved and its
//! CDATA sections joined to it; attribute values take XML's attribute-value normalization; and
//! the XML declaration and processing instructions keep only their place. Each node keeps
//! where its markup lies in the parsed bytes ([`Document::span`]), so that an edit replaces
//! those bytes and keeps every other byte of the part; new XML for an edit is parsed with the
//! namespace declarations of its place ([`Document::parse_fragment`]), and two nodes compare as
//! written or by meaning ([`Document::same_tree`]). Typed views in the
//! format crates read from this tree. The reader refuses a `DOCTYPE` and limits the
//! nesting depth and the number of nodes. A namespace prefix without a declaration does not
//! stop the reader: the tree lists it ([`Document::undeclared_prefixes`]), so that a format
//! crate can warn of it. The tables of the enumerations ([`enumeration`]) are the names that
//! the format crates read the values of such a type through.

mod compare;
pub mod enumeration;
mod fragment;
#[cfg(test)]
mod span_tests;
mod stream;

pub use compare::Equality;
pub use fragment::Fragment;
pub use stream::{StreamedBody, scan_body_children};

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;

use quick_xml::XmlVersion;
use quick_xml::events::{BytesDecl, BytesRef, BytesStart, Event};
use quick_xml::name::{QName, ResolveResult};
use quick_xml::reader::NsReader;

/// Limits that protect the reader against hostile input. Start from [`Limits::default`] and set
/// the limits that differ, so that a new limit breaks no caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
    /// The deepest element nesting allowed.
    pub max_depth: usize,
    /// The most nodes allowed in one document.
    pub max_nodes: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_depth: 256,
            max_nodes: 4_000_000,
        }
    }
}

impl Limits {
    /// Limits tuned for memory-constrained devices such as phones and browser tabs.
    #[must_use]
    pub const fn mobile() -> Self {
        Self {
            max_depth: 128,
            max_nodes: 500_000,
        }
    }
}

/// Why a part could not be read, or a node's span or a fragment not given.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The XML is not well formed.
    Syntax(String),
    /// The part has a `DOCTYPE`, which Office Open XML never uses.
    DocType,
    /// The nesting is deeper than [`Limits::max_depth`].
    TooDeep,
    /// The part has more nodes than [`Limits::max_nodes`].
    TooManyNodes,
    /// The part has no root element.
    NoRoot,
    /// The part has more bytes than a span can count, `u32::MAX`.
    TooLarge,
    /// The part is not in UTF-8, as its byte order mark or its XML declaration says: the
    /// encoding that it names. Its spans are not given ([`Document::span`]), because bytes in
    /// UTF-8 in their place would garble it.
    NotUtf8(String),
    /// The document has no such node.
    NoSuchNode,
    /// A fragment uses a namespace prefix that neither it nor the declarations in scope
    /// declare ([`Document::parse_fragment`]).
    UndeclaredPrefix(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax(message) => write!(f, "malformed XML: {message}"),
            Self::DocType => f.write_str("XML with a DOCTYPE is not allowed"),
            Self::TooDeep => f.write_str("XML nesting is too deep"),
            Self::TooManyNodes => f.write_str("XML has too many nodes"),
            Self::NoRoot => f.write_str("XML has no root element"),
            Self::TooLarge => f.write_str("XML part is larger than 4 GiB"),
            Self::NotUtf8(encoding) => write!(f, "XML part is in {encoding}, not in UTF-8"),
            Self::NoSuchNode => f.write_str("XML document has no such node"),
            Self::UndeclaredPrefix(prefix) => {
                write!(
                    f,
                    "XML fragment uses the prefix {prefix} without a declaration"
                )
            }
        }
    }
}

impl std::error::Error for Error {}

/// A node in a [`Document`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeId(u32);

/// A namespace URI interned in a [`Document`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NamespaceId(u32);

/// Byte range into [`Document::strings`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct StrSpan {
    start: u32,
    len: u32,
}

impl StrSpan {
    const EMPTY: Self = Self { start: 0, len: 0 };

    fn slice(self, buf: &str) -> &str {
        let start = self.start as usize;
        let end = start.saturating_add(self.len as usize);
        buf.get(start..end).unwrap_or("")
    }
}

/// Contiguous element range into an arena `Vec` (`children_pool` or `attrs`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct SliceRange {
    start: u32,
    len: u32,
}

impl SliceRange {
    const EMPTY: Self = Self { start: 0, len: 0 };

    fn bounds(self) -> std::ops::Range<usize> {
        let start = self.start as usize;
        start..start.saturating_add(self.len as usize)
    }
}

/// An element or attribute name borrowed from a [`Document`]'s string arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Name<'a> {
    /// The prefix as written in the part, if any.
    pub prefix: Option<&'a str>,
    /// The local name.
    pub local: &'a str,
    /// The namespace that the prefix resolves to, if any: `None` for a name without a prefix
    /// outside a default namespace, and for a prefix without a declaration
    /// ([`Document::undeclared_prefixes`]).
    pub namespace: Option<NamespaceId>,
}

/// One attribute of an element borrowed from a [`Document`]'s arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Attribute<'a> {
    /// The attribute name.
    pub name: Name<'a>,
    /// The value, with entity references resolved.
    pub value: &'a str,
}

/// Zero-copy view of an element's attributes stored contiguously in a [`Document`]'s arena.
#[derive(Clone, Copy, Debug)]
pub struct Attrs<'a> {
    strings: &'a str,
    attrs: &'a [ArenaAttr],
}

impl<'a> Attrs<'a> {
    /// Returns the number of attributes on this element.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.attrs.len()
    }

    /// Returns `true` when this element has no attributes.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.attrs.is_empty()
    }

    /// Returns an iterator over the element's attributes in document order.
    #[must_use]
    pub const fn iter(&self) -> AttrsIter<'a> {
        AttrsIter {
            strings: self.strings,
            attrs: self.attrs,
        }
    }

    /// Returns the attribute at `index`, or `None` if out of bounds.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<Attribute<'a>> {
        self.attrs.get(index).map(|attr| attr.view(self.strings))
    }
}

/// Iterator over an element's attributes in document order ([`Attrs::iter`]).
#[derive(Clone, Debug)]
pub struct AttrsIter<'a> {
    strings: &'a str,
    attrs: &'a [ArenaAttr],
}

impl<'a> Iterator for AttrsIter<'a> {
    type Item = Attribute<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let (first, rest) = self.attrs.split_first()?;
        self.attrs = rest;
        Some(first.view(self.strings))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.attrs.len(), Some(self.attrs.len()))
    }
}

impl DoubleEndedIterator for AttrsIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let (last, rest) = self.attrs.split_last()?;
        self.attrs = rest;
        Some(last.view(self.strings))
    }
}

impl ExactSizeIterator for AttrsIter<'_> {}

impl<'a> IntoIterator for Attrs<'a> {
    type Item = Attribute<'a>;
    type IntoIter = AttrsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &Attrs<'a> {
    type Item = Attribute<'a>;
    type IntoIter = AttrsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl PartialEq for Attrs<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.len() == other.len() && self.iter().eq(other.iter())
    }
}

impl Eq for Attrs<'_> {}

/// An element with its attributes, borrowed zero-copy from a [`Document`]'s arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Element<'a> {
    /// The element name.
    pub name: Name<'a>,
    /// The attributes in document order, including namespace declarations.
    pub attributes: Attrs<'a>,
}

/// What a node holds, borrowed zero-copy from a [`Document`]'s arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind<'a> {
    /// An element.
    Element(Element<'a>),
    /// Character data, with entity references resolved.
    Text(&'a str),
    /// A comment, a processing instruction or the XML declaration, kept as written.
    Other(&'a str),
}

/// Compact flat attribute entry stored in [`Document::attrs`].
#[derive(Clone, Copy, Debug)]
struct ArenaAttr {
    prefix: Option<StrSpan>,
    local: StrSpan,
    namespace: Option<NamespaceId>,
    value: StrSpan,
}

impl ArenaAttr {
    fn view<'a>(&self, strings: &'a str) -> Attribute<'a> {
        Attribute {
            name: Name {
                prefix: self.prefix.map(|span| span.slice(strings)),
                local: self.local.slice(strings),
                namespace: self.namespace,
            },
            value: self.value.slice(strings),
        }
    }
}

/// Compact flat node payload stored in [`Document::nodes`].
#[derive(Clone, Copy, Debug)]
enum ArenaKind {
    Element {
        prefix: Option<StrSpan>,
        local: StrSpan,
        namespace: Option<NamespaceId>,
        attrs: SliceRange,
    },
    Text(StrSpan),
    Other(StrSpan),
}

#[derive(Clone, Copy, Debug)]
struct Node {
    kind: ArenaKind,
    children: SliceRange,
    /// The namespace declarations in scope at an element: those of the nearest element, the
    /// element itself or an ancestor, that declares a namespace. `None` for other nodes and for
    /// an element with no declaration in scope.
    scope: Option<ScopeId>,
    /// Where the node's markup lies in the parsed bytes ([`Document::span`]).
    span: Span,
}

/// Where a node's markup lies in the parsed bytes: the offset of its first byte and the offset
/// after its last.
#[derive(Clone, Copy, Debug, Default)]
struct Span {
    start: u32,
    end: u32,
}

/// The place of a [`Scope`] in the document's list of them.
#[derive(Clone, Copy, Debug)]
struct ScopeId(u32);

/// The namespace declarations of one element, with the scope of the nearest ancestor that
/// declares a namespace: the prefixes in scope at the element and at each descendant that
/// declares none.
#[derive(Clone, Debug)]
struct Scope {
    /// The scope outside this one, if any.
    outer: Option<ScopeId>,
    /// Each prefix that the element declares, `""` for the default namespace, with the namespace
    /// that it binds, after the aliases of the parse.
    bindings: Vec<(String, NamespaceId)>,
}

/// The byte order mark of UTF-8.
const UTF8_MARK: [u8; 3] = [0xEF, 0xBB, 0xBF];

/// The namespace that the prefix `xml` is bound to by definition (Namespaces in XML 1.0, 3).
const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";

/// A parsed XML part stored in flat contiguous arenas (nodes, child indices, attributes, and a
/// single UTF-8 string buffer with interned tag and attribute names).
#[derive(Clone, Debug)]
pub struct Document {
    nodes: Vec<Node>,
    children_pool: Vec<NodeId>,
    attrs: Vec<ArenaAttr>,
    strings: String,
    top: Vec<NodeId>,
    namespaces: Vec<String>,
    scopes: Vec<Scope>,
    undeclared_prefixes: Vec<String>,
    /// The encoding that the part's byte order mark or XML declaration names when it is not
    /// UTF-8, and `None` for a part in UTF-8.
    encoding: Option<String>,
}

impl Document {
    /// Parses a part.
    ///
    /// # Errors
    ///
    /// Returns an error when the XML is malformed, has a `DOCTYPE`, or breaks a limit.
    pub fn parse(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
        Builder::new(*limits, &[]).run(bytes)
    }

    /// Parses a part and resolves each namespace URI on the left of an alias pair to the URI
    /// on the right, so that two spellings of one vocabulary read the same. The namespace
    /// declarations stay in the element attributes as written.
    ///
    /// # Errors
    ///
    /// Returns an error when the XML is malformed, has a `DOCTYPE`, or breaks a limit.
    pub fn parse_with_aliases(
        bytes: &[u8],
        limits: &Limits,
        aliases: &[(&str, &str)],
    ) -> Result<Self, Error> {
        Builder::new(*limits, aliases).run(bytes)
    }

    /// Returns the root element.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoRoot`] when the document has no element at the top level.
    pub fn root(&self) -> Result<NodeId, Error> {
        self.top
            .iter()
            .copied()
            .find(|id| self.element(*id).is_some())
            .ok_or(Error::NoRoot)
    }

    /// Returns what a node holds.
    #[must_use]
    pub fn kind(&self, id: NodeId) -> Option<NodeKind<'_>> {
        let node = self.node(id)?;
        Some(match node.kind {
            ArenaKind::Element {
                prefix,
                local,
                namespace,
                attrs,
            } => NodeKind::Element(Element {
                name: Name {
                    prefix: prefix.map(|span| span.slice(&self.strings)),
                    local: local.slice(&self.strings),
                    namespace,
                },
                attributes: Attrs {
                    strings: &self.strings,
                    attrs: self.attrs.get(attrs.bounds()).unwrap_or(&[]),
                },
            }),
            ArenaKind::Text(span) => NodeKind::Text(span.slice(&self.strings)),
            ArenaKind::Other(span) => NodeKind::Other(span.slice(&self.strings)),
        })
    }

    /// Returns the element at a node, or `None` for other nodes.
    #[must_use]
    pub fn element(&self, id: NodeId) -> Option<Element<'_>> {
        match self.kind(id)? {
            NodeKind::Element(element) => Some(element),
            NodeKind::Text(_) | NodeKind::Other(_) => None,
        }
    }

    /// Returns the text at a node, or `None` for other nodes.
    #[must_use]
    pub fn text(&self, id: NodeId) -> Option<&str> {
        match self.node(id)?.kind {
            ArenaKind::Text(span) => Some(span.slice(&self.strings)),
            ArenaKind::Element { .. } | ArenaKind::Other(_) => None,
        }
    }

    /// Returns the children of a node in document order.
    #[must_use]
    pub fn children(&self, id: NodeId) -> &[NodeId] {
        self.node(id)
            .and_then(|node| self.children_pool.get(node.children.bounds()))
            .unwrap_or(&[])
    }

    /// Returns the child elements of a node in document order.
    pub fn child_elements(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
        self.children(id)
            .iter()
            .copied()
            .filter(|child| self.element(*child).is_some())
    }

    /// Replaces the children of a node, in document order. The new children are nodes of this
    /// document, so that an edit can drop, keep and move nodes; a node that no parent lists any
    /// more drops out of the tree. Nothing changes for a node that the document lacks.
    pub fn set_children(&mut self, id: NodeId, children: Vec<NodeId>) {
        if self.nodes.get(id.0 as usize).is_none() {
            return;
        }
        let range = if children.is_empty() {
            SliceRange::EMPTY
        } else {
            let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
            let len = u32::try_from(children.len()).unwrap_or(u32::MAX);
            self.children_pool.extend(children);
            SliceRange { start, len }
        };
        if let Some(node) = self.nodes.get_mut(id.0 as usize) {
            node.children = range;
        }
    }

    /// Sets an attribute of an element, so that an edit can leave a note on it: the value of
    /// an attribute with this namespace URI and local name changes, or the attribute is added.
    /// Pass `None` as the namespace for an unprefixed attribute. Nothing changes for a node that
    /// is no element.
    pub fn set_attribute(&mut self, id: NodeId, namespace: Option<&str>, local: &str, value: &str) {
        let namespace = namespace.map(|uri| {
            let index = self.namespaces.iter().position(|known| known == uri);
            NamespaceId(
                u32::try_from(index.unwrap_or_else(|| {
                    self.namespaces.push(uri.to_owned());
                    self.namespaces.len() - 1
                }))
                .unwrap_or(u32::MAX),
            )
        });
        let Some(ArenaKind::Element { attrs, .. }) =
            self.nodes.get(id.0 as usize).map(|node| node.kind)
        else {
            return;
        };
        let bounds = attrs.bounds();
        let existing_index = self.attrs.get(bounds.clone()).and_then(|slice| {
            slice
                .iter()
                .position(|attr| {
                    attr.namespace == namespace && attr.local.slice(&self.strings) == local
                })
                .map(|offset| bounds.start + offset)
        });
        let value_span = push_str_arena(&mut self.strings, value);
        if let Some(idx) = existing_index {
            if let Some(attr) = self.attrs.get_mut(idx) {
                attr.value = value_span;
            }
            return;
        }
        let local_span = push_str_arena(&mut self.strings, local);
        let new_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
        let old_len = bounds.len();
        self.attrs.reserve(old_len + 1);
        for idx in bounds {
            if let Some(&copied) = self.attrs.get(idx) {
                self.attrs.push(copied);
            }
        }
        self.attrs.push(ArenaAttr {
            prefix: None,
            local: local_span,
            namespace,
            value: value_span,
        });
        let new_range = SliceRange {
            start: new_start,
            len: u32::try_from(old_len + 1).unwrap_or(u32::MAX),
        };
        if let Some(Node {
            kind: ArenaKind::Element { attrs, .. },
            ..
        }) = self.nodes.get_mut(id.0 as usize)
        {
            *attrs = new_range;
        }
    }

    /// Returns the namespace prefixes that the part uses on an element or an attribute without
    /// a declaration in scope, which XML's namespaces forbid, each once in the order of its
    /// first use. `xml` and `xmlns` need no declaration. Such a name keeps its prefix and has
    /// no namespace: an element of it is none that [`Document::is`] or [`Document::child`]
    /// finds, and an attribute of it reads as an attribute without a prefix.
    #[must_use]
    pub fn undeclared_prefixes(&self) -> &[String] {
        &self.undeclared_prefixes
    }

    /// Returns the namespace that the prefix `prefix` (`""` for the default namespace) is
    /// bound to at the element `id`: by the nearest declaration of the element or of an
    /// ancestor, as the part was parsed, after the aliases of [`Document::parse_with_aliases`].
    /// The prefix `xml` is bound as XML defines it. `None` for a prefix that no declaration in
    /// scope binds, for a declaration of the empty name, and for a node that is no element.
    /// A format crate reads a prefix in an attribute's value through it, such as the namespaces
    /// that a choice of alternate content requires.
    #[must_use]
    pub fn prefix_namespace(&self, id: NodeId, prefix: &str) -> Option<&str> {
        self.element(id)?;
        if prefix == "xml" {
            return Some(XML_NAMESPACE);
        }
        let mut scope = self.node(id)?.scope;
        while let Some(ScopeId(index)) = scope {
            let found = self.scopes.get(index as usize)?;
            if let Some((_, namespace)) = found.bindings.iter().find(|(name, _)| name == prefix) {
                let uri = self.namespace_uri(*namespace);
                return (!uri.is_empty()).then_some(uri);
            }
            scope = found.outer;
        }
        None
    }

    /// Returns where a node's markup lies in the bytes that were parsed, as offsets into those
    /// bytes, before any normalization: an element from the `<` of its start tag to the byte
    /// after the `>` of its end tag or of its empty tag; a text node from its first byte to the
    /// byte after its last, with the character and entity references and the CDATA sections
    /// that it joins; and a comment, a processing instruction or the XML declaration as
    /// written. A span keeps the bytes as parsed: [`Document::set_children`] does not change
    /// it. Replacing the bytes of a span replaces the node in the part, so that an edit keeps
    /// every other byte as it was.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotUtf8`] when the part is not in UTF-8, and [`Error::NoSuchNode`] for
    /// a node that the document lacks.
    pub fn span(&self, id: NodeId) -> Result<std::ops::Range<usize>, Error> {
        if let Some(encoding) = &self.encoding {
            return Err(Error::NotUtf8(encoding.clone()));
        }
        let span = self.node(id).ok_or(Error::NoSuchNode)?.span;
        Ok(span.start as usize..span.end as usize)
    }

    /// Returns the namespace declarations in scope at the element `id`, its own among them:
    /// each prefix (`""` for the default namespace) with the URI that it binds after the
    /// aliases of the parse, from the nearest declaration of the prefix only, the element's
    /// own first and then outward. Empty for a node that is no element. A fragment that takes
    /// the place of the element's content, or of a child, is parsed with them
    /// ([`Document::parse_fragment`]).
    #[must_use]
    pub fn namespaces_in_scope(&self, id: NodeId) -> Vec<(String, String)> {
        let mut found: Vec<(String, String)> = Vec::new();
        if self.element(id).is_none() {
            return found;
        }
        let mut scope = self.node(id).and_then(|node| node.scope);
        while let Some(ScopeId(index)) = scope {
            let Some(outer) = self.scopes.get(index as usize) else {
                break;
            };
            for (prefix, namespace) in &outer.bindings {
                if found.iter().all(|(known, _)| known != prefix) {
                    found.push((prefix.clone(), self.namespace_uri(*namespace).to_owned()));
                }
            }
            scope = outer.outer;
        }
        found
    }

    /// Returns the URI of an interned namespace.
    #[must_use]
    pub fn namespace_uri(&self, id: NamespaceId) -> &str {
        self.namespaces
            .get(id.0 as usize)
            .map_or("", String::as_str)
    }

    /// Tells whether a node is an element with this namespace URI and local name.
    #[must_use]
    pub fn is(&self, id: NodeId, namespace: &str, local: &str) -> bool {
        self.element(id)
            .is_some_and(|element| self.name_is(&element.name, Some(namespace), local))
    }

    /// Returns the first child element with this namespace URI and local name.
    #[must_use]
    pub fn child(&self, id: NodeId, namespace: &str, local: &str) -> Option<NodeId> {
        self.child_elements(id)
            .find(|child| self.is(*child, namespace, local))
    }

    /// Returns an attribute value. Pass `None` as the namespace for an unprefixed attribute.
    #[must_use]
    pub fn attribute(&self, id: NodeId, namespace: Option<&str>, local: &str) -> Option<&str> {
        self.element(id)?
            .attributes
            .iter()
            .find(|attribute| self.name_is(&attribute.name, namespace, local))
            .map(|attribute| attribute.value)
    }

    /// Returns all text below a node, in document order.
    #[must_use]
    pub fn text_content(&self, id: NodeId) -> String {
        let mut out = String::new();
        self.collect_text(id, &mut out);
        out
    }

    fn collect_text(&self, id: NodeId, out: &mut String) {
        if let Some(text) = self.text(id) {
            out.push_str(text);
        }
        for child in self.children(id) {
            self.collect_text(*child, out);
        }
    }

    fn name_is(&self, name: &Name<'_>, namespace: Option<&str>, local: &str) -> bool {
        let uri = name.namespace.map(|ns| self.namespace_uri(ns));
        name.local == local && uri == namespace
    }

    fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id.0 as usize)
    }
}

/// Appends `text` to `strings` and returns its [`StrSpan`].
fn push_str_arena(strings: &mut String, text: &str) -> StrSpan {
    if text.is_empty() {
        return StrSpan::EMPTY;
    }
    let start = u32::try_from(strings.len()).unwrap_or(u32::MAX);
    let len = u32::try_from(text.len()).unwrap_or(u32::MAX);
    strings.push_str(text);
    StrSpan { start, len }
}

struct Builder {
    limits: Limits,
    nodes: Vec<Node>,
    children_pool: Vec<NodeId>,
    /// Open parent child lists (one per nesting level, reused across sibling subtrees).
    pending_children: Vec<Vec<NodeId>>,
    attrs: Vec<ArenaAttr>,
    strings: String,
    /// Interned XML tag/attribute prefixes and local names stored once in `strings`.
    interned_names: HashMap<String, StrSpan>,
    top: Vec<NodeId>,
    stack: Vec<NodeId>,
    /// The scope of each open element, in the order of `stack`.
    scope_stack: Vec<Option<ScopeId>>,
    scopes: Vec<Scope>,
    namespaces: Vec<String>,
    namespace_ids: HashMap<String, NamespaceId>,
    aliases: HashMap<String, String>,
    undeclared_prefixes: Vec<String>,
    undeclared_seen: HashSet<String>,
    /// The number of bytes before the bytes whose offsets the spans count: those of the
    /// container of a fragment ([`Document::parse_fragment`]), else 0.
    offset: u64,
    /// Constant base offset added to every node span when parsing a slice of a larger part.
    base_offset: u64,
    /// The bytes of a byte order mark of UTF-8 at the start, which the reader skips and leaves
    /// out of its positions.
    skipped: u64,
    /// The encoding that the part names when it is not UTF-8.
    encoding: Option<String>,
}

impl Builder {
    fn new(limits: Limits, aliases: &[(&str, &str)]) -> Self {
        Self {
            limits,
            nodes: Vec::new(),
            children_pool: Vec::new(),
            pending_children: Vec::new(),
            attrs: Vec::new(),
            strings: String::new(),
            interned_names: HashMap::new(),
            top: Vec::new(),
            stack: Vec::new(),
            scope_stack: Vec::new(),
            scopes: Vec::new(),
            namespaces: Vec::new(),
            namespace_ids: HashMap::new(),
            aliases: aliases
                .iter()
                .map(|(from, to)| ((*from).to_owned(), (*to).to_owned()))
                .collect(),
            undeclared_prefixes: Vec::new(),
            undeclared_seen: HashSet::new(),
            offset: 0,
            base_offset: 0,
            skipped: 0,
            encoding: None,
        }
    }

    fn intern_name(&mut self, name: &str) -> StrSpan {
        if name.is_empty() {
            return StrSpan::EMPTY;
        }
        if let Some(&span) = self.interned_names.get(name) {
            return span;
        }
        let span = push_str_arena(&mut self.strings, name);
        self.interned_names.insert(name.to_owned(), span);
        span
    }

    fn run(mut self, bytes: &[u8]) -> Result<Document, Error> {
        u32::try_from(
            u64::try_from(bytes.len())
                .unwrap_or(u64::MAX)
                .saturating_add(self.base_offset),
        )
        .map_err(|_| Error::TooLarge)?;
        // A byte order mark of UTF-16 names the encoding before any declaration.
        if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
            self.encoding = Some("UTF-16".to_owned());
        }
        if bytes.starts_with(&UTF8_MARK) {
            self.skipped = UTF8_MARK.len() as u64;
        }
        let mut reader = NsReader::from_reader(bytes);
        reader.config_mut().check_end_names = true;
        let est_nodes = (bytes.len() / 64).min(self.limits.max_nodes);
        self.nodes.reserve(est_nodes);
        self.children_pool.reserve(est_nodes);
        self.attrs.reserve(est_nodes);
        self.strings.reserve(bytes.len() / 2);
        let mut buf = Vec::new();
        loop {
            buf.clear();
            let start = self.position(&reader)?;
            let (resolved, event) = reader
                .read_resolved_event_into(&mut buf)
                .map_err(|error| Error::Syntax(error.to_string()))?;
            let namespace = self.resolve(&resolved);
            let span = Span {
                start,
                end: self.position(&reader)?,
            };
            match event {
                Event::Eof => break,
                Event::Start(tag) => {
                    let id = self.start_element(&reader, &tag, namespace, span)?;
                    self.open(id)?;
                }
                Event::Empty(tag) => {
                    self.start_element(&reader, &tag, namespace, span)?;
                }
                Event::End(_) => {
                    self.close(span.end);
                }
                other => self.leaf(other, span)?,
            }
        }
        if self.stack.is_empty() {
            Ok(Document {
                nodes: self.nodes,
                children_pool: self.children_pool,
                attrs: self.attrs,
                strings: self.strings,
                top: self.top,
                namespaces: self.namespaces,
                scopes: self.scopes,
                undeclared_prefixes: self.undeclared_prefixes,
                encoding: self.encoding,
            })
        } else {
            Err(Error::Syntax("unclosed element".to_owned()))
        }
    }

    /// The offset that the reader has reached, counted from the bytes after [`Self::offset`],
    /// shifted by [`Self::base_offset`].
    fn position(&self, reader: &NsReader<&[u8]>) -> Result<u32, Error> {
        let position = (reader.buffer_position() + self.skipped)
            .saturating_sub(self.offset)
            .saturating_add(self.base_offset);
        u32::try_from(position).map_err(|_| Error::TooLarge)
    }

    fn leaf(&mut self, event: Event<'_>, span: Span) -> Result<(), Error> {
        match event {
            Event::Text(text) => self.add_text(&text.xml10_content(), span),
            Event::CData(data) => self.add_text(&data.into_inner(), span),
            Event::GeneralRef(reference) => self.add_text(&resolve_reference(&reference)?, span),
            Event::DocType(_) => Err(Error::DocType),
            Event::Comment(comment) => {
                let raw = comment.into_inner();
                let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
                self.strings.push_str("<!--");
                self.strings.push_str(&raw);
                self.strings.push_str("-->");
                let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
                self.add(ArenaKind::Other(StrSpan { start, len }), span)
                    .map(|_| ())
            }
            Event::Decl(declaration) => {
                if self.encoding.is_none() {
                    self.encoding = declared_encoding(&declaration);
                }
                self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ())
            }
            Event::PI(_) => self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ()),
            Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof => Ok(()),
        }
    }

    fn resolve(&mut self, resolved: &ResolveResult<'_>) -> Option<NamespaceId> {
        match resolved {
            ResolveResult::Bound(namespace) => Some(self.intern(namespace.as_ref())),
            ResolveResult::Unbound => None,
            ResolveResult::Unknown(prefix) => {
                if self.undeclared_seen.insert(prefix.clone()) {
                    self.undeclared_prefixes.push(prefix.clone());
                }
                None
            }
        }
    }

    fn intern(&mut self, uri: &str) -> NamespaceId {
        let uri = self.aliases.get(uri).map_or(uri, String::as_str);
        if let Some(id) = self.namespace_ids.get(uri) {
            return *id;
        }
        let id = NamespaceId(u32::try_from(self.namespaces.len()).unwrap_or(u32::MAX));
        let owned = uri.to_owned();
        self.namespaces.push(owned.clone());
        self.namespace_ids.insert(owned, id);
        id
    }

    fn start_element(
        &mut self,
        reader: &NsReader<&[u8]>,
        start: &BytesStart<'_>,
        namespace: Option<NamespaceId>,
        span: Span,
    ) -> Result<NodeId, Error> {
        let (prefix, local) = self.split_name(start.name());
        let attr_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
        for attribute in start.attributes() {
            let attribute = attribute.map_err(|error| Error::Syntax(error.to_string()))?;
            let (resolved, _) = reader.resolver().resolve_attribute(attribute.key);
            let attr_ns = self.resolve(&resolved);
            let (attr_prefix, attr_local) = self.split_name(attribute.key);
            let value = attribute
                .normalized_value(XmlVersion::Implicit1_0)
                .map_err(|error| Error::Syntax(error.to_string()))?;
            let value_span = push_str_arena(&mut self.strings, &value);
            self.attrs.push(ArenaAttr {
                prefix: attr_prefix,
                local: attr_local,
                namespace: attr_ns,
                value: value_span,
            });
        }
        let attr_len = u32::try_from(self.attrs.len())
            .unwrap_or(u32::MAX)
            .saturating_sub(attr_start);
        let attrs = SliceRange {
            start: attr_start,
            len: attr_len,
        };
        let scope = self.scope_of(attrs)?;
        let id = self.add(
            ArenaKind::Element {
                prefix,
                local,
                namespace,
                attrs,
            },
            span,
        )?;
        if let Some(node) = self.nodes.get_mut(id.0 as usize) {
            node.scope = scope;
        }
        Ok(id)
    }

    fn split_name(&mut self, name: QName<'_>) -> (Option<StrSpan>, StrSpan) {
        let local = self.intern_name(name.local_name().as_ref());
        let prefix = name
            .prefix()
            .map(|prefix| self.intern_name(prefix.as_ref()));
        (prefix, local)
    }

    /// The scope of an element with the attributes `attrs`: a new scope when they declare
    /// a namespace, else the scope of the open element.
    fn scope_of(&mut self, attrs: SliceRange) -> Result<Option<ScopeId>, Error> {
        let outer = self.scope_stack.last().copied().flatten();
        let declared: Vec<(String, String)> = self
            .attrs
            .get(attrs.bounds())
            .unwrap_or(&[])
            .iter()
            .filter_map(|attribute| {
                let prefix_str = attribute.prefix.map(|span| span.slice(&self.strings));
                let local_str = attribute.local.slice(&self.strings);
                let binding_prefix = match prefix_str {
                    Some("xmlns") => local_str.to_owned(),
                    None if local_str == "xmlns" => String::new(),
                    _ => return None,
                };
                Some((
                    binding_prefix,
                    attribute.value.slice(&self.strings).to_owned(),
                ))
            })
            .collect();
        if declared.is_empty() {
            return Ok(outer);
        }
        let bindings = declared
            .into_iter()
            .map(|(prefix, uri)| (prefix, self.intern(&uri)))
            .collect();
        let id = ScopeId(u32::try_from(self.scopes.len()).map_err(|_| Error::TooManyNodes)?);
        self.scopes.push(Scope { outer, bindings });
        Ok(Some(id))
    }

    /// Adds text, joined to a text node just before it, whose span then reaches to the end of
    /// `span`.
    fn add_text(&mut self, text: &str, span: Span) -> Result<(), Error> {
        let last = self.siblings().last().copied();
        if let Some(last_id) = last
            && let Some(Node {
                kind: ArenaKind::Text(prev_span),
                ..
            }) = self.nodes.get(last_id.0 as usize).copied()
        {
            let prev_end = (prev_span.start as usize).saturating_add(prev_span.len as usize);
            let new_span = if prev_end == self.strings.len() {
                self.strings.push_str(text);
                StrSpan {
                    start: prev_span.start,
                    len: prev_span
                        .len
                        .saturating_add(u32::try_from(text.len()).unwrap_or(u32::MAX)),
                }
            } else {
                let prev_text = prev_span.slice(&self.strings).to_owned();
                let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
                self.strings.push_str(&prev_text);
                self.strings.push_str(text);
                let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
                StrSpan { start, len }
            };
            if let Some(node) = self.nodes.get_mut(last_id.0 as usize) {
                node.kind = ArenaKind::Text(new_span);
                node.span.end = span.end;
            }
            return Ok(());
        }
        let text_span = push_str_arena(&mut self.strings, text);
        self.add(ArenaKind::Text(text_span), span).map(|_| ())
    }

    fn siblings(&self) -> &[NodeId] {
        let depth = self.stack.len();
        if depth == 0 {
            &self.top
        } else {
            self.pending_children
                .get(depth - 1)
                .map_or(&[], Vec::as_slice)
        }
    }

    fn add(&mut self, kind: ArenaKind, span: Span) -> Result<NodeId, Error> {
        if self.nodes.len() >= self.limits.max_nodes {
            return Err(Error::TooManyNodes);
        }
        let id = NodeId(u32::try_from(self.nodes.len()).map_err(|_| Error::TooManyNodes)?);
        self.nodes.push(Node {
            kind,
            children: SliceRange::EMPTY,
            scope: None,
            span,
        });
        let depth = self.stack.len();
        if depth == 0 {
            self.top.push(id);
        } else if let Some(slot) = self.pending_children.get_mut(depth - 1) {
            slot.push(id);
        }
        Ok(id)
    }

    fn open(&mut self, id: NodeId) -> Result<(), Error> {
        if self.stack.len() >= self.limits.max_depth {
            return Err(Error::TooDeep);
        }
        let depth = self.stack.len();
        if depth == self.pending_children.len() {
            self.pending_children.push(Vec::new());
        } else if let Some(slot) = self.pending_children.get_mut(depth) {
            slot.clear();
        }
        self.stack.push(id);
        let scope = self.nodes.get(id.0 as usize).and_then(|node| node.scope);
        self.scope_stack.push(scope);
        Ok(())
    }

    fn close(&mut self, end: u32) {
        let Some(parent_id) = self.stack.pop() else {
            return;
        };
        let depth = self.stack.len();
        let range = if let Some(slot) = self.pending_children.get_mut(depth) {
            if slot.is_empty() {
                SliceRange::EMPTY
            } else {
                let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
                let len = u32::try_from(slot.len()).unwrap_or(u32::MAX);
                self.children_pool.extend_from_slice(slot);
                slot.clear();
                SliceRange { start, len }
            }
        } else {
            SliceRange::EMPTY
        };
        if let Some(node) = self.nodes.get_mut(parent_id.0 as usize) {
            node.span.end = end;
            node.children = range;
        }
        self.scope_stack.pop();
    }
}

/// The encoding that an XML declaration names, when it names one other than UTF-8.
fn declared_encoding(declaration: &BytesDecl<'_>) -> Option<String> {
    let name = declaration.encoding()?.ok()?;
    let utf8 = name.eq_ignore_ascii_case("utf-8") || name.eq_ignore_ascii_case("utf8");
    (!utf8).then(|| name.into_owned())
}

fn resolve_reference(reference: &BytesRef<'_>) -> Result<Cow<'static, str>, Error> {
    if let Some(ch) = reference
        .resolve_char_ref()
        .map_err(|error| Error::Syntax(error.to_string()))?
    {
        return Ok(Cow::Owned(ch.to_string()));
    }
    let name: &str = reference.as_ref();
    let text = match name {
        "lt" => "<",
        "gt" => ">",
        "amp" => "&",
        "apos" => "'",
        "quot" => "\"",
        other => return Err(Error::Syntax(format!("unknown entity &{other};"))),
    };
    Ok(Cow::Borrowed(text))
}

#[cfg(test)]
mod tests {
    use super::{Document, Error, Limits, NodeKind};

    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    fn parse(xml: &str) -> Result<Document, Error> {
        Document::parse(xml.as_bytes(), &Limits::default())
    }

    #[test]
    fn reads_elements_attributes_and_text() {
        let doc = parse(&format!(
            r#"<?xml version="1.0"?><w:document xmlns:w="{W}"><w:p><w:r><w:t xml:space="preserve"> a &amp; b &#x41;</w:t></w:r><w:jc w:val="both"/></w:p></w:document>"#
        ))
        .unwrap();
        let root = doc.root().unwrap();
        assert!(doc.is(root, W, "document"));
        let p = doc.child(root, W, "p").unwrap();
        let t = doc.child(doc.child(p, W, "r").unwrap(), W, "t").unwrap();
        assert_eq!(doc.text_content(t), " a & b A");
        let jc = doc.child(p, W, "jc").unwrap();
        assert_eq!(doc.attribute(jc, Some(W), "val"), Some("both"));
        assert_eq!(doc.attribute(jc, None, "val"), None);
        let element = doc.element(jc).unwrap();
        assert_eq!(element.name.prefix, Some("w"));
        assert_eq!(doc.namespace_uri(element.name.namespace.unwrap()), W);
    }

    #[test]
    fn sets_the_children_of_a_node() {
        let mut doc = parse("<a><b>x</b><c/><d/></a>").unwrap();
        let root = doc.root().unwrap();
        let [b, c, d] = [0, 1, 2].map(|i| doc.children(root)[i]);
        let x = doc.children(b)[0];
        doc.set_children(root, vec![d, x, b]);
        doc.set_children(b, Vec::new());
        assert_eq!(doc.children(root), [d, x, b]);
        assert_eq!(doc.text_content(root), "x");
        assert_eq!(doc.children(c), []);
        let mut other = parse("<a/>").unwrap();
        other.set_children(d, vec![d]);
        assert_eq!(other.children(d), []);
    }

    #[test]
    fn sets_an_attribute_of_an_element() {
        let mut doc = parse(&format!(r#"<w:r xmlns:w="{W}" w:rsidR="00AB">x</w:r>"#)).unwrap();
        let root = doc.root().unwrap();
        doc.set_attribute(root, Some("urn:note"), "change", "3");
        doc.set_attribute(root, Some(W), "rsidR", "00CD");
        doc.set_attribute(root, Some("urn:note"), "change", "4");
        assert_eq!(doc.attribute(root, Some("urn:note"), "change"), Some("4"));
        assert_eq!(doc.attribute(root, Some(W), "rsidR"), Some("00CD"));
        let text = doc.children(root)[0];
        doc.set_attribute(text, None, "a", "b");
        assert_eq!(doc.attribute(text, None, "a"), None);
    }

    #[test]
    fn keeps_unprefixed_attributes_and_comments() {
        let doc = parse(r#"<Relationships><!-- note --><Relationship Id="rId1" Target="a.xml"/></Relationships>"#).unwrap();
        let root = doc.root().unwrap();
        let rel = doc.child_elements(root).next().unwrap();
        assert_eq!(doc.attribute(rel, None, "Id"), Some("rId1"));
        let comment = doc.children(root)[0];
        assert_eq!(doc.kind(comment), Some(NodeKind::Other("<!-- note -->")));
        assert!(doc.text(comment).is_none());
        assert!(doc.element(comment).is_none());
    }

    #[test]
    fn joins_text_around_references_and_cdata() {
        let doc = parse("<a>x&lt;y<![CDATA[<z>]]>&gt;&apos;&quot;</a>").unwrap();
        let root = doc.root().unwrap();
        assert_eq!(doc.children(root).len(), 1);
        assert_eq!(doc.text_content(root), "x<y<z>>'\"");
    }

    #[test]
    fn refuses_doctype_and_unknown_entities() {
        assert_eq!(parse("<!DOCTYPE a><a/>").unwrap_err(), Error::DocType);
        assert!(matches!(parse("<a>&bogus;</a>"), Err(Error::Syntax(_))));
        assert_eq!(
            parse("<!-- only -->").unwrap().root().unwrap_err(),
            Error::NoRoot
        );
    }

    #[test]
    fn refuses_bad_nesting() {
        assert!(matches!(parse("<a><b></a>"), Err(Error::Syntax(_))));
        assert!(matches!(parse("<a>"), Err(Error::Syntax(_))));
    }

    fn undeclared() -> Document {
        parse(&format!(
            r#"<w:document xmlns:w="{W}" xml:space="preserve"><p:a q:b="1" w:c="2"/><p:d></p:d><w:e p:f="3"/></w:document>"#
        ))
        .unwrap()
    }

    #[test]
    fn lists_each_undeclared_prefix_once_and_gives_its_elements_no_namespace() {
        let doc = undeclared();
        assert_eq!(doc.undeclared_prefixes(), ["p", "q"]);
        let root = doc.root().unwrap();
        let [a, _, e] = [0, 1, 2].map(|i| doc.children(root)[i]);
        let element = doc.element(a).unwrap();
        assert_eq!(element.name.prefix, Some("p"));
        assert_eq!(element.name.namespace, None);
        assert!(doc.is(e, W, "e"));
        let declared = parse(&format!(r#"<w:a xmlns:w="{W}" xml:space="preserve"/>"#)).unwrap();
        assert_eq!(declared.undeclared_prefixes(), [] as [&str; 0]);
    }

    #[test]
    fn reads_an_attribute_of_an_undeclared_prefix_as_one_without_a_prefix() {
        let doc = undeclared();
        let root = doc.root().unwrap();
        let [a, e] = [0, 2].map(|i| doc.children(root)[i]);
        assert_eq!(doc.attribute(a, None, "b"), Some("1"));
        assert_eq!(doc.attribute(a, Some(W), "c"), Some("2"));
        assert_eq!(doc.attribute(e, None, "f"), Some("3"));
    }

    #[test]
    fn resolves_namespace_aliases() {
        let xml = r#"<s:document xmlns:s="urn:strict"><s:body s:val="1"/></s:document>"#;
        let doc =
            Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
                .unwrap();
        let root = doc.root().unwrap();
        assert!(doc.is(root, W, "document"));
        let body = doc.child(root, W, "body").unwrap();
        assert_eq!(doc.attribute(body, Some(W), "val"), Some("1"));
        let plain = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        assert!(!plain.is(plain.root().unwrap(), W, "document"));
    }

    #[test]
    fn binds_a_prefix_by_the_nearest_declaration_in_scope() {
        let doc = parse(concat!(
            r#"<a xmlns:p="urn:outer" xmlns="urn:default">"#,
            r#"<b xmlns:p="urn:inner" xmlns:q="urn:q"><c/></b><d/><e xmlns=""/>t</a>"#,
        ))
        .unwrap();
        let root = doc.root().unwrap();
        let [b, d, e, text] = [0, 1, 2, 3].map(|i| doc.children(root)[i]);
        let c = doc.children(b)[0];
        let cases = [
            (root, "p", Some("urn:outer")),
            (c, "p", Some("urn:inner")),
            (c, "q", Some("urn:q")),
            (d, "p", Some("urn:outer")),
            (d, "q", None),
            (c, "", Some("urn:default")),
            (e, "", None),
            (e, "xml", Some(super::XML_NAMESPACE)),
            (text, "p", None),
            (text, "xml", None),
        ];
        for (node, prefix, namespace) in cases {
            assert_eq!(
                doc.prefix_namespace(node, prefix),
                namespace,
                "{node:?} {prefix}"
            );
        }
    }

    #[test]
    fn binds_a_prefix_to_its_alias() {
        let xml = r#"<a xmlns:s="urn:strict"><b/></a>"#;
        let doc =
            Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
                .unwrap();
        let b = doc.children(doc.root().unwrap())[0];
        assert_eq!(doc.prefix_namespace(b, "s"), Some(W));
    }

    #[test]
    fn enforces_limits() {
        let deep = Limits {
            max_depth: 2,
            max_nodes: 100,
        };
        assert_eq!(
            Document::parse(b"<a><b><c/></b></a>", &deep).map(|_| ()),
            Ok(())
        );
        assert_eq!(
            Document::parse(b"<a><b><c></c></b></a>", &deep).unwrap_err(),
            Error::TooDeep
        );
        let few = Limits {
            max_depth: 10,
            max_nodes: 2,
        };
        assert_eq!(
            Document::parse(b"<a><b/><c/></a>", &few).unwrap_err(),
            Error::TooManyNodes
        );
    }

    #[test]
    fn errors_display() {
        for error in [
            Error::Syntax("x".into()),
            Error::DocType,
            Error::TooDeep,
            Error::TooManyNodes,
            Error::NoRoot,
        ] {
            assert_ne!(error.to_string(), "");
        }
    }
}