Skip to main content

einvoice_pdf/
error.rs

1//! The error type.
2
3use std::fmt;
4
5/// Where in the input an error was found.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum Location {
9    /// A byte offset in the PDF file.
10    File(usize),
11    /// A byte offset in the decoded data of the object stream with this object number.
12    ObjectStream {
13        /// The object number of the object stream.
14        stream: u32,
15        /// The byte offset in its decoded data.
16        offset: usize,
17    },
18    /// In the object with this object number (no finer position is known).
19    Object(u32),
20}
21
22impl fmt::Display for Location {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::File(offset) => write!(f, "at byte {offset}"),
26            Self::ObjectStream { stream, offset } => {
27                write!(f, "at byte {offset} of object stream {stream}")
28            }
29            Self::Object(number) => write!(f, "in object {number}"),
30        }
31    }
32}
33
34/// Why a file could not be read, or why no invoice could be extracted from it.
35///
36/// A file that uses a PDF feature outside the supported subset is refused with
37/// [`Error::Unsupported`], never read approximately.
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum Error {
41    /// The input does not start with a PDF header (`%PDF-1.x` or `%PDF-2.0`).
42    NotPdf,
43    /// The file is encrypted (its trailer has `/Encrypt`); PDF/A forbids encryption.
44    Encrypted,
45    /// The file breaks the PDF syntax or structure.
46    Malformed {
47        /// Where the problem was found.
48        location: Option<Location>,
49        /// What is wrong.
50        message: String,
51    },
52    /// The file uses a PDF feature this crate does not read.
53    Unsupported {
54        /// Where the feature was found.
55        location: Option<Location>,
56        /// The feature.
57        feature: String,
58    },
59    /// A limit of [`Limits`](crate::Limits) was exceeded.
60    LimitExceeded {
61        /// The limit, by its field name in [`Limits`](crate::Limits).
62        limit: &'static str,
63        /// The value of the limit.
64        value: usize,
65    },
66    /// No embedded file has one of the names of [`INVOICE_FILE_NAMES`](crate::INVOICE_FILE_NAMES).
67    NoInvoice {
68        /// The file names of the embedded files found, in document order.
69        attachments: Vec<String>,
70    },
71    /// More than one embedded file has a name of [`INVOICE_FILE_NAMES`](crate::INVOICE_FILE_NAMES).
72    Ambiguous {
73        /// The names of the candidates, in document order.
74        names: Vec<String>,
75    },
76    /// The XMP metadata stream is not UTF-8, not well-formed XML, or gives conflicting
77    /// values for one property.
78    Metadata(String),
79}
80
81impl Error {
82    pub(crate) fn malformed(location: Option<Location>, message: impl Into<String>) -> Self {
83        Self::Malformed {
84            location,
85            message: message.into(),
86        }
87    }
88
89    pub(crate) fn unsupported(location: Option<Location>, feature: impl Into<String>) -> Self {
90        Self::Unsupported {
91            location,
92            feature: feature.into(),
93        }
94    }
95
96    /// The error with `location` when it has none yet.
97    pub(crate) fn at(self, at: Location) -> Self {
98        match self {
99            Self::Malformed {
100                location: None,
101                message,
102            } => Self::Malformed {
103                location: Some(at),
104                message,
105            },
106            Self::Unsupported {
107                location: None,
108                feature,
109            } => Self::Unsupported {
110                location: Some(at),
111                feature,
112            },
113            other => other,
114        }
115    }
116}
117
118fn suffix(location: Option<&Location>) -> String {
119    location.map_or_else(String::new, |l| format!(" ({l})"))
120}
121
122impl fmt::Display for Error {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        match self {
125            Self::NotPdf => f.write_str("not a PDF file: no %PDF-1.x or %PDF-2.0 header at byte 0"),
126            Self::Encrypted => f.write_str("encrypted PDF (PDF/A forbids encryption)"),
127            Self::Malformed { location, message } => {
128                write!(f, "malformed PDF: {message}{}", suffix(location.as_ref()))
129            }
130            Self::Unsupported { location, feature } => {
131                write!(
132                    f,
133                    "unsupported PDF feature: {feature}{}",
134                    suffix(location.as_ref())
135                )
136            }
137            Self::LimitExceeded { limit, value } => {
138                write!(f, "limit exceeded: {limit} ({value})")
139            }
140            Self::NoInvoice { attachments } => {
141                if attachments.is_empty() {
142                    f.write_str("no embedded invoice: the PDF has no embedded file")
143                } else {
144                    write!(
145                        f,
146                        "no embedded invoice: no embedded file has an invoice name; embedded files: {}",
147                        attachments.join(", ")
148                    )
149                }
150            }
151            Self::Ambiguous { names } => write!(
152                f,
153                "ambiguous embedded invoice: several embedded files have an invoice name: {}",
154                names.join(", ")
155            ),
156            Self::Metadata(message) => write!(f, "XMP metadata: {message}"),
157        }
158    }
159}
160
161impl std::error::Error for Error {}
162
163pub(crate) type Result<T> = std::result::Result<T, Error>;