1use std::borrow::Cow;
33use std::cell::{Cell, OnceCell};
34use std::cmp::Ordering;
35use std::collections::HashMap;
36use std::fmt::{self, Write as _};
37use std::path::Path;
38use std::rc::Rc;
39use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
40
41use std::sync::Arc;
42
43use einvoice_xdm::AtomicValue;
44use einvoice_xpath::{NamespaceBinding, QName, XML_NAMESPACE};
45
46use crate::limit::{DEFAULT_MAX_DEPTH, LimitExceeded};
47
48const NONE: u32 = u32::MAX;
50
51static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum NodeKind {
57 Document,
59 Element,
61 Attribute,
63 Text,
65 Comment,
67 ProcessingInstruction,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum NodeAxis {
75 Child,
77 Attribute,
79 SelfAxis,
81 Descendant,
83 DescendantOrSelf,
85 FollowingSibling,
87 Parent,
89 Ancestor,
91 AncestorOrSelf,
93 PrecedingSibling,
95 Preceding,
97}
98
99impl NodeAxis {
100 #[must_use]
102 pub const fn is_reverse(self) -> bool {
103 matches!(
104 self,
105 Self::Parent
106 | Self::Ancestor
107 | Self::AncestorOrSelf
108 | Self::PrecedingSibling
109 | Self::Preceding
110 )
111 }
112}
113
114#[derive(Debug, Clone, Copy)]
121struct Record {
122 kind: NodeKind,
123 name: u32,
125 parent: u32,
126 prev_sibling: u32,
127 first_child: u32,
130 end: u32,
132 text_start: u32,
136 text_len: u32,
137}
138
139impl Record {
140 const fn new(
142 kind: NodeKind,
143 name: u32,
144 parent: u32,
145 prev_sibling: u32,
146 index: u32,
147 (text_start, text_len): (u32, u32),
148 ) -> Self {
149 Self {
150 kind,
151 name,
152 parent,
153 prev_sibling,
154 first_child: index + 1,
155 end: index + 1,
156 text_start,
157 text_len,
158 }
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct DocumentError {
165 message: String,
166 limit: Option<LimitExceeded>,
167}
168
169impl DocumentError {
170 fn new(message: impl Into<String>) -> Self {
171 Self {
172 message: message.into(),
173 limit: None,
174 }
175 }
176
177 fn limit_exceeded(limit: LimitExceeded) -> Self {
178 Self {
179 message: limit.to_string(),
180 limit: Some(limit),
181 }
182 }
183
184 #[must_use]
186 pub fn message(&self) -> &str {
187 &self.message
188 }
189
190 #[must_use]
193 pub const fn limit(&self) -> Option<LimitExceeded> {
194 self.limit
195 }
196}
197
198impl fmt::Display for DocumentError {
199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200 f.write_str(&self.message)
201 }
202}
203
204impl std::error::Error for DocumentError {}
205
206pub struct Document {
213 serial: u64,
214 uri: Option<String>,
215 base_uri: Option<String>,
216 has_xml_base: bool,
217 records: Vec<Record>,
218 names: Vec<QName>,
219 namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
222 source: String,
224 text: String,
226 elements: OnceCell<ElementIndex>,
229 searches: Cell<u32>,
231 view: TreeView,
233 ids: OnceCell<HashMap<String, u32>>,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
240pub enum TreeView {
241 #[default]
245 Tiny,
246 Dom,
250}
251
252const INDEXED_SEARCH: u32 = 64;
254
255#[derive(Debug, Default)]
259struct ElementIndex {
260 names: Vec<IndexedName>,
261 elements: Vec<u32>,
262}
263
264#[derive(Debug, Clone, Copy)]
266struct IndexedName {
267 hash: u64,
268 name: u32,
270 start: u32,
271 len: u32,
272}
273
274fn name_hash(namespace: Option<&str>, local: &str) -> u64 {
276 use std::hash::{Hash as _, Hasher as _};
277 let mut hasher = std::hash::DefaultHasher::new();
278 (namespace, local).hash(&mut hasher);
279 hasher.finish()
280}
281
282impl fmt::Debug for Document {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 f.debug_struct("Document")
285 .field("serial", &self.serial)
286 .field("uri", &self.uri)
287 .field("nodes", &self.records.len())
288 .finish_non_exhaustive()
289 }
290}
291
292impl Document {
293 pub fn parse<'t>(
319 text: impl Into<Cow<'t, str>>,
320 base_uri: Option<&str>,
321 ) -> Result<Rc<Self>, DocumentError> {
322 Self::parse_with_uris(text.into(), None, base_uri, DEFAULT_MAX_DEPTH)
323 }
324
325 pub fn parse_with_max_depth<'t>(
334 text: impl Into<Cow<'t, str>>,
335 base_uri: Option<&str>,
336 max_depth: u32,
337 ) -> Result<Rc<Self>, DocumentError> {
338 Self::parse_with_uris(text.into(), None, base_uri, max_depth)
339 }
340
341 pub fn parse_loaded<'t>(
349 text: impl Into<Cow<'t, str>>,
350 uri: &str,
351 ) -> Result<Rc<Self>, DocumentError> {
352 Self::parse_with_uris(text.into(), Some(uri), Some(uri), DEFAULT_MAX_DEPTH)
353 }
354
355 pub fn parse_loaded_with_max_depth<'t>(
362 text: impl Into<Cow<'t, str>>,
363 uri: &str,
364 max_depth: u32,
365 ) -> Result<Rc<Self>, DocumentError> {
366 Self::parse_with_uris(text.into(), Some(uri), Some(uri), max_depth)
367 }
368
369 fn parse_with_uris(
370 text: Cow<'_, str>,
371 document_uri: Option<&str>,
372 base_uri: Option<&str>,
373 max_depth: u32,
374 ) -> Result<Rc<Self>, DocumentError> {
375 let keep_source = matches!(text, Cow::Owned(_));
376 let builder = build_parsed(&text, keep_source, max_depth)?;
377 let source = match text {
378 Cow::Owned(source) => source,
379 Cow::Borrowed(_) => String::new(),
380 };
381 builder.finish_with_source(
382 source,
383 document_uri.map(str::to_owned),
384 base_uri.map(str::to_owned),
385 )
386 }
387
388 fn copy_with_source(&self, source: String) -> Self {
391 debug_assert_eq!(source, self.source);
392 Self {
393 serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
394 uri: self.uri.clone(),
395 base_uri: self.base_uri.clone(),
396 has_xml_base: self.has_xml_base,
397 records: self.records.clone(),
398 names: self.names.clone(),
399 namespaces: self.namespaces.clone(),
400 source,
401 text: self.text.clone(),
402 elements: OnceCell::new(),
403 searches: Cell::new(0),
404 view: self.view,
405 ids: OnceCell::new(),
406 }
407 }
408
409 #[must_use]
411 pub fn root(self: &Rc<Self>) -> Node {
412 Node {
413 doc: Rc::clone(self),
414 index: 0,
415 }
416 }
417
418 #[must_use]
421 pub fn document_uri(&self) -> Option<&str> {
422 self.uri.as_deref()
423 }
424
425 #[must_use]
427 pub fn base_uri(&self) -> Option<&str> {
428 self.base_uri.as_deref()
429 }
430
431 #[must_use]
434 pub const fn has_xml_base(&self) -> bool {
435 self.has_xml_base
436 }
437
438 #[must_use]
440 pub fn name_count(&self) -> usize {
441 self.names.len()
442 }
443
444 #[must_use]
446 pub fn node_count(&self) -> usize {
447 self.records.len()
448 }
449
450 fn record(&self, index: u32) -> &Record {
451 &self.records[index as usize]
453 }
454
455 pub(crate) fn kind(&self, index: u32) -> NodeKind {
456 self.record(index).kind
457 }
458
459 pub(crate) fn name(&self, index: u32) -> Option<&QName> {
460 let name = self.record(index).name;
461 (name != NONE).then(|| &self.names[name as usize])
462 }
463
464 pub(crate) fn parent_index(&self, index: u32) -> Option<u32> {
465 let parent = self.record(index).parent;
466 (parent != NONE).then_some(parent)
467 }
468
469 fn own_text(&self, index: u32) -> &str {
472 let r = self.record(index);
473 let start = r.text_start as usize;
474 let end = start + r.text_len as usize;
475 match start.checked_sub(self.source.len()) {
476 None => &self.source[start..end],
477 Some(start) => &self.text[start..end - self.source.len()],
478 }
479 }
480
481 pub(crate) fn string_value(&self, index: u32) -> Cow<'_, str> {
482 match self.kind(index) {
483 NodeKind::Text
484 | NodeKind::Comment
485 | NodeKind::ProcessingInstruction
486 | NodeKind::Attribute => Cow::Borrowed(self.own_text(index)),
487 NodeKind::Element | NodeKind::Document => {
488 let mut texts = self
489 .cursor(index, NodeAxis::Descendant)
490 .walk(self)
491 .filter(|&i| self.kind(i) == NodeKind::Text);
492 let Some(first) = texts.next() else {
493 return Cow::Borrowed("");
494 };
495 let Some(second) = texts.next() else {
496 return Cow::Borrowed(self.own_text(first));
497 };
498 let mut value = String::from(self.own_text(first));
499 value.push_str(self.own_text(second));
500 for i in texts {
501 value.push_str(self.own_text(i));
502 }
503 Cow::Owned(value)
504 }
505 }
506 }
507
508 pub(crate) fn elements_named(
513 &self,
514 namespace: Option<&str>,
515 local: &str,
516 start: u32,
517 end: u32,
518 ) -> Option<&[u32]> {
519 if end.saturating_sub(start) < INDEXED_SEARCH {
520 return None;
521 }
522 let index = if let Some(index) = self.elements.get() {
523 index
524 } else {
525 let searches = self.searches.get().saturating_add(1);
526 self.searches.set(searches);
527 if searches < 2 {
528 return None;
529 }
530 self.elements.get_or_init(|| self.index_elements())
531 };
532 let hash = name_hash(namespace, local);
533 let first = index.names.partition_point(|n| n.hash < hash);
534 let all = index.names[first..]
535 .iter()
536 .take_while(|n| n.hash == hash)
537 .find(|n| {
538 self.names.get(n.name as usize).is_some_and(|name| {
539 name.local == local && name.namespace.as_deref() == namespace
540 })
541 })
542 .and_then(|n| {
543 let start = n.start as usize;
544 index.elements.get(start..start + n.len as usize)
545 })
546 .unwrap_or_default();
547 let from = all.partition_point(|&i| i < start);
548 let to = all.partition_point(|&i| i < end);
549 all.get(from..to)
550 }
551
552 fn index_elements(&self) -> ElementIndex {
554 let mut first_of_key: HashMap<(Option<&str>, &str), u32> =
557 HashMap::with_capacity(self.names.len());
558 let list_of_name: Vec<u32> = (0_u32..)
559 .zip(&self.names)
560 .map(|(id, name)| {
561 *first_of_key
562 .entry((name.namespace.as_deref(), name.local.as_str()))
563 .or_insert(id)
564 })
565 .collect();
566 drop(first_of_key);
567 let element_list = |record: &Record| {
568 (record.kind == NodeKind::Element)
569 .then(|| list_of_name.get(record.name as usize).copied())
570 .flatten()
571 };
572 let mut counts = vec![0_u32; self.names.len()];
573 for record in &self.records {
574 if let Some(count) = element_list(record).and_then(|l| counts.get_mut(l as usize)) {
575 *count += 1;
576 }
577 }
578 let mut names = Vec::new();
579 let mut next = vec![0_u32; self.names.len()];
580 let mut total = 0_u32;
581 for (list, (&count, next)) in (0_u32..).zip(counts.iter().zip(next.iter_mut())) {
582 if count > 0 {
583 let name = &self.names[list as usize];
584 names.push(IndexedName {
585 hash: name_hash(name.namespace.as_deref(), &name.local),
586 name: list,
587 start: total,
588 len: count,
589 });
590 *next = total;
591 total += count;
592 }
593 }
594 drop(counts);
595 let mut elements = vec![0_u32; total as usize];
596 for (index, record) in (0_u32..).zip(&self.records) {
597 if let Some(next) = element_list(record).and_then(|l| next.get_mut(l as usize))
598 && let Some(slot) = elements.get_mut(*next as usize)
599 {
600 *slot = index;
601 *next += 1;
602 }
603 }
604 names.sort_by_key(|n| n.hash);
605 names.shrink_to_fit();
606 ElementIndex { names, elements }
607 }
608
609 pub(crate) fn descendant_range(&self, index: u32) -> (u32, u32) {
612 let r = self.record(index);
613 (r.first_child, r.end)
614 }
615
616 pub(crate) fn cursor(&self, index: u32, axis: NodeAxis) -> Cursor {
618 let r = self.record(index);
619 let kind = r.kind;
620 let is_attribute = kind == NodeKind::Attribute;
621 match axis {
622 NodeAxis::SelfAxis => Cursor::One(index),
623 NodeAxis::Parent => match r.parent {
624 NONE => Cursor::Done,
625 parent => Cursor::One(parent),
626 },
627 NodeAxis::Child => Cursor::Siblings {
628 next: r.first_child,
629 end: r.end,
630 },
631 NodeAxis::Attribute => {
632 if kind == NodeKind::Element {
633 Cursor::Range {
634 next: index + 1,
635 end: r.first_child,
636 }
637 } else {
638 Cursor::Done
639 }
640 }
641 NodeAxis::Descendant => Cursor::Descendants {
642 next: r.first_child,
643 end: r.end,
644 },
645 NodeAxis::DescendantOrSelf => Cursor::Descendants {
646 next: index,
647 end: r.end,
648 },
649 NodeAxis::FollowingSibling => match r.parent {
650 NONE => Cursor::Done,
651 _ if is_attribute => Cursor::Done,
652 parent => Cursor::Siblings {
653 next: r.end,
654 end: self.record(parent).end,
655 },
656 },
657 NodeAxis::Ancestor => Cursor::Ancestors { next: r.parent },
658 NodeAxis::AncestorOrSelf => Cursor::Ancestors { next: index },
659 NodeAxis::PrecedingSibling => {
660 if is_attribute {
661 Cursor::Done
662 } else {
663 Cursor::PrecedingSiblings {
664 next: r.prev_sibling,
665 }
666 }
667 }
668 NodeAxis::Preceding => Cursor::Preceding {
669 next: index,
670 ancestor: r.parent,
671 },
672 }
673 }
674}
675
676#[derive(Debug, Clone, Copy)]
678pub(crate) enum Cursor {
679 Done,
680 One(u32),
681 Range {
683 next: u32,
684 end: u32,
685 },
686 Siblings {
688 next: u32,
689 end: u32,
690 },
691 Descendants {
693 next: u32,
694 end: u32,
695 },
696 Ancestors {
697 next: u32,
698 },
699 PrecedingSiblings {
700 next: u32,
701 },
702 Preceding {
705 next: u32,
706 ancestor: u32,
707 },
708}
709
710impl Cursor {
711 pub(crate) fn next(&mut self, doc: &Document) -> Option<u32> {
712 match self {
713 Self::Done => None,
714 Self::One(index) => {
715 let index = *index;
716 *self = Self::Done;
717 Some(index)
718 }
719 Self::Range { next, end } => {
720 if *next >= *end {
721 return None;
722 }
723 let index = *next;
724 *next += 1;
725 Some(index)
726 }
727 Self::Siblings { next, end } => {
728 if *next >= *end {
729 return None;
730 }
731 let index = *next;
732 *next = doc.record(index).end;
733 Some(index)
734 }
735 Self::Descendants { next, end } => {
736 if *next >= *end {
737 return None;
738 }
739 let index = *next;
740 *next = doc.record(index).first_child;
742 Some(index)
743 }
744 Self::Ancestors { next } => {
745 if *next == NONE {
746 return None;
747 }
748 let index = *next;
749 *next = doc.record(index).parent;
750 Some(index)
751 }
752 Self::PrecedingSiblings { next } => {
753 if *next == NONE {
754 return None;
755 }
756 let index = *next;
757 *next = doc.record(index).prev_sibling;
758 Some(index)
759 }
760 Self::Preceding { next, ancestor } => loop {
761 if *next == 0 {
762 return None;
763 }
764 *next -= 1;
765 let index = *next;
766 if index == *ancestor {
767 *ancestor = doc.record(index).parent;
768 continue;
769 }
770 if doc.record(index).kind != NodeKind::Attribute {
771 return Some(index);
772 }
773 },
774 }
775 }
776
777 pub(crate) fn walk(self, doc: &Document) -> impl Iterator<Item = u32> + '_ {
779 let mut cursor = self;
780 std::iter::from_fn(move || cursor.next(doc))
781 }
782}
783
784#[derive(Clone)]
788pub struct Node {
789 doc: Rc<Document>,
790 index: u32,
791}
792
793impl PartialEq for Node {
794 fn eq(&self, other: &Self) -> bool {
795 self.index == other.index && Rc::ptr_eq(&self.doc, &other.doc)
796 }
797}
798
799impl Eq for Node {}
800
801impl fmt::Debug for Node {
802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803 write!(f, "Node({:?}", self.kind())?;
804 if let Some(name) = self.name() {
805 write!(f, " {name}")?;
806 }
807 write!(f, " #{} of document {})", self.index, self.doc.serial)
808 }
809}
810
811impl Node {
812 pub(crate) fn new(doc: Rc<Document>, index: u32) -> Self {
813 Self { doc, index }
814 }
815
816 pub(crate) const fn index(&self) -> u32 {
817 self.index
818 }
819
820 #[must_use]
822 pub fn document(&self) -> &Rc<Document> {
823 &self.doc
824 }
825
826 #[must_use]
828 pub fn kind(&self) -> NodeKind {
829 self.doc.kind(self.index)
830 }
831
832 #[must_use]
835 pub fn name(&self) -> Option<&QName> {
836 self.doc.name(self.index)
837 }
838
839 #[must_use]
843 pub fn name_id(&self) -> Option<u32> {
844 let name = self.doc.record(self.index).name;
845 (name != NONE).then_some(name)
846 }
847
848 #[must_use]
850 pub fn parent(&self) -> Option<Self> {
851 self.doc
852 .parent_index(self.index)
853 .map(|p| Self::new(Rc::clone(&self.doc), p))
854 }
855
856 #[must_use]
859 pub fn root(&self) -> Self {
860 Self::new(Rc::clone(&self.doc), 0)
861 }
862
863 #[must_use]
869 pub fn namespaces_in_scope(&self) -> Vec<NamespaceBinding> {
870 let doc = &self.doc;
871 let mut out: Vec<NamespaceBinding> = Vec::new();
872 if doc.namespaces.is_empty() || self.kind() != NodeKind::Element {
873 return out;
874 }
875 let mut index = self.index;
876 while index != NONE {
877 if let Ok(i) = doc.namespaces.binary_search_by_key(&index, |(e, _)| *e) {
878 for binding in doc.namespaces[i].1.iter() {
879 if !out.iter().any(|b| b.prefix == binding.prefix) {
880 out.push(binding.clone());
881 }
882 }
883 }
884 index = doc.record(index).parent;
885 }
886 out.retain(|b| !b.uri.is_empty());
887 out
888 }
889
890 #[must_use]
892 pub fn string_value(&self) -> Cow<'_, str> {
893 self.doc.string_value(self.index)
894 }
895
896 #[must_use]
901 pub fn by_id(&self, id: &str) -> Option<Self> {
902 let doc = &self.doc;
903 if doc.view == TreeView::Dom {
904 return None;
905 }
906 let ids = doc.ids.get_or_init(|| {
907 let mut ids = HashMap::new();
908 for (index, record) in (0_u32..).zip(&doc.records) {
909 if record.kind != NodeKind::Attribute {
910 continue;
911 }
912 let is_xml_id = doc.name(index).is_some_and(|n| {
913 n.local == "id" && n.namespace.as_deref() == Some(XML_NAMESPACE)
914 });
915 if is_xml_id {
916 let value: Vec<&str> = doc
917 .own_text(index)
918 .split([' ', '\t', '\n', '\r'])
919 .filter(|t| !t.is_empty())
920 .collect();
921 ids.entry(value.join(" ")).or_insert(record.parent);
922 }
923 }
924 ids
925 });
926 ids.get(id).map(|&i| Self::new(Rc::clone(doc), i))
927 }
928
929 #[must_use]
936 pub fn generate_id(&self) -> String {
937 let doc = &self.doc;
938 let number = doc.serial + 1;
939 match doc.view {
940 TreeView::Tiny => {
941 let attributes_before = |index: u32| {
942 doc.records[..index as usize]
943 .iter()
944 .filter(|r| r.kind == NodeKind::Attribute)
945 .count()
946 };
947 let tiny = |index: u32| {
948 let kind = doc.kind(index);
949 if kind == NodeKind::Document {
950 return format!("d{number}");
951 }
952 let letter = match kind {
953 NodeKind::Text => 't',
954 NodeKind::Comment => 'c',
955 NodeKind::ProcessingInstruction => 'p',
956 _ => 'e',
957 };
958 let node_number = index as usize - attributes_before(index);
959 format!("d{number}{letter}{node_number}")
960 };
961 if self.kind() == NodeKind::Attribute {
962 let parent = doc.record(self.index).parent;
963 let owner = if parent == NONE {
964 format!("d{number}")
965 } else {
966 tiny(parent)
967 };
968 format!("{owner}a{}", attributes_before(self.index))
969 } else {
970 tiny(self.index)
971 }
972 }
973 TreeView::Dom => {
974 let lineage: Vec<u32> = doc
975 .cursor(self.index, NodeAxis::AncestorOrSelf)
976 .walk(doc)
977 .collect();
978 let mut id = format!("w{number}");
979 for &index in lineage.iter().rev() {
980 let record = doc.record(index);
981 if record.parent == NONE {
982 continue;
983 }
984 let position = if record.kind == NodeKind::Attribute {
985 id.push('a');
986 index - record.parent - 1
987 } else {
988 u32::try_from(
989 doc.cursor(index, NodeAxis::PrecedingSibling)
990 .walk(doc)
991 .count(),
992 )
993 .unwrap_or(u32::MAX)
994 };
995 id.push_str(&alpha_key(position));
996 }
997 id
998 }
999 }
1000 }
1001
1002 #[must_use]
1005 pub fn typed_value(&self) -> AtomicValue {
1006 let value = self.string_value().into_owned();
1007 match self.kind() {
1008 NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
1009 _ => AtomicValue::UntypedAtomic(value),
1010 }
1011 }
1012
1013 #[must_use]
1016 pub fn axis(&self, axis: NodeAxis) -> Axis {
1017 Axis {
1018 cursor: self.doc.cursor(self.index, axis),
1019 doc: Rc::clone(&self.doc),
1020 }
1021 }
1022
1023 #[must_use]
1025 pub fn children(&self) -> Axis {
1026 self.axis(NodeAxis::Child)
1027 }
1028
1029 #[must_use]
1031 pub fn attributes(&self) -> Axis {
1032 self.axis(NodeAxis::Attribute)
1033 }
1034
1035 #[must_use]
1038 pub fn cmp_document_order(&self, other: &Self) -> Ordering {
1039 self.doc
1040 .serial
1041 .cmp(&other.doc.serial)
1042 .then(self.index.cmp(&other.index))
1043 }
1044}
1045
1046#[derive(Debug, Clone)]
1048pub struct Axis {
1049 cursor: Cursor,
1050 doc: Rc<Document>,
1051}
1052
1053impl Iterator for Axis {
1054 type Item = Node;
1055
1056 fn next(&mut self) -> Option<Node> {
1057 let index = self.cursor.next(&self.doc)?;
1058 Some(Node::new(Rc::clone(&self.doc), index))
1059 }
1060
1061 fn count(self) -> usize {
1062 self.cursor.walk(&self.doc).count()
1063 }
1064}
1065
1066#[derive(Debug, Default)]
1078pub struct DocumentCache {
1079 entries: std::sync::Mutex<Vec<CachedDocument>>,
1080}
1081
1082#[derive(Debug)]
1084struct CachedDocument {
1085 max_depth: u32,
1086 document: Document,
1087}
1088
1089impl DocumentCache {
1090 pub const MAX_DOCUMENTS: usize = 64;
1092 pub const MAX_BYTES: usize = 64 << 20;
1094
1095 #[must_use]
1097 pub fn new() -> Self {
1098 Self::default()
1099 }
1100
1101 pub fn parse_loaded(
1109 &self,
1110 text: String,
1111 uri: &str,
1112 max_depth: u32,
1113 ) -> Result<Rc<Document>, DocumentError> {
1114 {
1115 let entries = self
1116 .entries
1117 .lock()
1118 .unwrap_or_else(std::sync::PoisonError::into_inner);
1119 if let Some(entry) = entries.iter().find(|e| {
1120 e.max_depth == max_depth
1121 && e.document.uri.as_deref() == Some(uri)
1122 && e.document.source == text
1123 }) {
1124 return Ok(Rc::new(entry.document.copy_with_source(text)));
1125 }
1126 }
1127 let document = Document::parse_loaded_with_max_depth(text, uri, max_depth)?;
1128 let mut entries = self
1129 .entries
1130 .lock()
1131 .unwrap_or_else(std::sync::PoisonError::into_inner);
1132 let bytes: usize = entries.iter().map(|e| e.document.source.len()).sum();
1133 if entries.len() < Self::MAX_DOCUMENTS
1134 && bytes.saturating_add(document.source.len()) <= Self::MAX_BYTES
1135 && !entries.iter().any(|e| {
1136 e.max_depth == max_depth
1137 && e.document.uri.as_deref() == Some(uri)
1138 && e.document.source == document.source
1139 })
1140 {
1141 entries.push(CachedDocument {
1142 max_depth,
1143 document: document.copy_with_source(document.source.clone()),
1144 });
1145 }
1146 Ok(document)
1147 }
1148}
1149
1150#[derive(Debug)]
1156pub struct TreeBuilder {
1157 records: Vec<Record>,
1158 names: Vec<QName>,
1159 name_ids: HashMap<QName, u32>,
1160 namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
1162 parentless: bool,
1164 source_len: usize,
1167 text: String,
1168 open: Vec<u32>,
1170 last_child: Vec<u32>,
1172 has_xml_base: bool,
1173 view: TreeView,
1174}
1175
1176impl Default for TreeBuilder {
1177 fn default() -> Self {
1178 Self::new()
1179 }
1180}
1181
1182fn to_u32(value: usize) -> Result<u32, DocumentError> {
1183 u32::try_from(value)
1184 .ok()
1185 .filter(|&v| v != NONE)
1186 .ok_or_else(|| DocumentError::new("document too large"))
1187}
1188
1189#[derive(Debug, Clone, Copy)]
1191enum NodeText<'s> {
1192 Source(u32, u32),
1194 Copy(&'s str),
1196}
1197
1198impl TreeBuilder {
1199 #[must_use]
1201 pub fn new() -> Self {
1202 Self {
1203 records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
1204 names: Vec::new(),
1205 name_ids: HashMap::new(),
1206 namespaces: Vec::new(),
1207 parentless: false,
1208 source_len: 0,
1209 text: String::new(),
1210 open: vec![0],
1211 last_child: vec![NONE],
1212 has_xml_base: false,
1213 view: TreeView::Tiny,
1214 }
1215 }
1216
1217 #[must_use]
1219 pub const fn dom_view(mut self) -> Self {
1220 self.view = TreeView::Dom;
1221 self
1222 }
1223
1224 #[must_use]
1229 pub fn parentless() -> Self {
1230 Self {
1231 records: Vec::new(),
1232 open: Vec::new(),
1233 parentless: true,
1234 ..Self::new()
1235 }
1236 }
1237
1238 fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
1242 let mut builder = Self::new();
1243 builder.records.reserve_exact(nodes.saturating_sub(1));
1244 builder.text.reserve_exact(text);
1245 builder.source_len = source_len;
1246 builder
1247 }
1248
1249 fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
1250 if let Some(&id) = self.name_ids.get(&name) {
1251 return Ok(id);
1252 }
1253 let id = self.push_name(name.clone())?;
1254 self.name_ids.insert(name, id);
1255 Ok(id)
1256 }
1257
1258 fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
1260 let id = to_u32(self.names.len())?;
1261 self.names.push(name);
1262 Ok(id)
1263 }
1264
1265 fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
1267 match value {
1268 NodeText::Source(start, len) => Ok((start, len)),
1269 NodeText::Copy(value) => {
1270 let start = to_u32(self.source_len + self.text.len())?;
1271 let len = to_u32(value.len())?;
1272 to_u32(self.source_len + self.text.len() + value.len())?;
1273 self.text.push_str(value);
1274 Ok((start, len))
1275 }
1276 }
1277 }
1278
1279 fn top(&self) -> u32 {
1281 self.open.last().copied().unwrap_or(NONE)
1282 }
1283
1284 const fn base(&self) -> usize {
1286 if self.parentless { 0 } else { 1 }
1287 }
1288
1289 fn append(
1292 &mut self,
1293 kind: NodeKind,
1294 name: u32,
1295 text: NodeText<'_>,
1296 ) -> Result<u32, DocumentError> {
1297 let index = to_u32(self.records.len())?;
1298 to_u32(self.records.len() + 1)?;
1299 if self.parentless && self.open.is_empty() && !self.records.is_empty() {
1300 return Err(DocumentError::new(
1301 "a second node at the top of a parentless tree",
1302 ));
1303 }
1304 let text = if kind == NodeKind::Element {
1305 (0, 0)
1306 } else {
1307 self.store_text(text)?
1308 };
1309 let parent = self.top();
1310 let last = self.last_child.last_mut().map_or(NONE, |l| {
1311 let previous = *l;
1312 *l = index;
1313 previous
1314 });
1315 self.records
1316 .push(Record::new(kind, name, parent, last, index, text));
1317 Ok(index)
1318 }
1319
1320 pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
1326 let name = self.intern(name)?;
1327 self.open_element(name)
1328 }
1329
1330 pub fn add_namespace(&mut self, binding: NamespaceBinding) -> Result<(), DocumentError> {
1336 let element = self.top();
1337 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1338 if element == NONE
1339 || self.records[element as usize].kind != NodeKind::Element
1340 || has_content
1341 {
1342 return Err(DocumentError::new(format!(
1343 "namespace {:?} outside an element start",
1344 binding.prefix
1345 )));
1346 }
1347 match self.namespaces.last_mut() {
1348 Some((e, bindings)) if *e == element => {
1349 let mut extended: Vec<NamespaceBinding> = bindings.to_vec();
1350 extended.retain(|b| b.prefix != binding.prefix);
1351 extended.push(binding);
1352 *bindings = extended.into();
1353 }
1354 _ => self.namespaces.push((element, vec![binding].into())),
1355 }
1356 Ok(())
1357 }
1358
1359 pub fn start_element_with_namespaces(
1366 &mut self,
1367 name: QName,
1368 namespaces: Arc<[NamespaceBinding]>,
1369 ) -> Result<(), DocumentError> {
1370 self.start_element(name)?;
1371 if !namespaces.is_empty() {
1372 let element = self.top();
1373 self.namespaces.push((element, namespaces));
1374 }
1375 Ok(())
1376 }
1377
1378 fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
1379 let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
1380 self.open.push(index);
1381 self.last_child.push(NONE);
1382 Ok(())
1383 }
1384
1385 pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
1391 if self.parentless && self.records.is_empty() {
1392 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1394 let id = self.intern(name)?;
1395 let text = self.store_text(NodeText::Copy(value))?;
1396 self.records
1397 .push(Record::new(NodeKind::Attribute, id, NONE, NONE, 0, text));
1398 self.has_xml_base |= xml_base;
1399 return Ok(());
1400 }
1401 let element = self.top();
1402 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1403 if element == NONE
1404 || self.records[element as usize].kind != NodeKind::Element
1405 || has_content
1406 {
1407 return Err(DocumentError::new(format!(
1408 "attribute {name} outside an element start"
1409 )));
1410 }
1411 let first = element as usize + 1;
1412 let existing = (first..self.records.len()).find(|&i| {
1413 let id = self.records[i].name;
1414 self.names[id as usize].same_expanded_name(&name)
1415 });
1416 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1417 let id = self.intern(name)?;
1418 if let Some(i) = existing {
1419 let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
1420 let record = &mut self.records[i];
1421 record.name = id;
1422 record.text_start = text_start;
1423 record.text_len = text_len;
1424 self.has_xml_base |= xml_base;
1425 return Ok(());
1426 }
1427 self.push_attribute(id, xml_base, NodeText::Copy(value))
1428 }
1429
1430 fn push_attribute(
1432 &mut self,
1433 name: u32,
1434 xml_base: bool,
1435 value: NodeText<'_>,
1436 ) -> Result<(), DocumentError> {
1437 let element = self.top();
1438 let index = to_u32(self.records.len())?;
1439 to_u32(self.records.len() + 1)?;
1440 let previous = if index == element + 1 {
1441 NONE
1442 } else {
1443 index - 1
1444 };
1445 let text = self.store_text(value)?;
1446 self.records.push(Record::new(
1447 NodeKind::Attribute,
1448 name,
1449 element,
1450 previous,
1451 index,
1452 text,
1453 ));
1454 self.records[element as usize].first_child = index + 1;
1455 self.has_xml_base |= xml_base;
1456 Ok(())
1457 }
1458
1459 pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
1465 if value.is_empty() {
1466 if self.parentless && self.records.is_empty() {
1469 return self
1470 .append(NodeKind::Text, NONE, NodeText::Copy(""))
1471 .map(drop);
1472 }
1473 return Ok(());
1474 }
1475 let last = self.last_child.last().copied().unwrap_or(NONE);
1476 let mergeable = last != NONE
1479 && last as usize + 1 == self.records.len()
1480 && self.records[last as usize].kind == NodeKind::Text
1481 && {
1482 let r = &self.records[last as usize];
1483 r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
1484 && r.text_start as usize >= self.source_len
1485 };
1486 if mergeable {
1487 self.store_text(NodeText::Copy(value))?;
1488 let record = &mut self.records[last as usize];
1489 record.text_len = to_u32(record.text_len as usize + value.len())?;
1490 return Ok(());
1491 }
1492 self.append(NodeKind::Text, NONE, NodeText::Copy(value))
1493 .map(drop)
1494 }
1495
1496 pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1502 self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
1503 .map(drop)
1504 }
1505
1506 pub fn processing_instruction(
1512 &mut self,
1513 target: &str,
1514 value: &str,
1515 ) -> Result<(), DocumentError> {
1516 let name = self.intern(QName::local(target))?;
1517 self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
1518 .map(drop)
1519 }
1520
1521 pub fn end_element(&mut self) -> Result<(), DocumentError> {
1527 if self.open.len() <= self.base() {
1528 return Err(DocumentError::new("end of element without a start"));
1529 }
1530 let element = self.top();
1531 self.open.pop();
1532 self.last_child.pop();
1533 let end = to_u32(self.records.len())?;
1534 self.records[element as usize].end = end;
1535 Ok(())
1536 }
1537
1538 pub fn finish(
1544 self,
1545 document_uri: Option<String>,
1546 base_uri: Option<String>,
1547 ) -> Result<Rc<Document>, DocumentError> {
1548 self.finish_with_source(String::new(), document_uri, base_uri)
1549 }
1550
1551 fn finish_with_source(
1554 mut self,
1555 source: String,
1556 document_uri: Option<String>,
1557 base_uri: Option<String>,
1558 ) -> Result<Rc<Document>, DocumentError> {
1559 if self.open.len() != self.base() {
1560 return Err(DocumentError::new("unclosed element"));
1561 }
1562 if source.len() != self.source_len {
1563 return Err(DocumentError::new("source text of another length"));
1564 }
1565 if self.parentless {
1566 if self.records.is_empty() {
1567 return Err(DocumentError::new("a parentless tree without a node"));
1568 }
1569 } else {
1570 self.records[0].end = to_u32(self.records.len())?;
1571 }
1572 self.records.shrink_to_fit();
1575 self.names.shrink_to_fit();
1576 self.text.shrink_to_fit();
1577 Ok(Rc::new(Document {
1578 serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1579 uri: document_uri,
1580 base_uri,
1581 has_xml_base: self.has_xml_base,
1582 records: self.records,
1583 names: self.names,
1584 namespaces: self.namespaces,
1585 source,
1586 text: self.text,
1587 elements: OnceCell::new(),
1588 searches: Cell::new(0),
1589 view: self.view,
1590 ids: OnceCell::new(),
1591 }))
1592 }
1593}
1594
1595fn alpha_key(value: u32) -> String {
1598 if value < 1 {
1599 return "a".to_owned();
1600 }
1601 let digits = value.to_string();
1602 let letter = char::from(b'a' + u8::try_from(digits.len()).unwrap_or(10));
1603 format!("{letter}{digits}")
1604}
1605
1606fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1607 local == "base" && namespace == Some(XML_NAMESPACE)
1608}
1609
1610fn offset_in(input: &str, part: &str) -> Option<usize> {
1612 let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1613 (start.checked_add(part.len())? <= input.len()).then_some(start)
1614}
1615
1616fn xml_error(e: &einvoice_xml::Error) -> DocumentError {
1618 DocumentError::new(format!("XML: {e}"))
1619}
1620
1621struct Namespaces<'a> {
1625 input: &'a str,
1626 ids: HashMap<Box<str>, u32>,
1627 last: Option<(usize, usize, u32)>,
1630}
1631
1632impl<'a> Namespaces<'a> {
1633 fn new(input: &'a str) -> Self {
1634 Self {
1635 input,
1636 ids: HashMap::new(),
1637 last: None,
1638 }
1639 }
1640
1641 fn id(&mut self, namespace: Option<&str>) -> Result<u32, DocumentError> {
1643 let Some(namespace) = namespace else {
1644 return Ok(NONE);
1645 };
1646 let at = offset_in(self.input, namespace);
1647 if let (Some(at), Some((last, len, id))) = (at, self.last)
1648 && at == last
1649 && namespace.len() == len
1650 {
1651 return Ok(id);
1652 }
1653 let id = if let Some(&id) = self.ids.get(namespace) {
1654 id
1655 } else {
1656 let id = to_u32(self.ids.len())?;
1657 self.ids.insert(namespace.into(), id);
1658 id
1659 };
1660 if let Some(at) = at {
1661 self.last = Some((at, namespace.len(), id));
1662 }
1663 Ok(id)
1664 }
1665}
1666
1667type NameKey<'a> = (&'a str, &'a str, u32);
1670
1671struct Names<'a> {
1673 namespaces: Namespaces<'a>,
1674 ids: HashMap<NameKey<'a>, u32>,
1675}
1676
1677impl<'a> Names<'a> {
1678 fn new(input: &'a str) -> Self {
1679 Self {
1680 namespaces: Namespaces::new(input),
1681 ids: HashMap::new(),
1682 }
1683 }
1684
1685 fn id(
1687 &mut self,
1688 builder: &mut TreeBuilder,
1689 name: einvoice_xml::Name<'_, 'a>,
1690 ) -> Result<u32, DocumentError> {
1691 let key = (name.prefix, name.local, self.namespaces.id(name.namespace)?);
1692 if let Some(&id) = self.ids.get(&key) {
1693 return Ok(id);
1694 }
1695 let id = builder.push_name(QName {
1696 prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
1697 namespace: name.namespace.map(str::to_owned),
1698 local: name.local.to_owned(),
1699 })?;
1700 self.ids.insert(key, id);
1701 Ok(id)
1702 }
1703}
1704
1705trait Pass<'a> {
1710 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError>;
1711 fn end(&mut self) -> Result<(), DocumentError>;
1712 fn text(&mut self, text: &str) -> Result<(), DocumentError>;
1713 fn comment(&mut self, value: &str) -> Result<(), DocumentError>;
1714 fn processing_instruction(
1715 &mut self,
1716 pi: &einvoice_xml::ProcessingInstruction<'a>,
1717 ) -> Result<(), DocumentError>;
1718}
1719
1720fn read<'a>(input: &'a str, max_depth: u32, pass: &mut impl Pass<'a>) -> Result<(), DocumentError> {
1724 let mut reader = einvoice_xml::Reader::new(input);
1725 let mut depth = 0u32;
1726 let mut text: Option<Cow<'a, str>> = None;
1729 let mut too_deep: Option<LimitExceeded> = None;
1730 while let Some(event) = reader.next_event().map_err(|e| xml_error(&e))? {
1731 if let einvoice_xml::Event::Text(t) = event {
1732 if depth > 0 && too_deep.is_none() {
1733 match &mut text {
1734 None => text = Some(t.value),
1735 Some(joined) => joined.to_mut().push_str(&t.value),
1736 }
1737 }
1738 continue;
1739 }
1740 if let Some(joined) = text.take()
1741 && !joined.is_empty()
1742 {
1743 pass.text(&joined)?;
1744 }
1745 match event {
1746 einvoice_xml::Event::Start(start) => {
1747 depth = depth.saturating_add(1);
1748 if depth > max_depth && too_deep.is_none() {
1749 let at = einvoice_xml::TextPos::at(input, start.range().start);
1751 too_deep = Some(LimitExceeded::Depth {
1752 max: max_depth,
1753 line: at.row,
1754 column: at.col,
1755 });
1756 }
1757 if too_deep.is_none() {
1758 pass.start(start)?;
1759 }
1760 }
1761 einvoice_xml::Event::End(_) => {
1762 depth = depth.saturating_sub(1);
1763 if too_deep.is_none() {
1764 pass.end()?;
1765 }
1766 }
1767 einvoice_xml::Event::Comment(comment) if too_deep.is_none() => {
1768 pass.comment(&comment.value)?;
1769 }
1770 einvoice_xml::Event::ProcessingInstruction(pi) if too_deep.is_none() => {
1771 pass.processing_instruction(&pi)?;
1772 }
1773 _ => {}
1774 }
1775 }
1776 match too_deep {
1777 Some(limit) => Err(DocumentError::limit_exceeded(limit)),
1778 None => Ok(()),
1779 }
1780}
1781
1782struct Sizes<'a> {
1786 input: &'a str,
1787 keep_source: bool,
1788 nodes: usize,
1789 text_bytes: usize,
1790}
1791
1792impl Sizes<'_> {
1793 fn add(&mut self, text: &str) {
1794 self.nodes += 1;
1795 if !(self.keep_source && offset_in(self.input, text).is_some()) {
1796 self.text_bytes += text.len();
1797 }
1798 }
1799}
1800
1801impl<'a> Pass<'a> for Sizes<'a> {
1802 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1803 self.nodes += 1;
1804 for attribute in start.attributes() {
1805 self.add(attribute.value);
1806 }
1807 Ok(())
1808 }
1809
1810 fn end(&mut self) -> Result<(), DocumentError> {
1811 Ok(())
1812 }
1813
1814 fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1815 self.add(text);
1816 Ok(())
1817 }
1818
1819 fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1820 self.add(value);
1821 Ok(())
1822 }
1823
1824 fn processing_instruction(
1825 &mut self,
1826 pi: &einvoice_xml::ProcessingInstruction<'a>,
1827 ) -> Result<(), DocumentError> {
1828 self.add(pi.value.as_deref().unwrap_or(""));
1829 Ok(())
1830 }
1831}
1832
1833struct Fill<'a> {
1835 input: &'a str,
1836 keep_source: bool,
1837 builder: TreeBuilder,
1838 names: Names<'a>,
1839}
1840
1841impl Fill<'_> {
1842 fn node_text<'s>(&self, text: &'s str) -> Result<NodeText<'s>, DocumentError> {
1845 Ok(
1846 match self
1847 .keep_source
1848 .then(|| offset_in(self.input, text))
1849 .flatten()
1850 {
1851 Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1852 None => NodeText::Copy(text),
1853 },
1854 )
1855 }
1856}
1857
1858impl<'a> Pass<'a> for Fill<'a> {
1859 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1860 let id = self.names.id(&mut self.builder, start.name())?;
1861 self.builder.open_element(id)?;
1862 let declarations = start.namespace_declarations();
1863 if declarations.len() > 0 {
1864 let bindings: Arc<[NamespaceBinding]> = declarations
1865 .map(|(prefix, uri)| NamespaceBinding {
1866 prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1867 uri: uri.to_owned(),
1868 })
1869 .collect();
1870 let element = self.builder.top();
1871 self.builder.namespaces.push((element, bindings));
1872 }
1873 for attribute in start.attributes() {
1875 let id = self.names.id(&mut self.builder, attribute.name)?;
1876 let text = self.node_text(attribute.value)?;
1877 self.builder.push_attribute(
1878 id,
1879 is_xml_base(attribute.name.namespace, attribute.name.local),
1880 text,
1881 )?;
1882 }
1883 Ok(())
1884 }
1885
1886 fn end(&mut self) -> Result<(), DocumentError> {
1887 self.builder.end_element()
1888 }
1889
1890 fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1891 let text = self.node_text(text)?;
1892 self.builder.append(NodeKind::Text, NONE, text).map(drop)
1893 }
1894
1895 fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1896 let text = self.node_text(value)?;
1897 self.builder.append(NodeKind::Comment, NONE, text).map(drop)
1898 }
1899
1900 fn processing_instruction(
1901 &mut self,
1902 pi: &einvoice_xml::ProcessingInstruction<'a>,
1903 ) -> Result<(), DocumentError> {
1904 let target = einvoice_xml::Name {
1905 prefix: "",
1906 local: pi.target,
1907 namespace: None,
1908 };
1909 let id = self.names.id(&mut self.builder, target)?;
1910 let text = self.node_text(pi.value.as_deref().unwrap_or(""))?;
1911 self.builder
1912 .append(NodeKind::ProcessingInstruction, id, text)
1913 .map(drop)
1914 }
1915}
1916
1917fn build_parsed(
1925 input: &str,
1926 keep_source: bool,
1927 max_depth: u32,
1928) -> Result<TreeBuilder, DocumentError> {
1929 let mut sizes = Sizes {
1930 input,
1931 keep_source,
1932 nodes: 1,
1933 text_bytes: 0,
1934 };
1935 read(input, max_depth, &mut sizes)?;
1936 let mut fill = Fill {
1937 input,
1938 keep_source,
1939 builder: TreeBuilder::with_capacity(
1940 sizes.nodes,
1941 sizes.text_bytes,
1942 if keep_source { input.len() } else { 0 },
1943 ),
1944 names: Names::new(input),
1945 };
1946 read(input, max_depth, &mut fill)?;
1947 Ok(fill.builder)
1948}
1949
1950#[must_use]
1958pub fn file_uri(path: &Path) -> Option<String> {
1959 if !path.is_absolute() {
1960 return None;
1961 }
1962 let text = path.to_str()?.replace('\\', "/");
1963 let mut uri = String::from("file:");
1964 if !text.starts_with('/') {
1965 uri.push('/');
1966 }
1967 for c in text.chars() {
1968 let keep = if c.is_ascii() {
1969 c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1970 } else {
1971 !(matches!(
1973 c,
1974 '\u{A0}' | '\u{1680}' | '\u{2000}'
1975 ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1976 ) || c.is_control())
1977 };
1978 if keep {
1979 uri.push(c);
1980 } else {
1981 let mut buffer = [0; 4];
1982 for byte in c.encode_utf8(&mut buffer).bytes() {
1983 let _ = write!(uri, "%{byte:02X}");
1984 }
1985 }
1986 }
1987 Some(uri)
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992 use super::*;
1993
1994 fn parse(xml: &str) -> Rc<Document> {
1995 Document::parse(xml, Some("file:/t.xml")).unwrap()
1996 }
1997
1998 fn describe(node: &Node) -> String {
1999 match node.kind() {
2000 NodeKind::Document => "/".to_owned(),
2001 NodeKind::Element => node.name().unwrap().to_string(),
2002 NodeKind::Attribute => format!("@{}", node.name().unwrap()),
2003 NodeKind::Text => format!("{:?}", node.string_value()),
2004 NodeKind::Comment => format!("<!--{}-->", node.string_value()),
2005 NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
2006 }
2007 }
2008
2009 fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
2010 node.axis(axis).map(|n| describe(&n)).collect()
2011 }
2012
2013 fn find(tree: &Rc<Document>, local: &str) -> Node {
2014 tree.root()
2015 .axis(NodeAxis::Descendant)
2016 .find(|n| n.name().is_some_and(|name| name.local == local))
2017 .unwrap()
2018 }
2019
2020 const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
2021 <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
2022
2023 const NONE: [&str; 0] = [];
2024
2025 #[test]
2026 fn document_order_and_axes() {
2027 let tree = parse(XML);
2028 let root = tree.root();
2029 assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
2030 let top = find(&tree, "r");
2031 assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
2032 assert_eq!(
2033 walk(&top, NodeAxis::Child),
2034 ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
2035 );
2036 assert_eq!(
2037 walk(&top, NodeAxis::Descendant),
2038 [
2039 "\" \"",
2040 "x",
2041 "\"1\"",
2042 "y",
2043 "\"2\"",
2044 "\"3\"",
2045 "p:z",
2046 "<!--c1-->",
2047 "<?pi?>",
2048 "w",
2049 "v"
2050 ]
2051 );
2052 let y = find(&tree, "y");
2053 assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
2054 assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
2055 assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
2056 assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
2057 assert_eq!(
2058 walk(&y, NodeAxis::Preceding),
2059 ["\"1\"", "\" \"", "<!--c0-->"]
2060 );
2061 let v = find(&tree, "v");
2062 assert_eq!(
2063 walk(&v, NodeAxis::Preceding),
2064 [
2065 "<?pi?>",
2066 "<!--c1-->",
2067 "p:z",
2068 "\"3\"",
2069 "\"2\"",
2070 "y",
2071 "\"1\"",
2072 "x",
2073 "\" \"",
2074 "<!--c0-->"
2075 ]
2076 );
2077 let q = y.attributes().next().unwrap();
2078 assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
2079 assert_eq!(
2080 walk(&q, NodeAxis::Preceding),
2081 ["\"1\"", "\" \"", "<!--c0-->"]
2082 );
2083 assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
2084 assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
2085 assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
2086 assert_eq!(walk(&q, NodeAxis::Child), NONE);
2087 let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
2088 assert!(
2089 all.windows(2)
2090 .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
2091 );
2092 }
2093
2094 #[test]
2095 fn values_names_and_prefixes() {
2096 let tree = parse(XML);
2097 let top = find(&tree, "r");
2098 assert_eq!(top.string_value(), " 123");
2099 assert_eq!(find(&tree, "x").string_value(), "123");
2100 assert_eq!(find(&tree, "y").string_value(), "2");
2101 assert_eq!(find(&tree, "w").string_value(), "");
2102 let z = find(&tree, "z");
2103 assert_eq!(z.name().unwrap().to_string(), "p:z");
2104 assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
2105 let prefixed = top.attributes().nth(1).unwrap();
2106 assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
2107 assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
2108 let comment = tree.root().children().next().unwrap();
2109 assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
2110 assert_eq!(tree.document_uri(), None);
2111 assert_eq!(tree.base_uri(), Some("file:/t.xml"));
2112 let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
2113 assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
2114 assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
2115 assert_eq!(z.root(), tree.root());
2116 assert_ne!(z, top);
2117 }
2118
2119 #[test]
2120 fn undeclared_default_namespace_is_no_namespace() {
2121 let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
2122 assert_eq!(
2123 find(&tree, "r").name().unwrap().namespace.as_deref(),
2124 Some("urn:d")
2125 );
2126 assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
2127 assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
2128 }
2129
2130 #[test]
2131 fn same_namespace_two_prefixes() {
2132 let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
2133 let inner = find(&tree, "c");
2134 assert_eq!(inner.name().unwrap().to_string(), "b:c");
2135 assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
2136 let attribute = inner.attributes().next().unwrap();
2137 assert_eq!(attribute.name().unwrap().to_string(), "a:d");
2138 }
2139
2140 #[test]
2141 fn builder_merges_text_and_replaces_attributes() {
2142 let mut builder = TreeBuilder::new();
2143 builder.start_element(QName::local("e")).unwrap();
2144 builder.attribute(QName::local("a"), "1").unwrap();
2145 builder.attribute(QName::local("a"), "2").unwrap();
2146 builder.text("x").unwrap();
2147 builder.text("").unwrap();
2148 builder.text("y").unwrap();
2149 assert!(builder.attribute(QName::local("late"), "1").is_err());
2150 builder.end_element().unwrap();
2151 assert!(builder.end_element().is_err());
2152 let tree = builder.finish(None, None).unwrap();
2153 let element = tree.root().children().next().unwrap();
2154 let attributes: Vec<_> = element
2155 .attributes()
2156 .map(|a| a.string_value().into_owned())
2157 .collect();
2158 assert_eq!(attributes, ["2"]);
2159 let texts: Vec<_> = element
2160 .children()
2161 .map(|t| t.string_value().into_owned())
2162 .collect();
2163 assert_eq!(texts, ["xy"]);
2164 }
2165
2166 #[test]
2167 fn whitespace_text_kept_and_dtd_refused() {
2168 let tree = parse("<r>\n <a/>\n</r>\n");
2169 let top = tree.root().children().next().unwrap();
2170 assert_eq!(top.children().count(), 3);
2171 assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
2172 assert!(Document::parse("<r><a></r>", None).is_err());
2173 }
2174
2175 #[test]
2176 fn adjacent_text_is_one_node() {
2177 let text = "<r>a<![CDATA[<b>]]>c&d<!--x-->e\r\nf<s/></r>";
2178 for tree in [parse(text), Document::parse(text.to_owned(), None).unwrap()] {
2179 let top = tree.root().children().next().unwrap();
2180 let children: Vec<_> = top
2181 .children()
2182 .map(|t| (t.kind(), t.string_value().into_owned()))
2183 .collect();
2184 assert_eq!(
2185 children,
2186 [
2187 (NodeKind::Text, "a<b>c&d".to_owned()),
2188 (NodeKind::Comment, "x".to_owned()),
2189 (NodeKind::Text, "e\nf".to_owned()),
2190 (NodeKind::Element, String::new()),
2191 ]
2192 );
2193 }
2194 let tree = parse("<r><!--a\r\nb\rc--><?p a\r\nb?></r>");
2197 let values: Vec<_> = tree
2198 .root()
2199 .children()
2200 .next()
2201 .unwrap()
2202 .children()
2203 .map(|n| n.string_value().into_owned())
2204 .collect();
2205 assert_eq!(values, ["a\nb\nc", "a\nb"]);
2206 assert_eq!(parse("<r>x\r&y</r>").root().string_value(), "x\n&y");
2208 }
2209
2210 #[test]
2211 fn errors_are_those_of_the_reader() {
2212 let error = Document::parse("<r>\n<a></r>", None).unwrap_err();
2213 assert_eq!(error.message(), "XML: expected 'a' tag, not 'r' at 2:4");
2214 assert_eq!(error.limit(), None);
2215 let error = Document::parse("<!DOCTYPE r><r/>", None).unwrap_err();
2216 assert_eq!(error.message(), "XML: XML with DTD detected");
2217 }
2218
2219 #[test]
2220 fn records_are_compact() {
2221 assert_eq!(std::mem::size_of::<Record>(), 32);
2222 }
2223
2224 fn dump(tree: &Rc<Document>) -> Vec<String> {
2226 (0..tree.node_count())
2227 .map(|i| {
2228 let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
2229 let name = node.name().map(|n| {
2230 format!(
2231 "{}{{{}}}{}",
2232 n,
2233 n.namespace.as_deref().unwrap_or(""),
2234 n.local
2235 )
2236 });
2237 format!(
2238 "{:?} {name:?} {:?} {:?}",
2239 node.kind(),
2240 node.string_value(),
2241 node.parent().map(|p| p.index())
2242 )
2243 })
2244 .collect()
2245 }
2246
2247 #[test]
2252 fn owned_source_is_referred_to() {
2253 let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
2254 <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&y' c='t\tu'>\
2255 verbatim<e p:f='1'>aAb</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
2256 <?pi in?><e/>tail</p:r>";
2257 let borrowed = Document::parse(xml, None).unwrap();
2258 let owned = Document::parse(xml.to_owned(), None).unwrap();
2259 assert_eq!(dump(&borrowed), dump(&owned));
2260 assert_eq!(borrowed.source, "");
2261 assert_eq!(owned.source, xml);
2262 assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
2264 let copied_whole: usize = (0..borrowed.node_count())
2265 .map(|i| {
2266 let i = u32::try_from(i).unwrap();
2267 match borrowed.kind(i) {
2268 NodeKind::Element | NodeKind::Document => 0,
2269 _ => borrowed.own_text(i).len(),
2270 }
2271 })
2272 .sum();
2273 assert_eq!(borrowed.text.len(), copied_whole);
2274 for tree in [&borrowed, &owned] {
2275 assert_eq!(tree.records.capacity(), tree.records.len());
2276 assert_eq!(tree.text.capacity(), tree.text.len());
2277 assert_eq!(tree.names.capacity(), tree.names.len());
2278 }
2279 let r = find(&owned, "r");
2280 let values: Vec<_> = r
2281 .attributes()
2282 .map(|a| a.string_value().into_owned())
2283 .collect();
2284 assert_eq!(values, ["plain", "x&y", "t u"]);
2285 assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
2286 assert_eq!(r.name().unwrap().to_string(), "p:r");
2287 let e = find(&owned, "e");
2288 assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
2289 let f = e.attributes().next().unwrap();
2290 assert_eq!(f.name().unwrap().to_string(), "p:f");
2291 assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
2292 assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
2294 }
2295
2296 #[test]
2297 fn built_trees_merge_text_after_a_parsed_shape() {
2298 let mut builder = TreeBuilder::new();
2301 builder.start_element(QName::local("e")).unwrap();
2302 builder.attribute(QName::local("a"), "v").unwrap();
2303 builder.comment("c").unwrap();
2304 builder.text("x").unwrap();
2305 builder.text("y").unwrap();
2306 builder.processing_instruction("t", "d").unwrap();
2307 builder.text("z").unwrap();
2308 builder.end_element().unwrap();
2309 let tree = builder.finish(None, None).unwrap();
2310 let e = tree.root().children().next().unwrap();
2311 let children: Vec<_> = e
2312 .children()
2313 .map(|c| (c.kind(), c.string_value().into_owned()))
2314 .collect();
2315 assert_eq!(
2316 children,
2317 [
2318 (NodeKind::Comment, "c".to_owned()),
2319 (NodeKind::Text, "xy".to_owned()),
2320 (NodeKind::ProcessingInstruction, "d".to_owned()),
2321 (NodeKind::Text, "z".to_owned()),
2322 ]
2323 );
2324 assert_eq!(tree.text, "vcxydz");
2325 }
2326
2327 #[test]
2328 fn the_document_cache_parses_a_text_once() {
2329 fn shape(doc: &Rc<Document>) -> Vec<String> {
2330 doc.root()
2331 .axis(NodeAxis::Descendant)
2332 .flat_map(|n| std::iter::once(n.clone()).chain(n.attributes()))
2333 .map(|n| format!("{} {}", describe(&n), n.string_value()))
2334 .collect()
2335 }
2336 let cache = DocumentCache::new();
2337 let xml = "<cl id='1'><e v='a'/>text & more<e v='b'/></cl>";
2338 let uri = "file:/codes.xml";
2339 let first = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2340 let between = parse("<x/>");
2341 let second = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2342 assert_eq!(shape(&first), shape(&second));
2344 assert_eq!(second.document_uri(), Some(uri));
2345 assert_eq!(second.base_uri(), Some(uri));
2346 assert_eq!(second.node_count(), first.node_count());
2347 assert_ne!(first.root(), second.root());
2348 assert_eq!(
2349 between.root().cmp_document_order(&second.root()),
2350 Ordering::Less
2351 );
2352 assert_eq!(
2353 first.root().cmp_document_order(&between.root()),
2354 Ordering::Less
2355 );
2356 assert_eq!(cache.entries.lock().unwrap().len(), 1);
2357 let other = cache.parse_loaded("<cl/>".to_owned(), uri, 8).unwrap();
2359 assert_eq!(other.node_count(), 2);
2360 let elsewhere = cache
2361 .parse_loaded(xml.to_owned(), "file:/other.xml", 8)
2362 .unwrap();
2363 assert_eq!(elsewhere.document_uri(), Some("file:/other.xml"));
2364 assert_eq!(shape(&elsewhere), shape(&first));
2365 let deeper = cache.parse_loaded(xml.to_owned(), uri, 1).unwrap_err();
2366 assert!(deeper.limit().is_some());
2367 assert_eq!(cache.entries.lock().unwrap().len(), 3);
2368 assert!(cache.parse_loaded("<cl>".to_owned(), uri, 8).is_err());
2370 assert_eq!(cache.entries.lock().unwrap().len(), 3);
2371 }
2372
2373 #[test]
2374 fn the_element_index_lists_the_elements_of_a_name_in_document_order() {
2375 let mut xml = String::from(r#"<r xmlns:a="urn:x" xmlns:b="urn:x" xmlns="urn:x">"#);
2376 for i in 0..40 {
2377 let prefix = ["a:", "b:", ""][i % 3];
2378 write!(xml, r#"<{prefix}e n="{i}"><f/><e/></{prefix}e><g>t</g>"#).unwrap();
2379 }
2380 xml.push_str("</r>");
2381 let doc = parse(&xml);
2382 let scan = |start: u32, end: u32| -> Vec<u32> {
2383 (start..end)
2384 .filter(|&i| {
2385 doc.kind(i) == NodeKind::Element
2386 && doc.name(i).is_some_and(|n| {
2387 n.local == "e" && n.namespace.as_deref() == Some("urn:x")
2388 })
2389 })
2390 .collect()
2391 };
2392 let (first, end) = doc.descendant_range(0);
2393 assert_eq!(doc.elements_named(Some("urn:x"), "e", first, end), None);
2395 let all = doc.elements_named(Some("urn:x"), "e", first, end).unwrap();
2396 assert_eq!(all, scan(first, end).as_slice());
2397 assert_eq!(all.len(), 80);
2398 let inner = doc.elements_named(Some("urn:x"), "e", 10, 200).unwrap();
2400 assert_eq!(inner, scan(10, 200).as_slice());
2401 assert_eq!(doc.elements_named(None, "e", first, end), Some(&[][..]));
2402 assert_eq!(
2403 doc.elements_named(Some("urn:x"), "zz", first, end),
2404 Some(&[][..])
2405 );
2406 assert_eq!(doc.elements_named(Some("urn:x"), "e", 10, 20), None);
2408 }
2409
2410 #[test]
2411 fn file_uris() {
2412 if cfg!(windows) {
2413 return;
2414 }
2415 assert_eq!(
2416 file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
2417 Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
2418 );
2419 assert_eq!(file_uri(Path::new("rel.xml")), None);
2420 }
2421}