Skip to main content

einvoice_xml/
event.rs

1//! The events of a document.
2
3use std::borrow::Cow;
4use std::ops::Range;
5
6use crate::Reader;
7
8/// One event of a document, in document order. `'r` is the borrow of the reader
9/// (names' namespaces and attributes live in it until the next event); `'a` is the
10/// text read.
11#[derive(Debug)]
12pub enum Event<'r, 'a> {
13    /// A start tag or an empty-element tag. An empty-element tag is followed at once by
14    /// its [`Event::End`].
15    Start(StartElement<'r, 'a>),
16    /// An end tag, or the end of an empty-element tag.
17    End(EndElement<'r, 'a>),
18    /// Character data or a CDATA section. Adjacent text events (character data,
19    /// references, CDATA sections not separated by markup) make one text node of the
20    /// data model.
21    Text(Text<'a>),
22    /// A comment.
23    Comment(Comment<'a>),
24    /// A processing instruction.
25    ProcessingInstruction(ProcessingInstruction<'a>),
26}
27
28/// A name with its namespace.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct Name<'r, 'a> {
31    /// The prefix as written, `""` for none.
32    pub prefix: &'a str,
33    /// The local part.
34    pub local: &'a str,
35    /// The namespace name, `None` for no namespace.
36    pub namespace: Option<&'r str>,
37}
38
39/// An attribute (namespace declarations are not attributes).
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct Attribute<'r, 'a> {
42    /// Its name.
43    pub name: Name<'r, 'a>,
44    /// The normalised value (references replaced, whitespace characters written as
45    /// spaces): a slice of the text unless that changed it.
46    pub value: &'r Cow<'a, str>,
47    /// The value as written, between the quotes.
48    pub raw: &'a str,
49    /// The byte range of the attribute, from its name to its closing quote.
50    pub range: Range<usize>,
51}
52
53/// The start of an element.
54#[derive(Clone, Copy)]
55pub struct StartElement<'r, 'a> {
56    pub(crate) reader: &'r Reader<'a>,
57}
58
59impl<'r, 'a> StartElement<'r, 'a> {
60    /// The element's name.
61    #[must_use]
62    pub fn name(&self) -> Name<'r, 'a> {
63        current_name(self.reader)
64    }
65
66    /// The attributes, in document order (namespace declarations excluded).
67    pub fn attributes(&self) -> impl ExactSizeIterator<Item = Attribute<'r, 'a>> + use<'r, 'a> {
68        let reader = self.reader;
69        reader
70            .attributes
71            .iter()
72            .map(move |data| reader.attribute_view(data))
73    }
74
75    /// The value of the attribute with this namespace (`None` for none) and local name.
76    #[must_use]
77    pub fn attribute(&self, namespace: Option<&str>, local: &str) -> Option<&'r Cow<'a, str>> {
78        let reader = self.reader;
79        reader
80            .attributes
81            .iter()
82            .find(|data| data.local == local && reader.namespace(data.ns) == namespace)
83            .map(|data| &data.value)
84    }
85
86    /// The namespace declarations of the element, in document order: the prefix (`""`
87    /// for the default namespace) and the namespace name (empty when the default
88    /// namespace is undeclared). A declaration of the `xml` prefix is not reported.
89    pub fn namespace_declarations(
90        &self,
91    ) -> impl ExactSizeIterator<Item = (&'a str, &'r str)> + use<'r, 'a> {
92        let scope = self.reader.stack.last().map_or(0, |open| open.scope);
93        self.reader.scope.since(scope)
94    }
95
96    /// The namespace bound to `prefix` in the scope of the element (see
97    /// [`Reader::lookup_namespace`]).
98    #[must_use]
99    pub fn lookup_namespace(&self, prefix: &str) -> Option<&'r str> {
100        self.reader.lookup_namespace(prefix)
101    }
102
103    /// Whether it is an empty-element tag (`<a/>`).
104    #[must_use]
105    pub fn is_empty(&self) -> bool {
106        self.reader.empty
107    }
108
109    /// The byte range of the start tag.
110    #[must_use]
111    pub fn range(&self) -> Range<usize> {
112        self.reader.tag.clone()
113    }
114}
115
116impl std::fmt::Debug for StartElement<'_, '_> {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.debug_struct("StartElement")
119            .field("name", &self.name())
120            .field("attributes", &self.attributes().collect::<Vec<_>>())
121            .field("empty", &self.is_empty())
122            .finish()
123    }
124}
125
126/// The end of an element.
127#[derive(Clone, Copy)]
128pub struct EndElement<'r, 'a> {
129    pub(crate) reader: &'r Reader<'a>,
130}
131
132impl<'r, 'a> EndElement<'r, 'a> {
133    /// The element's name.
134    #[must_use]
135    pub fn name(&self) -> Name<'r, 'a> {
136        current_name(self.reader)
137    }
138
139    /// Whether the element was an empty-element tag.
140    #[must_use]
141    pub fn is_empty(&self) -> bool {
142        self.reader.empty
143    }
144
145    /// The byte range of the end tag, or of the empty-element tag.
146    #[must_use]
147    pub fn range(&self) -> Range<usize> {
148        self.reader.tag.clone()
149    }
150}
151
152impl std::fmt::Debug for EndElement<'_, '_> {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("EndElement")
155            .field("name", &self.name())
156            .finish()
157    }
158}
159
160fn current_name<'r, 'a>(reader: &'r Reader<'a>) -> Name<'r, 'a> {
161    match reader.stack.last() {
162        Some(open) => reader.name_of(open.prefix, open.local, open.ns),
163        None => Name {
164            prefix: "",
165            local: "",
166            namespace: None,
167        },
168    }
169}
170
171/// Character data or a CDATA section.
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[non_exhaustive]
174pub struct Text<'a> {
175    /// The text: references replaced, line ends normalised; a slice of the input
176    /// unless that changed it.
177    pub value: Cow<'a, str>,
178    /// The byte range as written (a CDATA section's markup included).
179    pub range: Range<usize>,
180    /// Whether it is a CDATA section.
181    pub cdata: bool,
182}
183
184/// A comment.
185#[derive(Clone, Debug, PartialEq, Eq)]
186#[non_exhaustive]
187pub struct Comment<'a> {
188    /// The text between `<!--` and `-->`, line ends normalised.
189    pub value: Cow<'a, str>,
190    /// The byte range as written.
191    pub range: Range<usize>,
192}
193
194/// A processing instruction.
195#[derive(Clone, Debug, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct ProcessingInstruction<'a> {
198    /// The target.
199    pub target: &'a str,
200    /// The data after the whitespace that follows the target, line ends normalised;
201    /// `None` when empty.
202    pub value: Option<Cow<'a, str>>,
203    /// The byte range as written.
204    pub range: Range<usize>,
205}