1use std::borrow::Cow;
18use std::cmp::Ordering;
19use std::collections::HashMap;
20use std::fmt::{self, Write as _};
21use std::path::Path;
22use std::rc::Rc;
23use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
24
25use einvoice_xdm::AtomicValue;
26use einvoice_xpath::{QName, XML_NAMESPACE};
27
28const NONE: u32 = u32::MAX;
30
31static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum NodeKind {
37 Document,
39 Element,
41 Attribute,
43 Text,
45 Comment,
47 ProcessingInstruction,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub enum NodeAxis {
55 Child,
57 Attribute,
59 SelfAxis,
61 Descendant,
63 DescendantOrSelf,
65 FollowingSibling,
67 Parent,
69 Ancestor,
71 AncestorOrSelf,
73 PrecedingSibling,
75 Preceding,
77}
78
79impl NodeAxis {
80 #[must_use]
82 pub const fn is_reverse(self) -> bool {
83 matches!(
84 self,
85 Self::Parent
86 | Self::Ancestor
87 | Self::AncestorOrSelf
88 | Self::PrecedingSibling
89 | Self::Preceding
90 )
91 }
92}
93
94#[derive(Debug, Clone, Copy)]
101struct Record {
102 kind: NodeKind,
103 name: u32,
105 parent: u32,
106 prev_sibling: u32,
107 first_child: u32,
110 end: u32,
112 text_start: u32,
116 text_len: u32,
117}
118
119impl Record {
120 const fn new(
122 kind: NodeKind,
123 name: u32,
124 parent: u32,
125 prev_sibling: u32,
126 index: u32,
127 (text_start, text_len): (u32, u32),
128 ) -> Self {
129 Self {
130 kind,
131 name,
132 parent,
133 prev_sibling,
134 first_child: index + 1,
135 end: index + 1,
136 text_start,
137 text_len,
138 }
139 }
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct DocumentError {
145 message: String,
146}
147
148impl DocumentError {
149 fn new(message: impl Into<String>) -> Self {
150 Self {
151 message: message.into(),
152 }
153 }
154
155 #[must_use]
157 pub fn message(&self) -> &str {
158 &self.message
159 }
160}
161
162impl fmt::Display for DocumentError {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.write_str(&self.message)
165 }
166}
167
168impl std::error::Error for DocumentError {}
169
170pub struct Document {
177 serial: u64,
178 uri: Option<String>,
179 base_uri: Option<String>,
180 has_xml_base: bool,
181 records: Vec<Record>,
182 names: Vec<QName>,
183 source: String,
185 text: String,
187}
188
189impl fmt::Debug for Document {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.debug_struct("Document")
192 .field("serial", &self.serial)
193 .field("uri", &self.uri)
194 .field("nodes", &self.records.len())
195 .finish_non_exhaustive()
196 }
197}
198
199impl Document {
200 pub fn parse<'t>(
221 text: impl Into<Cow<'t, str>>,
222 base_uri: Option<&str>,
223 ) -> Result<Rc<Self>, DocumentError> {
224 Self::parse_with_uris(text.into(), None, base_uri)
225 }
226
227 pub fn parse_loaded<'t>(
235 text: impl Into<Cow<'t, str>>,
236 uri: &str,
237 ) -> Result<Rc<Self>, DocumentError> {
238 Self::parse_with_uris(text.into(), Some(uri), Some(uri))
239 }
240
241 fn parse_with_uris(
242 text: Cow<'_, str>,
243 document_uri: Option<&str>,
244 base_uri: Option<&str>,
245 ) -> Result<Rc<Self>, DocumentError> {
246 let keep_source = matches!(text, Cow::Owned(_));
247 let builder = build_parsed(&text, keep_source)?;
248 let source = match text {
249 Cow::Owned(source) => source,
250 Cow::Borrowed(_) => String::new(),
251 };
252 builder.finish_with_source(
253 source,
254 document_uri.map(str::to_owned),
255 base_uri.map(str::to_owned),
256 )
257 }
258
259 #[must_use]
261 pub fn root(self: &Rc<Self>) -> Node {
262 Node {
263 doc: Rc::clone(self),
264 index: 0,
265 }
266 }
267
268 #[must_use]
271 pub fn document_uri(&self) -> Option<&str> {
272 self.uri.as_deref()
273 }
274
275 #[must_use]
277 pub fn base_uri(&self) -> Option<&str> {
278 self.base_uri.as_deref()
279 }
280
281 #[must_use]
284 pub const fn has_xml_base(&self) -> bool {
285 self.has_xml_base
286 }
287
288 #[must_use]
290 pub fn node_count(&self) -> usize {
291 self.records.len()
292 }
293
294 fn record(&self, index: u32) -> &Record {
295 &self.records[index as usize]
297 }
298
299 pub(crate) fn kind(&self, index: u32) -> NodeKind {
300 self.record(index).kind
301 }
302
303 pub(crate) fn name(&self, index: u32) -> Option<&QName> {
304 let name = self.record(index).name;
305 (name != NONE).then(|| &self.names[name as usize])
306 }
307
308 pub(crate) fn parent_index(&self, index: u32) -> Option<u32> {
309 let parent = self.record(index).parent;
310 (parent != NONE).then_some(parent)
311 }
312
313 fn own_text(&self, index: u32) -> &str {
316 let r = self.record(index);
317 let start = r.text_start as usize;
318 let end = start + r.text_len as usize;
319 match start.checked_sub(self.source.len()) {
320 None => &self.source[start..end],
321 Some(start) => &self.text[start..end - self.source.len()],
322 }
323 }
324
325 pub(crate) fn string_value(&self, index: u32) -> Cow<'_, str> {
326 match self.kind(index) {
327 NodeKind::Text
328 | NodeKind::Comment
329 | NodeKind::ProcessingInstruction
330 | NodeKind::Attribute => Cow::Borrowed(self.own_text(index)),
331 NodeKind::Element | NodeKind::Document => {
332 let mut texts = self
333 .cursor(index, NodeAxis::Descendant)
334 .walk(self)
335 .filter(|&i| self.kind(i) == NodeKind::Text);
336 let Some(first) = texts.next() else {
337 return Cow::Borrowed("");
338 };
339 let Some(second) = texts.next() else {
340 return Cow::Borrowed(self.own_text(first));
341 };
342 let mut value = String::from(self.own_text(first));
343 value.push_str(self.own_text(second));
344 for i in texts {
345 value.push_str(self.own_text(i));
346 }
347 Cow::Owned(value)
348 }
349 }
350 }
351
352 pub(crate) fn cursor(&self, index: u32, axis: NodeAxis) -> Cursor {
354 let r = self.record(index);
355 let kind = r.kind;
356 let is_attribute = kind == NodeKind::Attribute;
357 match axis {
358 NodeAxis::SelfAxis => Cursor::One(index),
359 NodeAxis::Parent => match r.parent {
360 NONE => Cursor::Done,
361 parent => Cursor::One(parent),
362 },
363 NodeAxis::Child => Cursor::Siblings {
364 next: r.first_child,
365 end: r.end,
366 },
367 NodeAxis::Attribute => {
368 if kind == NodeKind::Element {
369 Cursor::Range {
370 next: index + 1,
371 end: r.first_child,
372 }
373 } else {
374 Cursor::Done
375 }
376 }
377 NodeAxis::Descendant => Cursor::Descendants {
378 next: r.first_child,
379 end: r.end,
380 },
381 NodeAxis::DescendantOrSelf => Cursor::Descendants {
382 next: index,
383 end: r.end,
384 },
385 NodeAxis::FollowingSibling => match r.parent {
386 NONE => Cursor::Done,
387 _ if is_attribute => Cursor::Done,
388 parent => Cursor::Siblings {
389 next: r.end,
390 end: self.record(parent).end,
391 },
392 },
393 NodeAxis::Ancestor => Cursor::Ancestors { next: r.parent },
394 NodeAxis::AncestorOrSelf => Cursor::Ancestors { next: index },
395 NodeAxis::PrecedingSibling => {
396 if is_attribute {
397 Cursor::Done
398 } else {
399 Cursor::PrecedingSiblings {
400 next: r.prev_sibling,
401 }
402 }
403 }
404 NodeAxis::Preceding => Cursor::Preceding {
405 next: index,
406 ancestor: r.parent,
407 },
408 }
409 }
410}
411
412#[derive(Debug, Clone, Copy)]
414pub(crate) enum Cursor {
415 Done,
416 One(u32),
417 Range {
419 next: u32,
420 end: u32,
421 },
422 Siblings {
424 next: u32,
425 end: u32,
426 },
427 Descendants {
429 next: u32,
430 end: u32,
431 },
432 Ancestors {
433 next: u32,
434 },
435 PrecedingSiblings {
436 next: u32,
437 },
438 Preceding {
441 next: u32,
442 ancestor: u32,
443 },
444}
445
446impl Cursor {
447 pub(crate) fn next(&mut self, doc: &Document) -> Option<u32> {
448 match self {
449 Self::Done => None,
450 Self::One(index) => {
451 let index = *index;
452 *self = Self::Done;
453 Some(index)
454 }
455 Self::Range { next, end } => {
456 if *next >= *end {
457 return None;
458 }
459 let index = *next;
460 *next += 1;
461 Some(index)
462 }
463 Self::Siblings { next, end } => {
464 if *next >= *end {
465 return None;
466 }
467 let index = *next;
468 *next = doc.record(index).end;
469 Some(index)
470 }
471 Self::Descendants { next, end } => {
472 if *next >= *end {
473 return None;
474 }
475 let index = *next;
476 *next = doc.record(index).first_child;
478 Some(index)
479 }
480 Self::Ancestors { next } => {
481 if *next == NONE {
482 return None;
483 }
484 let index = *next;
485 *next = doc.record(index).parent;
486 Some(index)
487 }
488 Self::PrecedingSiblings { next } => {
489 if *next == NONE {
490 return None;
491 }
492 let index = *next;
493 *next = doc.record(index).prev_sibling;
494 Some(index)
495 }
496 Self::Preceding { next, ancestor } => loop {
497 if *next == 0 {
498 return None;
499 }
500 *next -= 1;
501 let index = *next;
502 if index == *ancestor {
503 *ancestor = doc.record(index).parent;
504 continue;
505 }
506 if doc.record(index).kind != NodeKind::Attribute {
507 return Some(index);
508 }
509 },
510 }
511 }
512
513 pub(crate) fn walk(self, doc: &Document) -> impl Iterator<Item = u32> + '_ {
515 let mut cursor = self;
516 std::iter::from_fn(move || cursor.next(doc))
517 }
518}
519
520#[derive(Clone)]
524pub struct Node {
525 doc: Rc<Document>,
526 index: u32,
527}
528
529impl PartialEq for Node {
530 fn eq(&self, other: &Self) -> bool {
531 self.index == other.index && Rc::ptr_eq(&self.doc, &other.doc)
532 }
533}
534
535impl Eq for Node {}
536
537impl fmt::Debug for Node {
538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 write!(f, "Node({:?}", self.kind())?;
540 if let Some(name) = self.name() {
541 write!(f, " {name}")?;
542 }
543 write!(f, " #{} of document {})", self.index, self.doc.serial)
544 }
545}
546
547impl Node {
548 pub(crate) fn new(doc: Rc<Document>, index: u32) -> Self {
549 Self { doc, index }
550 }
551
552 pub(crate) const fn index(&self) -> u32 {
553 self.index
554 }
555
556 #[must_use]
558 pub fn document(&self) -> &Rc<Document> {
559 &self.doc
560 }
561
562 #[must_use]
564 pub fn kind(&self) -> NodeKind {
565 self.doc.kind(self.index)
566 }
567
568 #[must_use]
571 pub fn name(&self) -> Option<&QName> {
572 self.doc.name(self.index)
573 }
574
575 #[must_use]
577 pub fn parent(&self) -> Option<Self> {
578 self.doc
579 .parent_index(self.index)
580 .map(|p| Self::new(Rc::clone(&self.doc), p))
581 }
582
583 #[must_use]
585 pub fn root(&self) -> Self {
586 Self::new(Rc::clone(&self.doc), 0)
587 }
588
589 #[must_use]
591 pub fn string_value(&self) -> Cow<'_, str> {
592 self.doc.string_value(self.index)
593 }
594
595 #[must_use]
598 pub fn typed_value(&self) -> AtomicValue {
599 let value = self.string_value().into_owned();
600 match self.kind() {
601 NodeKind::Comment | NodeKind::ProcessingInstruction => AtomicValue::String(value),
602 _ => AtomicValue::UntypedAtomic(value),
603 }
604 }
605
606 #[must_use]
609 pub fn axis(&self, axis: NodeAxis) -> Axis {
610 Axis {
611 cursor: self.doc.cursor(self.index, axis),
612 doc: Rc::clone(&self.doc),
613 }
614 }
615
616 #[must_use]
618 pub fn children(&self) -> Axis {
619 self.axis(NodeAxis::Child)
620 }
621
622 #[must_use]
624 pub fn attributes(&self) -> Axis {
625 self.axis(NodeAxis::Attribute)
626 }
627
628 #[must_use]
631 pub fn cmp_document_order(&self, other: &Self) -> Ordering {
632 self.doc
633 .serial
634 .cmp(&other.doc.serial)
635 .then(self.index.cmp(&other.index))
636 }
637}
638
639#[derive(Debug, Clone)]
641pub struct Axis {
642 cursor: Cursor,
643 doc: Rc<Document>,
644}
645
646impl Iterator for Axis {
647 type Item = Node;
648
649 fn next(&mut self) -> Option<Node> {
650 let index = self.cursor.next(&self.doc)?;
651 Some(Node::new(Rc::clone(&self.doc), index))
652 }
653}
654
655#[derive(Debug)]
661pub struct TreeBuilder {
662 records: Vec<Record>,
663 names: Vec<QName>,
664 name_ids: HashMap<QName, u32>,
665 source_len: usize,
668 text: String,
669 open: Vec<u32>,
671 last_child: Vec<u32>,
673 has_xml_base: bool,
674}
675
676impl Default for TreeBuilder {
677 fn default() -> Self {
678 Self::new()
679 }
680}
681
682fn to_u32(value: usize) -> Result<u32, DocumentError> {
683 u32::try_from(value)
684 .ok()
685 .filter(|&v| v != NONE)
686 .ok_or_else(|| DocumentError::new("document too large"))
687}
688
689#[derive(Debug, Clone, Copy)]
691enum NodeText<'s> {
692 Source(u32, u32),
694 Copy(&'s str),
696}
697
698impl TreeBuilder {
699 #[must_use]
701 pub fn new() -> Self {
702 Self {
703 records: vec![Record::new(NodeKind::Document, NONE, NONE, NONE, 0, (0, 0))],
704 names: Vec::new(),
705 name_ids: HashMap::new(),
706 source_len: 0,
707 text: String::new(),
708 open: vec![0],
709 last_child: vec![NONE],
710 has_xml_base: false,
711 }
712 }
713
714 fn with_capacity(nodes: usize, text: usize, source_len: usize) -> Self {
718 let mut builder = Self::new();
719 builder.records.reserve_exact(nodes.saturating_sub(1));
720 builder.text.reserve_exact(text);
721 builder.source_len = source_len;
722 builder
723 }
724
725 fn intern(&mut self, name: QName) -> Result<u32, DocumentError> {
726 if let Some(&id) = self.name_ids.get(&name) {
727 return Ok(id);
728 }
729 let id = self.push_name(name.clone())?;
730 self.name_ids.insert(name, id);
731 Ok(id)
732 }
733
734 fn push_name(&mut self, name: QName) -> Result<u32, DocumentError> {
736 let id = to_u32(self.names.len())?;
737 self.names.push(name);
738 Ok(id)
739 }
740
741 fn store_text(&mut self, value: NodeText<'_>) -> Result<(u32, u32), DocumentError> {
743 match value {
744 NodeText::Source(start, len) => Ok((start, len)),
745 NodeText::Copy(value) => {
746 let start = to_u32(self.source_len + self.text.len())?;
747 let len = to_u32(value.len())?;
748 to_u32(self.source_len + self.text.len() + value.len())?;
749 self.text.push_str(value);
750 Ok((start, len))
751 }
752 }
753 }
754
755 fn top(&self) -> u32 {
756 self.open.last().copied().unwrap_or(0)
757 }
758
759 fn append(
762 &mut self,
763 kind: NodeKind,
764 name: u32,
765 text: NodeText<'_>,
766 ) -> Result<u32, DocumentError> {
767 let index = to_u32(self.records.len())?;
768 to_u32(self.records.len() + 1)?;
769 let text = if kind == NodeKind::Element {
770 (0, 0)
771 } else {
772 self.store_text(text)?
773 };
774 let parent = self.top();
775 let last = self.last_child.last_mut().map_or(NONE, |l| {
776 let previous = *l;
777 *l = index;
778 previous
779 });
780 self.records
781 .push(Record::new(kind, name, parent, last, index, text));
782 Ok(index)
783 }
784
785 pub fn start_element(&mut self, name: QName) -> Result<(), DocumentError> {
791 let name = self.intern(name)?;
792 self.open_element(name)
793 }
794
795 fn open_element(&mut self, name: u32) -> Result<(), DocumentError> {
796 let index = self.append(NodeKind::Element, name, NodeText::Copy(""))?;
797 self.open.push(index);
798 self.last_child.push(NONE);
799 Ok(())
800 }
801
802 pub fn attribute(&mut self, name: QName, value: &str) -> Result<(), DocumentError> {
808 let element = self.top();
809 let has_content = self.last_child.last().is_some_and(|&l| l != NONE);
810 if element == 0 || has_content {
811 return Err(DocumentError::new(format!(
812 "attribute {name} outside an element start"
813 )));
814 }
815 let first = element as usize + 1;
816 let existing = (first..self.records.len()).find(|&i| {
817 let id = self.records[i].name;
818 self.names[id as usize].same_expanded_name(&name)
819 });
820 let xml_base = is_xml_base(name.namespace.as_deref(), &name.local);
821 let id = self.intern(name)?;
822 if let Some(i) = existing {
823 let (text_start, text_len) = self.store_text(NodeText::Copy(value))?;
824 let record = &mut self.records[i];
825 record.name = id;
826 record.text_start = text_start;
827 record.text_len = text_len;
828 self.has_xml_base |= xml_base;
829 return Ok(());
830 }
831 self.push_attribute(id, xml_base, NodeText::Copy(value))
832 }
833
834 fn push_attribute(
836 &mut self,
837 name: u32,
838 xml_base: bool,
839 value: NodeText<'_>,
840 ) -> Result<(), DocumentError> {
841 let element = self.top();
842 let index = to_u32(self.records.len())?;
843 to_u32(self.records.len() + 1)?;
844 let previous = if index == element + 1 {
845 NONE
846 } else {
847 index - 1
848 };
849 let text = self.store_text(value)?;
850 self.records.push(Record::new(
851 NodeKind::Attribute,
852 name,
853 element,
854 previous,
855 index,
856 text,
857 ));
858 self.records[element as usize].first_child = index + 1;
859 self.has_xml_base |= xml_base;
860 Ok(())
861 }
862
863 pub fn text(&mut self, value: &str) -> Result<(), DocumentError> {
869 if value.is_empty() {
870 return Ok(());
871 }
872 let last = self.last_child.last().copied().unwrap_or(NONE);
873 let mergeable = last != NONE
876 && last as usize + 1 == self.records.len()
877 && self.records[last as usize].kind == NodeKind::Text
878 && {
879 let r = &self.records[last as usize];
880 r.text_start as usize + r.text_len as usize == self.source_len + self.text.len()
881 && r.text_start as usize >= self.source_len
882 };
883 if mergeable {
884 self.store_text(NodeText::Copy(value))?;
885 let record = &mut self.records[last as usize];
886 record.text_len = to_u32(record.text_len as usize + value.len())?;
887 return Ok(());
888 }
889 self.append(NodeKind::Text, NONE, NodeText::Copy(value))
890 .map(drop)
891 }
892
893 pub fn comment(&mut self, value: &str) -> Result<(), DocumentError> {
899 self.append(NodeKind::Comment, NONE, NodeText::Copy(value))
900 .map(drop)
901 }
902
903 pub fn processing_instruction(
909 &mut self,
910 target: &str,
911 value: &str,
912 ) -> Result<(), DocumentError> {
913 let name = self.intern(QName::local(target))?;
914 self.append(NodeKind::ProcessingInstruction, name, NodeText::Copy(value))
915 .map(drop)
916 }
917
918 pub fn end_element(&mut self) -> Result<(), DocumentError> {
924 if self.open.len() < 2 {
925 return Err(DocumentError::new("end of element without a start"));
926 }
927 let element = self.top();
928 self.open.pop();
929 self.last_child.pop();
930 let end = to_u32(self.records.len())?;
931 self.records[element as usize].end = end;
932 Ok(())
933 }
934
935 pub fn finish(
941 self,
942 document_uri: Option<String>,
943 base_uri: Option<String>,
944 ) -> Result<Rc<Document>, DocumentError> {
945 self.finish_with_source(String::new(), document_uri, base_uri)
946 }
947
948 fn finish_with_source(
951 mut self,
952 source: String,
953 document_uri: Option<String>,
954 base_uri: Option<String>,
955 ) -> Result<Rc<Document>, DocumentError> {
956 if self.open.len() != 1 {
957 return Err(DocumentError::new("unclosed element"));
958 }
959 if source.len() != self.source_len {
960 return Err(DocumentError::new("source text of another length"));
961 }
962 self.records[0].end = to_u32(self.records.len())?;
963 self.records.shrink_to_fit();
966 self.names.shrink_to_fit();
967 self.text.shrink_to_fit();
968 Ok(Rc::new(Document {
969 serial: NEXT_SERIAL.fetch_add(1, AtomicOrdering::Relaxed),
970 uri: document_uri,
971 base_uri,
972 has_xml_base: self.has_xml_base,
973 records: self.records,
974 names: self.names,
975 source,
976 text: self.text,
977 }))
978 }
979}
980
981fn is_xml_base(namespace: Option<&str>, local: &str) -> bool {
982 local == "base" && namespace == Some(XML_NAMESPACE)
983}
984
985fn offset_in(input: &str, part: &str) -> Option<usize> {
987 let start = part.as_ptr().addr().checked_sub(input.as_ptr().addr())?;
988 (start.checked_add(part.len())? <= input.len()).then_some(start)
989}
990
991type NameKey<'a> = (&'a str, Option<&'a str>, &'a str);
994
995fn build_parsed(input: &str, keep_source: bool) -> Result<TreeBuilder, DocumentError> {
1001 let options = roxmltree::ParsingOptions {
1002 allow_dtd: false,
1003 nodes_limit: u32::MAX,
1004 ..roxmltree::ParsingOptions::default()
1005 };
1006 let parsed = roxmltree::Document::parse_with_options(input, options)
1007 .map_err(|e| DocumentError::new(format!("XML: {e}")))?;
1008 let (nodes, text_bytes) = sizes(&parsed, input, keep_source);
1009 let mut builder =
1010 TreeBuilder::with_capacity(nodes, text_bytes, if keep_source { input.len() } else { 0 });
1011 let mut names: HashMap<NameKey<'_>, u32> = HashMap::new();
1012 let node_text = |text| node_text(input, keep_source, text);
1013 let mut open: Vec<roxmltree::NodeId> = Vec::new();
1016 for node in parsed.root().descendants().skip(1) {
1017 let parent = node.parent().map(|p| p.id());
1018 while open.last().is_some_and(|&id| Some(id) != parent) {
1019 open.pop();
1020 builder.end_element()?;
1021 }
1022 match node.node_type() {
1023 roxmltree::NodeType::Root => {}
1024 roxmltree::NodeType::Element => {
1025 let tag = node.tag_name();
1026 let key = (
1027 element_prefix(input, node),
1028 tag.namespace().filter(|ns| !ns.is_empty()),
1029 tag.name(),
1030 );
1031 let id = name_id(&mut builder, &mut names, key)?;
1032 builder.open_element(id)?;
1033 for attribute in node.attributes() {
1035 let namespace = attribute.namespace().filter(|ns| !ns.is_empty());
1036 let local = attribute.name();
1037 let prefix = input
1038 .get(attribute.range_qname())
1039 .and_then(|q| q.split_once(':'))
1040 .map_or("", |(prefix, _)| prefix);
1041 let id = name_id(&mut builder, &mut names, (prefix, namespace, local))?;
1042 builder.push_attribute(
1043 id,
1044 is_xml_base(namespace, local),
1045 node_text(attribute.value())?,
1046 )?;
1047 }
1048 open.push(node.id());
1049 }
1050 roxmltree::NodeType::Text => {
1051 if is_in_element(node) {
1054 let text = node.text().unwrap_or_default();
1055 if !text.is_empty() {
1056 builder.append(NodeKind::Text, NONE, node_text(text)?)?;
1057 }
1058 }
1059 }
1060 roxmltree::NodeType::Comment => {
1061 let text = node_text(node.text().unwrap_or_default())?;
1062 builder.append(NodeKind::Comment, NONE, text)?;
1063 }
1064 roxmltree::NodeType::PI => {
1065 if let Some(pi) = node.pi() {
1066 let id = name_id(&mut builder, &mut names, ("", None, pi.target))?;
1067 let text = node_text(pi.value.unwrap_or(""))?;
1068 builder.append(NodeKind::ProcessingInstruction, id, text)?;
1069 }
1070 }
1071 }
1072 }
1073 for _ in open {
1074 builder.end_element()?;
1075 }
1076 Ok(builder)
1077}
1078
1079fn sizes(parsed: &roxmltree::Document<'_>, input: &str, keep_source: bool) -> (usize, usize) {
1083 let copied = |text: &str| {
1084 if keep_source && offset_in(input, text).is_some() {
1085 0
1086 } else {
1087 text.len()
1088 }
1089 };
1090 let (mut nodes, mut text_bytes) = (1usize, 0usize);
1091 for node in parsed.root().descendants().skip(1) {
1092 match node.node_type() {
1093 roxmltree::NodeType::Root => {}
1094 roxmltree::NodeType::Element => {
1095 nodes += 1;
1096 for attribute in node.attributes() {
1097 nodes += 1;
1098 text_bytes += copied(attribute.value());
1099 }
1100 }
1101 roxmltree::NodeType::Text => {
1102 if is_in_element(node) {
1103 nodes += 1;
1104 text_bytes += copied(node.text().unwrap_or_default());
1105 }
1106 }
1107 roxmltree::NodeType::Comment => {
1108 nodes += 1;
1109 text_bytes += copied(node.text().unwrap_or_default());
1110 }
1111 roxmltree::NodeType::PI => {
1112 nodes += 1;
1113 text_bytes += node.pi().map_or(0, |pi| copied(pi.value.unwrap_or("")));
1114 }
1115 }
1116 }
1117 (nodes, text_bytes)
1118}
1119
1120fn name_id<'a>(
1122 builder: &mut TreeBuilder,
1123 names: &mut HashMap<NameKey<'a>, u32>,
1124 key: NameKey<'a>,
1125) -> Result<u32, DocumentError> {
1126 if let Some(&id) = names.get(&key) {
1127 return Ok(id);
1128 }
1129 let (prefix, namespace, local) = key;
1130 let id = builder.push_name(QName {
1131 prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
1132 namespace: namespace.map(str::to_owned),
1133 local: local.to_owned(),
1134 })?;
1135 names.insert(key, id);
1136 Ok(id)
1137}
1138
1139fn node_text<'s>(
1142 input: &str,
1143 keep_source: bool,
1144 text: &'s str,
1145) -> Result<NodeText<'s>, DocumentError> {
1146 Ok(
1147 match keep_source.then(|| offset_in(input, text)).flatten() {
1148 Some(start) => NodeText::Source(to_u32(start)?, to_u32(text.len())?),
1149 None => NodeText::Copy(text),
1150 },
1151 )
1152}
1153
1154fn is_in_element(node: roxmltree::Node<'_, '_>) -> bool {
1157 node.parent().is_some_and(|p| !p.is_root())
1158}
1159
1160fn element_prefix<'a>(input: &'a str, node: roxmltree::Node<'_, '_>) -> &'a str {
1162 let start = node.range().start + 1;
1163 let written = input
1164 .get(start..)
1165 .map(|rest| {
1166 let end = rest
1167 .find(|c: char| c.is_ascii_whitespace() || c == '/' || c == '>')
1168 .unwrap_or(rest.len());
1169 &rest[..end]
1170 })
1171 .unwrap_or_default();
1172 written.split_once(':').map_or("", |(prefix, _)| prefix)
1173}
1174
1175#[must_use]
1183pub fn file_uri(path: &Path) -> Option<String> {
1184 if !path.is_absolute() {
1185 return None;
1186 }
1187 let text = path.to_str()?.replace('\\', "/");
1188 let mut uri = String::from("file:");
1189 if !text.starts_with('/') {
1190 uri.push('/');
1191 }
1192 for c in text.chars() {
1193 let keep = if c.is_ascii() {
1194 c.is_ascii_alphanumeric() || "-_.!~*'():@&=+$,;/".contains(c)
1195 } else {
1196 !(matches!(
1198 c,
1199 '\u{A0}' | '\u{1680}' | '\u{2000}'
1200 ..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
1201 ) || c.is_control())
1202 };
1203 if keep {
1204 uri.push(c);
1205 } else {
1206 let mut buffer = [0; 4];
1207 for byte in c.encode_utf8(&mut buffer).bytes() {
1208 let _ = write!(uri, "%{byte:02X}");
1209 }
1210 }
1211 }
1212 Some(uri)
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217 use super::*;
1218
1219 fn parse(xml: &str) -> Rc<Document> {
1220 Document::parse(xml, Some("file:/t.xml")).unwrap()
1221 }
1222
1223 fn describe(node: &Node) -> String {
1224 match node.kind() {
1225 NodeKind::Document => "/".to_owned(),
1226 NodeKind::Element => node.name().unwrap().to_string(),
1227 NodeKind::Attribute => format!("@{}", node.name().unwrap()),
1228 NodeKind::Text => format!("{:?}", node.string_value()),
1229 NodeKind::Comment => format!("<!--{}-->", node.string_value()),
1230 NodeKind::ProcessingInstruction => format!("<?{}?>", node.name().unwrap()),
1231 }
1232 }
1233
1234 fn walk(node: &Node, axis: NodeAxis) -> Vec<String> {
1235 node.axis(axis).map(|n| describe(&n)).collect()
1236 }
1237
1238 fn find(tree: &Rc<Document>, local: &str) -> Node {
1239 tree.root()
1240 .axis(NodeAxis::Descendant)
1241 .find(|n| n.name().is_some_and(|name| name.local == local))
1242 .unwrap()
1243 }
1244
1245 const XML: &str = "<?xml version='1.0'?><!--c0--><r xmlns:p='urn:p' a='1' p:b='2'> \
1246 <x>1<y q='3'>2</y>3</x><p:z/><!--c1--><?pi data?><w><v/></w></r>";
1247
1248 const NONE: [&str; 0] = [];
1249
1250 #[test]
1251 fn document_order_and_axes() {
1252 let tree = parse(XML);
1253 let root = tree.root();
1254 assert_eq!(walk(&root, NodeAxis::Child), ["<!--c0-->", "r"]);
1255 let top = find(&tree, "r");
1256 assert_eq!(walk(&top, NodeAxis::Attribute), ["@a", "@p:b"]);
1257 assert_eq!(
1258 walk(&top, NodeAxis::Child),
1259 ["\" \"", "x", "p:z", "<!--c1-->", "<?pi?>", "w"]
1260 );
1261 assert_eq!(
1262 walk(&top, NodeAxis::Descendant),
1263 [
1264 "\" \"",
1265 "x",
1266 "\"1\"",
1267 "y",
1268 "\"2\"",
1269 "\"3\"",
1270 "p:z",
1271 "<!--c1-->",
1272 "<?pi?>",
1273 "w",
1274 "v"
1275 ]
1276 );
1277 let y = find(&tree, "y");
1278 assert_eq!(walk(&y, NodeAxis::Ancestor), ["x", "r", "/"]);
1279 assert_eq!(walk(&y, NodeAxis::AncestorOrSelf), ["y", "x", "r", "/"]);
1280 assert_eq!(walk(&y, NodeAxis::PrecedingSibling), ["\"1\""]);
1281 assert_eq!(walk(&y, NodeAxis::FollowingSibling), ["\"3\""]);
1282 assert_eq!(
1283 walk(&y, NodeAxis::Preceding),
1284 ["\"1\"", "\" \"", "<!--c0-->"]
1285 );
1286 let v = find(&tree, "v");
1287 assert_eq!(
1288 walk(&v, NodeAxis::Preceding),
1289 [
1290 "<?pi?>",
1291 "<!--c1-->",
1292 "p:z",
1293 "\"3\"",
1294 "\"2\"",
1295 "y",
1296 "\"1\"",
1297 "x",
1298 "\" \"",
1299 "<!--c0-->"
1300 ]
1301 );
1302 let q = y.attributes().next().unwrap();
1303 assert_eq!(walk(&q, NodeAxis::Parent), ["y"]);
1304 assert_eq!(
1305 walk(&q, NodeAxis::Preceding),
1306 ["\"1\"", "\" \"", "<!--c0-->"]
1307 );
1308 assert_eq!(walk(&q, NodeAxis::FollowingSibling), NONE);
1309 assert_eq!(walk(&q, NodeAxis::PrecedingSibling), NONE);
1310 assert_eq!(walk(&q, NodeAxis::DescendantOrSelf), ["@q"]);
1311 assert_eq!(walk(&q, NodeAxis::Child), NONE);
1312 let all: Vec<Node> = root.axis(NodeAxis::DescendantOrSelf).collect();
1313 assert!(
1314 all.windows(2)
1315 .all(|w| w[0].cmp_document_order(&w[1]) == Ordering::Less)
1316 );
1317 }
1318
1319 #[test]
1320 fn values_names_and_prefixes() {
1321 let tree = parse(XML);
1322 let top = find(&tree, "r");
1323 assert_eq!(top.string_value(), " 123");
1324 assert_eq!(find(&tree, "x").string_value(), "123");
1325 assert_eq!(find(&tree, "y").string_value(), "2");
1326 assert_eq!(find(&tree, "w").string_value(), "");
1327 let z = find(&tree, "z");
1328 assert_eq!(z.name().unwrap().to_string(), "p:z");
1329 assert_eq!(z.name().unwrap().namespace.as_deref(), Some("urn:p"));
1330 let prefixed = top.attributes().nth(1).unwrap();
1331 assert_eq!(prefixed.name().unwrap().prefix.as_deref(), Some("p"));
1332 assert!(matches!(prefixed.typed_value(), AtomicValue::UntypedAtomic(s) if s == "2"));
1333 let comment = tree.root().children().next().unwrap();
1334 assert!(matches!(comment.typed_value(), AtomicValue::String(s) if s == "c0"));
1335 assert_eq!(tree.document_uri(), None);
1336 assert_eq!(tree.base_uri(), Some("file:/t.xml"));
1337 let loaded = Document::parse_loaded("<a/>", "file:/t.xml").unwrap();
1338 assert_eq!(loaded.document_uri(), Some("file:/t.xml"));
1339 assert_eq!(loaded.base_uri(), Some("file:/t.xml"));
1340 assert_eq!(z.root(), tree.root());
1341 assert_ne!(z, top);
1342 }
1343
1344 #[test]
1345 fn undeclared_default_namespace_is_no_namespace() {
1346 let tree = parse("<r xmlns='urn:d'><n xmlns=''><m/></n></r>");
1347 assert_eq!(
1348 find(&tree, "r").name().unwrap().namespace.as_deref(),
1349 Some("urn:d")
1350 );
1351 assert_eq!(find(&tree, "n").name().unwrap().namespace, None);
1352 assert_eq!(find(&tree, "m").name().unwrap().namespace, None);
1353 }
1354
1355 #[test]
1356 fn same_namespace_two_prefixes() {
1357 let tree = parse("<a:r xmlns:a='urn:x' xmlns:b='urn:x'><b:c a:d='1'/></a:r>");
1358 let inner = find(&tree, "c");
1359 assert_eq!(inner.name().unwrap().to_string(), "b:c");
1360 assert_eq!(find(&tree, "r").name().unwrap().to_string(), "a:r");
1361 let attribute = inner.attributes().next().unwrap();
1362 assert_eq!(attribute.name().unwrap().to_string(), "a:d");
1363 }
1364
1365 #[test]
1366 fn builder_merges_text_and_replaces_attributes() {
1367 let mut builder = TreeBuilder::new();
1368 builder.start_element(QName::local("e")).unwrap();
1369 builder.attribute(QName::local("a"), "1").unwrap();
1370 builder.attribute(QName::local("a"), "2").unwrap();
1371 builder.text("x").unwrap();
1372 builder.text("").unwrap();
1373 builder.text("y").unwrap();
1374 assert!(builder.attribute(QName::local("late"), "1").is_err());
1375 builder.end_element().unwrap();
1376 assert!(builder.end_element().is_err());
1377 let tree = builder.finish(None, None).unwrap();
1378 let element = tree.root().children().next().unwrap();
1379 let attributes: Vec<_> = element
1380 .attributes()
1381 .map(|a| a.string_value().into_owned())
1382 .collect();
1383 assert_eq!(attributes, ["2"]);
1384 let texts: Vec<_> = element
1385 .children()
1386 .map(|t| t.string_value().into_owned())
1387 .collect();
1388 assert_eq!(texts, ["xy"]);
1389 }
1390
1391 #[test]
1392 fn whitespace_text_kept_and_dtd_refused() {
1393 let tree = parse("<r>\n <a/>\n</r>\n");
1394 let top = tree.root().children().next().unwrap();
1395 assert_eq!(top.children().count(), 3);
1396 assert!(Document::parse("<!DOCTYPE r [<!ENTITY e 'x'>]><r>&e;</r>", None).is_err());
1397 assert!(Document::parse("<r><a></r>", None).is_err());
1398 }
1399
1400 #[test]
1401 fn records_are_compact() {
1402 assert_eq!(std::mem::size_of::<Record>(), 32);
1403 }
1404
1405 fn dump(tree: &Rc<Document>) -> Vec<String> {
1407 (0..tree.node_count())
1408 .map(|i| {
1409 let node = Node::new(Rc::clone(tree), u32::try_from(i).unwrap());
1410 let name = node.name().map(|n| {
1411 format!(
1412 "{}{{{}}}{}",
1413 n,
1414 n.namespace.as_deref().unwrap_or(""),
1415 n.local
1416 )
1417 });
1418 format!(
1419 "{:?} {name:?} {:?} {:?}",
1420 node.kind(),
1421 node.string_value(),
1422 node.parent().map(|p| p.index())
1423 )
1424 })
1425 .collect()
1426 }
1427
1428 #[test]
1433 fn owned_source_is_referred_to() {
1434 let xml = "<?xml version='1.0'?><!--top--><?pi top data?>\
1435 <p:r xmlns:p='urn:p' xmlns='urn:d' a='plain' b='x&y' c='t\tu'>\
1436 verbatim<e p:f='1'>aAb</e>line\r\nend<![CDATA[<&>]]>more<!--c-->\
1437 <?pi in?><e/>tail</p:r>";
1438 let borrowed = Document::parse(xml, None).unwrap();
1439 let owned = Document::parse(xml.to_owned(), None).unwrap();
1440 assert_eq!(dump(&borrowed), dump(&owned));
1441 assert_eq!(borrowed.source, "");
1442 assert_eq!(owned.source, xml);
1443 assert_eq!(owned.text, "x&yt uaAbline\nend<&>more");
1445 let copied_whole: usize = (0..borrowed.node_count())
1446 .map(|i| {
1447 let i = u32::try_from(i).unwrap();
1448 match borrowed.kind(i) {
1449 NodeKind::Element | NodeKind::Document => 0,
1450 _ => borrowed.own_text(i).len(),
1451 }
1452 })
1453 .sum();
1454 assert_eq!(borrowed.text.len(), copied_whole);
1455 for tree in [&borrowed, &owned] {
1456 assert_eq!(tree.records.capacity(), tree.records.len());
1457 assert_eq!(tree.text.capacity(), tree.text.len());
1458 assert_eq!(tree.names.capacity(), tree.names.len());
1459 }
1460 let r = find(&owned, "r");
1461 let values: Vec<_> = r
1462 .attributes()
1463 .map(|a| a.string_value().into_owned())
1464 .collect();
1465 assert_eq!(values, ["plain", "x&y", "t u"]);
1466 assert_eq!(r.string_value(), "verbatimaAbline\nend<&>moretail");
1467 assert_eq!(r.name().unwrap().to_string(), "p:r");
1468 let e = find(&owned, "e");
1469 assert_eq!(e.name().unwrap().namespace.as_deref(), Some("urn:d"));
1470 let f = e.attributes().next().unwrap();
1471 assert_eq!(f.name().unwrap().to_string(), "p:f");
1472 assert_eq!(f.name().unwrap().namespace.as_deref(), Some("urn:p"));
1473 assert_eq!(owned.names.iter().filter(|n| n.local == "e").count(), 1);
1475 }
1476
1477 #[test]
1478 fn built_trees_merge_text_after_a_parsed_shape() {
1479 let mut builder = TreeBuilder::new();
1482 builder.start_element(QName::local("e")).unwrap();
1483 builder.attribute(QName::local("a"), "v").unwrap();
1484 builder.comment("c").unwrap();
1485 builder.text("x").unwrap();
1486 builder.text("y").unwrap();
1487 builder.processing_instruction("t", "d").unwrap();
1488 builder.text("z").unwrap();
1489 builder.end_element().unwrap();
1490 let tree = builder.finish(None, None).unwrap();
1491 let e = tree.root().children().next().unwrap();
1492 let children: Vec<_> = e
1493 .children()
1494 .map(|c| (c.kind(), c.string_value().into_owned()))
1495 .collect();
1496 assert_eq!(
1497 children,
1498 [
1499 (NodeKind::Comment, "c".to_owned()),
1500 (NodeKind::Text, "xy".to_owned()),
1501 (NodeKind::ProcessingInstruction, "d".to_owned()),
1502 (NodeKind::Text, "z".to_owned()),
1503 ]
1504 );
1505 assert_eq!(tree.text, "vcxydz");
1506 }
1507
1508 #[test]
1509 fn file_uris() {
1510 if cfg!(windows) {
1511 return;
1512 }
1513 assert_eq!(
1514 file_uri(Path::new("/a b/c,d%é#[1]\u{a0}.xml")).as_deref(),
1515 Some("file:/a%20b/c,d%25é%23%5B1%5D%C2%A0.xml")
1516 );
1517 assert_eq!(file_uri(Path::new("rel.xml")), None);
1518 }
1519}