Skip to main content

einvoice_validator/
validator.rs

1//! Loading a rule set once, then validating documents with it.
2
3use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5
6use einvoice_xpath_eval::{Clock, DEFAULT_MAX_DEPTH, LimitExceeded};
7use einvoice_xslt::LoadErrorKind;
8use einvoice_xslt_exec::{
9    DEFAULT_MAX_STACK, Executable, TransformError, TransformOptions, max_nesting_for_depth,
10};
11use roxmltree::ParsingOptions;
12use sha2::{Digest, Sha256};
13
14use crate::manifest::{MANIFEST_FILE, RuleSet, SchemaId, StylesheetEntry};
15use crate::report::{Report, RuleSetVersion, StylesheetFailure, StylesheetReport};
16use crate::{Error, builtin};
17
18/// Options of one validation.
19#[derive(Debug, Clone, Copy)]
20pub struct ValidateOptions<'a> {
21    document_uri: Option<&'a str>,
22    clock: Option<Clock>,
23    max_depth: u32,
24    max_stack: u32,
25}
26
27impl Default for ValidateOptions<'_> {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33impl<'a> ValidateOptions<'a> {
34    /// The default options: the document has no URI, the clock is the system clock in
35    /// UTC, the maximum element depth is [`DEFAULT_MAX_DEPTH`] and the stack the
36    /// stylesheets may use is [`DEFAULT_MAX_STACK`].
37    #[must_use]
38    pub const fn new() -> Self {
39        Self {
40            document_uri: None,
41            clock: None,
42            max_depth: DEFAULT_MAX_DEPTH,
43            max_stack: DEFAULT_MAX_STACK,
44        }
45    }
46
47    /// The maximum element depth of the document, and of any document a stylesheet
48    /// loads with `document()`: the document element is at depth 1, its children at
49    /// depth 2, and so on. A document with an element nested deeper is refused with
50    /// [`Error::Limit`] before its schema is checked. Default: [`DEFAULT_MAX_DEPTH`]
51    /// (256, libxml2's default).
52    ///
53    /// The stylesheets apply their template rules one element level inside another, so
54    /// their stack use grows with the depth: with the default, a validation runs on a
55    /// thread with the default 2 MiB stack, debug builds included. The nesting of
56    /// template and function invocations the stylesheets are allowed grows with the
57    /// maximum ([`max_nesting_for_depth`](crate::max_nesting_for_depth)), and so does the
58    /// stack they need: a larger maximum depth needs a larger
59    /// [`ValidateOptions::max_stack`], and a thread with that much stack.
60    #[must_use]
61    pub const fn max_depth(mut self, max_depth: u32) -> Self {
62        self.max_depth = max_depth;
63        self
64    }
65
66    /// The most stack, in bytes, the stylesheets' template and function invocations may
67    /// use, measured from the start of each stylesheet: beyond it, the validation fails
68    /// with [`Error::Limit`] ([`LimitExceeded::Stack`]) instead of overflowing the
69    /// stack, which would abort the process. Default: [`DEFAULT_MAX_STACK`] (1.5 MiB), for
70    /// the default 2 MiB stack of a spawned thread. The thread that validates must have
71    /// this much stack and at least 512 KiB more, for its caller and the deepest
72    /// invocation.
73    #[must_use]
74    pub const fn max_stack(mut self, bytes: u32) -> Self {
75        self.max_stack = bytes;
76        self
77    }
78
79    /// The clock of the stylesheets: the implicit timezone and the value of
80    /// `fn:current-dateTime()` (read once per validation, as the reference engine reads
81    /// it once per transformation). By default, the system clock in UTC; required on
82    /// targets without a system clock, such as `wasm32-unknown-unknown`, where
83    /// validating without it fails with [`Error::Unsupported`].
84    #[must_use]
85    pub const fn clock(mut self, clock: Clock) -> Self {
86        self.clock = Some(clock);
87        self
88    }
89
90    /// The URI of the document: what `document-uri(/)` returns in the stylesheets, and
91    /// what the SVRL report states in `svrl:active-pattern/@documents`. For a file,
92    /// [`file_uri`] gives the URI the reference engine uses.
93    #[must_use]
94    pub const fn document_uri(mut self, uri: &'a str) -> Self {
95        self.document_uri = Some(uri);
96        self
97    }
98}
99
100/// The `file:` URI that the reference engine (Saxon-HE) gives a document read from the
101/// file at `path` (absolute). `None` for a relative path or one that is not Unicode.
102#[must_use]
103pub fn file_uri(path: &Path) -> Option<String> {
104    einvoice_xpath_eval::file_uri(path)
105}
106
107/// A rule set ready to validate documents: its schema loaded and its stylesheets
108/// prepared, once. Validating a document only reads it, so one `Validator` serves any
109/// number of documents, from any number of threads at once (`Send + Sync`); nothing of
110/// the rule set is copied per document.
111#[derive(Debug)]
112pub struct Validator {
113    rule_set: RuleSet,
114    schema: Option<einvoice_xsd::Schema>,
115    /// The prepared stylesheets, in the order of `rule_set.stylesheets()`.
116    stylesheets: Vec<Executable>,
117}
118
119impl Validator {
120    /// The built-in rule set `name` (see [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)).
121    ///
122    /// # Errors
123    ///
124    /// [`Error::Bundle`] for an unknown name; otherwise as [`Validator::from_bundle`],
125    /// which none of the built-in rule sets fails in practice (a test loads each).
126    pub fn builtin(name: &str) -> Result<Self, Error> {
127        let (manifest, files) = builtin::get(name)?;
128        Self::from_bundle(manifest, files)
129    }
130
131    /// The built-in rule set `cen-ubl`: the CEN EN 16931 validation artefacts for UBL,
132    /// release 1.3.17 (EUPL-1.2), embedded unmodified, with the UBL 2.1 schemas.
133    ///
134    /// # Errors
135    ///
136    /// None in practice (a test loads it); the error is returned rather than hidden.
137    #[cfg(feature = "cen-ubl")]
138    pub fn cen_ubl() -> Result<Self, Error> {
139        Self::builtin("cen-ubl")
140    }
141
142    /// The built-in rule set `cen-cii`: the CEN EN 16931 validation artefacts for UN/CEFACT
143    /// CII D16B, release 1.3.17 (EUPL-1.2), embedded unmodified, without an XML schema
144    /// (the CII D16B schemas are not embedded).
145    ///
146    /// # Errors
147    ///
148    /// None in practice (a test loads it); the error is returned rather than hidden.
149    #[cfg(feature = "cen-cii")]
150    pub fn cen_cii() -> Result<Self, Error> {
151        Self::builtin("cen-cii")
152    }
153
154    /// Loads a bundle from memory: its manifest and its files, by their paths in the
155    /// manifest. Files not named by the manifest are ignored.
156    ///
157    /// # Errors
158    ///
159    /// [`Error::Bundle`] for an invalid manifest, a missing file or a stylesheet that is
160    /// not well-formed; [`Error::Checksum`] for a file whose SHA-256 differs from the
161    /// manifest's; [`Error::Unsupported`] for a stylesheet or schema outside the
162    /// supported subset.
163    pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
164        let rule_set = RuleSet::parse(manifest)?;
165        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
166        for entry in rule_set.stylesheets() {
167            let Some((_, bytes)) = files.iter().find(|(path, _)| *path == entry.path()) else {
168                return Err(Error::bundle(format!(
169                    "stylesheet {}: file {} missing from the bundle",
170                    entry.name(),
171                    entry.path()
172                )));
173            };
174            stylesheets.push(prepare(entry, bytes, None)?);
175        }
176        Self::with(rule_set, stylesheets)
177    }
178
179    /// Loads the bundle in the directory `dir`: its manifest [`MANIFEST_FILE`] and the
180    /// files it names, relative to `dir`.
181    ///
182    /// # Errors
183    ///
184    /// [`Error::Io`] when a file cannot be read, otherwise as
185    /// [`Validator::from_bundle`].
186    pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
187        let dir = dir.as_ref();
188        let manifest_path = dir.join(MANIFEST_FILE);
189        let manifest = read(&manifest_path)?;
190        let manifest = std::str::from_utf8(&manifest)
191            .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
192        let rule_set = RuleSet::parse(manifest)?;
193        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
194        for entry in rule_set.stylesheets() {
195            let mut path = dir.to_path_buf();
196            path.extend(entry.path().split('/'));
197            let bytes = read(&path)?;
198            let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
199            stylesheets.push(prepare(entry, &bytes, base_uri)?);
200        }
201        Self::with(rule_set, stylesheets)
202    }
203
204    fn with(rule_set: RuleSet, stylesheets: Vec<Executable>) -> Result<Self, Error> {
205        let schema = match rule_set.schema() {
206            None => None,
207            Some(SchemaId::Ubl21) => Some(einvoice_xsd::Schema::ubl_2_1().map_err(|e| {
208                if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
209                    Error::unsupported(format!("schema ubl-2.1: {e}"))
210                } else {
211                    Error::internal(format!("the embedded schema ubl-2.1 does not load: {e}"))
212                }
213            })?),
214        };
215        Ok(Self {
216            rule_set,
217            schema,
218            stylesheets,
219        })
220    }
221
222    /// The rule set: name, version, schema, stylesheets and their checksums.
223    #[must_use]
224    pub const fn rule_set(&self) -> &RuleSet {
225        &self.rule_set
226    }
227
228    /// Validates a document with the default options (no document URI).
229    ///
230    /// # Errors
231    ///
232    /// As [`Validator::validate_with`].
233    pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
234        self.validate_with(document, &ValidateOptions::new())
235    }
236
237    /// Validates a document given as a buffer, with the default options (no document
238    /// URI).
239    ///
240    /// # Errors
241    ///
242    /// As [`Validator::validate_with`].
243    pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
244        self.validate_owned_with(document, &ValidateOptions::new())
245    }
246
247    /// [`Validator::validate_with`] on a document given as a buffer, which the
248    /// validation keeps instead of copying: the buffer becomes the text without a copy,
249    /// and the tree of the last stylesheet refers to it, so that while that stylesheet
250    /// runs the document is in memory once rather than twice. Same report as
251    /// [`Validator::validate_with`]; for a caller that has no further use for the bytes
252    /// (a file just read).
253    ///
254    /// # Errors
255    ///
256    /// As [`Validator::validate_with`].
257    pub fn validate_owned_with(
258        &self,
259        document: Vec<u8>,
260        options: &ValidateOptions<'_>,
261    ) -> Result<Report, Error> {
262        self.validate_text(Cow::Owned(decode_owned(document)?), options)
263    }
264
265    /// Validates a document: checks that it is well-formed XML, validates it against
266    /// the rule set's schema, then runs every stylesheet of the rule set on it. The
267    /// stylesheets run even when the schema reports errors, so that the report is
268    /// complete. When a stylesheet raises a dynamic error on a document that has schema
269    /// errors (a non-numeric amount the rules compute with, ...), the report is returned
270    /// all the same, invalid, with the error in [`StylesheetReport::failure`]; without
271    /// schema errors, the error is returned.
272    ///
273    /// The document must be UTF-8 (a byte order mark is allowed) and have no document
274    /// type declaration.
275    ///
276    /// # Errors
277    ///
278    /// [`Error::NotXml`] when the document is not well-formed XML (or not UTF-8);
279    /// [`Error::Unsupported`] for another encoding, a document type declaration, or a
280    /// construct the engine refuses; [`Error::Transform`] when a stylesheet raises a
281    /// dynamic error on the document; [`Error::Bundle`] when a stylesheet's result is
282    /// not an SVRL report; [`Error::Internal`] for a bug.
283    pub fn validate_with(
284        &self,
285        document: &[u8],
286        options: &ValidateOptions<'_>,
287    ) -> Result<Report, Error> {
288        self.validate_text(Cow::Borrowed(decode(document)?), options)
289    }
290
291    /// The validation of a decoded document: borrowed by the schema and every stylesheet
292    /// but the last, which is given it when it is owned.
293    fn validate_text(
294        &self,
295        text: Cow<'_, str>,
296        options: &ValidateOptions<'_>,
297    ) -> Result<Report, Error> {
298        check_well_formed(&text, options.max_depth)?;
299        let schema_errors = match &self.schema {
300            None => Vec::new(),
301            Some(schema) => {
302                schema
303                    .validate(&text)
304                    .map_err(|e| match e {
305                        einvoice_xsd::DocumentError::Malformed {
306                            line,
307                            column,
308                            message,
309                        } => Error::NotXml {
310                            line,
311                            column,
312                            message,
313                        },
314                        einvoice_xsd::DocumentError::Unsupported {
315                            line,
316                            column,
317                            message,
318                        } => Error::unsupported(format!(
319                            "document, line {line}, column {column}: {message}"
320                        )),
321                    })?
322                    .errors
323            }
324        };
325        let transform_options = TransformOptions {
326            implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
327            current_date_time: options.clock.map(|c| c.current_date_time()),
328            max_depth: options.max_depth,
329            max_nesting: max_nesting_for_depth(options.max_depth),
330            max_stack: options.max_stack,
331            ..TransformOptions::default()
332        };
333        let mut stylesheets = Vec::with_capacity(self.stylesheets.len());
334        let count = self.stylesheets.len();
335        // The text, until the last stylesheet is given it.
336        let mut text = Some(text);
337        for (index, (entry, executable)) in self
338            .rule_set
339            .stylesheets()
340            .iter()
341            .zip(&self.stylesheets)
342            .enumerate()
343        {
344            let source = if index + 1 == count {
345                text.take()
346            } else {
347                text.as_deref().map(Cow::Borrowed)
348            }
349            .ok_or_else(|| Error::internal("the document text was given away early"))?;
350            let result =
351                executable.transform_with(source, options.document_uri, &transform_options);
352            let report = match result {
353                Ok(result) => StylesheetReport::new(
354                    entry,
355                    result.output,
356                    result.warnings,
357                    options.document_uri,
358                )?,
359                Err(e) => match transform_error(entry, &e) {
360                    // The schema errors already make the document invalid: the verdict
361                    // stands, the report says which stylesheet could not finish.
362                    Error::Transform {
363                        code,
364                        line,
365                        message,
366                        ..
367                    } if !schema_errors.is_empty() => StylesheetReport::failed(
368                        entry,
369                        StylesheetFailure {
370                            code,
371                            line,
372                            message,
373                        },
374                        options.document_uri,
375                    ),
376                    other => return Err(other),
377                },
378            };
379            stylesheets.push(report);
380        }
381        Ok(Report {
382            rule_set: RuleSetVersion {
383                name: self.rule_set.name().to_owned(),
384                title: self.rule_set.title().to_owned(),
385                version: self.rule_set.version().to_owned(),
386                schema: self.rule_set.schema(),
387            },
388            document_uri: options.document_uri.map(str::to_owned),
389            schema_errors,
390            stylesheets,
391        })
392    }
393}
394
395fn read(path: &Path) -> Result<Vec<u8>, Error> {
396    std::fs::read(path).map_err(|source| Error::Io {
397        path: PathBuf::from(path),
398        source,
399    })
400}
401
402/// Lower-case hexadecimal SHA-256.
403pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
404    const HEX: &[u8; 16] = b"0123456789abcdef";
405    let digest = Sha256::digest(bytes);
406    let mut hex = String::with_capacity(64);
407    for byte in digest {
408        hex.push(char::from(HEX[usize::from(byte >> 4)]));
409        hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
410    }
411    hex
412}
413
414/// Checks the checksum of a stylesheet, loads and prepares it.
415fn prepare(
416    entry: &StylesheetEntry,
417    bytes: &[u8],
418    base_uri: Option<String>,
419) -> Result<Executable, Error> {
420    let actual = sha256_hex(bytes);
421    if actual != entry.sha256() {
422        return Err(Error::Checksum {
423            path: entry.path().to_owned(),
424            expected: entry.sha256().to_owned(),
425            actual,
426        });
427    }
428    let what = format!("stylesheet {} ({})", entry.name(), entry.path());
429    let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
430    let sheet = einvoice_xslt::load(text).map_err(|errors| {
431        let unsupported = errors.0.iter().any(|e| {
432            matches!(
433                e.kind,
434                LoadErrorKind::UnsupportedElement { .. }
435                    | LoadErrorKind::UnsupportedAttribute { .. }
436                    | LoadErrorKind::UnsupportedValue { .. }
437                    | LoadErrorKind::XPath { .. }
438            )
439        });
440        let message = format!("{what}: {}", first_lines(&errors.to_string()));
441        if unsupported {
442            Error::unsupported(message)
443        } else {
444            Error::bundle(message)
445        }
446    })?;
447    let executable = Executable::new(&sheet).map_err(|errors| {
448        Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
449    })?;
450    Ok(match base_uri {
451        Some(uri) => executable.with_base_uri(uri),
452        None => executable,
453    })
454}
455
456/// At most the first ten lines of a list of errors, with the number left out.
457fn first_lines(text: &str) -> String {
458    const MAX: usize = 10;
459    let lines: Vec<&str> = text.lines().collect();
460    if lines.len() <= MAX {
461        return lines.join("; ");
462    }
463    format!(
464        "{}; and {} more",
465        lines[..MAX].join("; "),
466        lines.len() - MAX
467    )
468}
469
470fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
471    let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
472    if let Some(limit) = e.limit() {
473        return Error::Limit {
474            limit,
475            message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
476        };
477    }
478    match e.code() {
479        "UNSUPPORTED" => {
480            Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
481        }
482        // The document was checked before: a parse error here means two parsers
483        // disagree, which is a bug.
484        "INTERNAL" | "SXXP0003" => Error::internal(format!(
485            "stylesheet {}{at}: {}: {}",
486            entry.name(),
487            e.code(),
488            e.message()
489        )),
490        code => Error::Transform {
491            stylesheet: entry.name().to_owned(),
492            code: code.to_owned(),
493            line: e.line(),
494            message: e.message().to_owned(),
495        },
496    }
497}
498
499/// The UTF-8 byte order mark.
500const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
501
502/// The text of a document given as bytes: UTF-8, with or without a byte order mark,
503/// and an XML declaration, if any, naming UTF-8 or US-ASCII.
504fn decode(bytes: &[u8]) -> Result<&str, Error> {
505    refuse_utf16(bytes)?;
506    let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
507    check_encoding(bytes)?;
508    std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
509}
510
511/// [`decode`] on a buffer, which becomes the text without being copied (the byte order
512/// mark, if any, is removed in place).
513fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
514    refuse_utf16(&bytes)?;
515    if bytes.starts_with(BOM) {
516        bytes.drain(..BOM.len());
517    }
518    check_encoding(&bytes)?;
519    String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
520}
521
522/// The error for bytes (after the byte order mark) that are not UTF-8.
523fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
524    bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
525}
526
527/// A [`Error::NotXml`] at the byte `valid_up_to` of `bytes` (after the byte order mark).
528fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
529    let before = &bytes[..valid_up_to];
530    let line_start = before
531        .iter()
532        .rposition(|&b| b == b'\n')
533        .map_or(0, |i| i + 1);
534    let line = before.split(|&b| b == b'\n').count();
535    let column = String::from_utf8_lossy(&before[line_start..])
536        .chars()
537        .count()
538        + 1;
539    Error::NotXml {
540        line: u32::try_from(line).unwrap_or(u32::MAX),
541        column: u32::try_from(column).unwrap_or(u32::MAX),
542        message,
543    }
544}
545
546/// Refuses a document that starts with a UTF-16 byte order mark.
547fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
548    if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
549        return Err(Error::unsupported(
550            "a UTF-16 document: only UTF-8 is supported",
551        ));
552    }
553    Ok(())
554}
555
556/// Checks the XML declaration of a document given as bytes (after the byte order mark,
557/// if any): its encoding, if any, must be UTF-8 or US-ASCII, and with US-ASCII every
558/// byte must be ASCII. Whether the bytes are UTF-8 is checked by the caller.
559fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
560    let ascii = match declared_encoding(bytes) {
561        None => false,
562        Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
563        Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
564        Some(e) => {
565            return Err(Error::unsupported(format!(
566                "the {e} encoding: only UTF-8 is supported"
567            )));
568        }
569    };
570    if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
571        return Err(bad_at(
572            bytes,
573            i,
574            "a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
575        ));
576    }
577    Ok(())
578}
579
580/// The `encoding` pseudo-attribute of the XML declaration, if any.
581fn declared_encoding(bytes: &[u8]) -> Option<&str> {
582    let declaration = bytes.strip_prefix(b"<?xml")?;
583    if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
584        return None;
585    }
586    let end = declaration.windows(2).position(|w| w == b"?>")?;
587    let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
588    let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
589    let rest = rest.trim_start().strip_prefix('=')?.trim_start();
590    let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
591    let value = &rest[1..];
592    value.find(quote).map(|end| &value[..end])
593}
594
595/// Checks that the text is namespace-well-formed XML without a document type
596/// declaration, as the stylesheets' parser requires, and without an element nested
597/// deeper than `max_depth`.
598fn check_well_formed(text: &str, max_depth: u32) -> Result<(), Error> {
599    let options = ParsingOptions {
600        allow_dtd: false,
601        nodes_limit: u32::MAX,
602        ..ParsingOptions::default()
603    };
604    match roxmltree::Document::parse_with_options(text, options) {
605        Ok(document) => check_depth(&document, max_depth),
606        Err(roxmltree::Error::DtdDetected) => Err(Error::unsupported(
607            "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
608        )),
609        Err(e) => Err(Error::NotXml {
610            line: e.pos().row,
611            column: e.pos().col,
612            message: e.to_string(),
613        }),
614    }
615}
616
617/// [`Error::Limit`] for the first element, in document order, nested deeper than
618/// `max_depth` (the document element is at depth 1).
619fn check_depth(document: &roxmltree::Document<'_>, max_depth: u32) -> Result<(), Error> {
620    // The elements still open, innermost last: their number is the depth of the parent
621    // of the next element.
622    let mut open: Vec<roxmltree::NodeId> = Vec::new();
623    for node in document
624        .root()
625        .descendants()
626        .filter(roxmltree::Node::is_element)
627    {
628        let parent = node.parent().map(|p| p.id());
629        while open.last().is_some_and(|&id| Some(id) != parent) {
630            open.pop();
631        }
632        if u32::try_from(open.len()).map_or(true, |depth| depth >= max_depth) {
633            let at = document.text_pos_at(node.range().start);
634            let limit = LimitExceeded::Depth {
635                max: max_depth,
636                line: at.row,
637                column: at.col,
638            };
639            return Err(Error::Limit {
640                limit,
641                message: format!("document, {limit}"),
642            });
643        }
644        open.push(node.id());
645    }
646    Ok(())
647}
648
649#[cfg(test)]
650mod tests {
651    use super::*;
652
653    #[test]
654    fn decoding_a_buffer_gives_the_same_result() {
655        for bytes in [
656            &b"<a/>"[..],
657            b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
658            b"<?xml version='1.0' encoding='UTF-8'?><a/>",
659            b"\xFF\xFE<\0a\0/\0>\0",
660            b"\xFE\xFF\0<\0a\0/\0>",
661            b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
662            b"<a>\n  \xC3\xA9\xFF</a>",
663            b"\xEF\xBB\xBF<a>\n\xFF</a>",
664            b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
665            b"\xEF\xBB\xBF",
666            b"",
667        ] {
668            let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
669            let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
670            assert_eq!(owned, borrowed, "{bytes:?}");
671        }
672    }
673
674    #[test]
675    fn decoding() {
676        assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
677        assert_eq!(
678            decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
679            "<?xml version='1.0' encoding='UTF-8'?><a/>"
680        );
681        assert!(matches!(
682            decode(b"\xFF\xFE<\0a\0/\0>\0"),
683            Err(Error::Unsupported { .. })
684        ));
685        assert!(matches!(
686            decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
687            Err(Error::Unsupported { .. })
688        ));
689        match decode(b"<a>\n  \xC3\xA9\xFF</a>") {
690            Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
691            other => panic!("{other:?}"),
692        }
693        match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
694            Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
695            other => panic!("{other:?}"),
696        }
697        assert_eq!(
698            declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
699            None
700        );
701    }
702
703    #[test]
704    fn well_formedness() {
705        assert!(check_well_formed("<a/>", 1).is_ok());
706        match check_well_formed("<a>\n<b></a>", DEFAULT_MAX_DEPTH) {
707            Err(Error::NotXml { line, .. }) => assert_eq!(line, 2),
708            other => panic!("{other:?}"),
709        }
710        assert!(matches!(
711            check_well_formed(
712                "<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
713                DEFAULT_MAX_DEPTH
714            ),
715            Err(Error::Unsupported { .. })
716        ));
717        assert!(matches!(
718            check_well_formed("<p:a/>", DEFAULT_MAX_DEPTH),
719            Err(Error::NotXml { .. })
720        ));
721    }
722
723    #[test]
724    fn checksums() {
725        assert_eq!(
726            sha256_hex(b"abc"),
727            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
728        );
729    }
730
731    #[test]
732    fn errors_are_summarised() {
733        let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
734        let text = first_lines(&many.join("\n"));
735        assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
736    }
737}