use std::fmt;
use einvoice_xpath_eval::LimitExceeded;
pub(crate) const LIMIT: &str = "LIMIT";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrepareError {
pub line: u32,
pub message: String,
}
impl fmt::Display for PrepareError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "line {}: {}", self.line, self.message)
}
}
impl std::error::Error for PrepareError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrepareErrors(pub Vec<PrepareError>);
impl fmt::Display for PrepareErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, error) in self.0.iter().enumerate() {
if i > 0 {
f.write_str("\n")?;
}
write!(f, "{error}")?;
}
Ok(())
}
}
impl std::error::Error for PrepareErrors {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransformError(Box<Inner>);
#[derive(Debug, Clone, PartialEq, Eq)]
struct Inner {
code: String,
message: String,
line: Option<u32>,
limit: Option<LimitExceeded>,
}
impl TransformError {
#[must_use]
pub fn new(code: &str, message: impl Into<String>) -> Self {
Self(Box::new(Inner {
code: code.to_owned(),
message: message.into(),
line: None,
limit: None,
}))
}
#[must_use]
pub fn limit_exceeded(limit: LimitExceeded) -> Self {
Self(Box::new(Inner {
code: LIMIT.to_owned(),
message: limit.to_string(),
line: None,
limit: Some(limit),
}))
}
#[must_use]
pub fn code(&self) -> &str {
&self.0.code
}
#[must_use]
pub fn limit(&self) -> Option<LimitExceeded> {
self.0.limit
}
#[must_use]
pub fn message(&self) -> &str {
&self.0.message
}
#[must_use]
pub fn line(&self) -> Option<u32> {
self.0.line
}
#[must_use]
pub(crate) fn in_document(mut self, uri: &str) -> Self {
self.0.message = format!("{uri}: {}", self.0.message);
self
}
#[must_use]
pub(crate) fn at(mut self, line: u32) -> Self {
if self.0.line.is_none() {
self.0.line = Some(line);
}
self
}
}
impl fmt::Display for TransformError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(line) = self.0.line {
write!(f, "line {line}: ")?;
}
write!(f, "{}: {}", self.0.code, self.0.message)
}
}
impl std::error::Error for TransformError {}
impl From<einvoice_xpath_eval::Error> for TransformError {
fn from(e: einvoice_xpath_eval::Error) -> Self {
Self::new(e.code().as_str(), e.message())
}
}
impl From<einvoice_xdm::XdmError> for TransformError {
fn from(e: einvoice_xdm::XdmError) -> Self {
einvoice_xpath_eval::Error::from(e).into()
}
}
pub(crate) type Result<T> = std::result::Result<T, TransformError>;
pub(crate) fn err<T>(code: &str, message: impl Into<String>) -> Result<T> {
Err(TransformError::new(code, message))
}