docling-pdf 2.84.0

PDF/image backend for docling.rs: pure-Rust text layer and page renderer + ONNX layout/table/OCR pipeline.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! What the PDF reader had to repair to read a file (#934): typed provenance
//! for callers that must tell recovered input from well-formed input — an
//! admission guard refusing repaired sources, say.
//!
//! The reader repairs silently, by design (degradation over failure): lopdf
//! 0.45 recovers a stream whose `/Length` does not end at `endstream` by
//! searching for the unambiguous `endstream … endobj` boundary, and then
//! `Stream::new` overwrites `/Length` with the recovered size — the declared
//! value and the fact of the repair do not survive in the loaded object, only
//! in a `log::warn!`. [`crate::textparse`]'s own repairs (19-byte xref entries
//! padded to 20, overstated lengths rewritten in place) leave no trace either.
//! So this reads the *original* bytes once more, on demand, with lopdf's own
//! stream grammar — `dict space "stream" space0 eol`, then exactly `/Length`
//! bytes, an optional EOL and `endstream` — and reports every stream that
//! fails it, with the declared and the recovered length. A conversion runs
//! it only when asked (`pdf_report_repairs`, off by default), and the
//! document it produces is the same either way.

use std::collections::HashMap;

pub use docling_core::PdfRepair;

/// Every repair reading `bytes` takes (#934), in file order; empty for a
/// well-formed file. The input as given — encrypted files included, whose
/// lengths are those of the encrypted bytes. Cost: one linear pass over the
/// file and one lopdf load (a second when the xref needs its repair).
///
/// Unbounded and infallible: a file lopdf cannot load is scanned anyway, and
/// an empty list cannot tell "well-formed" from "not inspected". A caller
/// that must bound the decoding or see a failure uses [`try_pdf_repairs`].
pub fn pdf_repairs(bytes: &[u8]) -> Vec<PdfRepair> {
    let mut repairs = Vec::new();
    let doc = load(bytes, &mut repairs, None).ok();
    scan_repairs(bytes, &scan_objects(bytes), doc.as_ref(), repairs)
}

/// Why [`try_pdf_repairs`] could not inspect a file (#938).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RepairInspectError {
    /// A stream the load must decode (a cross-reference stream) would
    /// inflate past the caller's `max_decompressed_size`; the repairs of a
    /// file whose structure is not fully read cannot be called complete.
    LimitExceeded {
        /// The bound that was exceeded, in bytes.
        limit: usize,
    },
    /// The load returned a document, but without an object stream — it
    /// inflates past the bound, or is damaged — and so without the objects in
    /// it, an indirect `/Length` among them: the list would not be complete.
    ObjectStreamSkipped {
        /// The object stream's number and generation.
        object: (u32, u16),
    },
    /// lopdf cannot load the file, even with the reader's xref repair.
    Unreadable,
}

impl std::fmt::Display for RepairInspectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::LimitExceeded { limit } => {
                write!(f, "a stream decodes past the {limit}-byte limit")
            }
            Self::ObjectStreamSkipped { object: (num, gen) } => {
                write!(f, "object stream {num} {gen} was not read within the limit")
            }
            Self::Unreadable => f.write_str("the PDF cannot be loaded"),
        }
    }
}

impl std::error::Error for RepairInspectError {}

/// [`pdf_repairs`] with a caller-supplied bound on what one stream may decode
/// to (#938), and a failure channel: `Ok` is a *complete* repair list — empty
/// for a well-formed file — never a partial one.
///
/// `max_decompressed_size` caps every stream the load decodes (lopdf's
/// `LoadOptions::max_decompressed_size`: object streams, cross-reference
/// streams); `None` is unbounded, as in [`pdf_repairs`]. lopdf's lenient load
/// *skips* an oversized object stream and returns the document without its
/// objects, while its strict load stops at the first malformed stream — which
/// is exactly the repair this reports — so neither alone is usable. The load
/// here stays lenient and every `/Type /ObjStm` of the result is decoded once
/// more under the bound, so an omission is an [`Err`] instead of a silent gap
/// (an indirect `/Length` living in the skipped stream would otherwise read
/// as unresolved).
pub fn try_pdf_repairs(
    bytes: &[u8],
    max_decompressed_size: Option<usize>,
) -> Result<Vec<PdfRepair>, RepairInspectError> {
    let mut repairs = Vec::new();
    let doc = load(bytes, &mut repairs, max_decompressed_size)?;
    let objects = scan_objects(bytes);
    if max_decompressed_size.is_some() {
        // A bounded load that skips an object stream drops the stream object
        // itself from the document (lopdf's reader), so a `/Type /ObjStm` the
        // raw scan sees but the document lacks is a stream the bound — or
        // damage — kept unread. lopdf's strict load cannot say which: it stops
        // at the first malformed stream, a repair this reports, before it
        // reaches the oversized one.
        if let Some(o) = objects
            .iter()
            .find(|o| o.objstm && !doc.objects.contains_key(&o.id))
        {
            return Err(RepairInspectError::ObjectStreamSkipped { object: o.id });
        }
    }
    Ok(scan_repairs(bytes, &objects, Some(&doc), repairs))
}

/// The one load: a file lopdf reads as it is, or — the reader's xref repair —
/// once its 19-byte entries are padded.
fn load(
    bytes: &[u8],
    repairs: &mut Vec<PdfRepair>,
    limit: Option<usize>,
) -> Result<lopdf::Document, RepairInspectError> {
    let options = lopdf::LoadOptions {
        max_decompressed_size: limit,
        ..lopdf::LoadOptions::default()
    };
    let over = |e: &lopdf::Error| {
        matches!(
            e,
            lopdf::Error::Decompress(lopdf::DecompressError::MemoryLimitExceeded { .. })
        )
    };
    let err = match lopdf::Document::load_mem_with_options(bytes, options.clone()) {
        Ok(doc) => return Ok(doc),
        Err(err) => err,
    };
    if let (Some(limit), true) = (limit, over(&err)) {
        return Err(RepairInspectError::LimitExceeded { limit });
    }
    let fixed = crate::textparse::pad_short_xref_entries(bytes)
        .map_err(|_| RepairInspectError::Unreadable)?;
    match lopdf::Document::load_mem_with_options(&fixed, options) {
        Ok(doc) => {
            repairs.push(PdfRepair::XrefEntriesPadded);
            Ok(doc)
        }
        Err(e) => Err(match (limit, over(&e)) {
            (Some(limit), true) => RepairInspectError::LimitExceeded { limit },
            _ => RepairInspectError::Unreadable,
        }),
    }
}

/// The stream-length repairs found by one raw scan of `bytes`, after
/// `repairs` (the load's own).
fn scan_repairs(
    bytes: &[u8],
    objects: &[RawObject],
    doc: Option<&lopdf::Document>,
    mut repairs: Vec<PdfRepair>,
) -> Vec<PdfRepair> {
    let integers: HashMap<(u32, u16), i64> = objects
        .iter()
        .filter_map(|o| Some((o.id, o.integer?)))
        .collect();
    // An indirect length can live in an object stream (PDF 1.5+), out of
    // the raw scan's reach: ask the loaded document — integers are not
    // touched by any repair.
    let resolve = |id: (u32, u16)| -> Option<i64> {
        if let Some(&n) = integers.get(&id) {
            return Some(n);
        }
        doc?.get_object(id).ok()?.as_i64().ok()
    };
    for o in objects {
        let Some(stream) = &o.stream else { continue };
        let declared = match stream.length {
            Some(LengthValue::Direct(n)) => Some(n),
            Some(LengthValue::Ref(id)) => resolve(id),
            None => None,
        }
        .filter(|&n| n >= 0);
        let ends_at_endstream = declared
            .and_then(|n| usize::try_from(n).ok())
            .and_then(|n| stream.data.checked_add(n))
            .is_some_and(|end| ends_at_endstream(bytes, end));
        if !ends_at_endstream {
            repairs.push(PdfRepair::StreamLength {
                object: o.id,
                offset: o.offset,
                declared,
                recovered: recover_length(bytes, stream.data),
            });
        }
    }
    repairs
}

/// lopdf's acceptance test: `take(length)`, an optional EOL, `endstream`.
fn ends_at_endstream(bytes: &[u8], end: usize) -> bool {
    let Some(rest) = bytes.get(end..) else {
        return false;
    };
    let rest = rest
        .strip_prefix(b"\r\n")
        .or_else(|| rest.strip_prefix(b"\n"))
        .or_else(|| rest.strip_prefix(b"\r"))
        .unwrap_or(rest);
    rest.starts_with(b"endstream")
}

/// lopdf's `recover_stream_length`: the data runs to the EOL before the one
/// `endstream` that is followed by whitespace and `endobj`; none, or two
/// candidates before the next object, recover nothing (lopdf bounds its
/// search by the next object's xref offset; the next `N G obj` header here).
fn recover_length(bytes: &[u8], data: usize) -> Option<usize> {
    let window = &bytes[data..];
    let (first_end, after_first) = boundary(window, 0)?;
    let bound = next_object_header(window, after_first).unwrap_or(window.len());
    match boundary(&window[..bound], after_first) {
        Some(_) => None,
        None => Some(first_end),
    }
}

/// The first `EOL endstream space endobj` in `window` from `from`: the data
/// end before it and the offset after its `endstream`.
fn boundary(window: &[u8], from: usize) -> Option<(usize, usize)> {
    const ENDSTREAM: &[u8] = b"endstream";
    let mut at = from;
    while let Some(rel) = find(&window[at..], ENDSTREAM) {
        let pos = at + rel;
        at = pos + ENDSTREAM.len();
        let before = &window[..pos];
        let data_end = if before.ends_with(b"\r\n") {
            pos - 2
        } else if before.ends_with(b"\n") || before.ends_with(b"\r") {
            pos - 1
        } else {
            continue;
        };
        let after = &window[at..];
        let ws = after.iter().take_while(|&&c| is_whitespace(c)).count();
        if !after[ws..].starts_with(b"endobj")
            || after.get(ws + 6).is_some_and(|&c| !is_whitespace(c))
        {
            continue;
        }
        return Some((data_end, at));
    }
    None
}

/// The offset of the next `N G obj` header in `window` from `from`.
fn next_object_header(window: &[u8], from: usize) -> Option<usize> {
    let mut at = from;
    while let Some(rel) = find(&window[at..], b"obj") {
        let kw = at + rel;
        at = kw + 3;
        if header_before(window, kw).is_some() {
            return Some(kw);
        }
    }
    None
}

/// A stream's declared length as written.
enum LengthValue {
    Direct(i64),
    Ref((u32, u16)),
}

struct StreamInfo {
    /// `/Length` in the dictionary, if any.
    length: Option<LengthValue>,
    /// Offset of the first data byte (after `stream` and its EOL).
    data: usize,
}

struct RawObject {
    id: (u32, u16),
    offset: usize,
    /// The object's value when it is a bare integer — an indirect length.
    integer: Option<i64>,
    stream: Option<StreamInfo>,
    /// A stream dictionary with `/Type /ObjStm`.
    objstm: bool,
}

/// Every `N G obj` in the file, front to back, skipping stream data so that
/// binary content is never read as syntax. Objects inside object streams
/// cannot be streams (ISO 32000 7.5.7), so the top level is all there is.
fn scan_objects(bytes: &[u8]) -> Vec<RawObject> {
    let mut objects = Vec::new();
    let mut at = 0;
    while let Some(rel) = find(&bytes[at..], b"obj") {
        let kw = at + rel;
        at = kw + 3;
        // `obj` as a keyword: not `endobj`, followed by a delimiter.
        if bytes
            .get(kw + 3)
            .is_some_and(|&c| !is_whitespace(c) && !is_delimiter(c))
        {
            continue;
        }
        let Some((id, offset)) = header_before(bytes, kw) else {
            continue;
        };
        let body = skip_space(bytes, kw + 3);
        let mut object = RawObject {
            id,
            offset,
            integer: None,
            stream: None,
            objstm: false,
        };
        if bytes[body..].starts_with(b"<<") {
            let Some((dict_end, length, objstm)) = dictionary(bytes, body) else {
                objects.push(object);
                continue;
            };
            let after = skip_space(bytes, dict_end);
            if bytes[after..].starts_with(b"stream") {
                let mut data = after + 6;
                while matches!(bytes.get(data), Some(b' ' | b'\t')) {
                    data += 1;
                }
                if bytes[data..].starts_with(b"\r\n") {
                    data += 2;
                } else if matches!(bytes.get(data), Some(b'\n' | b'\r')) {
                    data += 1;
                } else {
                    // No EOL after `stream`: not a stream lopdf reads either.
                    objects.push(object);
                    at = after + 6;
                    continue;
                }
                // Resume past the data: at the declared end when it holds
                // (direct lengths only — an indirect one is resolved later),
                // else at the `endstream` that follows.
                at = match &length {
                    Some(LengthValue::Direct(n))
                        if usize::try_from(*n)
                            .ok()
                            .and_then(|n| data.checked_add(n))
                            .is_some_and(|end| ends_at_endstream(bytes, end)) =>
                    {
                        data + *n as usize
                    }
                    _ => find(&bytes[data..], b"endstream").map_or(bytes.len(), |r| data + r),
                };
                object.stream = Some(StreamInfo { length, data });
                object.objstm = objstm;
            } else {
                at = dict_end;
            }
        } else {
            let (value, end) = integer(bytes, body);
            if let Some(v) = value {
                if bytes[skip_space(bytes, end)..].starts_with(b"endobj") {
                    object.integer = Some(v);
                }
            }
        }
        objects.push(object);
    }
    objects
}

/// `N G` immediately before the `obj` keyword at `kw`, at a token boundary:
/// the object id and the offset of `N`.
fn header_before(bytes: &[u8], kw: usize) -> Option<((u32, u16), usize)> {
    let mut i = kw;
    let ws_end = i;
    while i > 0 && is_whitespace(bytes[i - 1]) {
        i -= 1;
    }
    if i == ws_end {
        return None;
    }
    let gen_end = i;
    while i > 0 && bytes[i - 1].is_ascii_digit() {
        i -= 1;
    }
    let gen = std::str::from_utf8(&bytes[i..gen_end])
        .ok()?
        .parse::<u16>()
        .ok()?;
    let sp = i;
    while i > 0 && is_whitespace(bytes[i - 1]) {
        i -= 1;
    }
    if i == sp {
        return None;
    }
    let num_end = i;
    while i > 0 && bytes[i - 1].is_ascii_digit() {
        i -= 1;
    }
    let num = std::str::from_utf8(&bytes[i..num_end])
        .ok()?
        .parse::<u32>()
        .ok()?;
    if i > 0 && !is_whitespace(bytes[i - 1]) && !is_delimiter(bytes[i - 1]) {
        return None;
    }
    Some(((num, gen), i))
}

/// The dictionary opening at `start` (`<<`): the offset just past its `>>`
/// and its top-level `/Length` value. Strings, hex strings, comments and
/// nested dictionaries are skipped, so `>>` or `/Length` inside them do not
/// count; `/Length1`–`/Length3` (font programs) are other keys.
fn dictionary(bytes: &[u8], start: usize) -> Option<(usize, Option<LengthValue>, bool)> {
    let mut depth = 0usize;
    let mut i = start;
    let mut length = None;
    let mut objstm = false;
    while i < bytes.len() {
        match bytes[i] {
            b'<' if bytes.get(i + 1) == Some(&b'<') => {
                depth += 1;
                i += 2;
            }
            b'>' if bytes.get(i + 1) == Some(&b'>') => {
                depth -= 1;
                i += 2;
                if depth == 0 {
                    return Some((i, length, objstm));
                }
            }
            b'<' => {
                i = bytes[i..]
                    .iter()
                    .position(|&c| c == b'>')
                    .map(|p| i + p + 1)?
            }
            b'(' => i = literal_string_end(bytes, i)?,
            b'%' => {
                while i < bytes.len() && !matches!(bytes[i], b'\r' | b'\n') {
                    i += 1;
                }
            }
            b'/' => {
                let name_end = i
                    + 1
                    + bytes[i + 1..]
                        .iter()
                        .take_while(|&&c| !is_whitespace(c) && !is_delimiter(c))
                        .count();
                if depth == 1 && &bytes[i + 1..name_end] == b"Length" {
                    length = length_value(bytes, name_end);
                }
                if depth == 1 && &bytes[i + 1..name_end] == b"Type" {
                    let at = skip_space(bytes, name_end);
                    objstm = bytes[at..].starts_with(b"/ObjStm");
                }
                i = name_end;
            }
            _ => i += 1,
        }
    }
    None
}

/// `/Length`'s value at `at`: an integer, or `N G R`.
fn length_value(bytes: &[u8], at: usize) -> Option<LengthValue> {
    let (first, end) = integer(bytes, skip_space(bytes, at));
    let first = first?;
    let (gen, gen_end) = integer(bytes, skip_space(bytes, end));
    if let Some(gen) = gen {
        let r = skip_space(bytes, gen_end);
        if bytes.get(r) == Some(&b'R')
            && bytes
                .get(r + 1)
                .is_none_or(|&c| is_whitespace(c) || is_delimiter(c))
        {
            return Some(LengthValue::Ref((
                u32::try_from(first).ok()?,
                u16::try_from(gen).ok()?,
            )));
        }
    }
    Some(LengthValue::Direct(first))
}

/// A signed integer token at `at` (not a real: `3.0` is not an integer), and
/// the offset after it.
fn integer(bytes: &[u8], at: usize) -> (Option<i64>, usize) {
    let mut i = at;
    if matches!(bytes.get(i), Some(b'+' | b'-')) {
        i += 1;
    }
    let digits = bytes[i.min(bytes.len())..]
        .iter()
        .take_while(|c| c.is_ascii_digit())
        .count();
    let end = i + digits;
    if digits == 0 || bytes.get(end) == Some(&b'.') {
        return (None, at);
    }
    let value = std::str::from_utf8(&bytes[at..end])
        .ok()
        .and_then(|s| s.parse().ok());
    (value, end)
}

/// Past the `)` closing the literal string opening at `start`: balanced
/// parentheses, backslash escapes.
fn literal_string_end(bytes: &[u8], start: usize) -> Option<usize> {
    let mut depth = 0usize;
    let mut i = start;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 1,
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// Past whitespace and comments (lopdf's `space`).
fn skip_space(bytes: &[u8], mut i: usize) -> usize {
    loop {
        while i < bytes.len() && is_whitespace(bytes[i]) {
            i += 1;
        }
        if bytes.get(i) == Some(&b'%') {
            while i < bytes.len() && !matches!(bytes[i], b'\r' | b'\n') {
                i += 1;
            }
        } else {
            return i;
        }
    }
}

fn is_whitespace(c: u8) -> bool {
    b" \t\n\r\0\x0C".contains(&c)
}

fn is_delimiter(c: u8) -> bool {
    b"()<>[]{}/%".contains(&c)
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// #934's reproduction: a one-page PDF whose content stream `q Q\n` (4
    /// bytes up to `endstream`) declares `declared` bytes, and `objects`
    /// spliced in after it.
    fn pdf(length: &str, extra: &[&str]) -> Vec<u8> {
        let mut objects = vec![
            "<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_owned(),
            format!("<< /Length {length} >>\nstream\nq Q\nendstream"),
        ];
        objects.extend(extra.iter().map(|s| s.to_string()));
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let mut offsets = vec![0];
        for (i, object) in objects.iter().enumerate() {
            offsets.push(bytes.len());
            bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
        }
        let xref = bytes.len();
        let n = objects.len() + 1;
        bytes.extend_from_slice(format!("xref\n0 {n}\n0000000000 65535 f \n").as_bytes());
        for offset in &offsets[1..] {
            bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        bytes.extend_from_slice(
            format!("trailer\n<< /Size {n} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
        );
        bytes
    }

    #[test]
    fn a_well_formed_file_reports_nothing() {
        // 4 = `q Q\n` (the EOL before `endstream` counted), 3 = `q Q`: lopdf
        // accepts both — the EOL after the data is optional.
        assert_eq!(pdf_repairs(&pdf("4", &[])), []);
        assert_eq!(pdf_repairs(&pdf("3", &[])), []);
    }

    #[test]
    fn an_overstated_length_is_reported_with_both_lengths() {
        let bytes = pdf("5", &[]);
        let offset = find(&bytes, b"4 0 obj").unwrap();
        assert_eq!(
            pdf_repairs(&bytes),
            [PdfRepair::StreamLength {
                object: (4, 0),
                offset,
                declared: Some(5),
                recovered: Some(3),
            }]
        );
        // What lopdf loads — and why the loaded object cannot tell: the
        // recovered content, `/Length` overwritten to match it.
        let doc = lopdf::Document::load_mem(&bytes).unwrap();
        let stream = doc.get_object((4, 0)).unwrap().as_stream().unwrap();
        assert_eq!(stream.content, b"q Q");
        assert_eq!(stream.dict.get(b"Length").unwrap().as_i64().unwrap(), 3);
    }

    #[test]
    fn understated_missing_and_indirect_lengths() {
        let repair = |length: &str, extra: &[&str]| match &pdf_repairs(&pdf(length, extra))[..] {
            [PdfRepair::StreamLength {
                declared,
                recovered,
                ..
            }] => Some((*declared, *recovered)),
            [] => None,
            other => panic!("{other:?}"),
        };
        assert_eq!(repair("2", &[]), Some((Some(2), Some(3))));
        assert_eq!(repair("-1", &[]), Some((None, Some(3))));
        assert_eq!(repair("/Foo", &[]), Some((None, Some(3))));
        // `/Length 5 0 R` → 4: well-formed; → 9: overstated.
        assert_eq!(repair("5 0 R", &["4"]), None);
        assert_eq!(repair("5 0 R", &["9"]), Some((Some(9), Some(3))));
        // A reference to nothing.
        assert_eq!(repair("7 0 R", &["4"]), Some((None, Some(3))));
    }

    #[test]
    fn short_xref_entries_lopdf_reads_are_no_repair() {
        // 19-byte entries (a bare LF): lopdf 0.45 reads them as they are, so
        // the reader's padding fallback does not fire and is not reported;
        // the overstated stream still is.
        let bytes = pdf("5", &[]);
        let text = String::from_utf8(bytes).unwrap();
        let short = text.replace(" n \n", " n\n").replace(" f \n", " f\n");
        assert!(lopdf::Document::load_mem(short.as_bytes()).is_ok());
        assert!(matches!(
            &pdf_repairs(short.as_bytes())[..],
            [PdfRepair::StreamLength {
                object: (4, 0),
                declared: Some(5),
                recovered: Some(3),
                ..
            }]
        ));
    }

    #[test]
    fn binary_data_and_other_length_keys_are_not_syntax() {
        // A font program's `/Length1` is another key; data holding `obj`,
        // `>>` and `endstream`-free binary is skipped by its declared length.
        let font = "<< /Length1 99 /Length 12 >>\nstream\n1 0 obj >> (\nendstream";
        assert_eq!(pdf_repairs(&pdf("4", &[font])), []);
    }

    #[test]
    fn a_stream_without_an_unambiguous_end_recovers_nothing() {
        // Two `endstream … endobj` candidates inside one object's span: lopdf
        // refuses to guess and drops the stream.
        let bytes = pdf("5", &[]);
        let at = find(&bytes, b"q Q\nendstream").unwrap() + 4;
        let mut twice = bytes[..at].to_vec();
        twice.extend_from_slice(b"endstream\nendobj\nQ\n");
        twice.extend_from_slice(&bytes[at..]);
        assert!(matches!(
            &pdf_repairs(&twice)[..],
            [PdfRepair::StreamLength {
                recovered: None,
                ..
            }]
        ));
    }

    /// #938's fixture: `pdf(…)` plus object 5 / 6 — a 4 KiB object stream
    /// holding object 10 (`7`), listed in a classic xref (lopdf's writer
    /// omits ObjStm, so the file is written by hand).
    fn pdf_with_object_stream(declared: &str) -> Vec<u8> {
        let mut data = b"10 0 7 ".to_vec();
        data.resize(4096, b' ');
        let mut stream = lopdf::Stream::new(lopdf::Dictionary::new(), data);
        stream.compress().unwrap();
        let mut objstm = format!(
            "<< /Type /ObjStm /N 1 /First 5 /Filter /FlateDecode /Length {} >>\nstream\n",
            stream.content.len()
        )
        .into_bytes();
        objstm.extend_from_slice(&stream.content);
        objstm.extend_from_slice(b"\nendstream");
        let bodies: Vec<Vec<u8>> = vec![
            b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
            b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 20 20] /Contents 4 0 R >>".to_vec(),
            format!("<< /Length {declared} >>\nstream\nq Q\nendstream").into_bytes(),
            b"4".to_vec(),
            objstm,
        ];
        let mut bytes = b"%PDF-1.5\n".to_vec();
        let mut offsets = Vec::new();
        for (i, body) in bodies.iter().enumerate() {
            offsets.push(bytes.len());
            bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
            bytes.extend_from_slice(body);
            bytes.extend_from_slice(b"\nendobj\n");
        }
        let xref = bytes.len();
        let n = bodies.len() + 1;
        bytes.extend_from_slice(format!("xref\n0 {n}\n0000000000 65535 f \n").as_bytes());
        for offset in &offsets {
            bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        bytes.extend_from_slice(
            format!("trailer\n<< /Root 1 0 R /Size {n} >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
        );
        bytes
    }

    #[test]
    fn a_bounded_inspection_still_reports_the_repair() {
        // Strict parsing would reject this file before any provenance; the
        // bounded load stays lenient (#938).
        let bytes = pdf("5", &[]);
        assert_eq!(
            try_pdf_repairs(&bytes, Some(256)).unwrap(),
            pdf_repairs(&bytes)
        );
        assert!(!try_pdf_repairs(&bytes, Some(256)).unwrap().is_empty());
        assert_eq!(try_pdf_repairs(&pdf("4", &[]), Some(256)).unwrap(), []);
    }

    #[test]
    fn an_oversized_object_stream_is_an_error_not_a_silent_gap() {
        let bytes = pdf_with_object_stream("5");
        // Unbounded and generously bounded: the repair, complete.
        for limit in [None, Some(1 << 20)] {
            assert!(matches!(
                &try_pdf_repairs(&bytes, limit).unwrap()[..],
                [PdfRepair::StreamLength { object: (4, 0), .. }]
            ));
        }
        // 256 < 4096 decoded: lopdf's lenient load drops object 10 and
        // returns Ok; the inspection must not call that complete.
        assert_eq!(
            try_pdf_repairs(&bytes, Some(256)),
            Err(RepairInspectError::ObjectStreamSkipped { object: (6, 0) })
        );
        // The convenience form keeps its unbounded, infallible shape.
        assert_eq!(pdf_repairs(&bytes).len(), 1);
    }

    #[test]
    fn an_unreadable_file_is_an_error() {
        assert_eq!(
            try_pdf_repairs(b"not a pdf", None),
            Err(RepairInspectError::Unreadable)
        );
        assert_eq!(pdf_repairs(b"not a pdf"), []);
    }
}