1mod compare;
20pub mod enumeration;
21mod fragment;
22#[cfg(test)]
23mod span_tests;
24mod stream;
25
26pub use compare::Equality;
27pub use fragment::Fragment;
28pub use stream::{StreamedBody, scan_body_children};
29
30use std::borrow::Cow;
31use std::collections::{HashMap, HashSet};
32use std::fmt;
33
34use quick_xml::XmlVersion;
35use quick_xml::events::{BytesDecl, BytesRef, BytesStart, Event};
36use quick_xml::name::{QName, ResolveResult};
37use quick_xml::reader::NsReader;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Limits {
44 pub max_depth: usize,
46 pub max_nodes: usize,
48}
49
50impl Default for Limits {
51 fn default() -> Self {
52 Self {
53 max_depth: 256,
54 max_nodes: 4_000_000,
55 }
56 }
57}
58
59impl Limits {
60 #[must_use]
62 pub const fn mobile() -> Self {
63 Self {
64 max_depth: 128,
65 max_nodes: 500_000,
66 }
67 }
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Error {
74 Syntax(String),
76 DocType,
78 TooDeep,
80 TooManyNodes,
82 NoRoot,
84 TooLarge,
86 NotUtf8(String),
90 NoSuchNode,
92 UndeclaredPrefix(String),
95}
96
97impl fmt::Display for Error {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 Self::Syntax(message) => write!(f, "malformed XML: {message}"),
101 Self::DocType => f.write_str("XML with a DOCTYPE is not allowed"),
102 Self::TooDeep => f.write_str("XML nesting is too deep"),
103 Self::TooManyNodes => f.write_str("XML has too many nodes"),
104 Self::NoRoot => f.write_str("XML has no root element"),
105 Self::TooLarge => f.write_str("XML part is larger than 4 GiB"),
106 Self::NotUtf8(encoding) => write!(f, "XML part is in {encoding}, not in UTF-8"),
107 Self::NoSuchNode => f.write_str("XML document has no such node"),
108 Self::UndeclaredPrefix(prefix) => {
109 write!(
110 f,
111 "XML fragment uses the prefix {prefix} without a declaration"
112 )
113 }
114 }
115 }
116}
117
118impl std::error::Error for Error {}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122pub struct NodeId(u32);
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct NamespaceId(u32);
127
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
130struct StrSpan {
131 start: u32,
132 len: u32,
133}
134
135impl StrSpan {
136 const EMPTY: Self = Self { start: 0, len: 0 };
137
138 fn slice(self, buf: &str) -> &str {
139 let start = self.start as usize;
140 let end = start.saturating_add(self.len as usize);
141 buf.get(start..end).unwrap_or("")
142 }
143}
144
145#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
147struct SliceRange {
148 start: u32,
149 len: u32,
150}
151
152impl SliceRange {
153 const EMPTY: Self = Self { start: 0, len: 0 };
154
155 fn bounds(self) -> std::ops::Range<usize> {
156 let start = self.start as usize;
157 start..start.saturating_add(self.len as usize)
158 }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
163pub struct Name<'a> {
164 pub prefix: Option<&'a str>,
166 pub local: &'a str,
168 pub namespace: Option<NamespaceId>,
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
176pub struct Attribute<'a> {
177 pub name: Name<'a>,
179 pub value: &'a str,
181}
182
183#[derive(Clone, Copy, Debug)]
185pub struct Attrs<'a> {
186 strings: &'a str,
187 attrs: &'a [ArenaAttr],
188}
189
190impl<'a> Attrs<'a> {
191 #[must_use]
193 pub const fn len(&self) -> usize {
194 self.attrs.len()
195 }
196
197 #[must_use]
199 pub const fn is_empty(&self) -> bool {
200 self.attrs.is_empty()
201 }
202
203 #[must_use]
205 pub const fn iter(&self) -> AttrsIter<'a> {
206 AttrsIter {
207 strings: self.strings,
208 attrs: self.attrs,
209 }
210 }
211
212 #[must_use]
214 pub fn get(&self, index: usize) -> Option<Attribute<'a>> {
215 self.attrs.get(index).map(|attr| attr.view(self.strings))
216 }
217}
218
219#[derive(Clone, Debug)]
221pub struct AttrsIter<'a> {
222 strings: &'a str,
223 attrs: &'a [ArenaAttr],
224}
225
226impl<'a> Iterator for AttrsIter<'a> {
227 type Item = Attribute<'a>;
228
229 fn next(&mut self) -> Option<Self::Item> {
230 let (first, rest) = self.attrs.split_first()?;
231 self.attrs = rest;
232 Some(first.view(self.strings))
233 }
234
235 fn size_hint(&self) -> (usize, Option<usize>) {
236 (self.attrs.len(), Some(self.attrs.len()))
237 }
238}
239
240impl DoubleEndedIterator for AttrsIter<'_> {
241 fn next_back(&mut self) -> Option<Self::Item> {
242 let (last, rest) = self.attrs.split_last()?;
243 self.attrs = rest;
244 Some(last.view(self.strings))
245 }
246}
247
248impl ExactSizeIterator for AttrsIter<'_> {}
249
250impl<'a> IntoIterator for Attrs<'a> {
251 type Item = Attribute<'a>;
252 type IntoIter = AttrsIter<'a>;
253
254 fn into_iter(self) -> Self::IntoIter {
255 self.iter()
256 }
257}
258
259impl<'a> IntoIterator for &Attrs<'a> {
260 type Item = Attribute<'a>;
261 type IntoIter = AttrsIter<'a>;
262
263 fn into_iter(self) -> Self::IntoIter {
264 self.iter()
265 }
266}
267
268impl PartialEq for Attrs<'_> {
269 fn eq(&self, other: &Self) -> bool {
270 self.len() == other.len() && self.iter().eq(other.iter())
271 }
272}
273
274impl Eq for Attrs<'_> {}
275
276#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub struct Element<'a> {
279 pub name: Name<'a>,
281 pub attributes: Attrs<'a>,
283}
284
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287pub enum NodeKind<'a> {
288 Element(Element<'a>),
290 Text(&'a str),
292 Other(&'a str),
294}
295
296#[derive(Clone, Copy, Debug)]
298struct ArenaAttr {
299 prefix: Option<StrSpan>,
300 local: StrSpan,
301 namespace: Option<NamespaceId>,
302 value: StrSpan,
303}
304
305impl ArenaAttr {
306 fn view<'a>(&self, strings: &'a str) -> Attribute<'a> {
307 Attribute {
308 name: Name {
309 prefix: self.prefix.map(|span| span.slice(strings)),
310 local: self.local.slice(strings),
311 namespace: self.namespace,
312 },
313 value: self.value.slice(strings),
314 }
315 }
316}
317
318#[derive(Clone, Copy, Debug)]
320enum ArenaKind {
321 Element {
322 prefix: Option<StrSpan>,
323 local: StrSpan,
324 namespace: Option<NamespaceId>,
325 attrs: SliceRange,
326 },
327 Text(StrSpan),
328 Other(StrSpan),
329}
330
331#[derive(Clone, Copy, Debug)]
332struct Node {
333 kind: ArenaKind,
334 children: SliceRange,
335 scope: Option<ScopeId>,
339 span: Span,
341}
342
343#[derive(Clone, Copy, Debug, Default)]
346struct Span {
347 start: u32,
348 end: u32,
349}
350
351#[derive(Clone, Copy, Debug)]
353struct ScopeId(u32);
354
355#[derive(Clone, Debug)]
359struct Scope {
360 outer: Option<ScopeId>,
362 bindings: Vec<(String, NamespaceId)>,
365}
366
367const UTF8_MARK: [u8; 3] = [0xEF, 0xBB, 0xBF];
369
370const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
372
373#[derive(Clone, Debug)]
376pub struct Document {
377 nodes: Vec<Node>,
378 children_pool: Vec<NodeId>,
379 attrs: Vec<ArenaAttr>,
380 strings: String,
381 top: Vec<NodeId>,
382 namespaces: Vec<String>,
383 scopes: Vec<Scope>,
384 undeclared_prefixes: Vec<String>,
385 encoding: Option<String>,
388}
389
390impl Document {
391 pub fn parse(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
397 Builder::new(*limits, &[]).run(bytes)
398 }
399
400 pub fn parse_with_aliases(
408 bytes: &[u8],
409 limits: &Limits,
410 aliases: &[(&str, &str)],
411 ) -> Result<Self, Error> {
412 Builder::new(*limits, aliases).run(bytes)
413 }
414
415 pub fn root(&self) -> Result<NodeId, Error> {
421 self.top
422 .iter()
423 .copied()
424 .find(|id| self.element(*id).is_some())
425 .ok_or(Error::NoRoot)
426 }
427
428 #[must_use]
430 pub fn kind(&self, id: NodeId) -> Option<NodeKind<'_>> {
431 let node = self.node(id)?;
432 Some(match node.kind {
433 ArenaKind::Element {
434 prefix,
435 local,
436 namespace,
437 attrs,
438 } => NodeKind::Element(Element {
439 name: Name {
440 prefix: prefix.map(|span| span.slice(&self.strings)),
441 local: local.slice(&self.strings),
442 namespace,
443 },
444 attributes: Attrs {
445 strings: &self.strings,
446 attrs: self.attrs.get(attrs.bounds()).unwrap_or(&[]),
447 },
448 }),
449 ArenaKind::Text(span) => NodeKind::Text(span.slice(&self.strings)),
450 ArenaKind::Other(span) => NodeKind::Other(span.slice(&self.strings)),
451 })
452 }
453
454 #[must_use]
456 pub fn element(&self, id: NodeId) -> Option<Element<'_>> {
457 match self.kind(id)? {
458 NodeKind::Element(element) => Some(element),
459 NodeKind::Text(_) | NodeKind::Other(_) => None,
460 }
461 }
462
463 #[must_use]
465 pub fn text(&self, id: NodeId) -> Option<&str> {
466 match self.node(id)?.kind {
467 ArenaKind::Text(span) => Some(span.slice(&self.strings)),
468 ArenaKind::Element { .. } | ArenaKind::Other(_) => None,
469 }
470 }
471
472 #[must_use]
474 pub fn children(&self, id: NodeId) -> &[NodeId] {
475 self.node(id)
476 .and_then(|node| self.children_pool.get(node.children.bounds()))
477 .unwrap_or(&[])
478 }
479
480 pub fn child_elements(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
482 self.children(id)
483 .iter()
484 .copied()
485 .filter(|child| self.element(*child).is_some())
486 }
487
488 pub fn set_children(&mut self, id: NodeId, children: Vec<NodeId>) {
492 if self.nodes.get(id.0 as usize).is_none() {
493 return;
494 }
495 let range = if children.is_empty() {
496 SliceRange::EMPTY
497 } else {
498 let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
499 let len = u32::try_from(children.len()).unwrap_or(u32::MAX);
500 self.children_pool.extend(children);
501 SliceRange { start, len }
502 };
503 if let Some(node) = self.nodes.get_mut(id.0 as usize) {
504 node.children = range;
505 }
506 }
507
508 pub fn set_attribute(&mut self, id: NodeId, namespace: Option<&str>, local: &str, value: &str) {
513 let namespace = namespace.map(|uri| {
514 let index = self.namespaces.iter().position(|known| known == uri);
515 NamespaceId(
516 u32::try_from(index.unwrap_or_else(|| {
517 self.namespaces.push(uri.to_owned());
518 self.namespaces.len() - 1
519 }))
520 .unwrap_or(u32::MAX),
521 )
522 });
523 let Some(ArenaKind::Element { attrs, .. }) =
524 self.nodes.get(id.0 as usize).map(|node| node.kind)
525 else {
526 return;
527 };
528 let bounds = attrs.bounds();
529 let existing_index = self.attrs.get(bounds.clone()).and_then(|slice| {
530 slice
531 .iter()
532 .position(|attr| {
533 attr.namespace == namespace && attr.local.slice(&self.strings) == local
534 })
535 .map(|offset| bounds.start + offset)
536 });
537 let value_span = push_str_arena(&mut self.strings, value);
538 if let Some(idx) = existing_index {
539 if let Some(attr) = self.attrs.get_mut(idx) {
540 attr.value = value_span;
541 }
542 return;
543 }
544 let local_span = push_str_arena(&mut self.strings, local);
545 let new_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
546 let old_len = bounds.len();
547 self.attrs.reserve(old_len + 1);
548 for idx in bounds {
549 if let Some(&copied) = self.attrs.get(idx) {
550 self.attrs.push(copied);
551 }
552 }
553 self.attrs.push(ArenaAttr {
554 prefix: None,
555 local: local_span,
556 namespace,
557 value: value_span,
558 });
559 let new_range = SliceRange {
560 start: new_start,
561 len: u32::try_from(old_len + 1).unwrap_or(u32::MAX),
562 };
563 if let Some(Node {
564 kind: ArenaKind::Element { attrs, .. },
565 ..
566 }) = self.nodes.get_mut(id.0 as usize)
567 {
568 *attrs = new_range;
569 }
570 }
571
572 #[must_use]
578 pub fn undeclared_prefixes(&self) -> &[String] {
579 &self.undeclared_prefixes
580 }
581
582 #[must_use]
590 pub fn prefix_namespace(&self, id: NodeId, prefix: &str) -> Option<&str> {
591 self.element(id)?;
592 if prefix == "xml" {
593 return Some(XML_NAMESPACE);
594 }
595 let mut scope = self.node(id)?.scope;
596 while let Some(ScopeId(index)) = scope {
597 let found = self.scopes.get(index as usize)?;
598 if let Some((_, namespace)) = found.bindings.iter().find(|(name, _)| name == prefix) {
599 let uri = self.namespace_uri(*namespace);
600 return (!uri.is_empty()).then_some(uri);
601 }
602 scope = found.outer;
603 }
604 None
605 }
606
607 pub fn span(&self, id: NodeId) -> Result<std::ops::Range<usize>, Error> {
621 if let Some(encoding) = &self.encoding {
622 return Err(Error::NotUtf8(encoding.clone()));
623 }
624 let span = self.node(id).ok_or(Error::NoSuchNode)?.span;
625 Ok(span.start as usize..span.end as usize)
626 }
627
628 #[must_use]
635 pub fn namespaces_in_scope(&self, id: NodeId) -> Vec<(String, String)> {
636 let mut found: Vec<(String, String)> = Vec::new();
637 if self.element(id).is_none() {
638 return found;
639 }
640 let mut scope = self.node(id).and_then(|node| node.scope);
641 while let Some(ScopeId(index)) = scope {
642 let Some(outer) = self.scopes.get(index as usize) else {
643 break;
644 };
645 for (prefix, namespace) in &outer.bindings {
646 if found.iter().all(|(known, _)| known != prefix) {
647 found.push((prefix.clone(), self.namespace_uri(*namespace).to_owned()));
648 }
649 }
650 scope = outer.outer;
651 }
652 found
653 }
654
655 #[must_use]
657 pub fn namespace_uri(&self, id: NamespaceId) -> &str {
658 self.namespaces
659 .get(id.0 as usize)
660 .map_or("", String::as_str)
661 }
662
663 #[must_use]
665 pub fn is(&self, id: NodeId, namespace: &str, local: &str) -> bool {
666 self.element(id)
667 .is_some_and(|element| self.name_is(&element.name, Some(namespace), local))
668 }
669
670 #[must_use]
672 pub fn child(&self, id: NodeId, namespace: &str, local: &str) -> Option<NodeId> {
673 self.child_elements(id)
674 .find(|child| self.is(*child, namespace, local))
675 }
676
677 #[must_use]
679 pub fn attribute(&self, id: NodeId, namespace: Option<&str>, local: &str) -> Option<&str> {
680 self.element(id)?
681 .attributes
682 .iter()
683 .find(|attribute| self.name_is(&attribute.name, namespace, local))
684 .map(|attribute| attribute.value)
685 }
686
687 #[must_use]
689 pub fn text_content(&self, id: NodeId) -> String {
690 let mut out = String::new();
691 self.collect_text(id, &mut out);
692 out
693 }
694
695 fn collect_text(&self, id: NodeId, out: &mut String) {
696 if let Some(text) = self.text(id) {
697 out.push_str(text);
698 }
699 for child in self.children(id) {
700 self.collect_text(*child, out);
701 }
702 }
703
704 fn name_is(&self, name: &Name<'_>, namespace: Option<&str>, local: &str) -> bool {
705 let uri = name.namespace.map(|ns| self.namespace_uri(ns));
706 name.local == local && uri == namespace
707 }
708
709 fn node(&self, id: NodeId) -> Option<&Node> {
710 self.nodes.get(id.0 as usize)
711 }
712}
713
714fn push_str_arena(strings: &mut String, text: &str) -> StrSpan {
716 if text.is_empty() {
717 return StrSpan::EMPTY;
718 }
719 let start = u32::try_from(strings.len()).unwrap_or(u32::MAX);
720 let len = u32::try_from(text.len()).unwrap_or(u32::MAX);
721 strings.push_str(text);
722 StrSpan { start, len }
723}
724
725struct Builder {
726 limits: Limits,
727 nodes: Vec<Node>,
728 children_pool: Vec<NodeId>,
729 pending_children: Vec<Vec<NodeId>>,
731 attrs: Vec<ArenaAttr>,
732 strings: String,
733 interned_names: HashMap<String, StrSpan>,
735 top: Vec<NodeId>,
736 stack: Vec<NodeId>,
737 scope_stack: Vec<Option<ScopeId>>,
739 scopes: Vec<Scope>,
740 namespaces: Vec<String>,
741 namespace_ids: HashMap<String, NamespaceId>,
742 aliases: HashMap<String, String>,
743 undeclared_prefixes: Vec<String>,
744 undeclared_seen: HashSet<String>,
745 offset: u64,
748 base_offset: u64,
750 skipped: u64,
753 encoding: Option<String>,
755}
756
757impl Builder {
758 fn new(limits: Limits, aliases: &[(&str, &str)]) -> Self {
759 Self {
760 limits,
761 nodes: Vec::new(),
762 children_pool: Vec::new(),
763 pending_children: Vec::new(),
764 attrs: Vec::new(),
765 strings: String::new(),
766 interned_names: HashMap::new(),
767 top: Vec::new(),
768 stack: Vec::new(),
769 scope_stack: Vec::new(),
770 scopes: Vec::new(),
771 namespaces: Vec::new(),
772 namespace_ids: HashMap::new(),
773 aliases: aliases
774 .iter()
775 .map(|(from, to)| ((*from).to_owned(), (*to).to_owned()))
776 .collect(),
777 undeclared_prefixes: Vec::new(),
778 undeclared_seen: HashSet::new(),
779 offset: 0,
780 base_offset: 0,
781 skipped: 0,
782 encoding: None,
783 }
784 }
785
786 fn intern_name(&mut self, name: &str) -> StrSpan {
787 if name.is_empty() {
788 return StrSpan::EMPTY;
789 }
790 if let Some(&span) = self.interned_names.get(name) {
791 return span;
792 }
793 let span = push_str_arena(&mut self.strings, name);
794 self.interned_names.insert(name.to_owned(), span);
795 span
796 }
797
798 fn run(mut self, bytes: &[u8]) -> Result<Document, Error> {
799 u32::try_from(
800 u64::try_from(bytes.len())
801 .unwrap_or(u64::MAX)
802 .saturating_add(self.base_offset),
803 )
804 .map_err(|_| Error::TooLarge)?;
805 if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
807 self.encoding = Some("UTF-16".to_owned());
808 }
809 if bytes.starts_with(&UTF8_MARK) {
810 self.skipped = UTF8_MARK.len() as u64;
811 }
812 let mut reader = NsReader::from_reader(bytes);
813 reader.config_mut().check_end_names = true;
814 let est_nodes = (bytes.len() / 64).min(self.limits.max_nodes);
815 self.nodes.reserve(est_nodes);
816 self.children_pool.reserve(est_nodes);
817 self.attrs.reserve(est_nodes);
818 self.strings.reserve(bytes.len() / 2);
819 let mut buf = Vec::new();
820 loop {
821 buf.clear();
822 let start = self.position(&reader)?;
823 let (resolved, event) = reader
824 .read_resolved_event_into(&mut buf)
825 .map_err(|error| Error::Syntax(error.to_string()))?;
826 let namespace = self.resolve(&resolved);
827 let span = Span {
828 start,
829 end: self.position(&reader)?,
830 };
831 match event {
832 Event::Eof => break,
833 Event::Start(tag) => {
834 let id = self.start_element(&reader, &tag, namespace, span)?;
835 self.open(id)?;
836 }
837 Event::Empty(tag) => {
838 self.start_element(&reader, &tag, namespace, span)?;
839 }
840 Event::End(_) => {
841 self.close(span.end);
842 }
843 other => self.leaf(other, span)?,
844 }
845 }
846 if self.stack.is_empty() {
847 Ok(Document {
848 nodes: self.nodes,
849 children_pool: self.children_pool,
850 attrs: self.attrs,
851 strings: self.strings,
852 top: self.top,
853 namespaces: self.namespaces,
854 scopes: self.scopes,
855 undeclared_prefixes: self.undeclared_prefixes,
856 encoding: self.encoding,
857 })
858 } else {
859 Err(Error::Syntax("unclosed element".to_owned()))
860 }
861 }
862
863 fn position(&self, reader: &NsReader<&[u8]>) -> Result<u32, Error> {
866 let position = (reader.buffer_position() + self.skipped)
867 .saturating_sub(self.offset)
868 .saturating_add(self.base_offset);
869 u32::try_from(position).map_err(|_| Error::TooLarge)
870 }
871
872 fn leaf(&mut self, event: Event<'_>, span: Span) -> Result<(), Error> {
873 match event {
874 Event::Text(text) => self.add_text(&text.xml10_content(), span),
875 Event::CData(data) => self.add_text(&data.into_inner(), span),
876 Event::GeneralRef(reference) => self.add_text(&resolve_reference(&reference)?, span),
877 Event::DocType(_) => Err(Error::DocType),
878 Event::Comment(comment) => {
879 let raw = comment.into_inner();
880 let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
881 self.strings.push_str("<!--");
882 self.strings.push_str(&raw);
883 self.strings.push_str("-->");
884 let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
885 self.add(ArenaKind::Other(StrSpan { start, len }), span)
886 .map(|_| ())
887 }
888 Event::Decl(declaration) => {
889 if self.encoding.is_none() {
890 self.encoding = declared_encoding(&declaration);
891 }
892 self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ())
893 }
894 Event::PI(_) => self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ()),
895 Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof => Ok(()),
896 }
897 }
898
899 fn resolve(&mut self, resolved: &ResolveResult<'_>) -> Option<NamespaceId> {
900 match resolved {
901 ResolveResult::Bound(namespace) => Some(self.intern(namespace.as_ref())),
902 ResolveResult::Unbound => None,
903 ResolveResult::Unknown(prefix) => {
904 if self.undeclared_seen.insert(prefix.clone()) {
905 self.undeclared_prefixes.push(prefix.clone());
906 }
907 None
908 }
909 }
910 }
911
912 fn intern(&mut self, uri: &str) -> NamespaceId {
913 let uri = self.aliases.get(uri).map_or(uri, String::as_str);
914 if let Some(id) = self.namespace_ids.get(uri) {
915 return *id;
916 }
917 let id = NamespaceId(u32::try_from(self.namespaces.len()).unwrap_or(u32::MAX));
918 let owned = uri.to_owned();
919 self.namespaces.push(owned.clone());
920 self.namespace_ids.insert(owned, id);
921 id
922 }
923
924 fn start_element(
925 &mut self,
926 reader: &NsReader<&[u8]>,
927 start: &BytesStart<'_>,
928 namespace: Option<NamespaceId>,
929 span: Span,
930 ) -> Result<NodeId, Error> {
931 let (prefix, local) = self.split_name(start.name());
932 let attr_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
933 for attribute in start.attributes() {
934 let attribute = attribute.map_err(|error| Error::Syntax(error.to_string()))?;
935 let (resolved, _) = reader.resolver().resolve_attribute(attribute.key);
936 let attr_ns = self.resolve(&resolved);
937 let (attr_prefix, attr_local) = self.split_name(attribute.key);
938 let value = attribute
939 .normalized_value(XmlVersion::Implicit1_0)
940 .map_err(|error| Error::Syntax(error.to_string()))?;
941 let value_span = push_str_arena(&mut self.strings, &value);
942 self.attrs.push(ArenaAttr {
943 prefix: attr_prefix,
944 local: attr_local,
945 namespace: attr_ns,
946 value: value_span,
947 });
948 }
949 let attr_len = u32::try_from(self.attrs.len())
950 .unwrap_or(u32::MAX)
951 .saturating_sub(attr_start);
952 let attrs = SliceRange {
953 start: attr_start,
954 len: attr_len,
955 };
956 let scope = self.scope_of(attrs)?;
957 let id = self.add(
958 ArenaKind::Element {
959 prefix,
960 local,
961 namespace,
962 attrs,
963 },
964 span,
965 )?;
966 if let Some(node) = self.nodes.get_mut(id.0 as usize) {
967 node.scope = scope;
968 }
969 Ok(id)
970 }
971
972 fn split_name(&mut self, name: QName<'_>) -> (Option<StrSpan>, StrSpan) {
973 let local = self.intern_name(name.local_name().as_ref());
974 let prefix = name
975 .prefix()
976 .map(|prefix| self.intern_name(prefix.as_ref()));
977 (prefix, local)
978 }
979
980 fn scope_of(&mut self, attrs: SliceRange) -> Result<Option<ScopeId>, Error> {
983 let outer = self.scope_stack.last().copied().flatten();
984 let declared: Vec<(String, String)> = self
985 .attrs
986 .get(attrs.bounds())
987 .unwrap_or(&[])
988 .iter()
989 .filter_map(|attribute| {
990 let prefix_str = attribute.prefix.map(|span| span.slice(&self.strings));
991 let local_str = attribute.local.slice(&self.strings);
992 let binding_prefix = match prefix_str {
993 Some("xmlns") => local_str.to_owned(),
994 None if local_str == "xmlns" => String::new(),
995 _ => return None,
996 };
997 Some((
998 binding_prefix,
999 attribute.value.slice(&self.strings).to_owned(),
1000 ))
1001 })
1002 .collect();
1003 if declared.is_empty() {
1004 return Ok(outer);
1005 }
1006 let bindings = declared
1007 .into_iter()
1008 .map(|(prefix, uri)| (prefix, self.intern(&uri)))
1009 .collect();
1010 let id = ScopeId(u32::try_from(self.scopes.len()).map_err(|_| Error::TooManyNodes)?);
1011 self.scopes.push(Scope { outer, bindings });
1012 Ok(Some(id))
1013 }
1014
1015 fn add_text(&mut self, text: &str, span: Span) -> Result<(), Error> {
1018 let last = self.siblings().last().copied();
1019 if let Some(last_id) = last
1020 && let Some(Node {
1021 kind: ArenaKind::Text(prev_span),
1022 ..
1023 }) = self.nodes.get(last_id.0 as usize).copied()
1024 {
1025 let prev_end = (prev_span.start as usize).saturating_add(prev_span.len as usize);
1026 let new_span = if prev_end == self.strings.len() {
1027 self.strings.push_str(text);
1028 StrSpan {
1029 start: prev_span.start,
1030 len: prev_span
1031 .len
1032 .saturating_add(u32::try_from(text.len()).unwrap_or(u32::MAX)),
1033 }
1034 } else {
1035 let prev_text = prev_span.slice(&self.strings).to_owned();
1036 let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
1037 self.strings.push_str(&prev_text);
1038 self.strings.push_str(text);
1039 let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
1040 StrSpan { start, len }
1041 };
1042 if let Some(node) = self.nodes.get_mut(last_id.0 as usize) {
1043 node.kind = ArenaKind::Text(new_span);
1044 node.span.end = span.end;
1045 }
1046 return Ok(());
1047 }
1048 let text_span = push_str_arena(&mut self.strings, text);
1049 self.add(ArenaKind::Text(text_span), span).map(|_| ())
1050 }
1051
1052 fn siblings(&self) -> &[NodeId] {
1053 let depth = self.stack.len();
1054 if depth == 0 {
1055 &self.top
1056 } else {
1057 self.pending_children
1058 .get(depth - 1)
1059 .map_or(&[], Vec::as_slice)
1060 }
1061 }
1062
1063 fn add(&mut self, kind: ArenaKind, span: Span) -> Result<NodeId, Error> {
1064 if self.nodes.len() >= self.limits.max_nodes {
1065 return Err(Error::TooManyNodes);
1066 }
1067 let id = NodeId(u32::try_from(self.nodes.len()).map_err(|_| Error::TooManyNodes)?);
1068 self.nodes.push(Node {
1069 kind,
1070 children: SliceRange::EMPTY,
1071 scope: None,
1072 span,
1073 });
1074 let depth = self.stack.len();
1075 if depth == 0 {
1076 self.top.push(id);
1077 } else if let Some(slot) = self.pending_children.get_mut(depth - 1) {
1078 slot.push(id);
1079 }
1080 Ok(id)
1081 }
1082
1083 fn open(&mut self, id: NodeId) -> Result<(), Error> {
1084 if self.stack.len() >= self.limits.max_depth {
1085 return Err(Error::TooDeep);
1086 }
1087 let depth = self.stack.len();
1088 if depth == self.pending_children.len() {
1089 self.pending_children.push(Vec::new());
1090 } else if let Some(slot) = self.pending_children.get_mut(depth) {
1091 slot.clear();
1092 }
1093 self.stack.push(id);
1094 let scope = self.nodes.get(id.0 as usize).and_then(|node| node.scope);
1095 self.scope_stack.push(scope);
1096 Ok(())
1097 }
1098
1099 fn close(&mut self, end: u32) {
1100 let Some(parent_id) = self.stack.pop() else {
1101 return;
1102 };
1103 let depth = self.stack.len();
1104 let range = if let Some(slot) = self.pending_children.get_mut(depth) {
1105 if slot.is_empty() {
1106 SliceRange::EMPTY
1107 } else {
1108 let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
1109 let len = u32::try_from(slot.len()).unwrap_or(u32::MAX);
1110 self.children_pool.extend_from_slice(slot);
1111 slot.clear();
1112 SliceRange { start, len }
1113 }
1114 } else {
1115 SliceRange::EMPTY
1116 };
1117 if let Some(node) = self.nodes.get_mut(parent_id.0 as usize) {
1118 node.span.end = end;
1119 node.children = range;
1120 }
1121 self.scope_stack.pop();
1122 }
1123}
1124
1125fn declared_encoding(declaration: &BytesDecl<'_>) -> Option<String> {
1127 let name = declaration.encoding()?.ok()?;
1128 let utf8 = name.eq_ignore_ascii_case("utf-8") || name.eq_ignore_ascii_case("utf8");
1129 (!utf8).then(|| name.into_owned())
1130}
1131
1132fn resolve_reference(reference: &BytesRef<'_>) -> Result<Cow<'static, str>, Error> {
1133 if let Some(ch) = reference
1134 .resolve_char_ref()
1135 .map_err(|error| Error::Syntax(error.to_string()))?
1136 {
1137 return Ok(Cow::Owned(ch.to_string()));
1138 }
1139 let name: &str = reference.as_ref();
1140 let text = match name {
1141 "lt" => "<",
1142 "gt" => ">",
1143 "amp" => "&",
1144 "apos" => "'",
1145 "quot" => "\"",
1146 other => return Err(Error::Syntax(format!("unknown entity &{other};"))),
1147 };
1148 Ok(Cow::Borrowed(text))
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153 use super::{Document, Error, Limits, NodeKind};
1154
1155 const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1156
1157 fn parse(xml: &str) -> Result<Document, Error> {
1158 Document::parse(xml.as_bytes(), &Limits::default())
1159 }
1160
1161 #[test]
1162 fn reads_elements_attributes_and_text() {
1163 let doc = parse(&format!(
1164 r#"<?xml version="1.0"?><w:document xmlns:w="{W}"><w:p><w:r><w:t xml:space="preserve"> a & b A</w:t></w:r><w:jc w:val="both"/></w:p></w:document>"#
1165 ))
1166 .unwrap();
1167 let root = doc.root().unwrap();
1168 assert!(doc.is(root, W, "document"));
1169 let p = doc.child(root, W, "p").unwrap();
1170 let t = doc.child(doc.child(p, W, "r").unwrap(), W, "t").unwrap();
1171 assert_eq!(doc.text_content(t), " a & b A");
1172 let jc = doc.child(p, W, "jc").unwrap();
1173 assert_eq!(doc.attribute(jc, Some(W), "val"), Some("both"));
1174 assert_eq!(doc.attribute(jc, None, "val"), None);
1175 let element = doc.element(jc).unwrap();
1176 assert_eq!(element.name.prefix, Some("w"));
1177 assert_eq!(doc.namespace_uri(element.name.namespace.unwrap()), W);
1178 }
1179
1180 #[test]
1181 fn sets_the_children_of_a_node() {
1182 let mut doc = parse("<a><b>x</b><c/><d/></a>").unwrap();
1183 let root = doc.root().unwrap();
1184 let [b, c, d] = [0, 1, 2].map(|i| doc.children(root)[i]);
1185 let x = doc.children(b)[0];
1186 doc.set_children(root, vec![d, x, b]);
1187 doc.set_children(b, Vec::new());
1188 assert_eq!(doc.children(root), [d, x, b]);
1189 assert_eq!(doc.text_content(root), "x");
1190 assert_eq!(doc.children(c), []);
1191 let mut other = parse("<a/>").unwrap();
1192 other.set_children(d, vec![d]);
1193 assert_eq!(other.children(d), []);
1194 }
1195
1196 #[test]
1197 fn sets_an_attribute_of_an_element() {
1198 let mut doc = parse(&format!(r#"<w:r xmlns:w="{W}" w:rsidR="00AB">x</w:r>"#)).unwrap();
1199 let root = doc.root().unwrap();
1200 doc.set_attribute(root, Some("urn:note"), "change", "3");
1201 doc.set_attribute(root, Some(W), "rsidR", "00CD");
1202 doc.set_attribute(root, Some("urn:note"), "change", "4");
1203 assert_eq!(doc.attribute(root, Some("urn:note"), "change"), Some("4"));
1204 assert_eq!(doc.attribute(root, Some(W), "rsidR"), Some("00CD"));
1205 let text = doc.children(root)[0];
1206 doc.set_attribute(text, None, "a", "b");
1207 assert_eq!(doc.attribute(text, None, "a"), None);
1208 }
1209
1210 #[test]
1211 fn keeps_unprefixed_attributes_and_comments() {
1212 let doc = parse(r#"<Relationships><!-- note --><Relationship Id="rId1" Target="a.xml"/></Relationships>"#).unwrap();
1213 let root = doc.root().unwrap();
1214 let rel = doc.child_elements(root).next().unwrap();
1215 assert_eq!(doc.attribute(rel, None, "Id"), Some("rId1"));
1216 let comment = doc.children(root)[0];
1217 assert_eq!(doc.kind(comment), Some(NodeKind::Other("<!-- note -->")));
1218 assert!(doc.text(comment).is_none());
1219 assert!(doc.element(comment).is_none());
1220 }
1221
1222 #[test]
1223 fn joins_text_around_references_and_cdata() {
1224 let doc = parse("<a>x<y<![CDATA[<z>]]>>'"</a>").unwrap();
1225 let root = doc.root().unwrap();
1226 assert_eq!(doc.children(root).len(), 1);
1227 assert_eq!(doc.text_content(root), "x<y<z>>'\"");
1228 }
1229
1230 #[test]
1231 fn refuses_doctype_and_unknown_entities() {
1232 assert_eq!(parse("<!DOCTYPE a><a/>").unwrap_err(), Error::DocType);
1233 assert!(matches!(parse("<a>&bogus;</a>"), Err(Error::Syntax(_))));
1234 assert_eq!(
1235 parse("<!-- only -->").unwrap().root().unwrap_err(),
1236 Error::NoRoot
1237 );
1238 }
1239
1240 #[test]
1241 fn refuses_bad_nesting() {
1242 assert!(matches!(parse("<a><b></a>"), Err(Error::Syntax(_))));
1243 assert!(matches!(parse("<a>"), Err(Error::Syntax(_))));
1244 }
1245
1246 fn undeclared() -> Document {
1247 parse(&format!(
1248 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>"#
1249 ))
1250 .unwrap()
1251 }
1252
1253 #[test]
1254 fn lists_each_undeclared_prefix_once_and_gives_its_elements_no_namespace() {
1255 let doc = undeclared();
1256 assert_eq!(doc.undeclared_prefixes(), ["p", "q"]);
1257 let root = doc.root().unwrap();
1258 let [a, _, e] = [0, 1, 2].map(|i| doc.children(root)[i]);
1259 let element = doc.element(a).unwrap();
1260 assert_eq!(element.name.prefix, Some("p"));
1261 assert_eq!(element.name.namespace, None);
1262 assert!(doc.is(e, W, "e"));
1263 let declared = parse(&format!(r#"<w:a xmlns:w="{W}" xml:space="preserve"/>"#)).unwrap();
1264 assert_eq!(declared.undeclared_prefixes(), [] as [&str; 0]);
1265 }
1266
1267 #[test]
1268 fn reads_an_attribute_of_an_undeclared_prefix_as_one_without_a_prefix() {
1269 let doc = undeclared();
1270 let root = doc.root().unwrap();
1271 let [a, e] = [0, 2].map(|i| doc.children(root)[i]);
1272 assert_eq!(doc.attribute(a, None, "b"), Some("1"));
1273 assert_eq!(doc.attribute(a, Some(W), "c"), Some("2"));
1274 assert_eq!(doc.attribute(e, None, "f"), Some("3"));
1275 }
1276
1277 #[test]
1278 fn resolves_namespace_aliases() {
1279 let xml = r#"<s:document xmlns:s="urn:strict"><s:body s:val="1"/></s:document>"#;
1280 let doc =
1281 Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
1282 .unwrap();
1283 let root = doc.root().unwrap();
1284 assert!(doc.is(root, W, "document"));
1285 let body = doc.child(root, W, "body").unwrap();
1286 assert_eq!(doc.attribute(body, Some(W), "val"), Some("1"));
1287 let plain = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
1288 assert!(!plain.is(plain.root().unwrap(), W, "document"));
1289 }
1290
1291 #[test]
1292 fn binds_a_prefix_by_the_nearest_declaration_in_scope() {
1293 let doc = parse(concat!(
1294 r#"<a xmlns:p="urn:outer" xmlns="urn:default">"#,
1295 r#"<b xmlns:p="urn:inner" xmlns:q="urn:q"><c/></b><d/><e xmlns=""/>t</a>"#,
1296 ))
1297 .unwrap();
1298 let root = doc.root().unwrap();
1299 let [b, d, e, text] = [0, 1, 2, 3].map(|i| doc.children(root)[i]);
1300 let c = doc.children(b)[0];
1301 let cases = [
1302 (root, "p", Some("urn:outer")),
1303 (c, "p", Some("urn:inner")),
1304 (c, "q", Some("urn:q")),
1305 (d, "p", Some("urn:outer")),
1306 (d, "q", None),
1307 (c, "", Some("urn:default")),
1308 (e, "", None),
1309 (e, "xml", Some(super::XML_NAMESPACE)),
1310 (text, "p", None),
1311 (text, "xml", None),
1312 ];
1313 for (node, prefix, namespace) in cases {
1314 assert_eq!(
1315 doc.prefix_namespace(node, prefix),
1316 namespace,
1317 "{node:?} {prefix}"
1318 );
1319 }
1320 }
1321
1322 #[test]
1323 fn binds_a_prefix_to_its_alias() {
1324 let xml = r#"<a xmlns:s="urn:strict"><b/></a>"#;
1325 let doc =
1326 Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
1327 .unwrap();
1328 let b = doc.children(doc.root().unwrap())[0];
1329 assert_eq!(doc.prefix_namespace(b, "s"), Some(W));
1330 }
1331
1332 #[test]
1333 fn enforces_limits() {
1334 let deep = Limits {
1335 max_depth: 2,
1336 max_nodes: 100,
1337 };
1338 assert_eq!(
1339 Document::parse(b"<a><b><c/></b></a>", &deep).map(|_| ()),
1340 Ok(())
1341 );
1342 assert_eq!(
1343 Document::parse(b"<a><b><c></c></b></a>", &deep).unwrap_err(),
1344 Error::TooDeep
1345 );
1346 let few = Limits {
1347 max_depth: 10,
1348 max_nodes: 2,
1349 };
1350 assert_eq!(
1351 Document::parse(b"<a><b/><c/></a>", &few).unwrap_err(),
1352 Error::TooManyNodes
1353 );
1354 }
1355
1356 #[test]
1357 fn errors_display() {
1358 for error in [
1359 Error::Syntax("x".into()),
1360 Error::DocType,
1361 Error::TooDeep,
1362 Error::TooManyNodes,
1363 Error::NoRoot,
1364 ] {
1365 assert_ne!(error.to_string(), "");
1366 }
1367 }
1368}