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]
894 pub fn has_own_namespaces(&self) -> bool {
895 self.kind() == NodeKind::Element
896 && self
897 .doc
898 .namespaces
899 .binary_search_by_key(&self.index, |(e, _)| *e)
900 .is_ok()
901 }
902
903 #[must_use]
905 pub fn string_value(&self) -> Cow<'_, str> {
906 self.doc.string_value(self.index)
907 }
908
909 #[must_use]
914 pub fn by_id(&self, id: &str) -> Option<Self> {
915 let doc = &self.doc;
916 if doc.view == TreeView::Dom {
917 return None;
918 }
919 let ids = doc.ids.get_or_init(|| {
920 let mut ids = HashMap::new();
921 for (index, record) in (0_u32..).zip(&doc.records) {
922 if record.kind != NodeKind::Attribute {
923 continue;
924 }
925 let is_xml_id = doc.name(index).is_some_and(|n| {
926 n.local == "id" && n.namespace.as_deref() == Some(XML_NAMESPACE)
927 });
928 if is_xml_id {
929 let value: Vec<&str> = doc
930 .own_text(index)
931 .split([' ', '\t', '\n', '\r'])
932 .filter(|t| !t.is_empty())
933 .collect();
934 ids.entry(value.join(" ")).or_insert(record.parent);
935 }
936 }
937 ids
938 });
939 ids.get(id).map(|&i| Self::new(Rc::clone(doc), i))
940 }
941
942 #[must_use]
949 pub fn generate_id(&self) -> String {
950 let doc = &self.doc;
951 let number = doc.serial + 1;
952 match doc.view {
953 TreeView::Tiny => {
954 let attributes_before = |index: u32| {
955 doc.records[..index as usize]
956 .iter()
957 .filter(|r| r.kind == NodeKind::Attribute)
958 .count()
959 };
960 let tiny = |index: u32| {
961 let kind = doc.kind(index);
962 if kind == NodeKind::Document {
963 return format!("d{number}");
964 }
965 let letter = match kind {
966 NodeKind::Text => 't',
967 NodeKind::Comment => 'c',
968 NodeKind::ProcessingInstruction => 'p',
969 _ => 'e',
970 };
971 let node_number = index as usize - attributes_before(index);
972 format!("d{number}{letter}{node_number}")
973 };
974 if self.kind() == NodeKind::Attribute {
975 let parent = doc.record(self.index).parent;
976 let owner = if parent == NONE {
977 format!("d{number}")
978 } else {
979 tiny(parent)
980 };
981 format!("{owner}a{}", attributes_before(self.index))
982 } else {
983 tiny(self.index)
984 }
985 }
986 TreeView::Dom => {
987 let lineage: Vec<u32> = doc
988 .cursor(self.index, NodeAxis::AncestorOrSelf)
989 .walk(doc)
990 .collect();
991 let mut id = format!("w{number}");
992 for &index in lineage.iter().rev() {
993 let record = doc.record(index);
994 if record.parent == NONE {
995 continue;
996 }
997 let position = if record.kind == NodeKind::Attribute {
998 id.push('a');
999 index - record.parent - 1
1000 } else {
1001 u32::try_from(
1002 doc.cursor(index, NodeAxis::PrecedingSibling)
1003 .walk(doc)
1004 .count(),
1005 )
1006 .unwrap_or(u32::MAX)
1007 };
1008 id.push_str(&alpha_key(position));
1009 }
1010 id
1011 }
1012 }
1013 }
1014
1015 #[must_use]
1018 pub fn typed_value(&self) -> AtomicValue {
1019 let value = self.string_value().into_owned();
1020 match self.kind() {
1021 NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
1022 _ => AtomicValue::UntypedAtomic(value),
1023 }
1024 }
1025
1026 #[must_use]
1029 pub fn axis(&self, axis: NodeAxis) -> Axis {
1030 Axis {
1031 cursor: self.doc.cursor(self.index, axis),
1032 doc: Rc::clone(&self.doc),
1033 }
1034 }
1035
1036 #[must_use]
1038 pub fn children(&self) -> Axis {
1039 self.axis(NodeAxis::Child)
1040 }
1041
1042 #[must_use]
1044 pub fn attributes(&self) -> Axis {
1045 self.axis(NodeAxis::Attribute)
1046 }
1047
1048 #[must_use]
1051 pub fn cmp_document_order(&self, other: &Self) -> Ordering {
1052 self.doc
1053 .serial
1054 .cmp(&other.doc.serial)
1055 .then(self.index.cmp(&other.index))
1056 }
1057}
1058
1059#[derive(Debug, Clone)]
1061pub struct Axis {
1062 cursor: Cursor,
1063 doc: Rc<Document>,
1064}
1065
1066impl Iterator for Axis {
1067 type Item = Node;
1068
1069 fn next(&mut self) -> Option<Node> {
1070 let index = self.cursor.next(&self.doc)?;
1071 Some(Node::new(Rc::clone(&self.doc), index))
1072 }
1073
1074 fn count(self) -> usize {
1075 self.cursor.walk(&self.doc).count()
1076 }
1077}
1078
1079#[derive(Debug, Default)]
1091pub struct DocumentCache {
1092 entries: std::sync::Mutex<Vec<CachedDocument>>,
1093}
1094
1095#[derive(Debug)]
1097struct CachedDocument {
1098 max_depth: u32,
1099 document: Document,
1100}
1101
1102impl DocumentCache {
1103 pub const MAX_DOCUMENTS: usize = 64;
1105 pub const MAX_BYTES: usize = 64 << 20;
1107
1108 #[must_use]
1110 pub fn new() -> Self {
1111 Self::default()
1112 }
1113
1114 pub fn parse_loaded(
1122 &self,
1123 text: String,
1124 uri: &str,
1125 max_depth: u32,
1126 ) -> Result<Rc<Document>, DocumentError> {
1127 {
1128 let entries = self
1129 .entries
1130 .lock()
1131 .unwrap_or_else(std::sync::PoisonError::into_inner);
1132 if let Some(entry) = entries.iter().find(|e| {
1133 e.max_depth == max_depth
1134 && e.document.uri.as_deref() == Some(uri)
1135 && e.document.source == text
1136 }) {
1137 return Ok(Rc::new(entry.document.copy_with_source(text)));
1138 }
1139 }
1140 let document = Document::parse_loaded_with_max_depth(text, uri, max_depth)?;
1141 let mut entries = self
1142 .entries
1143 .lock()
1144 .unwrap_or_else(std::sync::PoisonError::into_inner);
1145 let bytes: usize = entries.iter().map(|e| e.document.source.len()).sum();
1146 if entries.len() < Self::MAX_DOCUMENTS
1147 && bytes.saturating_add(document.source.len()) <= Self::MAX_BYTES
1148 && !entries.iter().any(|e| {
1149 e.max_depth == max_depth
1150 && e.document.uri.as_deref() == Some(uri)
1151 && e.document.source == document.source
1152 })
1153 {
1154 entries.push(CachedDocument {
1155 max_depth,
1156 document: document.copy_with_source(document.source.clone()),
1157 });
1158 }
1159 Ok(document)
1160 }
1161}
1162
1163#[derive(Debug)]
1169pub struct TreeBuilder {
1170 records: Vec<Record>,
1171 names: Vec<QName>,
1172 name_ids: HashMap<QName, u32>,
1173 namespaces: Vec<(u32, Arc<[NamespaceBinding]>)>,
1175 parentless: bool,
1177 source_len: usize,
1180 text: String,
1181 open: Vec<u32>,
1183 last_child: Vec<u32>,
1185 has_xml_base: bool,
1186 view: TreeView,
1187}
1188
1189impl Default for TreeBuilder {
1190 fn default() -> Self {
1191 Self::new()
1192 }
1193}
1194
1195fn to_u32(value: usize) -> Result<u32, DocumentError> {
1196 u32::try_from(value)
1197 .ok()
1198 .filter(|&v| v != NONE)
1199 .ok_or_else(|| DocumentError::new("document too large"))
1200}
1201
1202#[derive(Debug, Clone, Copy)]
1204enum NodeText<'s> {
1205 Source(u32, u32),
1207 Copy(&'s str),
1209}
1210
1211impl TreeBuilder {
1212 #[must_use]
1214 pub fn new() -> Self {
1215 Self {
1216 records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
1217 names: Vec::new(),
1218 name_ids: HashMap::new(),
1219 namespaces: Vec::new(),
1220 parentless: false,
1221 source_len: 0,
1222 text: String::new(),
1223 open: vec![0],
1224 last_child: vec![NONE],
1225 has_xml_base: false,
1226 view: TreeView::Tiny,
1227 }
1228 }
1229
1230 #[must_use]
1232 pub const fn dom_view(mut self) -> Self {
1233 self.view = TreeView::Dom;
1234 self
1235 }
1236
1237 #[must_use]
1242 pub fn parentless() -> Self {
1243 Self {
1244 records: Vec::new(),
1245 open: Vec::new(),
1246 parentless: true,
1247 ..Self::new()
1248 }
1249 }
1250
1251 fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
1255 let mut builder = Self::new();
1256 builder.records.reserve_exact(nodes.saturating_sub(1));
1257 builder.text.reserve_exact(text);
1258 builder.source_len = source_len;
1259 builder
1260 }
1261
1262 fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
1263 if let Some(&id) = self.name_ids.get(&name) {
1264 return Ok(id);
1265 }
1266 let id = self.push_name(name.clone())?;
1267 self.name_ids.insert(name, id);
1268 Ok(id)
1269 }
1270
1271 fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
1273 let id = to_u32(self.names.len())?;
1274 self.names.push(name);
1275 Ok(id)
1276 }
1277
1278 fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
1280 match value {
1281 NodeText::Source(start, len) => Ok((start, len)),
1282 NodeText::Copy(value) => {
1283 let start = to_u32(self.source_len + self.text.len())?;
1284 let len = to_u32(value.len())?;
1285 to_u32(self.source_len + self.text.len() + value.len())?;
1286 self.text.push_str(value);
1287 Ok((start, len))
1288 }
1289 }
1290 }
1291
1292 fn top(&self) -> u32 {
1294 self.open.last().copied().unwrap_or(NONE)
1295 }
1296
1297 const fn base(&self) -> usize {
1299 if self.parentless { 0 } else { 1 }
1300 }
1301
1302 fn append(
1305 &mut self,
1306 kind: NodeKind,
1307 name: u32,
1308 text: NodeText<'_>,
1309 ) -> Result<u32, DocumentError> {
1310 let index = to_u32(self.records.len())?;
1311 to_u32(self.records.len() + 1)?;
1312 if self.parentless && self.open.is_empty() && !self.records.is_empty() {
1313 return Err(DocumentError::new(
1314 "a second node at the top of a parentless tree",
1315 ));
1316 }
1317 let text = if kind == NodeKind::Element {
1318 (0, 0)
1319 } else {
1320 self.store_text(text)?
1321 };
1322 let parent = self.top();
1323 let last = self.last_child.last_mut().map_or(NONE, |l| {
1324 let previous = *l;
1325 *l = index;
1326 previous
1327 });
1328 self.records
1329 .push(Record::new(kind, name, parent, last, index, text));
1330 Ok(index)
1331 }
1332
1333 pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
1339 let name = self.intern(name)?;
1340 self.open_element(name)
1341 }
1342
1343 pub fn add_namespace(&mut self, binding: NamespaceBinding) -> Result<(), DocumentError> {
1349 let element = self.top();
1350 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1351 if element == NONE
1352 || self.records[element as usize].kind != NodeKind::Element
1353 || has_content
1354 {
1355 return Err(DocumentError::new(format!(
1356 "namespace {:?} outside an element start",
1357 binding.prefix
1358 )));
1359 }
1360 match self.namespaces.last_mut() {
1361 Some((e, bindings)) if *e == element => {
1362 let mut extended: Vec<NamespaceBinding> = bindings.to_vec();
1363 extended.retain(|b| b.prefix != binding.prefix);
1364 extended.push(binding);
1365 *bindings = extended.into();
1366 }
1367 _ => self.namespaces.push((element, vec![binding].into())),
1368 }
1369 Ok(())
1370 }
1371
1372 pub fn start_element_with_namespaces(
1379 &mut self,
1380 name: QName,
1381 namespaces: Arc<[NamespaceBinding]>,
1382 ) -> Result<(), DocumentError> {
1383 self.start_element(name)?;
1384 if !namespaces.is_empty() {
1385 let element = self.top();
1386 self.namespaces.push((element, namespaces));
1387 }
1388 Ok(())
1389 }
1390
1391 fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
1392 let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
1393 self.open.push(index);
1394 self.last_child.push(NONE);
1395 Ok(())
1396 }
1397
1398 pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
1404 if self.parentless && self.records.is_empty() {
1405 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1407 let id = self.intern(name)?;
1408 let text = self.store_text(NodeText::Copy(value))?;
1409 self.records
1410 .push(Record::new(NodeKind::Attribute, id, NONE, NONE, 0, text));
1411 self.has_xml_base |= xml_base;
1412 return Ok(());
1413 }
1414 let element = self.top();
1415 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
1416 if element == NONE
1417 || self.records[element as usize].kind != NodeKind::Element
1418 || has_content
1419 {
1420 return Err(DocumentError::new(format!(
1421 "attribute {name} outside an element start"
1422 )));
1423 }
1424 let first = element as usize + 1;
1425 let existing = (first..self.records.len()).find(|&i| {
1426 let id = self.records[i].name;
1427 self.names[id as usize].same_expanded_name(&name)
1428 });
1429 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
1430 let id = self.intern(name)?;
1431 if let Some(i) = existing {
1432 let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
1433 let record = &mut self.records[i];
1434 record.name = id;
1435 record.text_start = text_start;
1436 record.text_len = text_len;
1437 self.has_xml_base |= xml_base;
1438 return Ok(());
1439 }
1440 self.push_attribute(id, xml_base, NodeText::Copy(value))
1441 }
1442
1443 fn push_attribute(
1445 &mut self,
1446 name: u32,
1447 xml_base: bool,
1448 value: NodeText<'_>,
1449 ) -> Result<(), DocumentError> {
1450 let element = self.top();
1451 let index = to_u32(self.records.len())?;
1452 to_u32(self.records.len() + 1)?;
1453 let previous = if index == element + 1 {
1454 NONE
1455 } else {
1456 index - 1
1457 };
1458 let text = self.store_text(value)?;
1459 self.records.push(Record::new(
1460 NodeKind::Attribute,
1461 name,
1462 element,
1463 previous,
1464 index,
1465 text,
1466 ));
1467 self.records[element as usize].first_child = index + 1;
1468 self.has_xml_base |= xml_base;
1469 Ok(())
1470 }
1471
1472 pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
1478 if value.is_empty() {
1479 if self.parentless && self.records.is_empty() {
1482 return self
1483 .append(NodeKind::Text, NONE, NodeText::Copy(""))
1484 .map(drop);
1485 }
1486 return Ok(());
1487 }
1488 let last = self.last_child.last().copied().unwrap_or(NONE);
1489 let mergeable = last != NONE
1492 && last as usize + 1 == self.records.len()
1493 && self.records[last as usize].kind == NodeKind::Text
1494 && {
1495 let r = &self.records[last as usize];
1496 r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
1497 && r.text_start as usize >= self.source_len
1498 };
1499 if mergeable {
1500 self.store_text(NodeText::Copy(value))?;
1501 let record = &mut self.records[last as usize];
1502 record.text_len = to_u32(record.text_len as usize + value.len())?;
1503 return Ok(());
1504 }
1505 self.append(NodeKind::Text, NONE, NodeText::Copy(value))
1506 .map(drop)
1507 }
1508
1509 pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1515 self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
1516 .map(drop)
1517 }
1518
1519 pub fn processing_instruction(
1525 &mut self,
1526 target: &str,
1527 value: &str,
1528 ) -> Result<(), DocumentError> {
1529 let name = self.intern(QName::local(target))?;
1530 self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
1531 .map(drop)
1532 }
1533
1534 pub fn end_element(&mut self) -> Result<(), DocumentError> {
1540 if self.open.len() <= self.base() {
1541 return Err(DocumentError::new("end of element without a start"));
1542 }
1543 let element = self.top();
1544 self.open.pop();
1545 self.last_child.pop();
1546 let end = to_u32(self.records.len())?;
1547 self.records[element as usize].end = end;
1548 Ok(())
1549 }
1550
1551 pub fn finish(
1557 self,
1558 document_uri: Option<String>,
1559 base_uri: Option<String>,
1560 ) -> Result<Rc<Document>, DocumentError> {
1561 self.finish_with_source(String::new(), document_uri, base_uri)
1562 }
1563
1564 fn finish_with_source(
1567 mut self,
1568 source: String,
1569 document_uri: Option<String>,
1570 base_uri: Option<String>,
1571 ) -> Result<Rc<Document>, DocumentError> {
1572 if self.open.len() != self.base() {
1573 return Err(DocumentError::new("unclosed element"));
1574 }
1575 if source.len() != self.source_len {
1576 return Err(DocumentError::new("source text of another length"));
1577 }
1578 if self.parentless {
1579 if self.records.is_empty() {
1580 return Err(DocumentError::new("a parentless tree without a node"));
1581 }
1582 } else {
1583 self.records[0].end = to_u32(self.records.len())?;
1584 }
1585 self.records.shrink_to_fit();
1588 self.names.shrink_to_fit();
1589 self.text.shrink_to_fit();
1590 Ok(Rc::new(Document {
1591 serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
1592 uri: document_uri,
1593 base_uri,
1594 has_xml_base: self.has_xml_base,
1595 records: self.records,
1596 names: self.names,
1597 namespaces: self.namespaces,
1598 source,
1599 text: self.text,
1600 elements: OnceCell::new(),
1601 searches: Cell::new(0),
1602 view: self.view,
1603 ids: OnceCell::new(),
1604 }))
1605 }
1606}
1607
1608fn alpha_key(value: u32) -> String {
1611 if value < 1 {
1612 return "a".to_owned();
1613 }
1614 let digits = value.to_string();
1615 let letter = char::from(b'a' + u8::try_from(digits.len()).unwrap_or(10));
1616 format!("{letter}{digits}")
1617}
1618
1619fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
1620 local == "base" && namespace == Some(XML_NAMESPACE)
1621}
1622
1623fn offset_in(input: &str, part: &str) -> Option<usize> {
1625 let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
1626 (start.checked_add(part.len())? <= input.len()).then_some(start)
1627}
1628
1629fn xml_error(e: &einvoice_xml::Error) -> DocumentError {
1631 DocumentError::new(format!("XML: {e}"))
1632}
1633
1634struct Namespaces<'a> {
1638 input: &'a str,
1639 ids: HashMap<Box<str>, u32>,
1640 last: Option<(usize, usize, u32)>,
1643}
1644
1645impl<'a> Namespaces<'a> {
1646 fn new(input: &'a str) -> Self {
1647 Self {
1648 input,
1649 ids: HashMap::new(),
1650 last: None,
1651 }
1652 }
1653
1654 fn id(&mut self, namespace: Option<&str>) -> Result<u32, DocumentError> {
1656 let Some(namespace) = namespace else {
1657 return Ok(NONE);
1658 };
1659 let at = offset_in(self.input, namespace);
1660 if let (Some(at), Some((last, len, id))) = (at, self.last)
1661 && at == last
1662 && namespace.len() == len
1663 {
1664 return Ok(id);
1665 }
1666 let id = if let Some(&id) = self.ids.get(namespace) {
1667 id
1668 } else {
1669 let id = to_u32(self.ids.len())?;
1670 self.ids.insert(namespace.into(), id);
1671 id
1672 };
1673 if let Some(at) = at {
1674 self.last = Some((at, namespace.len(), id));
1675 }
1676 Ok(id)
1677 }
1678}
1679
1680type NameKey<'a> = (&'a str, &'a str, u32);
1683
1684struct Names<'a> {
1686 namespaces: Namespaces<'a>,
1687 ids: HashMap<NameKey<'a>, u32>,
1688}
1689
1690impl<'a> Names<'a> {
1691 fn new(input: &'a str) -> Self {
1692 Self {
1693 namespaces: Namespaces::new(input),
1694 ids: HashMap::new(),
1695 }
1696 }
1697
1698 fn id(
1700 &mut self,
1701 builder: &mut TreeBuilder,
1702 name: einvoice_xml::Name<'_, 'a>,
1703 ) -> Result<u32, DocumentError> {
1704 let key = (name.prefix, name.local, self.namespaces.id(name.namespace)?);
1705 if let Some(&id) = self.ids.get(&key) {
1706 return Ok(id);
1707 }
1708 let id = builder.push_name(QName {
1709 prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
1710 namespace: name.namespace.map(str::to_owned),
1711 local: name.local.to_owned(),
1712 })?;
1713 self.ids.insert(key, id);
1714 Ok(id)
1715 }
1716}
1717
1718trait Pass<'a> {
1723 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError>;
1724 fn end(&mut self) -> Result<(), DocumentError>;
1725 fn text(&mut self, text: &str) -> Result<(), DocumentError>;
1726 fn comment(&mut self, value: &str) -> Result<(), DocumentError>;
1727 fn processing_instruction(
1728 &mut self,
1729 pi: &einvoice_xml::ProcessingInstruction<'a>,
1730 ) -> Result<(), DocumentError>;
1731}
1732
1733fn read<'a>(input: &'a str, max_depth: u32, pass: &mut impl Pass<'a>) -> Result<(), DocumentError> {
1737 let mut reader = einvoice_xml::Reader::new(input);
1738 let mut depth = 0u32;
1739 let mut text: Option<Cow<'a, str>> = None;
1742 let mut too_deep: Option<LimitExceeded> = None;
1743 while let Some(event) = reader.next_event().map_err(|e| xml_error(&e))? {
1744 if let einvoice_xml::Event::Text(t) = event {
1745 if depth > 0 && too_deep.is_none() {
1746 match &mut text {
1747 None => text = Some(t.value),
1748 Some(joined) => joined.to_mut().push_str(&t.value),
1749 }
1750 }
1751 continue;
1752 }
1753 if let Some(joined) = text.take()
1754 && !joined.is_empty()
1755 {
1756 pass.text(&joined)?;
1757 }
1758 match event {
1759 einvoice_xml::Event::Start(start) => {
1760 depth = depth.saturating_add(1);
1761 if depth > max_depth && too_deep.is_none() {
1762 let at = einvoice_xml::TextPos::at(input, start.range().start);
1764 too_deep = Some(LimitExceeded::Depth {
1765 max: max_depth,
1766 line: at.row,
1767 column: at.col,
1768 });
1769 }
1770 if too_deep.is_none() {
1771 pass.start(start)?;
1772 }
1773 }
1774 einvoice_xml::Event::End(_) => {
1775 depth = depth.saturating_sub(1);
1776 if too_deep.is_none() {
1777 pass.end()?;
1778 }
1779 }
1780 einvoice_xml::Event::Comment(comment) if too_deep.is_none() => {
1781 pass.comment(&comment.value)?;
1782 }
1783 einvoice_xml::Event::ProcessingInstruction(pi) if too_deep.is_none() => {
1784 pass.processing_instruction(&pi)?;
1785 }
1786 _ => {}
1787 }
1788 }
1789 match too_deep {
1790 Some(limit) => Err(DocumentError::limit_exceeded(limit)),
1791 None => Ok(()),
1792 }
1793}
1794
1795struct Sizes<'a> {
1799 input: &'a str,
1800 keep_source: bool,
1801 nodes: usize,
1802 text_bytes: usize,
1803}
1804
1805impl Sizes<'_> {
1806 fn add(&mut self, text: &str) {
1807 self.nodes += 1;
1808 if !(self.keep_source && offset_in(self.input, text).is_some()) {
1809 self.text_bytes += text.len();
1810 }
1811 }
1812}
1813
1814impl<'a> Pass<'a> for Sizes<'a> {
1815 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1816 self.nodes += 1;
1817 for attribute in start.attributes() {
1818 self.add(attribute.value);
1819 }
1820 Ok(())
1821 }
1822
1823 fn end(&mut self) -> Result<(), DocumentError> {
1824 Ok(())
1825 }
1826
1827 fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1828 self.add(text);
1829 Ok(())
1830 }
1831
1832 fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1833 self.add(value);
1834 Ok(())
1835 }
1836
1837 fn processing_instruction(
1838 &mut self,
1839 pi: &einvoice_xml::ProcessingInstruction<'a>,
1840 ) -> Result<(), DocumentError> {
1841 self.add(pi.value.as_deref().unwrap_or(""));
1842 Ok(())
1843 }
1844}
1845
1846struct Fill<'a> {
1848 input: &'a str,
1849 keep_source: bool,
1850 builder: TreeBuilder,
1851 names: Names<'a>,
1852}
1853
1854impl Fill<'_> {
1855 fn node_text<'s>(&self, text: &'s str) -> Result<NodeText<'s>, DocumentError> {
1858 Ok(
1859 match self
1860 .keep_source
1861 .then(|| offset_in(self.input, text))
1862 .flatten()
1863 {
1864 Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1865 None => NodeText::Copy(text),
1866 },
1867 )
1868 }
1869}
1870
1871impl<'a> Pass<'a> for Fill<'a> {
1872 fn start(&mut self, start: einvoice_xml::StartElement<'_, 'a>) -> Result<(), DocumentError> {
1873 let id = self.names.id(&mut self.builder, start.name())?;
1874 self.builder.open_element(id)?;
1875 let declarations = start.namespace_declarations();
1876 if declarations.len() > 0 {
1877 let bindings: Arc<[NamespaceBinding]> = declarations
1878 .map(|(prefix, uri)| NamespaceBinding {
1879 prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1880 uri: uri.to_owned(),
1881 })
1882 .collect();
1883 let element = self.builder.top();
1884 self.builder.namespaces.push((element, bindings));
1885 }
1886 for attribute in start.attributes() {
1888 let id = self.names.id(&mut self.builder, attribute.name)?;
1889 let text = self.node_text(attribute.value)?;
1890 self.builder.push_attribute(
1891 id,
1892 is_xml_base(attribute.name.namespace, attribute.name.local),
1893 text,
1894 )?;
1895 }
1896 Ok(())
1897 }
1898
1899 fn end(&mut self) -> Result<(), DocumentError> {
1900 self.builder.end_element()
1901 }
1902
1903 fn text(&mut self, text: &str) -> Result<(), DocumentError> {
1904 let text = self.node_text(text)?;
1905 self.builder.append(NodeKind::Text, NONE, text).map(drop)
1906 }
1907
1908 fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
1909 let text = self.node_text(value)?;
1910 self.builder.append(NodeKind::Comment, NONE, text).map(drop)
1911 }
1912
1913 fn processing_instruction(
1914 &mut self,
1915 pi: &einvoice_xml::ProcessingInstruction<'a>,
1916 ) -> Result<(), DocumentError> {
1917 let target = einvoice_xml::Name {
1918 prefix: "",
1919 local: pi.target,
1920 namespace: None,
1921 };
1922 let id = self.names.id(&mut self.builder, target)?;
1923 let text = self.node_text(pi.value.as_deref().unwrap_or(""))?;
1924 self.builder
1925 .append(NodeKind::ProcessingInstruction, id, text)
1926 .map(drop)
1927 }
1928}
1929
1930fn build_parsed(
1938 input: &str,
1939 keep_source: bool,
1940 max_depth: u32,
1941) -> Result<TreeBuilder, DocumentError> {
1942 let mut sizes = Sizes {
1943 input,
1944 keep_source,
1945 nodes: 1,
1946 text_bytes: 0,
1947 };
1948 read(input, max_depth, &mut sizes)?;
1949 let mut fill = Fill {
1950 input,
1951 keep_source,
1952 builder: TreeBuilder::with_capacity(
1953 sizes.nodes,
1954 sizes.text_bytes,
1955 if keep_source { input.len() } else { 0 },
1956 ),
1957 names: Names::new(input),
1958 };
1959 read(input, max_depth, &mut fill)?;
1960 Ok(fill.builder)
1961}
1962
1963#[must_use]
1971pub fn file_uri(path: &Path) -> Option<String> {
1972 if !path.is_absolute() {
1973 return None;
1974 }
1975 let text = path.to_str()?.replace('\\', "/");
1976 let mut uri = String::from("file:");
1977 if !text.starts_with('/') {
1978 uri.push('/');
1979 }
1980 for c in text.chars() {
1981 let keep = if c.is_ascii() {
1982 c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1983 } else {
1984 !(matches!(
1986 c,
1987 '\u{A0}' | '\u{1680}' | '\u{2000}'
1988 ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1989 ) || c.is_control())
1990 };
1991 if keep {
1992 uri.push(c);
1993 } else {
1994 let mut buffer = [0; 4];
1995 for byte in c.encode_utf8(&mut buffer).bytes() {
1996 let _ = write!(uri, "%{byte:02X}");
1997 }
1998 }
1999 }
2000 Some(uri)
2001}
2002
2003#[cfg(test)]
2004mod tests {
2005 use super::*;
2006
2007 fn parse(xml: &str) -> Rc<Document> {
2008 Document::parse(xml, Some("file:/t.xml")).unwrap()
2009 }
2010
2011 fn describe(node: &Node) -> String {
2012 match node.kind() {
2013 NodeKind::Document => "/".to_owned(),
2014 NodeKind::Element => node.name().unwrap().to_string(),
2015 NodeKind::Attribute => format!("@{}", node.name().unwrap()),
2016 NodeKind::Text => format!("{:?}", node.string_value()),
2017 NodeKind::Comment => format!("<!--{}-->", node.string_value()),
2018 NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
2019 }
2020 }
2021
2022 fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
2023 node.axis(axis).map(|n| describe(&n)).collect()
2024 }
2025
2026 fn find(tree: &Rc<Document>, local: &str) -> Node {
2027 tree.root()
2028 .axis(NodeAxis::Descendant)
2029 .find(|n| n.name().is_some_and(|name| name.local == local))
2030 .unwrap()
2031 }
2032
2033 const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
2034 <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
2035
2036 const NONE: [&str; 0] = [];
2037
2038 #[test]
2039 fn document_order_and_axes() {
2040 let tree = parse(XML);
2041 let root = tree.root();
2042 assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
2043 let top = find(&tree, "r");
2044 assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
2045 assert_eq!(
2046 walk(&top, NodeAxis::Child),
2047 ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
2048 );
2049 assert_eq!(
2050 walk(&top, NodeAxis::Descendant),
2051 [
2052 "\" \"",
2053 "x",
2054 "\"1\"",
2055 "y",
2056 "\"2\"",
2057 "\"3\"",
2058 "p:z",
2059 "<!--c1-->",
2060 "<?pi?>",
2061 "w",
2062 "v"
2063 ]
2064 );
2065 let y = find(&tree, "y");
2066 assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
2067 assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
2068 assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
2069 assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
2070 assert_eq!(
2071 walk(&y, NodeAxis::Preceding),
2072 ["\"1\"", "\" \"", "<!--c0-->"]
2073 );
2074 let v = find(&tree, "v");
2075 assert_eq!(
2076 walk(&v, NodeAxis::Preceding),
2077 [
2078 "<?pi?>",
2079 "<!--c1-->",
2080 "p:z",
2081 "\"3\"",
2082 "\"2\"",
2083 "y",
2084 "\"1\"",
2085 "x",
2086 "\" \"",
2087 "<!--c0-->"
2088 ]
2089 );
2090 let q = y.attributes().next().unwrap();
2091 assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
2092 assert_eq!(
2093 walk(&q, NodeAxis::Preceding),
2094 ["\"1\"", "\" \"", "<!--c0-->"]
2095 );
2096 assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
2097 assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
2098 assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
2099 assert_eq!(walk(&q, NodeAxis::Child), NONE);
2100 let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
2101 assert!(
2102 all.windows(2)
2103 .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
2104 );
2105 }
2106
2107 #[test]
2108 fn values_names_and_prefixes() {
2109 let tree = parse(XML);
2110 let top = find(&tree, "r");
2111 assert_eq!(top.string_value(), " 123");
2112 assert_eq!(find(&tree, "x").string_value(), "123");
2113 assert_eq!(find(&tree, "y").string_value(), "2");
2114 assert_eq!(find(&tree, "w").string_value(), "");
2115 let z = find(&tree, "z");
2116 assert_eq!(z.name().unwrap().to_string(), "p:z");
2117 assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
2118 let prefixed = top.attributes().nth(1).unwrap();
2119 assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
2120 assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
2121 let comment = tree.root().children().next().unwrap();
2122 assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
2123 assert_eq!(tree.document_uri(), None);
2124 assert_eq!(tree.base_uri(), Some("file:/t.xml"));
2125 let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
2126 assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
2127 assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
2128 assert_eq!(z.root(), tree.root());
2129 assert_ne!(z, top);
2130 }
2131
2132 #[test]
2133 fn undeclared_default_namespace_is_no_namespace() {
2134 let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
2135 assert_eq!(
2136 find(&tree, "r").name().unwrap().namespace.as_deref(),
2137 Some("urn:d")
2138 );
2139 assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
2140 assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
2141 }
2142
2143 #[test]
2144 fn same_namespace_two_prefixes() {
2145 let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
2146 let inner = find(&tree, "c");
2147 assert_eq!(inner.name().unwrap().to_string(), "b:c");
2148 assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
2149 let attribute = inner.attributes().next().unwrap();
2150 assert_eq!(attribute.name().unwrap().to_string(), "a:d");
2151 }
2152
2153 #[test]
2154 fn builder_merges_text_and_replaces_attributes() {
2155 let mut builder = TreeBuilder::new();
2156 builder.start_element(QName::local("e")).unwrap();
2157 builder.attribute(QName::local("a"), "1").unwrap();
2158 builder.attribute(QName::local("a"), "2").unwrap();
2159 builder.text("x").unwrap();
2160 builder.text("").unwrap();
2161 builder.text("y").unwrap();
2162 assert!(builder.attribute(QName::local("late"), "1").is_err());
2163 builder.end_element().unwrap();
2164 assert!(builder.end_element().is_err());
2165 let tree = builder.finish(None, None).unwrap();
2166 let element = tree.root().children().next().unwrap();
2167 let attributes: Vec<_> = element
2168 .attributes()
2169 .map(|a| a.string_value().into_owned())
2170 .collect();
2171 assert_eq!(attributes, ["2"]);
2172 let texts: Vec<_> = element
2173 .children()
2174 .map(|t| t.string_value().into_owned())
2175 .collect();
2176 assert_eq!(texts, ["xy"]);
2177 }
2178
2179 #[test]
2180 fn whitespace_text_kept_and_dtd_refused() {
2181 let tree = parse("<r>\n <a/>\n</r>\n");
2182 let top = tree.root().children().next().unwrap();
2183 assert_eq!(top.children().count(), 3);
2184 assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
2185 assert!(Document::parse("<r><a></r>", None).is_err());
2186 }
2187
2188 #[test]
2189 fn adjacent_text_is_one_node() {
2190 let text = "<r>a<![CDATA[<b>]]>c&d<!--x-->e\r\nf<s/></r>";
2191 for tree in [parse(text), Document::parse(text.to_owned(), None).unwrap()] {
2192 let top = tree.root().children().next().unwrap();
2193 let children: Vec<_> = top
2194 .children()
2195 .map(|t| (t.kind(), t.string_value().into_owned()))
2196 .collect();
2197 assert_eq!(
2198 children,
2199 [
2200 (NodeKind::Text, "a<b>c&d".to_owned()),
2201 (NodeKind::Comment, "x".to_owned()),
2202 (NodeKind::Text, "e\nf".to_owned()),
2203 (NodeKind::Element, String::new()),
2204 ]
2205 );
2206 }
2207 let tree = parse("<r><!--a\r\nb\rc--><?p a\r\nb?></r>");
2210 let values: Vec<_> = tree
2211 .root()
2212 .children()
2213 .next()
2214 .unwrap()
2215 .children()
2216 .map(|n| n.string_value().into_owned())
2217 .collect();
2218 assert_eq!(values, ["a\nb\nc", "a\nb"]);
2219 assert_eq!(parse("<r>x\r&y</r>").root().string_value(), "x\n&y");
2221 }
2222
2223 #[test]
2224 fn errors_are_those_of_the_reader() {
2225 let error = Document::parse("<r>\n<a></r>", None).unwrap_err();
2226 assert_eq!(error.message(), "XML: expected 'a' tag, not 'r' at 2:4");
2227 assert_eq!(error.limit(), None);
2228 let error = Document::parse("<!DOCTYPE r><r/>", None).unwrap_err();
2229 assert_eq!(error.message(), "XML: XML with DTD detected");
2230 }
2231
2232 #[test]
2233 fn records_are_compact() {
2234 assert_eq!(std::mem::size_of::<Record>(), 32);
2235 }
2236
2237 fn dump(tree: &Rc<Document>) -> Vec<String> {
2239 (0..tree.node_count())
2240 .map(|i| {
2241 let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
2242 let name = node.name().map(|n| {
2243 format!(
2244 "{}{{{}}}{}",
2245 n,
2246 n.namespace.as_deref().unwrap_or(""),
2247 n.local
2248 )
2249 });
2250 format!(
2251 "{:?} {name:?} {:?} {:?}",
2252 node.kind(),
2253 node.string_value(),
2254 node.parent().map(|p| p.index())
2255 )
2256 })
2257 .collect()
2258 }
2259
2260 #[test]
2265 fn owned_source_is_referred_to() {
2266 let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
2267 <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&y' c='t\tu'>\
2268 verbatim<e p:f='1'>aAb</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
2269 <?pi in?><e/>tail</p:r>";
2270 let borrowed = Document::parse(xml, None).unwrap();
2271 let owned = Document::parse(xml.to_owned(), None).unwrap();
2272 assert_eq!(dump(&borrowed), dump(&owned));
2273 assert_eq!(borrowed.source, "");
2274 assert_eq!(owned.source, xml);
2275 assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
2277 let copied_whole: usize = (0..borrowed.node_count())
2278 .map(|i| {
2279 let i = u32::try_from(i).unwrap();
2280 match borrowed.kind(i) {
2281 NodeKind::Element | NodeKind::Document => 0,
2282 _ => borrowed.own_text(i).len(),
2283 }
2284 })
2285 .sum();
2286 assert_eq!(borrowed.text.len(), copied_whole);
2287 for tree in [&borrowed, &owned] {
2288 assert_eq!(tree.records.capacity(), tree.records.len());
2289 assert_eq!(tree.text.capacity(), tree.text.len());
2290 assert_eq!(tree.names.capacity(), tree.names.len());
2291 }
2292 let r = find(&owned, "r");
2293 let values: Vec<_> = r
2294 .attributes()
2295 .map(|a| a.string_value().into_owned())
2296 .collect();
2297 assert_eq!(values, ["plain", "x&y", "t u"]);
2298 assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
2299 assert_eq!(r.name().unwrap().to_string(), "p:r");
2300 let e = find(&owned, "e");
2301 assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
2302 let f = e.attributes().next().unwrap();
2303 assert_eq!(f.name().unwrap().to_string(), "p:f");
2304 assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
2305 assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
2307 }
2308
2309 #[test]
2310 fn built_trees_merge_text_after_a_parsed_shape() {
2311 let mut builder = TreeBuilder::new();
2314 builder.start_element(QName::local("e")).unwrap();
2315 builder.attribute(QName::local("a"), "v").unwrap();
2316 builder.comment("c").unwrap();
2317 builder.text("x").unwrap();
2318 builder.text("y").unwrap();
2319 builder.processing_instruction("t", "d").unwrap();
2320 builder.text("z").unwrap();
2321 builder.end_element().unwrap();
2322 let tree = builder.finish(None, None).unwrap();
2323 let e = tree.root().children().next().unwrap();
2324 let children: Vec<_> = e
2325 .children()
2326 .map(|c| (c.kind(), c.string_value().into_owned()))
2327 .collect();
2328 assert_eq!(
2329 children,
2330 [
2331 (NodeKind::Comment, "c".to_owned()),
2332 (NodeKind::Text, "xy".to_owned()),
2333 (NodeKind::ProcessingInstruction, "d".to_owned()),
2334 (NodeKind::Text, "z".to_owned()),
2335 ]
2336 );
2337 assert_eq!(tree.text, "vcxydz");
2338 }
2339
2340 #[test]
2341 fn the_document_cache_parses_a_text_once() {
2342 fn shape(doc: &Rc<Document>) -> Vec<String> {
2343 doc.root()
2344 .axis(NodeAxis::Descendant)
2345 .flat_map(|n| std::iter::once(n.clone()).chain(n.attributes()))
2346 .map(|n| format!("{} {}", describe(&n), n.string_value()))
2347 .collect()
2348 }
2349 let cache = DocumentCache::new();
2350 let xml = "<cl id='1'><e v='a'/>text & more<e v='b'/></cl>";
2351 let uri = "file:/codes.xml";
2352 let first = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2353 let between = parse("<x/>");
2354 let second = cache.parse_loaded(xml.to_owned(), uri, 8).unwrap();
2355 assert_eq!(shape(&first), shape(&second));
2357 assert_eq!(second.document_uri(), Some(uri));
2358 assert_eq!(second.base_uri(), Some(uri));
2359 assert_eq!(second.node_count(), first.node_count());
2360 assert_ne!(first.root(), second.root());
2361 assert_eq!(
2362 between.root().cmp_document_order(&second.root()),
2363 Ordering::Less
2364 );
2365 assert_eq!(
2366 first.root().cmp_document_order(&between.root()),
2367 Ordering::Less
2368 );
2369 assert_eq!(cache.entries.lock().unwrap().len(), 1);
2370 let other = cache.parse_loaded("<cl/>".to_owned(), uri, 8).unwrap();
2372 assert_eq!(other.node_count(), 2);
2373 let elsewhere = cache
2374 .parse_loaded(xml.to_owned(), "file:/other.xml", 8)
2375 .unwrap();
2376 assert_eq!(elsewhere.document_uri(), Some("file:/other.xml"));
2377 assert_eq!(shape(&elsewhere), shape(&first));
2378 let deeper = cache.parse_loaded(xml.to_owned(), uri, 1).unwrap_err();
2379 assert!(deeper.limit().is_some());
2380 assert_eq!(cache.entries.lock().unwrap().len(), 3);
2381 assert!(cache.parse_loaded("<cl>".to_owned(), uri, 8).is_err());
2383 assert_eq!(cache.entries.lock().unwrap().len(), 3);
2384 }
2385
2386 #[test]
2387 fn the_element_index_lists_the_elements_of_a_name_in_document_order() {
2388 let mut xml = String::from(r#"<r xmlns:a="urn:x" xmlns:b="urn:x" xmlns="urn:x">"#);
2389 for i in 0..40 {
2390 let prefix = ["a:", "b:", ""][i % 3];
2391 write!(xml, r#"<{prefix}e n="{i}"><f/><e/></{prefix}e><g>t</g>"#).unwrap();
2392 }
2393 xml.push_str("</r>");
2394 let doc = parse(&xml);
2395 let scan = |start: u32, end: u32| -> Vec<u32> {
2396 (start..end)
2397 .filter(|&i| {
2398 doc.kind(i) == NodeKind::Element
2399 && doc.name(i).is_some_and(|n| {
2400 n.local == "e" && n.namespace.as_deref() == Some("urn:x")
2401 })
2402 })
2403 .collect()
2404 };
2405 let (first, end) = doc.descendant_range(0);
2406 assert_eq!(doc.elements_named(Some("urn:x"), "e", first, end), None);
2408 let all = doc.elements_named(Some("urn:x"), "e", first, end).unwrap();
2409 assert_eq!(all, scan(first, end).as_slice());
2410 assert_eq!(all.len(), 80);
2411 let inner = doc.elements_named(Some("urn:x"), "e", 10, 200).unwrap();
2413 assert_eq!(inner, scan(10, 200).as_slice());
2414 assert_eq!(doc.elements_named(None, "e", first, end), Some(&[][..]));
2415 assert_eq!(
2416 doc.elements_named(Some("urn:x"), "zz", first, end),
2417 Some(&[][..])
2418 );
2419 assert_eq!(doc.elements_named(Some("urn:x"), "e", 10, 20), None);
2421 }
2422
2423 #[test]
2424 fn file_uris() {
2425 if cfg!(windows) {
2426 return;
2427 }
2428 assert_eq!(
2429 file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
2430 Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
2431 );
2432 assert_eq!(file_uri(Path::new("rel.xml")), None);
2433 }
2434}