use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Location {
File(usize),
ObjectStream {
stream: u32,
offset: usize,
},
Object(u32),
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::File(offset) => write!(f, "at byte {offset}"),
Self::ObjectStream { stream, offset } => {
write!(f, "at byte {offset} of object stream {stream}")
}
Self::Object(number) => write!(f, "in object {number}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
NotPdf,
Encrypted,
Malformed {
location: Option<Location>,
message: String,
},
Unsupported {
location: Option<Location>,
feature: String,
},
LimitExceeded {
limit: &'static str,
value: usize,
},
NoInvoice {
attachments: Vec<String>,
},
Ambiguous {
names: Vec<String>,
},
Metadata(String),
}
impl Error {
pub(crate) fn malformed(location: Option<Location>, message: impl Into<String>) -> Self {
Self::Malformed {
location,
message: message.into(),
}
}
pub(crate) fn unsupported(location: Option<Location>, feature: impl Into<String>) -> Self {
Self::Unsupported {
location,
feature: feature.into(),
}
}
pub(crate) fn at(self, at: Location) -> Self {
match self {
Self::Malformed {
location: None,
message,
} => Self::Malformed {
location: Some(at),
message,
},
Self::Unsupported {
location: None,
feature,
} => Self::Unsupported {
location: Some(at),
feature,
},
other => other,
}
}
}
fn suffix(location: Option<&Location>) -> String {
location.map_or_else(String::new, |l| format!(" ({l})"))
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotPdf => f.write_str("not a PDF file: no %PDF-1.x or %PDF-2.0 header at byte 0"),
Self::Encrypted => f.write_str("encrypted PDF (PDF/A forbids encryption)"),
Self::Malformed { location, message } => {
write!(f, "malformed PDF: {message}{}", suffix(location.as_ref()))
}
Self::Unsupported { location, feature } => {
write!(
f,
"unsupported PDF feature: {feature}{}",
suffix(location.as_ref())
)
}
Self::LimitExceeded { limit, value } => {
write!(f, "limit exceeded: {limit} ({value})")
}
Self::NoInvoice { attachments } => {
if attachments.is_empty() {
f.write_str("no embedded invoice: the PDF has no embedded file")
} else {
write!(
f,
"no embedded invoice: no embedded file has an invoice name; embedded files: {}",
attachments.join(", ")
)
}
}
Self::Ambiguous { names } => write!(
f,
"ambiguous embedded invoice: several embedded files have an invoice name: {}",
names.join(", ")
),
Self::Metadata(message) => write!(f, "XMP metadata: {message}"),
}
}
}
impl std::error::Error for Error {}
pub(crate) type Result<T> = std::result::Result<T, Error>;