Skip to main content

justpdf_core/
error.rs

1/// All errors that can occur in justpdf-core.
2#[derive(Debug, thiserror::Error)]
3pub enum JustPdfError {
4    #[error("I/O error: {0}")]
5    Io(#[from] std::io::Error),
6
7    #[error("not a PDF file")]
8    NotPdf,
9
10    #[error("unexpected end of file at offset {offset}")]
11    UnexpectedEof { offset: usize },
12
13    #[error("invalid token at offset {offset}: {detail}")]
14    InvalidToken { offset: usize, detail: String },
15
16    #[error("invalid xref at offset {offset}: {detail}")]
17    InvalidXref { offset: usize, detail: String },
18
19    #[error("object not found: {obj_num} {gen_num} R")]
20    ObjectNotFound { obj_num: u32, gen_num: u16 },
21
22    #[error("stream decode error ({filter}): {detail}")]
23    StreamDecode { filter: String, detail: String },
24
25    #[error("circular reference detected at object {obj_num} {gen_num}")]
26    CircularReference { obj_num: u32, gen_num: u16 },
27
28    #[error("unsupported PDF version: {version}")]
29    UnsupportedVersion { version: String },
30
31    #[error("invalid object definition at offset {offset}: {detail}")]
32    InvalidObject { offset: usize, detail: String },
33
34    #[error("startxref not found")]
35    StartXrefNotFound,
36
37    #[error("trailer not found")]
38    TrailerNotFound,
39
40    #[error("annotation error: {detail}")]
41    AnnotationError { detail: String },
42
43    #[error("form error: {detail}")]
44    FormError { detail: String },
45
46    #[error("encryption error: {detail}")]
47    EncryptionError { detail: String },
48
49    #[error("incorrect password")]
50    IncorrectPassword,
51
52    #[error("unsupported encryption: {detail}")]
53    UnsupportedEncryption { detail: String },
54
55    #[error("document is encrypted, call authenticate() first")]
56    EncryptedDocument,
57
58    #[error("signature error: {detail}")]
59    SignatureError { detail: String },
60
61    #[error("outline error: {detail}")]
62    OutlineError { detail: String },
63
64    #[error("embedded file error: {detail}")]
65    EmbeddedFileError { detail: String },
66
67    #[error("optional content error: {detail}")]
68    OptionalContentError { detail: String },
69
70    #[error("repair error: {detail}")]
71    RepairError { detail: String },
72}
73
74pub type Result<T> = std::result::Result<T, JustPdfError>;
75
76/// Pretty-print a byte slice as a short preview (for error messages).
77#[allow(dead_code)]
78pub(crate) fn preview_bytes(data: &[u8], max_len: usize) -> String {
79    let len = data.len().min(max_len);
80    let s: String = data[..len]
81        .iter()
82        .map(|&b| {
83            if b.is_ascii_graphic() || b == b' ' {
84                b as char
85            } else {
86                '.'
87            }
88        })
89        .collect();
90    if data.len() > max_len {
91        format!("{s}...")
92    } else {
93        s
94    }
95}