einvoice_validator/
detect.rs1use std::fmt;
5
6use einvoice_xml::Encoding;
7
8use crate::manifest::{CII, UBL_CREDIT_NOTE, UBL_INVOICE};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum Syntax {
14 Ubl,
17 Cii,
20}
21
22impl Syntax {
23 #[must_use]
31 pub fn detect(document: &[u8]) -> Option<Self> {
32 let (local, namespace) = match einvoice_xml::encoding_of(document) {
33 Ok(encoding @ (Encoding::Utf16Le | Encoding::Utf16Be)) => {
34 root_name(utf16_lossy(document, encoding).as_bytes())?
35 }
36 _ => root_name(document)?,
37 };
38 match (local.as_str(), namespace.as_str()) {
39 ("Invoice", UBL_INVOICE) | ("CreditNote", UBL_CREDIT_NOTE) => Some(Self::Ubl),
40 ("CrossIndustryInvoice", CII) => Some(Self::Cii),
41 _ => None,
42 }
43 }
44
45 #[must_use]
49 pub const fn builtin_rule_set(self) -> &'static str {
50 match self {
51 Self::Ubl => "cen-ubl",
52 Self::Cii => "cen-cii",
53 }
54 }
55
56 #[must_use]
58 pub const fn as_str(self) -> &'static str {
59 match self {
60 Self::Ubl => "ubl",
61 Self::Cii => "cii",
62 }
63 }
64}
65
66impl fmt::Display for Syntax {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(self.as_str())
69 }
70}
71
72fn utf16_lossy(document: &[u8], encoding: Encoding) -> String {
75 let bytes = document
76 .strip_prefix(&[0xFF, 0xFE])
77 .or_else(|| document.strip_prefix(&[0xFE, 0xFF]))
78 .unwrap_or(document);
79 let units = bytes.as_chunks::<2>().0.iter().map(|&pair| {
80 if encoding == Encoding::Utf16Le {
81 u16::from_le_bytes(pair)
82 } else {
83 u16::from_be_bytes(pair)
84 }
85 });
86 char::decode_utf16(units)
87 .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
88 .collect()
89}
90
91const fn is_space(b: u8) -> bool {
93 matches!(b, b' ' | b'\t' | b'\r' | b'\n')
94}
95
96fn root_name(document: &[u8]) -> Option<(String, String)> {
101 let text = document.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(document);
102 let mut rest = text;
103 loop {
104 let skip = rest.iter().position(|&b| !is_space(b))?;
105 rest = &rest[skip..];
106 if let Some(after) = rest.strip_prefix(b"<?") {
107 rest = &after[find(after, b"?>")? + 2..];
108 } else if let Some(after) = rest.strip_prefix(b"<!--") {
109 rest = &after[find(after, b"-->")? + 3..];
110 } else if rest.starts_with(b"<!") {
111 return None;
113 } else {
114 rest = rest.strip_prefix(b"<")?;
115 break;
116 }
117 }
118 let (qname, mut rest) = name(rest)?;
119 let mut namespaces: Vec<(String, String)> = Vec::new();
120 loop {
121 let skip = rest.iter().position(|&b| !is_space(b))?;
122 let spaced = skip > 0;
123 rest = &rest[skip..];
124 if rest.starts_with(b">") || rest.starts_with(b"/>") {
125 break;
126 }
127 if !spaced {
128 return None;
129 }
130 let (attribute, after) = name(rest)?;
131 let after = trim_start(after).strip_prefix(b"=")?;
132 let after = trim_start(after);
133 let quote = *after.first().filter(|q| matches!(q, b'"' | b'\''))?;
134 let after = &after[1..];
135 let end = after.iter().position(|&b| b == quote)?;
136 rest = &after[end + 1..];
137 let Ok(value) = std::str::from_utf8(&after[..end]) else {
140 continue;
141 };
142 if value.contains(['&', '<']) {
143 continue;
144 }
145 if attribute == "xmlns" {
146 namespaces.push((String::new(), value.to_owned()));
147 } else if let Some(prefix) = attribute.strip_prefix("xmlns:") {
148 namespaces.push((prefix.to_owned(), value.to_owned()));
149 }
150 }
151 let (prefix, local) = qname.split_once(':').unwrap_or(("", &qname));
152 let namespace = namespaces
153 .iter()
154 .rev()
155 .find(|(p, _)| p == prefix)
156 .map(|(_, uri)| uri.clone())
157 .unwrap_or_default();
158 Some((local.to_owned(), namespace))
159}
160
161fn trim_start(bytes: &[u8]) -> &[u8] {
162 let skip = bytes
163 .iter()
164 .position(|&b| !is_space(b))
165 .unwrap_or(bytes.len());
166 &bytes[skip..]
167}
168
169fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
170 haystack.windows(needle.len()).position(|w| w == needle)
171}
172
173fn name(bytes: &[u8]) -> Option<(String, &[u8])> {
175 let end = bytes
176 .iter()
177 .position(|&b| is_space(b) || matches!(b, b'=' | b'>' | b'/'))
178 .unwrap_or(bytes.len());
179 if end == 0 {
180 return None;
181 }
182 let text = std::str::from_utf8(&bytes[..end]).ok()?;
183 Some((text.to_owned(), &bytes[end..]))
184}
185
186#[cfg(test)]
187mod tests {
188 use super::Syntax;
189
190 fn detect(text: &str) -> Option<Syntax> {
191 Syntax::detect(text.as_bytes())
192 }
193
194 #[test]
195 fn root_elements() {
196 assert_eq!(
197 detect(r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#),
198 Some(Syntax::Ubl)
199 );
200 assert_eq!(
201 detect(
202 "\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'>"
203 ),
204 Some(Syntax::Ubl)
205 );
206 assert_eq!(
207 detect(
208 r#"<rsm:CrossIndustryInvoice xmlns:a="x" xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"><x/></rsm:CrossIndustryInvoice>"#
209 ),
210 Some(Syntax::Cii)
211 );
212 assert_eq!(
213 detect(
214 "<CrossIndustryInvoice\n xmlns = \"urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100\" >"
215 ),
216 Some(Syntax::Cii)
217 );
218 }
219
220 #[test]
221 fn other_encodings() {
222 let ubl = "<?xml version='1.0' encoding='UTF-16'?><Invoice note='\u{e9}' xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2'/>";
223 let le: Vec<u8> = [0xFF, 0xFE]
224 .into_iter()
225 .chain(ubl.encode_utf16().flat_map(u16::to_le_bytes))
226 .collect();
227 assert_eq!(Syntax::detect(&le), Some(Syntax::Ubl));
228 let be: Vec<u8> = ubl.encode_utf16().flat_map(u16::to_be_bytes).collect();
229 assert_eq!(Syntax::detect(&be), Some(Syntax::Ubl));
230 let mut lone = le.clone();
232 lone.extend([0x00, 0xD8]);
233 assert_eq!(Syntax::detect(&lone), Some(Syntax::Ubl));
234 let latin1 = b"<?xml version='1.0' encoding='ISO-8859-1'?><rsm:CrossIndustryInvoice a='\xE9' xmlns:rsm='urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'/>";
236 assert_eq!(Syntax::detect(latin1), Some(Syntax::Cii));
237 }
238
239 #[test]
240 fn anything_else() {
241 for text in [
242 "",
243 " ",
244 "not xml",
245 "<Invoice/>",
246 r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"/>"#,
247 r#"<CreditNote xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
248 r#"<x:Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
249 r#"<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:13"/>"#,
250 r#"<!DOCTYPE Invoice><Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#,
251 r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-21"/>"#,
252 r#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"x="1"/>"#,
253 "<!-- unterminated",
254 "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
255 ] {
256 assert_eq!(detect(text), None, "{text}");
257 }
258 }
259
260 #[test]
261 fn rule_set_names() {
262 assert_eq!(Syntax::Ubl.builtin_rule_set(), "cen-ubl");
263 assert_eq!(Syntax::Cii.builtin_rule_set(), "cen-cii");
264 assert_eq!(Syntax::Cii.to_string(), "cii");
265 }
266}