use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
pub kind: ErrorKind,
pub path: String,
pub offset: u64,
pub expected: String,
pub found: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Syntax,
NotDatex2,
UnknownPublication,
UnexpectedPublication,
MissingRequired,
InvalidCount,
InvalidValue,
InvalidExtension,
LimitExceeded,
DoctypeNotAllowed,
UnsupportedEncoding,
Io,
}
impl ErrorKind {
fn text(self) -> &'static str {
match self {
Self::Syntax => "malformed XML",
Self::NotDatex2 => "not a DATEX II document of this version",
Self::UnknownPublication => "unknown publication type",
Self::UnexpectedPublication => "publication without such records",
Self::MissingRequired => "required content missing",
Self::InvalidCount => "wrong number of elements",
Self::InvalidValue => "value not allowed by the schema",
Self::InvalidExtension => "extension content not allowed",
Self::LimitExceeded => "limit exceeded",
Self::DoctypeNotAllowed => {
"document type declarations and custom entities are not allowed"
}
Self::UnsupportedEncoding => "unsupported encoding",
Self::Io => "read error",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: expected {}, found {}",
self.kind.text(),
self.expected,
self.found
)?;
write_place(f, &self.path, self.offset)
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning {
pub kind: WarningKind,
pub path: String,
pub offset: u64,
pub detail: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum WarningKind {
LevelCNamespace,
WrongNamespace,
MissingXsiType,
UnknownElement,
UnknownAttribute,
UnknownType,
UnexpectedType,
UnknownEnumValue,
InvalidValue,
EmptyValue,
NoTimeZone,
MissingElement,
MissingAttribute,
UnexpectedPublication,
Repeated,
}
impl WarningKind {
fn text(self) -> &'static str {
match self {
Self::LevelCNamespace => "Level C namespace read as standard",
Self::WrongNamespace => "element in another DATEX II namespace",
Self::MissingXsiType => "publication type inferred",
Self::UnknownElement => "unknown element skipped",
Self::UnknownAttribute => "unknown attribute skipped",
Self::UnknownType => "unknown type skipped",
Self::UnexpectedType => "unexpected type ignored",
Self::UnknownEnumValue => "unknown enumeration value kept as extended",
Self::InvalidValue => "invalid value dropped",
Self::EmptyValue => "empty value treated as absent",
Self::NoTimeZone => "timestamp without time zone",
Self::MissingElement => "missing element",
Self::MissingAttribute => "missing attribute",
Self::UnexpectedPublication => "publication without such records skipped",
Self::Repeated => "repeated element ignored",
}
}
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.kind.text(), self.detail)?;
write_place(f, &self.path, self.offset)
}
}
fn write_place(f: &mut fmt::Formatter<'_>, path: &str, offset: u64) -> fmt::Result {
if path.is_empty() {
write!(f, " at document start (byte {offset})")
} else {
write!(f, " at {path} (byte {offset})")
}
}
const QUOTE_MAX: usize = 80;
pub(crate) fn quote(text: &str) -> String {
format!("\"{}\"", clean(text, QUOTE_MAX))
}
pub(crate) fn parser_message(text: &str) -> String {
clean(text, 2 * QUOTE_MAX)
}
fn clean(text: &str, max: usize) -> String {
let mut out = String::with_capacity(text.len().min(max) + 2);
for (n, c) in text.chars().enumerate() {
if n == max {
out.push('…');
break;
}
if c.is_control() || c == '\u{2028}' || c == '\u{2029}' {
out.extend(c.escape_unicode());
} else {
out.push(c);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quote_escapes_and_shortens() {
assert_eq!(quote("a\nb\u{1b}[31m"), "\"a\\u{a}b\\u{1b}[31m\"");
let long = quote(&"x".repeat(10_000));
assert_eq!(long.chars().count(), QUOTE_MAX + 3);
}
#[test]
fn display_is_one_line() {
let e = Error {
kind: ErrorKind::Syntax,
path: "payload/situation".into(),
offset: 42,
expected: "well-formed XML".into(),
found: quote("abc"),
};
assert_eq!(
e.to_string(),
"malformed XML: expected well-formed XML, found \"abc\" at payload/situation (byte 42)"
);
}
}