Skip to main content

einvoice_validator/
detect.rs

1//! The syntax of a document, from the name of its root element: what picks the built-in
2//! rule set when none is named.
3
4use std::fmt;
5
6/// The namespace of a UBL 2 invoice.
7const UBL_INVOICE: &str = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
8/// The namespace of a UBL 2 credit note.
9const UBL_CREDIT_NOTE: &str = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
10/// The namespace of a UN/CEFACT Cross Industry Invoice (D16B and the other releases of
11/// version 100).
12const CII: &str = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
13
14/// The syntax of an e-invoice, as its root element names it.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum Syntax {
18    /// OASIS UBL 2: a root element `Invoice` or `CreditNote` in the UBL 2 namespace of
19    /// that name.
20    Ubl,
21    /// UN/CEFACT Cross Industry Invoice: a root element `CrossIndustryInvoice` in the
22    /// namespace `urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100`.
23    Cii,
24}
25
26impl Syntax {
27    /// The syntax of `document`, from its root element alone: its local name and
28    /// namespace. `None` when the document does not start like XML with one of the root
29    /// elements above (another root element, a document that is not XML, a document type
30    /// declaration before the root, an encoding other than UTF-8). Only the start of the
31    /// document is read; whether it is well-formed is for the validation to say.
32    #[must_use]
33    pub fn detect(document: &[u8]) -> Option<Self> {
34        let (local, namespace) = root_name(document)?;
35        match (local.as_str(), namespace.as_str()) {
36            ("Invoice", UBL_INVOICE) | ("CreditNote", UBL_CREDIT_NOTE) => Some(Self::Ubl),
37            ("CrossIndustryInvoice", CII) => Some(Self::Cii),
38            _ => None,
39        }
40    }
41
42    /// The name of the built-in rule set of this syntax: `cen-ubl` or `cen-cii`, the CEN
43    /// EN 16931 rules (whether this build has it is in
44    /// [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)).
45    #[must_use]
46    pub const fn builtin_rule_set(self) -> &'static str {
47        match self {
48            Self::Ubl => "cen-ubl",
49            Self::Cii => "cen-cii",
50        }
51    }
52
53    /// `ubl` or `cii`.
54    #[must_use]
55    pub const fn as_str(self) -> &'static str {
56        match self {
57            Self::Ubl => "ubl",
58            Self::Cii => "cii",
59        }
60    }
61}
62
63impl fmt::Display for Syntax {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(self.as_str())
66    }
67}
68
69/// Whitespace in the sense of XML (`S`).
70const fn is_space(b: u8) -> bool {
71    matches!(b, b' ' | b'\t' | b'\r' | b'\n')
72}
73
74/// The local name and namespace of the root element: after an optional byte order mark,
75/// XML declaration, comments, processing instructions and whitespace, the first start
76/// tag, its name resolved with the namespace declarations of that tag (the root element
77/// has no ancestor to inherit others from).
78fn root_name(document: &[u8]) -> Option<(String, String)> {
79    let text = document.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(document);
80    let mut rest = text;
81    loop {
82        let skip = rest.iter().position(|&b| !is_space(b))?;
83        rest = &rest[skip..];
84        if let Some(after) = rest.strip_prefix(b"<?") {
85            rest = &after[find(after, b"?>")? + 2..];
86        } else if let Some(after) = rest.strip_prefix(b"<!--") {
87            rest = &after[find(after, b"-->")? + 3..];
88        } else if rest.starts_with(b"<!") {
89            // A document type declaration: refused by the validation.
90            return None;
91        } else {
92            rest = rest.strip_prefix(b"<")?;
93            break;
94        }
95    }
96    let (qname, mut rest) = name(rest)?;
97    let mut namespaces: Vec<(String, String)> = Vec::new();
98    loop {
99        let skip = rest.iter().position(|&b| !is_space(b))?;
100        let spaced = skip > 0;
101        rest = &rest[skip..];
102        if rest.starts_with(b">") || rest.starts_with(b"/>") {
103            break;
104        }
105        if !spaced {
106            return None;
107        }
108        let (attribute, after) = name(rest)?;
109        let after = trim_start(after).strip_prefix(b"=")?;
110        let after = trim_start(after);
111        let quote = *after.first().filter(|q| matches!(q, b'"' | b'\''))?;
112        let after = &after[1..];
113        let end = after.iter().position(|&b| b == quote)?;
114        let value = std::str::from_utf8(&after[..end]).ok()?;
115        rest = &after[end + 1..];
116        // A value with a reference would need decoding: not one of the namespaces above.
117        if value.contains(['&', '<']) {
118            continue;
119        }
120        if attribute == "xmlns" {
121            namespaces.push((String::new(), value.to_owned()));
122        } else if let Some(prefix) = attribute.strip_prefix("xmlns:") {
123            namespaces.push((prefix.to_owned(), value.to_owned()));
124        }
125    }
126    let (prefix, local) = qname.split_once(':').unwrap_or(("", &qname));
127    let namespace = namespaces
128        .iter()
129        .rev()
130        .find(|(p, _)| p == prefix)
131        .map(|(_, uri)| uri.clone())
132        .unwrap_or_default();
133    Some((local.to_owned(), namespace))
134}
135
136fn trim_start(bytes: &[u8]) -> &[u8] {
137    let skip = bytes
138        .iter()
139        .position(|&b| !is_space(b))
140        .unwrap_or(bytes.len());
141    &bytes[skip..]
142}
143
144fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
145    haystack.windows(needle.len()).position(|w| w == needle)
146}
147
148/// A name at the start of `bytes` (up to whitespace, `=`, `>` or `/`), and what follows.
149fn name(bytes: &[u8]) -> Option<(String, &[u8])> {
150    let end = bytes
151        .iter()
152        .position(|&b| is_space(b) || matches!(b, b'=' | b'>' | b'/'))
153        .unwrap_or(bytes.len());
154    if end == 0 {
155        return None;
156    }
157    let text = std::str::from_utf8(&bytes[..end]).ok()?;
158    Some((text.to_owned(), &bytes[end..]))
159}
160
161#[cfg(test)]
162mod tests {
163    use super::Syntax;
164
165    fn detect(text: &str) -> Option<Syntax> {
166        Syntax::detect(text.as_bytes())
167    }
168
169    #[test]
170    fn root_elements() {
171        assert_eq!(
172            detect(r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#),
173            Some(Syntax::Ubl)
174        );
175        assert_eq!(
176            detect(
177                "\u{feff}<?xml version='1.0'?>\n<!-- c --><?pi x?>\n<ubl:CreditNote a='1' xmlns:ubl='urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2'>"
178            ),
179            Some(Syntax::Ubl)
180        );
181        assert_eq!(
182            detect(
183                r#"<rsm:CrossIndustryInvoice xmlns:a="x" xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"><x/></rsm:CrossIndustryInvoice>"#
184            ),
185            Some(Syntax::Cii)
186        );
187        assert_eq!(
188            detect(
189                "<CrossIndustryInvoice\n xmlns = \"urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100\" >"
190            ),
191            Some(Syntax::Cii)
192        );
193    }
194
195    #[test]
196    fn anything_else() {
197        for text in [
198            "",
199            "   ",
200            "not xml",
201            "<Invoice/>",
202            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"/>"#,
203            r#"<CreditNote xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
204            r#"<x:Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
205            r#"<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:13"/>"#,
206            r#"<!DOCTYPE Invoice><Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
207            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2&#x31;"/>"#,
208            r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"x="1"/>"#,
209            "<!-- unterminated",
210            "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
211        ] {
212            assert_eq!(detect(text), None, "{text}");
213        }
214    }
215
216    #[test]
217    fn rule_set_names() {
218        assert_eq!(Syntax::Ubl.builtin_rule_set(), "cen-ubl");
219        assert_eq!(Syntax::Cii.builtin_rule_set(), "cen-cii");
220        assert_eq!(Syntax::Cii.to_string(), "cii");
221    }
222}