docling_core/pdf_repair.rs
1//! What the PDF reader repaired to read a file (#934) — the typed value
2//! `docling_pdf::pdf_repairs` returns and a conversion with
3//! `pdf_report_repairs` carries on its result. It lives here, in the crate
4//! every surface's result type already depends on, so the converter's
5//! `ConversionResult` holds it whatever PDF features are compiled in.
6
7use std::fmt;
8
9use serde::Serialize;
10
11/// One repair the reader makes (or has to give up on) to read the file.
12///
13/// Serialized (serve, Node, Python) as an object tagged by `kind`:
14/// `{"kind": "stream_length", "object": [4, 0], "offset": 202, "declared": 5,
15/// "recovered": 3}`, `{"kind": "xref_entries_padded"}`.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
17#[serde(tag = "kind", rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum PdfRepair {
20 /// lopdf rejects the file, and it loads once the classic cross-reference
21 /// table's 19-byte entries (a bare LF where the spec wants a two-byte
22 /// EOL) are padded to 20 — the reader's fallback for parsers that refuse
23 /// them (lopdf 0.45 itself reads such entries as they are; then no
24 /// repair is taken and none is reported).
25 XrefEntriesPadded,
26 /// A stream whose declared `/Length` does not end at its `endstream`.
27 StreamLength {
28 /// The stream's object number and generation.
29 object: (u32, u16),
30 /// Byte offset of the object's `N G obj` header in the input.
31 offset: usize,
32 /// The declared length: the integer in the dictionary, or the one an
33 /// indirect `/Length N G R` points at. `None` when it is missing,
34 /// negative or not an integer, or the reference does not resolve.
35 declared: Option<i64>,
36 /// The length the reader recovers: the bytes up to the EOL before the
37 /// one `endstream` followed by `endobj` (lopdf's rule, and what pdfium
38 /// trusts). `None` when there is no such boundary or more than one —
39 /// the stream is then dropped, not read.
40 recovered: Option<usize>,
41 },
42}
43
44impl fmt::Display for PdfRepair {
45 /// One line for a log or a CLI: `stream 4 0 at byte 202: /Length 5,
46 /// recovered 3`.
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 PdfRepair::XrefEntriesPadded => {
50 f.write_str("cross-reference entries padded to 20 bytes")
51 }
52 PdfRepair::StreamLength {
53 object: (num, gen),
54 offset,
55 declared,
56 recovered,
57 } => {
58 write!(f, "stream {num} {gen} at byte {offset}: /Length ")?;
59 match declared {
60 Some(n) => write!(f, "{n}")?,
61 None => f.write_str("missing")?,
62 }
63 match recovered {
64 Some(n) => write!(f, ", recovered {n}"),
65 None => f.write_str(", no unambiguous end (stream dropped)"),
66 }
67 }
68 }
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn wire_and_display_forms() {
78 let r = PdfRepair::StreamLength {
79 object: (4, 0),
80 offset: 202,
81 declared: Some(5),
82 recovered: Some(3),
83 };
84 assert_eq!(
85 serde_json::to_string(&r).unwrap(),
86 r#"{"kind":"stream_length","object":[4,0],"offset":202,"declared":5,"recovered":3}"#
87 );
88 assert_eq!(
89 r.to_string(),
90 "stream 4 0 at byte 202: /Length 5, recovered 3"
91 );
92 assert_eq!(
93 serde_json::to_string(&PdfRepair::XrefEntriesPadded).unwrap(),
94 r#"{"kind":"xref_entries_padded"}"#
95 );
96 }
97}