use laminapdf_syntax::{ErrorKind, Limit, Location, Position};
use crate::reader::Warning;
use crate::source::SourceError;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Syntax(laminapdf_syntax::Error),
#[error("{} exceeded{}", limit.name(), at.map(|at| format!(" at {at}")).unwrap_or_default())]
LimitExceeded {
limit: Limit,
at: Option<Position>,
},
#[error("strict mode: {}", warning.code())]
Strict {
warning: Warning,
},
#[error("input bytes not available yet: {ranges:?}")]
DataPending {
ranges: Vec<(u64, u64)>,
},
#[error(transparent)]
Source(SourceError),
#[error("not a PDF: {0}")]
NotPdf(&'static str),
#[error("no document catalog (/Root) found")]
MissingRoot,
#[error("reference cycle detected at object {0}")]
ReferenceCycle(u32),
#[error("type error: expected {expected} for {context}")]
Type {
expected: &'static str,
context: &'static str,
},
#[error("invalid {kind}: {message}")]
InvalidStructure {
kind: &'static str,
message: &'static str,
},
#[error("object {0} was reserved but never set")]
UnsetObject(u32),
#[error("cannot append an incremental update to a document whose xref needed repair")]
RepairedBase,
#[error("cannot save an encrypted document yet")]
EncryptedBase,
#[error("the document needs a password")]
PasswordRequired,
#[error("wrong password")]
WrongPassword,
#[error("unsupported security handler (V {version:?}, R {revision:?})")]
UnsupportedSecurityHandler {
filter: String,
version: Option<i64>,
revision: Option<i64>,
},
}
impl From<laminapdf_syntax::Error> for Error {
fn from(e: laminapdf_syntax::Error) -> Self {
match e {
laminapdf_syntax::Error::LimitExceeded { limit, at } => Self::LimitExceeded { limit, at },
other => Self::Syntax(other),
}
}
}
impl From<SourceError> for Error {
fn from(e: SourceError) -> Self {
match e {
SourceError::Pending { offset, len } => Self::DataPending {
ranges: vec![(offset, len)],
},
other => Self::Source(other),
}
}
}
impl Error {
pub const CODES: &'static [&'static str] = &[
"not-pdf",
"missing-root",
"reference-cycle",
"limit-exceeded",
"strict",
"data-pending",
"source",
"type",
"invalid-structure",
"unset-object",
"repaired-base",
"encrypted-base",
"password-required",
"wrong-password",
"unsupported-security-handler",
"unexpected-eof",
"syntax",
"unsupported-filter",
"decompress",
];
#[must_use]
pub const fn code(&self) -> &'static str {
match self {
Self::Syntax(e) => e.code(),
Self::LimitExceeded { .. } => "limit-exceeded",
Self::Strict { .. } => "strict",
Self::DataPending { .. } => "data-pending",
Self::Source(_) => "source",
Self::NotPdf(_) => "not-pdf",
Self::MissingRoot => "missing-root",
Self::ReferenceCycle(_) => "reference-cycle",
Self::Type { .. } => "type",
Self::InvalidStructure { .. } => "invalid-structure",
Self::UnsetObject(_) => "unset-object",
Self::RepairedBase => "repaired-base",
Self::EncryptedBase => "encrypted-base",
Self::PasswordRequired => "password-required",
Self::WrongPassword => "wrong-password",
Self::UnsupportedSecurityHandler { .. } => "unsupported-security-handler",
}
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
match self {
Self::Syntax(e) => e.kind(),
Self::Strict { .. }
| Self::NotPdf(_)
| Self::MissingRoot
| Self::ReferenceCycle(_)
| Self::Type { .. }
| Self::InvalidStructure { .. } => ErrorKind::Input,
Self::LimitExceeded { .. } => ErrorKind::Limit,
Self::DataPending { .. } | Self::RepairedBase => ErrorKind::State,
Self::Source(_) => ErrorKind::Io,
Self::UnsetObject(_) => ErrorKind::Internal,
Self::EncryptedBase | Self::UnsupportedSecurityHandler { .. } => ErrorKind::Unsupported,
Self::PasswordRequired | Self::WrongPassword => ErrorKind::Security,
}
}
#[must_use]
pub fn location(&self) -> Location {
match self {
Self::Syntax(e) => e.location(),
Self::LimitExceeded { at, .. } => Location::from(*at),
Self::Strict { warning } => warning.location(),
Self::Source(SourceError::Failed { offset, .. }) => Location::from(Position::FileOffset(*offset)),
Self::ReferenceCycle(object) | Self::UnsetObject(object) => Location::object(Some(*object)),
_ => Location::NONE,
}
}
#[must_use]
pub(crate) fn map_position(self, f: impl FnOnce(Position) -> Position) -> Self {
match self {
Self::Syntax(e) => Self::Syntax(e.map_position(f)),
Self::LimitExceeded { limit, at } => Self::LimitExceeded { limit, at: at.map(f) },
other => other,
}
}
#[must_use]
pub const fn must_propagate(&self) -> bool {
matches!(self, Self::Strict { .. } | Self::DataPending { .. } | Self::Source(_))
}
#[must_use]
pub const fn ends_page_walk(&self) -> bool {
matches!(self, Self::ReferenceCycle(_)) || self.must_propagate()
}
#[must_use]
pub const fn is_security_refusal(&self) -> bool {
matches!(
self,
Self::PasswordRequired | Self::WrongPassword | Self::UnsupportedSecurityHandler { .. }
)
}
pub(crate) const fn is_read_window_limit(&self) -> bool {
matches!(
self,
Self::LimitExceeded {
limit: Limit::ReadWindow,
..
}
)
}
pub(crate) const fn limit_at_object(limit: Limit, num: u32) -> Self {
Self::LimitExceeded {
limit,
at: Some(Position::Object(num)),
}
}
}
pub type Result<T> = core::result::Result<T, Error>;
pub fn tolerant<T>(result: Result<T>) -> Result<Option<T>> {
match result {
Ok(v) => Ok(Some(v)),
Err(e) if e.must_propagate() => Err(e),
Err(_) => Ok(None),
}
}
pub fn absent_if_malformed<T>(result: Result<T>) -> Result<Option<T>> {
match result {
Ok(value) => Ok(Some(value)),
Err(e) if e.must_propagate() || matches!(e, Error::ReferenceCycle(_) | Error::LimitExceeded { .. }) => Err(e),
Err(_) => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_codes as codes;
fn samples() -> Vec<Error> {
let at = Position::FileOffset(0);
let syntax = [
laminapdf_syntax::Error::UnexpectedEof { at },
laminapdf_syntax::Error::Syntax { at, message: "m" },
laminapdf_syntax::Error::Type {
expected: "name",
context: "/Filter",
},
laminapdf_syntax::Error::UnsupportedFilter(String::new()),
laminapdf_syntax::Error::Decompress("m"),
laminapdf_syntax::Error::InvalidStructure {
kind: "k",
message: "m",
},
];
let mut all = vec![
Error::NotPdf("m"),
Error::MissingRoot,
Error::ReferenceCycle(1),
Error::LimitExceeded {
limit: Limit::ResolveDepth,
at: None,
},
Error::Strict {
warning: Warning::XrefRepaired,
},
Error::DataPending { ranges: Vec::new() },
Error::Source(SourceError::Failed { offset: 0, len: 1 }),
Error::Type {
expected: "dictionary",
context: "/Kids",
},
Error::InvalidStructure {
kind: "k",
message: "m",
},
Error::UnsetObject(1),
Error::RepairedBase,
Error::EncryptedBase,
Error::PasswordRequired,
Error::WrongPassword,
Error::UnsupportedSecurityHandler {
filter: String::new(),
version: None,
revision: None,
},
];
all.extend(syntax.into_iter().map(Error::Syntax));
all
}
#[test]
fn codes_lists_the_code_of_every_variant_in_order() {
assert_eq!(codes::distinct(samples().iter().map(Error::code)), Error::CODES);
}
#[test]
fn every_variant_has_the_kind_codes_json_lists() {
codes::assert_kinds_match(samples().iter().map(|e| (e.code(), e.kind().as_str())));
}
}