1use std::borrow::Cow;
24use std::cmp::Ordering;
25use std::collections::HashMap;
26use std::fmt::{self, Write as _};
27use std::path::Path;
28use std::rc::Rc;
29use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
30
31use einvoice_xdm::AtomicValue;
32use einvoice_xpath::{QName, XML_NAMESPACE};
33
34use crate::limit::{DEFAULT_MAX_DEPTH, LimitExceeded};
35
36const NONE: u32 = u32::MAX;
38
39static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum NodeKind {
45 Document,
47 Element,
49 Attribute,
51 Text,
53 Comment,
55 ProcessingInstruction,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum NodeAxis {
63 Child,
65 Attribute,
67 SelfAxis,
69 Descendant,
71 DescendantOrSelf,
73 FollowingSibling,
75 Parent,
77 Ancestor,
79 AncestorOrSelf,
81 PrecedingSibling,
83 Preceding,
85}
86
87impl NodeAxis {
88 #[must_use]
90 pub const fn is_reverse(self) -> bool {
91 matches!(
92 self,
93 Self::Parent
94 | Self::Ancestor
95 | Self::AncestorOrSelf
96 | Self::PrecedingSibling
97 | Self::Preceding
98 )
99 }
100}
101
102#[derive(Debug, Clone, Copy)]
109struct Record {
110 kind: NodeKind,
111 name: u32,
113 parent: u32,
114 prev_sibling: u32,
115 first_child: u32,
118 end: u32,
120 text_start: u32,
124 text_len: u32,
125}
126
127impl Record {
128 const fn new(
130 kind: NodeKind,
131 name: u32,
132 parent: u32,
133 prev_sibling: u32,
134 index: u32,
135 (text_start, text_len): (u32, u32),
136 ) -> Self {
137 Self {
138 kind,
139 name,
140 parent,
141 prev_sibling,
142 first_child: index + 1,
143 end: index + 1,
144 text_start,
145 text_len,
146 }
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct DocumentError {
153 message: String,
154 limit: Option<LimitExceeded>,
155}
156
157impl DocumentError {
158 fn new(message: impl Into<String>) -> Self {
159 Self {
160 message: message.into(),
161 limit: None,
162 }
163 }
164
165 fn limit_exceeded(limit: LimitExceeded) -> Self {
166 Self {
167 message: limit.to_string(),
168 limit: Some(limit),
169 }
170 }
171
172 #[must_use]
174 pub fn message(&self) -> &str {
175 &self.message
176 }
177
178 #[must_use]
181 pub const fn limit(&self) -> Option<LimitExceeded> {
182 self.limit
183 }
184}
185
186impl fmt::Display for DocumentError {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.write_str(&self.message)
189 }
190}
191
192impl std::error::Error for DocumentError {}
193
194pub struct Document {
201 serial: u64,
202 uri: Option<String>,
203 base_uri: Option<String>,
204 has_xml_base: bool,
205 records: Vec<Record>,
206 names: Vec<QName>,
207 source: String,
209 text: String,
211}
212
213impl fmt::Debug for Document {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 f.debug_struct("Document")
216 .field("serial", &self.serial)
217 .field("uri", &self.uri)
218 .field("nodes", &self.records.len())
219 .finish_non_exhaustive()
220 }
221}
222
223impl Document {
224 pub fn parse<'t>(
249 text: impl Into<Cow<'t, str>>,
250 base_uri: Option<&str>,
251 ) -> Result<Rc<Self>, DocumentError> {
252 Self::parse_with_uris(text.into(), None, base_uri, DEFAULT_MAX_DEPTH)
253 }
254
255 pub fn parse_with_max_depth<'t>(
264 text: impl Into<Cow<'t, str>>,
265 base_uri: Option<&str>,
266 max_depth: u32,
267 ) -> Result<Rc<Self>, DocumentError> {
268 Self::parse_with_uris(text.into(), None, base_uri, max_depth)
269 }
270
271 pub fn parse_loaded<'t>(
279 text: impl Into<Cow<'t, str>>,
280 uri: &str,
281 ) -> Result<Rc<Self>, DocumentError> {
282 Self::parse_with_uris(text.into(), Some(uri), Some(uri), DEFAULT_MAX_DEPTH)
283 }
284
285 pub fn parse_loaded_with_max_depth<'t>(
292 text: impl Into<Cow<'t, str>>,
293 uri: &str,
294 max_depth: u32,
295 ) -> Result<Rc<Self>, DocumentError> {
296 Self::parse_with_uris(text.into(), Some(uri), Some(uri), max_depth)
297 }
298
299 fn parse_with_uris(
300 text: Cow<'_, str>,
301 document_uri: Option<&str>,
302 base_uri: Option<&str>,
303 max_depth: u32,
304 ) -> Result<Rc<Self>, DocumentError> {
305 let keep_source = matches!(text, Cow::Owned(_));
306 let builder = build_parsed(&text, keep_source, max_depth)?;
307 let source = match text {
308 Cow::Owned(source) => source,
309 Cow::Borrowed(_) => String::new(),
310 };
311 builder.finish_with_source(
312 source,
313 document_uri.map(str::to_owned),
314 base_uri.map(str::to_owned),
315 )
316 }
317
318 #[must_use]
320 pub fn root(self: &Rc<Self>) -> Node {
321 Node {
322 doc: Rc::clone(self),
323 index: 0,
324 }
325 }
326
327 #[must_use]
330 pub fn document_uri(&self) -> Option<&str> {
331 self.uri.as_deref()
332 }
333
334 #[must_use]
336 pub fn base_uri(&self) -> Option<&str> {
337 self.base_uri.as_deref()
338 }
339
340 #[must_use]
343 pub const fn has_xml_base(&self) -> bool {
344 self.has_xml_base
345 }
346
347 #[must_use]
349 pub fn node_count(&self) -> usize {
350 self.records.len()
351 }
352
353 fn record(&self, index: u32) -> &Record {
354 &self.records[index as usize]
356 }
357
358 pub(crate) fn kind(&self, index: u32) -> NodeKind {
359 self.record(index).kind
360 }
361
362 pub(crate) fn name(&self, index: u32) -> Option<&QName> {
363 let name = self.record(index).name;
364 (name != NONE).then(|| &self.names[name as usize])
365 }
366
367 pub(crate) fn parent_index(&self, index: u32) -> Option<u32> {
368 let parent = self.record(index).parent;
369 (parent != NONE).then_some(parent)
370 }
371
372 fn own_text(&self, index: u32) -> &str {
375 let r = self.record(index);
376 let start = r.text_start as usize;
377 let end = start + r.text_len as usize;
378 match start.checked_sub(self.source.len()) {
379 None => &self.source[start..end],
380 Some(start) => &self.text[start..end - self.source.len()],
381 }
382 }
383
384 pub(crate) fn string_value(&self, index: u32) -> Cow<'_, str> {
385 match self.kind(index) {
386 NodeKind::Text
387 | NodeKind::Comment
388 | NodeKind::ProcessingInstruction
389 | NodeKind::Attribute => Cow::Borrowed(self.own_text(index)),
390 NodeKind::Element | NodeKind::Document => {
391 let mut texts = self
392 .cursor(index, NodeAxis::Descendant)
393 .walk(self)
394 .filter(|&i| self.kind(i) == NodeKind::Text);
395 let Some(first) = texts.next() else {
396 return Cow::Borrowed("");
397 };
398 let Some(second) = texts.next() else {
399 return Cow::Borrowed(self.own_text(first));
400 };
401 let mut value = String::from(self.own_text(first));
402 value.push_str(self.own_text(second));
403 for i in texts {
404 value.push_str(self.own_text(i));
405 }
406 Cow::Owned(value)
407 }
408 }
409 }
410
411 pub(crate) fn cursor(&self, index: u32, axis: NodeAxis) -> Cursor {
413 let r = self.record(index);
414 let kind = r.kind;
415 let is_attribute = kind == NodeKind::Attribute;
416 match axis {
417 NodeAxis::SelfAxis => Cursor::One(index),
418 NodeAxis::Parent => match r.parent {
419 NONE => Cursor::Done,
420 parent => Cursor::One(parent),
421 },
422 NodeAxis::Child => Cursor::Siblings {
423 next: r.first_child,
424 end: r.end,
425 },
426 NodeAxis::Attribute => {
427 if kind == NodeKind::Element {
428 Cursor::Range {
429 next: index + 1,
430 end: r.first_child,
431 }
432 } else {
433 Cursor::Done
434 }
435 }
436 NodeAxis::Descendant => Cursor::Descendants {
437 next: r.first_child,
438 end: r.end,
439 },
440 NodeAxis::DescendantOrSelf => Cursor::Descendants {
441 next: index,
442 end: r.end,
443 },
444 NodeAxis::FollowingSibling => match r.parent {
445 NONE => Cursor::Done,
446 _ if is_attribute => Cursor::Done,
447 parent => Cursor::Siblings {
448 next: r.end,
449 end: self.record(parent).end,
450 },
451 },
452 NodeAxis::Ancestor => Cursor::Ancestors { next: r.parent },
453 NodeAxis::AncestorOrSelf => Cursor::Ancestors { next: index },
454 NodeAxis::PrecedingSibling => {
455 if is_attribute {
456 Cursor::Done
457 } else {
458 Cursor::PrecedingSiblings {
459 next: r.prev_sibling,
460 }
461 }
462 }
463 NodeAxis::Preceding => Cursor::Preceding {
464 next: index,
465 ancestor: r.parent,
466 },
467 }
468 }
469}
470
471#[derive(Debug, Clone, Copy)]
473pub(crate) enum Cursor {
474 Done,
475 One(u32),
476 Range {
478 next: u32,
479 end: u32,
480 },
481 Siblings {
483 next: u32,
484 end: u32,
485 },
486 Descendants {
488 next: u32,
489 end: u32,
490 },
491 Ancestors {
492 next: u32,
493 },
494 PrecedingSiblings {
495 next: u32,
496 },
497 Preceding {
500 next: u32,
501 ancestor: u32,
502 },
503}
504
505impl Cursor {
506 pub(crate) fn next(&mut self, doc: &Document) -> Option<u32> {
507 match self {
508 Self::Done => None,
509 Self::One(index) => {
510 let index = *index;
511 *self = Self::Done;
512 Some(index)
513 }
514 Self::Range { next, end } => {
515 if *next >= *end {
516 return None;
517 }
518 let index = *next;
519 *next += 1;
520 Some(index)
521 }
522 Self::Siblings { next, end } => {
523 if *next >= *end {
524 return None;
525 }
526 let index = *next;
527 *next = doc.record(index).end;
528 Some(index)
529 }
530 Self::Descendants { next, end } => {
531 if *next >= *end {
532 return None;
533 }
534 let index = *next;
535 *next = doc.record(index).first_child;
537 Some(index)
538 }
539 Self::Ancestors { next } => {
540 if *next == NONE {
541 return None;
542 }
543 let index = *next;
544 *next = doc.record(index).parent;
545 Some(index)
546 }
547 Self::PrecedingSiblings { next } => {
548 if *next == NONE {
549 return None;
550 }
551 let index = *next;
552 *next = doc.record(index).prev_sibling;
553 Some(index)
554 }
555 Self::Preceding { next, ancestor } => loop {
556 if *next == 0 {
557 return None;
558 }
559 *next -= 1;
560 let index = *next;
561 if index == *ancestor {
562 *ancestor = doc.record(index).parent;
563 continue;
564 }
565 if doc.record(index).kind != NodeKind::Attribute {
566 return Some(index);
567 }
568 },
569 }
570 }
571
572 pub(crate) fn walk(self, doc: &Document) -> impl Iterator<Item = u32> + '_ {
574 let mut cursor = self;
575 std::iter::from_fn(move || cursor.next(doc))
576 }
577}
578
579#[derive(Clone)]
583pub struct Node {
584 doc: Rc<Document>,
585 index: u32,
586}
587
588impl PartialEq for Node {
589 fn eq(&self, other: &Self) -> bool {
590 self.index == other.index && Rc::ptr_eq(&self.doc, &other.doc)
591 }
592}
593
594impl Eq for Node {}
595
596impl fmt::Debug for Node {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598 write!(f, "Node({:?}", self.kind())?;
599 if let Some(name) = self.name() {
600 write!(f, " {name}")?;
601 }
602 write!(f, " #{} of document {})", self.index, self.doc.serial)
603 }
604}
605
606impl Node {
607 pub(crate) fn new(doc: Rc<Document>, index: u32) -> Self {
608 Self { doc, index }
609 }
610
611 pub(crate) const fn index(&self) -> u32 {
612 self.index
613 }
614
615 #[must_use]
617 pub fn document(&self) -> &Rc<Document> {
618 &self.doc
619 }
620
621 #[must_use]
623 pub fn kind(&self) -> NodeKind {
624 self.doc.kind(self.index)
625 }
626
627 #[must_use]
630 pub fn name(&self) -> Option<&QName> {
631 self.doc.name(self.index)
632 }
633
634 #[must_use]
636 pub fn parent(&self) -> Option<Self> {
637 self.doc
638 .parent_index(self.index)
639 .map(|p| Self::new(Rc::clone(&self.doc), p))
640 }
641
642 #[must_use]
644 pub fn root(&self) -> Self {
645 Self::new(Rc::clone(&self.doc), 0)
646 }
647
648 #[must_use]
650 pub fn string_value(&self) -> Cow<'_, str> {
651 self.doc.string_value(self.index)
652 }
653
654 #[must_use]
657 pub fn typed_value(&self) -> AtomicValue {
658 let value = self.string_value().into_owned();
659 match self.kind() {
660 NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
661 _ => AtomicValue::UntypedAtomic(value),
662 }
663 }
664
665 #[must_use]
668 pub fn axis(&self, axis: NodeAxis) -> Axis {
669 Axis {
670 cursor: self.doc.cursor(self.index, axis),
671 doc: Rc::clone(&self.doc),
672 }
673 }
674
675 #[must_use]
677 pub fn children(&self) -> Axis {
678 self.axis(NodeAxis::Child)
679 }
680
681 #[must_use]
683 pub fn attributes(&self) -> Axis {
684 self.axis(NodeAxis::Attribute)
685 }
686
687 #[must_use]
690 pub fn cmp_document_order(&self, other: &Self) -> Ordering {
691 self.doc
692 .serial
693 .cmp(&other.doc.serial)
694 .then(self.index.cmp(&other.index))
695 }
696}
697
698#[derive(Debug, Clone)]
700pub struct Axis {
701 cursor: Cursor,
702 doc: Rc<Document>,
703}
704
705impl Iterator for Axis {
706 type Item = Node;
707
708 fn next(&mut self) -> Option<Node> {
709 let index = self.cursor.next(&self.doc)?;
710 Some(Node::new(Rc::clone(&self.doc), index))
711 }
712}
713
714#[derive(Debug)]
720pub struct TreeBuilder {
721 records: Vec<Record>,
722 names: Vec<QName>,
723 name_ids: HashMap<QName, u32>,
724 source_len: usize,
727 text: String,
728 open: Vec<u32>,
730 last_child: Vec<u32>,
732 has_xml_base: bool,
733}
734
735impl Default for TreeBuilder {
736 fn default() -> Self {
737 Self::new()
738 }
739}
740
741fn to_u32(value: usize) -> Result<u32, DocumentError> {
742 u32::try_from(value)
743 .ok()
744 .filter(|&v| v != NONE)
745 .ok_or_else(|| DocumentError::new("document too large"))
746}
747
748#[derive(Debug, Clone, Copy)]
750enum NodeText<'s> {
751 Source(u32, u32),
753 Copy(&'s str),
755}
756
757impl TreeBuilder {
758 #[must_use]
760 pub fn new() -> Self {
761 Self {
762 records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
763 names: Vec::new(),
764 name_ids: HashMap::new(),
765 source_len: 0,
766 text: String::new(),
767 open: vec![0],
768 last_child: vec![NONE],
769 has_xml_base: false,
770 }
771 }
772
773 fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
777 let mut builder = Self::new();
778 builder.records.reserve_exact(nodes.saturating_sub(1));
779 builder.text.reserve_exact(text);
780 builder.source_len = source_len;
781 builder
782 }
783
784 fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
785 if let Some(&id) = self.name_ids.get(&name) {
786 return Ok(id);
787 }
788 let id = self.push_name(name.clone())?;
789 self.name_ids.insert(name, id);
790 Ok(id)
791 }
792
793 fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
795 let id = to_u32(self.names.len())?;
796 self.names.push(name);
797 Ok(id)
798 }
799
800 fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
802 match value {
803 NodeText::Source(start, len) => Ok((start, len)),
804 NodeText::Copy(value) => {
805 let start = to_u32(self.source_len + self.text.len())?;
806 let len = to_u32(value.len())?;
807 to_u32(self.source_len + self.text.len() + value.len())?;
808 self.text.push_str(value);
809 Ok((start, len))
810 }
811 }
812 }
813
814 fn top(&self) -> u32 {
815 self.open.last().copied().unwrap_or(0)
816 }
817
818 fn append(
821 &mut self,
822 kind: NodeKind,
823 name: u32,
824 text: NodeText<'_>,
825 ) -> Result<u32, DocumentError> {
826 let index = to_u32(self.records.len())?;
827 to_u32(self.records.len() + 1)?;
828 let text = if kind == NodeKind::Element {
829 (0, 0)
830 } else {
831 self.store_text(text)?
832 };
833 let parent = self.top();
834 let last = self.last_child.last_mut().map_or(NONE, |l| {
835 let previous = *l;
836 *l = index;
837 previous
838 });
839 self.records
840 .push(Record::new(kind, name, parent, last, index, text));
841 Ok(index)
842 }
843
844 pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
850 let name = self.intern(name)?;
851 self.open_element(name)
852 }
853
854 fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
855 let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
856 self.open.push(index);
857 self.last_child.push(NONE);
858 Ok(())
859 }
860
861 pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
867 let element = self.top();
868 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
869 if element == 0 || has_content {
870 return Err(DocumentError::new(format!(
871 "attribute {name} outside an element start"
872 )));
873 }
874 let first = element as usize + 1;
875 let existing = (first..self.records.len()).find(|&i| {
876 let id = self.records[i].name;
877 self.names[id as usize].same_expanded_name(&name)
878 });
879 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
880 let id = self.intern(name)?;
881 if let Some(i) = existing {
882 let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
883 let record = &mut self.records[i];
884 record.name = id;
885 record.text_start = text_start;
886 record.text_len = text_len;
887 self.has_xml_base |= xml_base;
888 return Ok(());
889 }
890 self.push_attribute(id, xml_base, NodeText::Copy(value))
891 }
892
893 fn push_attribute(
895 &mut self,
896 name: u32,
897 xml_base: bool,
898 value: NodeText<'_>,
899 ) -> Result<(), DocumentError> {
900 let element = self.top();
901 let index = to_u32(self.records.len())?;
902 to_u32(self.records.len() + 1)?;
903 let previous = if index == element + 1 {
904 NONE
905 } else {
906 index - 1
907 };
908 let text = self.store_text(value)?;
909 self.records.push(Record::new(
910 NodeKind::Attribute,
911 name,
912 element,
913 previous,
914 index,
915 text,
916 ));
917 self.records[element as usize].first_child = index + 1;
918 self.has_xml_base |= xml_base;
919 Ok(())
920 }
921
922 pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
928 if value.is_empty() {
929 return Ok(());
930 }
931 let last = self.last_child.last().copied().unwrap_or(NONE);
932 let mergeable = last != NONE
935 && last as usize + 1 == self.records.len()
936 && self.records[last as usize].kind == NodeKind::Text
937 && {
938 let r = &self.records[last as usize];
939 r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
940 && r.text_start as usize >= self.source_len
941 };
942 if mergeable {
943 self.store_text(NodeText::Copy(value))?;
944 let record = &mut self.records[last as usize];
945 record.text_len = to_u32(record.text_len as usize + value.len())?;
946 return Ok(());
947 }
948 self.append(NodeKind::Text, NONE, NodeText::Copy(value))
949 .map(drop)
950 }
951
952 pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
958 self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
959 .map(drop)
960 }
961
962 pub fn processing_instruction(
968 &mut self,
969 target: &str,
970 value: &str,
971 ) -> Result<(), DocumentError> {
972 let name = self.intern(QName::local(target))?;
973 self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
974 .map(drop)
975 }
976
977 pub fn end_element(&mut self) -> Result<(), DocumentError> {
983 if self.open.len() < 2 {
984 return Err(DocumentError::new("end of element without a start"));
985 }
986 let element = self.top();
987 self.open.pop();
988 self.last_child.pop();
989 let end = to_u32(self.records.len())?;
990 self.records[element as usize].end = end;
991 Ok(())
992 }
993
994 pub fn finish(
1000 self,
1001 document_uri: Option<String>,
1002 base_uri: Option<String>,
1003 ) -> Result<Rc<Document>, DocumentError> {
1004 self.finish_with_source(String::new(), document_uri, base_uri)
1005 }
1006
1007 fn finish_with_source(
1010 mut self,
1011 source: String,
1012 document_uri: Option<String>,
1013 base_uri: Option<String>,
1014 ) -> Result<Rc<Document>, DocumentError> {
1015 if self.open.len() != 1 {
1016 return Err(DocumentError::new("unclosed element"));
1017 }
1018 if source.len() != self.source_len {
1019 return Err(DocumentError::new("source text of another length"));
1020 }
1021 self.records[0].end = to_u32(self.records.len())?;
1022 self.records.shrink_to_fit();
1025 self.names.shrink_to_fit();
1026 self.text.shrink_to_fit();
1027 Ok(Rc::new(Document {
1028 serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1029 uri: document_uri,
1030 base_uri,
1031 has_xml_base: self.has_xml_base,
1032 records: self.records,
1033 names: self.names,
1034 source,
1035 text: self.text,
1036 }))
1037 }
1038}
1039
1040fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1041 local == "base" && namespace == Some(XML_NAMESPACE)
1042}
1043
1044fn offset_in(input: &str, part: &str) -> Option<usize> {
1046 let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1047 (start.checked_add(part.len())? <= input.len()).then_some(start)
1048}
1049
1050type NameKey<'a> = (&'a str, Option<&'a str>, &'a str);
1053
1054fn build_parsed(
1061 input: &str,
1062 keep_source: bool,
1063 max_depth: u32,
1064) -> Result<TreeBuilder, DocumentError> {
1065 let options = roxmltree::ParsingOptions {
1066 allow_dtd: false,
1067 nodes_limit: u32::MAX,
1068 ..roxmltree::ParsingOptions::default()
1069 };
1070 let parsed = roxmltree::Document::parse_with_options(input, options)
1071 .map_err(|e| DocumentError::new(format!("XML: {e}")))?;
1072 let (nodes, text_bytes) = sizes(&parsed, input, keep_source, max_depth)?;
1073 let mut builder =
1074 TreeBuilder::with_capacity(nodes, text_bytes, if keep_source { input.len() } else { 0 });
1075 let mut names: HashMap<NameKey<'_>, u32> = HashMap::new();
1076 let node_text = |text| node_text(input, keep_source, text);
1077 let mut open: Vec<roxmltree::NodeId> = Vec::new();
1080 for node in parsed.root().descendants().skip(1) {
1081 let parent = node.parent().map(|p| p.id());
1082 while open.last().is_some_and(|&id| Some(id) != parent) {
1083 open.pop();
1084 builder.end_element()?;
1085 }
1086 match node.node_type() {
1087 roxmltree::NodeType::Root => {}
1088 roxmltree::NodeType::Element => {
1089 let tag = node.tag_name();
1090 let key = (
1091 element_prefix(input, node),
1092 tag.namespace().filter(|ns| !ns.is_empty()),
1093 tag.name(),
1094 );
1095 let id = name_id(&mut builder, &mut names, key)?;
1096 builder.open_element(id)?;
1097 for attribute in node.attributes() {
1099 let namespace = attribute.namespace().filter(|ns| !ns.is_empty());
1100 let local = attribute.name();
1101 let prefix = input
1102 .get(attribute.range_qname())
1103 .and_then(|q| q.split_once(':'))
1104 .map_or("", |(prefix, _)| prefix);
1105 let id = name_id(&mut builder, &mut names, (prefix, namespace, local))?;
1106 builder.push_attribute(
1107 id,
1108 is_xml_base(namespace, local),
1109 node_text(attribute.value())?,
1110 )?;
1111 }
1112 open.push(node.id());
1113 }
1114 roxmltree::NodeType::Text => {
1115 if is_in_element(node) {
1118 let text = node.text().unwrap_or_default();
1119 if !text.is_empty() {
1120 builder.append(NodeKind::Text, NONE, node_text(text)?)?;
1121 }
1122 }
1123 }
1124 roxmltree::NodeType::Comment => {
1125 let text = node_text(node.text().unwrap_or_default())?;
1126 builder.append(NodeKind::Comment, NONE, text)?;
1127 }
1128 roxmltree::NodeType::PI => {
1129 if let Some(pi) = node.pi() {
1130 let id = name_id(&mut builder, &mut names, ("", None, pi.target))?;
1131 let text = node_text(pi.value.unwrap_or(""))?;
1132 builder.append(NodeKind::ProcessingInstruction, id, text)?;
1133 }
1134 }
1135 }
1136 }
1137 for _ in open {
1138 builder.end_element()?;
1139 }
1140 Ok(builder)
1141}
1142
1143fn sizes(
1151 parsed: &roxmltree::Document<'_>,
1152 input: &str,
1153 keep_source: bool,
1154 max_depth: u32,
1155) -> Result<(usize, usize), DocumentError> {
1156 let copied = |text: &str| {
1157 if keep_source && offset_in(input, text).is_some() {
1158 0
1159 } else {
1160 text.len()
1161 }
1162 };
1163 let (mut nodes, mut text_bytes) = (1usize, 0usize);
1164 let mut open: Vec<roxmltree::NodeId> = Vec::new();
1167 for node in parsed.root().descendants().skip(1) {
1168 match node.node_type() {
1169 roxmltree::NodeType::Root => {}
1170 roxmltree::NodeType::Element => {
1171 let parent = node.parent().map(|p| p.id());
1172 while open.last().is_some_and(|&id| Some(id) != parent) {
1173 open.pop();
1174 }
1175 if u32::try_from(open.len()).map_or(true, |depth| depth >= max_depth) {
1176 let at = parsed.text_pos_at(node.range().start);
1177 return Err(DocumentError::limit_exceeded(LimitExceeded::Depth {
1178 max: max_depth,
1179 line: at.row,
1180 column: at.col,
1181 }));
1182 }
1183 open.push(node.id());
1184 nodes += 1;
1185 for attribute in node.attributes() {
1186 nodes += 1;
1187 text_bytes += copied(attribute.value());
1188 }
1189 }
1190 roxmltree::NodeType::Text => {
1191 if is_in_element(node) {
1192 nodes += 1;
1193 text_bytes += copied(node.text().unwrap_or_default());
1194 }
1195 }
1196 roxmltree::NodeType::Comment => {
1197 nodes += 1;
1198 text_bytes += copied(node.text().unwrap_or_default());
1199 }
1200 roxmltree::NodeType::PI => {
1201 nodes += 1;
1202 text_bytes += node.pi().map_or(0, |pi| copied(pi.value.unwrap_or("")));
1203 }
1204 }
1205 }
1206 Ok((nodes, text_bytes))
1207}
1208
1209fn name_id<'a>(
1211 builder: &mut TreeBuilder,
1212 names: &mut HashMap<NameKey<'a>, u32>,
1213 key: NameKey<'a>,
1214) -> Result<u32, DocumentError> {
1215 if let Some(&id) = names.get(&key) {
1216 return Ok(id);
1217 }
1218 let (prefix, namespace, local) = key;
1219 let id = builder.push_name(QName {
1220 prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1221 namespace: namespace.map(str::to_owned),
1222 local: local.to_owned(),
1223 })?;
1224 names.insert(key, id);
1225 Ok(id)
1226}
1227
1228fn node_text<'s>(
1231 input: &str,
1232 keep_source: bool,
1233 text: &'s str,
1234) -> Result<NodeText<'s>, DocumentError> {
1235 Ok(
1236 match keep_source.then(|| offset_in(input, text)).flatten() {
1237 Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1238 None => NodeText::Copy(text),
1239 },
1240 )
1241}
1242
1243fn is_in_element(node: roxmltree::Node<'_, '_>) -> bool {
1246 node.parent().is_some_and(|p| !p.is_root())
1247}
1248
1249fn element_prefix<'a>(input: &'a str, node: roxmltree::Node<'_, '_>) -> &'a str {
1251 let start = node.range().start + 1;
1252 let written = input
1253 .get(start..)
1254 .map(|rest| {
1255 let end = rest
1256 .find(|c: char| c.is_ascii_whitespace() || c == '/' || c == '>')
1257 .unwrap_or(rest.len());
1258 &rest[..end]
1259 })
1260 .unwrap_or_default();
1261 written.split_once(':').map_or("", |(prefix, _)| prefix)
1262}
1263
1264#[must_use]
1272pub fn file_uri(path: &Path) -> Option<String> {
1273 if !path.is_absolute() {
1274 return None;
1275 }
1276 let text = path.to_str()?.replace('\\', "/");
1277 let mut uri = String::from("file:");
1278 if !text.starts_with('/') {
1279 uri.push('/');
1280 }
1281 for c in text.chars() {
1282 let keep = if c.is_ascii() {
1283 c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1284 } else {
1285 !(matches!(
1287 c,
1288 '\u{A0}' | '\u{1680}' | '\u{2000}'
1289 ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1290 ) || c.is_control())
1291 };
1292 if keep {
1293 uri.push(c);
1294 } else {
1295 let mut buffer = [0; 4];
1296 for byte in c.encode_utf8(&mut buffer).bytes() {
1297 let _ = write!(uri, "%{byte:02X}");
1298 }
1299 }
1300 }
1301 Some(uri)
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306 use super::*;
1307
1308 fn parse(xml: &str) -> Rc<Document> {
1309 Document::parse(xml, Some("file:/t.xml")).unwrap()
1310 }
1311
1312 fn describe(node: &Node) -> String {
1313 match node.kind() {
1314 NodeKind::Document => "/".to_owned(),
1315 NodeKind::Element => node.name().unwrap().to_string(),
1316 NodeKind::Attribute => format!("@{}", node.name().unwrap()),
1317 NodeKind::Text => format!("{:?}", node.string_value()),
1318 NodeKind::Comment => format!("<!--{}-->", node.string_value()),
1319 NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
1320 }
1321 }
1322
1323 fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
1324 node.axis(axis).map(|n| describe(&n)).collect()
1325 }
1326
1327 fn find(tree: &Rc<Document>, local: &str) -> Node {
1328 tree.root()
1329 .axis(NodeAxis::Descendant)
1330 .find(|n| n.name().is_some_and(|name| name.local == local))
1331 .unwrap()
1332 }
1333
1334 const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
1335 <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
1336
1337 const NONE: [&str; 0] = [];
1338
1339 #[test]
1340 fn document_order_and_axes() {
1341 let tree = parse(XML);
1342 let root = tree.root();
1343 assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
1344 let top = find(&tree, "r");
1345 assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
1346 assert_eq!(
1347 walk(&top, NodeAxis::Child),
1348 ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
1349 );
1350 assert_eq!(
1351 walk(&top, NodeAxis::Descendant),
1352 [
1353 "\" \"",
1354 "x",
1355 "\"1\"",
1356 "y",
1357 "\"2\"",
1358 "\"3\"",
1359 "p:z",
1360 "<!--c1-->",
1361 "<?pi?>",
1362 "w",
1363 "v"
1364 ]
1365 );
1366 let y = find(&tree, "y");
1367 assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
1368 assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
1369 assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
1370 assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
1371 assert_eq!(
1372 walk(&y, NodeAxis::Preceding),
1373 ["\"1\"", "\" \"", "<!--c0-->"]
1374 );
1375 let v = find(&tree, "v");
1376 assert_eq!(
1377 walk(&v, NodeAxis::Preceding),
1378 [
1379 "<?pi?>",
1380 "<!--c1-->",
1381 "p:z",
1382 "\"3\"",
1383 "\"2\"",
1384 "y",
1385 "\"1\"",
1386 "x",
1387 "\" \"",
1388 "<!--c0-->"
1389 ]
1390 );
1391 let q = y.attributes().next().unwrap();
1392 assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
1393 assert_eq!(
1394 walk(&q, NodeAxis::Preceding),
1395 ["\"1\"", "\" \"", "<!--c0-->"]
1396 );
1397 assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
1398 assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
1399 assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
1400 assert_eq!(walk(&q, NodeAxis::Child), NONE);
1401 let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
1402 assert!(
1403 all.windows(2)
1404 .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
1405 );
1406 }
1407
1408 #[test]
1409 fn values_names_and_prefixes() {
1410 let tree = parse(XML);
1411 let top = find(&tree, "r");
1412 assert_eq!(top.string_value(), " 123");
1413 assert_eq!(find(&tree, "x").string_value(), "123");
1414 assert_eq!(find(&tree, "y").string_value(), "2");
1415 assert_eq!(find(&tree, "w").string_value(), "");
1416 let z = find(&tree, "z");
1417 assert_eq!(z.name().unwrap().to_string(), "p:z");
1418 assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
1419 let prefixed = top.attributes().nth(1).unwrap();
1420 assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
1421 assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
1422 let comment = tree.root().children().next().unwrap();
1423 assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
1424 assert_eq!(tree.document_uri(), None);
1425 assert_eq!(tree.base_uri(), Some("file:/t.xml"));
1426 let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
1427 assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
1428 assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
1429 assert_eq!(z.root(), tree.root());
1430 assert_ne!(z, top);
1431 }
1432
1433 #[test]
1434 fn undeclared_default_namespace_is_no_namespace() {
1435 let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
1436 assert_eq!(
1437 find(&tree, "r").name().unwrap().namespace.as_deref(),
1438 Some("urn:d")
1439 );
1440 assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
1441 assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
1442 }
1443
1444 #[test]
1445 fn same_namespace_two_prefixes() {
1446 let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
1447 let inner = find(&tree, "c");
1448 assert_eq!(inner.name().unwrap().to_string(), "b:c");
1449 assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
1450 let attribute = inner.attributes().next().unwrap();
1451 assert_eq!(attribute.name().unwrap().to_string(), "a:d");
1452 }
1453
1454 #[test]
1455 fn builder_merges_text_and_replaces_attributes() {
1456 let mut builder = TreeBuilder::new();
1457 builder.start_element(QName::local("e")).unwrap();
1458 builder.attribute(QName::local("a"), "1").unwrap();
1459 builder.attribute(QName::local("a"), "2").unwrap();
1460 builder.text("x").unwrap();
1461 builder.text("").unwrap();
1462 builder.text("y").unwrap();
1463 assert!(builder.attribute(QName::local("late"), "1").is_err());
1464 builder.end_element().unwrap();
1465 assert!(builder.end_element().is_err());
1466 let tree = builder.finish(None, None).unwrap();
1467 let element = tree.root().children().next().unwrap();
1468 let attributes: Vec<_> = element
1469 .attributes()
1470 .map(|a| a.string_value().into_owned())
1471 .collect();
1472 assert_eq!(attributes, ["2"]);
1473 let texts: Vec<_> = element
1474 .children()
1475 .map(|t| t.string_value().into_owned())
1476 .collect();
1477 assert_eq!(texts, ["xy"]);
1478 }
1479
1480 #[test]
1481 fn whitespace_text_kept_and_dtd_refused() {
1482 let tree = parse("<r>\n <a/>\n</r>\n");
1483 let top = tree.root().children().next().unwrap();
1484 assert_eq!(top.children().count(), 3);
1485 assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
1486 assert!(Document::parse("<r><a></r>", None).is_err());
1487 }
1488
1489 #[test]
1490 fn records_are_compact() {
1491 assert_eq!(std::mem::size_of::<Record>(), 32);
1492 }
1493
1494 fn dump(tree: &Rc<Document>) -> Vec<String> {
1496 (0..tree.node_count())
1497 .map(|i| {
1498 let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
1499 let name = node.name().map(|n| {
1500 format!(
1501 "{}{{{}}}{}",
1502 n,
1503 n.namespace.as_deref().unwrap_or(""),
1504 n.local
1505 )
1506 });
1507 format!(
1508 "{:?} {name:?} {:?} {:?}",
1509 node.kind(),
1510 node.string_value(),
1511 node.parent().map(|p| p.index())
1512 )
1513 })
1514 .collect()
1515 }
1516
1517 #[test]
1522 fn owned_source_is_referred_to() {
1523 let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
1524 <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&y' c='t\tu'>\
1525 verbatim<e p:f='1'>aAb</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
1526 <?pi in?><e/>tail</p:r>";
1527 let borrowed = Document::parse(xml, None).unwrap();
1528 let owned = Document::parse(xml.to_owned(), None).unwrap();
1529 assert_eq!(dump(&borrowed), dump(&owned));
1530 assert_eq!(borrowed.source, "");
1531 assert_eq!(owned.source, xml);
1532 assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
1534 let copied_whole: usize = (0..borrowed.node_count())
1535 .map(|i| {
1536 let i = u32::try_from(i).unwrap();
1537 match borrowed.kind(i) {
1538 NodeKind::Element | NodeKind::Document => 0,
1539 _ => borrowed.own_text(i).len(),
1540 }
1541 })
1542 .sum();
1543 assert_eq!(borrowed.text.len(), copied_whole);
1544 for tree in [&borrowed, &owned] {
1545 assert_eq!(tree.records.capacity(), tree.records.len());
1546 assert_eq!(tree.text.capacity(), tree.text.len());
1547 assert_eq!(tree.names.capacity(), tree.names.len());
1548 }
1549 let r = find(&owned, "r");
1550 let values: Vec<_> = r
1551 .attributes()
1552 .map(|a| a.string_value().into_owned())
1553 .collect();
1554 assert_eq!(values, ["plain", "x&y", "t u"]);
1555 assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
1556 assert_eq!(r.name().unwrap().to_string(), "p:r");
1557 let e = find(&owned, "e");
1558 assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
1559 let f = e.attributes().next().unwrap();
1560 assert_eq!(f.name().unwrap().to_string(), "p:f");
1561 assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
1562 assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
1564 }
1565
1566 #[test]
1567 fn built_trees_merge_text_after_a_parsed_shape() {
1568 let mut builder = TreeBuilder::new();
1571 builder.start_element(QName::local("e")).unwrap();
1572 builder.attribute(QName::local("a"), "v").unwrap();
1573 builder.comment("c").unwrap();
1574 builder.text("x").unwrap();
1575 builder.text("y").unwrap();
1576 builder.processing_instruction("t", "d").unwrap();
1577 builder.text("z").unwrap();
1578 builder.end_element().unwrap();
1579 let tree = builder.finish(None, None).unwrap();
1580 let e = tree.root().children().next().unwrap();
1581 let children: Vec<_> = e
1582 .children()
1583 .map(|c| (c.kind(), c.string_value().into_owned()))
1584 .collect();
1585 assert_eq!(
1586 children,
1587 [
1588 (NodeKind::Comment, "c".to_owned()),
1589 (NodeKind::Text, "xy".to_owned()),
1590 (NodeKind::ProcessingInstruction, "d".to_owned()),
1591 (NodeKind::Text, "z".to_owned()),
1592 ]
1593 );
1594 assert_eq!(tree.text, "vcxydz");
1595 }
1596
1597 #[test]
1598 fn file_uris() {
1599 if cfg!(windows) {
1600 return;
1601 }
1602 assert_eq!(
1603 file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
1604 Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
1605 );
1606 assert_eq!(file_uri(Path::new("rel.xml")), None);
1607 }
1608}