einvoice_validator/
detect.rs1use std::fmt;
5
6const UBL_INVOICE: &str = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
8const UBL_CREDIT_NOTE: &str = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
10const CII: &str = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum Syntax {
18 Ubl,
21 Cii,
24}
25
26impl Syntax {
27 #[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 #[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 #[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
69const fn is_space(b: u8) -> bool {
71 matches!(b, b' ' | b'\t' | b'\r' | b'\n')
72}
73
74fn 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 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 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
148fn 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-21"/>"#,
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}