Skip to main content

rustium_pdf/
error.rs

1//! Error type. One enum, no dependency on an error-derive crate.
2
3use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Debug)]
8pub enum Error {
9    /// The file could not be read from disk.
10    Io(std::io::Error),
11    /// The file is not a PDF or its cross-reference structure is beyond repair.
12    Parse(String),
13    /// The document is encrypted and the supplied password does not open it.
14    Password,
15    /// The document uses an encryption scheme this crate does not implement.
16    UnsupportedEncryption(String),
17    /// A page index past the end of the document.
18    PageOutOfRange(usize),
19    /// A page exists but its content could not be processed.
20    Page { index: usize, message: String },
21    /// Rendering failed (allocation, encoding).
22    Render(String),
23}
24
25impl fmt::Display for Error {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Error::Io(e) => write!(f, "io error: {e}"),
29            Error::Parse(m) => write!(f, "malformed pdf: {m}"),
30            Error::Password => write!(f, "invalid password"),
31            Error::UnsupportedEncryption(m) => write!(f, "unsupported encryption: {m}"),
32            Error::PageOutOfRange(i) => write!(f, "page index {i} out of range"),
33            Error::Page { index, message } => write!(f, "page {index}: {message}"),
34            Error::Render(m) => write!(f, "render error: {m}"),
35        }
36    }
37}
38
39impl std::error::Error for Error {
40    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41        match self {
42            Error::Io(e) => Some(e),
43            _ => None,
44        }
45    }
46}
47
48impl From<std::io::Error> for Error {
49    fn from(e: std::io::Error) -> Self {
50        Error::Io(e)
51    }
52}