Skip to main content

einvoice_xml/
lib.rs

1//! A streaming (pull) parser of XML 1.0 documents with namespaces, in pure Rust: no
2//! tree is built, so that well-formedness checking and validation can run in one pass
3//! over a document in memory that does not grow with the document.
4//!
5//! [`Reader::next_event`] returns the [`Event`]s of a document one by one. Names, and
6//! text and attribute values without references or characters to normalise, are
7//! slices of the input; the reader keeps only the open elements, the namespace
8//! declarations in scope, the attributes of the current start tag and the distinct
9//! namespace declarations seen (at most [`Limits::namespaces`]).
10//!
11//! ```
12//! use einvoice_xml::{Event, Reader};
13//!
14//! let mut reader = Reader::new(r#"<i:Invoice xmlns:i="urn:i" id="1">a &amp; b</i:Invoice>"#);
15//! let mut events = Vec::new();
16//! while let Some(event) = reader.next_event()? {
17//!     match event {
18//!         Event::Start(start) => {
19//!             let name = start.name();
20//!             assert_eq!((name.namespace, name.local), (Some("urn:i"), "Invoice"));
21//!             assert_eq!(start.attribute(None, "id").map(|v| v.as_ref()), Some("1"));
22//!             events.push("start");
23//!         }
24//!         Event::Text(text) => {
25//!             assert_eq!(text.value, "a & b");
26//!             events.push("text");
27//!         }
28//!         Event::End(_) => events.push("end"),
29//!         _ => {}
30//!     }
31//! }
32//! assert_eq!(events, ["start", "text", "end"]);
33//! assert!(einvoice_xml::check("<a><b></a>").is_err());
34//! # Ok::<(), einvoice_xml::Error>(())
35//! ```
36//!
37//! # What is accepted
38//!
39//! The text is UTF-8 (a `&str`; a byte order mark at the start is skipped; the
40//! `encoding` of the XML declaration is checked for syntax only). Supported: the XML
41//! declaration, elements and attributes, namespaces (prefixes, the default namespace
42//! and its undeclaration with `xmlns=""`, the predefined `xml` prefix for attributes),
43//! comments, processing instructions, CDATA sections, character references and the five
44//! predefined entity references, line-end normalisation and attribute-value
45//! normalisation for the CDATA type. A document type declaration is refused
46//! ([`Error::DtdDetected`]), and so is a reference to any other entity.
47//!
48//! The reader accepts the documents that the `roxmltree` crate (0.21, document type
49//! declarations refused) accepts and that are namespace-well-formed: on a document it
50//! refuses, the reader reports the same error, with the same message and position,
51//! unless the document contains one of the constructs below, which `roxmltree` accepts
52//! although XML 1.0 or Namespaces in XML 1.0 forbids them; each is refused with its own
53//! error:
54//!
55//! * a character reference to a surrogate or to a number above `0x10FFFF`
56//!   ([`Error::InvalidCharacterReference`]; `roxmltree` reads U+FFFD);
57//! * a processing instruction whose target is `xml` in any case or contains a colon,
58//!   or that has no whitespace between its target and its data
59//!   ([`Error::InvalidPiTarget`], [`Error::PiWithoutWhitespace`]);
60//! * an XML declaration with a pseudo-attribute other than `version`, `encoding` and
61//!   `standalone` as written, a version other than `1.` and digits, an encoding that is
62//!   not an encoding name, or a `standalone` other than `yes` and `no`
63//!   ([`Error::InvalidXmlDeclaration`]);
64//! * a name that starts with a colon ([`Error::InvalidQName`]);
65//! * `xmlns:p=""` ([`Error::EmptyPrefixedNamespace`]), a declaration of the `xmlns`
66//!   prefix ([`Error::XmlnsPrefixDeclared`]), the default namespace or the `xml` prefix
67//!   declared twice on an element ([`Error::DuplicatedNamespaceDeclaration`]);
68//! * an attribute named `p:xmlns`, which `roxmltree` takes for a declaration of the
69//!   default namespace ([`Error::PrefixedXmlnsAttribute`]).
70//!
71//! The errors that only these constructs cause are raised once the checks that
72//! `roxmltree` makes on the same start tag, text, processing instruction or XML
73//! declaration have passed, so that a document with an error of both kinds in one tag
74//! gets the error that `roxmltree` reports.
75//!
76//! As with `roxmltree`, an element name with the `xml` prefix is refused
77//! ([`Error::UnknownNamespace`]), although XML allows it.
78//!
79//! The data differs from `roxmltree`'s, following XML 1.0, in three cases: a carriage
80//! return written next to a reference in character data is a line end like any other
81//! (`roxmltree` can keep it as a carriage return); comments and processing
82//! instructions have their line ends normalised; and `<?xml` followed by a tab, a line
83//! feed or a carriage return at the start of the text is an XML declaration (for
84//! `roxmltree`, a processing instruction).
85//!
86//! # Limits
87//!
88//! [`Limits`] bounds the number of nodes, the depth, the number of attributes and the
89//! number of distinct namespace declarations; the defaults are `roxmltree`'s. Time is
90//! linear in the length of the text: duplicate attributes and prefixes are found
91//! through hash sets when an element has many.
92
93mod chars;
94mod decode;
95mod error;
96mod event;
97mod namespaces;
98mod reader;
99
100pub use error::{Error, TextPos};
101pub use event::{
102    Attribute, Comment, EndElement, Event, Name, ProcessingInstruction, StartElement, Text,
103};
104pub use reader::{Limits, Reader, XML_NAMESPACE, XMLNS_NAMESPACE};
105
106/// Checks that `text` is a well-formed document that the [`Reader`] accepts, with the
107/// default [`Limits`].
108///
109/// # Errors
110///
111/// The first error.
112pub fn check(text: &str) -> Result<(), Error> {
113    Reader::new(text).read_to_end()
114}