exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
//! `load_structure`: header scan → startxref → xref chain (tables, streams,
//! hybrids) → trailer resolution, with full-file rebuild as the last-resort
//! recovery path.
//!
//! Tolerances are ported from PDFium's `CPDF_Parser` (intent only). All
//! offsets in this module — startxref values, xref entry offsets, `/Prev`,
//! `/XRefStm`, `XrefSection::offset`, `XrefMap` offsets — are relative to
//! the **header position**: files with leading garbage prepend a delta that
//! writers did not account for, so the header becomes offset zero (PDFium's
//! `header_offset_`). `DocumentStructure::header_offset` carries the delta;
//! the document layer adds it back when reading object bytes.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::object::parser::ObjectParser;
use crate::object::{Dictionary, NameTable, ObjectId, PdfObject, PdfString, StreamData};
use crate::source::PdfSource;
use crate::syntax::{Lexer, SyntaxLimits, Token};

use crate::structure::decode::{DecodeBudget, decode_stream};
use crate::structure::objstm::parse_object_stream_layout;
use crate::structure::{
    DocumentStructure, ObjectLocation, PdfVersion, RecoveryEvent, RevisionXrefEntry,
    StructureError, Trailer, XrefMap, XrefSection, XrefSectionKind,
};

/// Limits enforced while loading structure. A structural mirror of the
/// document-level limits (`exprim::document` constructs one from its
/// `DocumentLimits`; this crate cannot see that type — dependency
/// direction).
#[derive(Debug, Clone)]
pub struct StructureLimits {
    pub syntax: SyntaxLimits,
    /// Maximum revisions (incremental updates) followed.
    pub max_revisions: usize,
    /// Maximum object number admitted to the xref map.
    pub max_objects: u32,
    /// Decompressed-byte budget for xref streams during open.
    pub max_decoded_bytes: usize,
    /// Audit path only: retain every entry each xref section declared on
    /// [`XrefSection::entries`]. Off by default so the fast render path keeps
    /// its behavior and performance (no per-section entry retention); audit
    /// tooling opts in to diff sections into per-object change histories.
    pub preserve_section_entries: bool,
}

impl Default for StructureLimits {
    fn default() -> Self {
        Self {
            syntax: SyntaxLimits::default(),
            max_revisions: 4096,
            max_objects: 8 * 1024 * 1024,
            max_decoded_bytes: 256 * 1024 * 1024,
            preserve_section_entries: false,
        }
    }
}

/// How far leading garbage may push the `%PDF` header (PDFium scans
/// `0..=1024`).
const MAX_HEADER_GARBAGE: usize = 1024;

/// How far from the end `startxref` may sit (PDFium searches 4096 bytes).
const STARTXREF_TAIL_SCAN: usize = 4096;

/// Load all structural information from `source`.
pub fn load_structure(
    source: &dyn PdfSource,
    names: &NameTable,
    limits: &StructureLimits,
) -> Result<DocumentStructure, StructureError> {
    let len = source.len();
    let bytes: Cow<'_, [u8]> = source.read_range(0..len)?;
    let bytes: &[u8] = &bytes;

    // --- Header scan -----------------------------------------------------
    let header_offset = find_header(bytes).ok_or(StructureError::NoHeader)?;
    let file = &bytes[header_offset..];
    let mut recovery: Vec<RecoveryEvent> = Vec::new();
    let version = parse_version(file, &mut recovery);

    let mut loader = Loader {
        file,
        names,
        limits,
        budget: DecodeBudget::new(limits.max_decoded_bytes),
        entries: HashMap::new(),
        sections: Vec::new(),
        visited: HashSet::new(),
        recovery,
    };

    // --- startxref → xref chain, with recovery fallbacks -----------------
    let mut usable = false;
    // Whether the usable chain came from a recovery fallback rather than the
    // reported `startxref`. A clean reported chain that resolves an empty page
    // tree is a legitimately empty document; only a *recovered* chain that
    // lands on a degenerate stub warrants escalating to a full rebuild.
    let mut used_recovery = false;
    let reported = find_startxref(file, &loader.limits.syntax);
    if let Some(reported) = reported
        && (reported as usize) < file.len()
    {
        usable = loader.try_chain(reported)?;
    }
    if !usable {
        // The reported chain was missing or unusable: scan for the last
        // classic `xref` keyword before giving up (partial recovery that
        // preserves incremental-update semantics when only startxref lied).
        if let Some(found) = find_last_xref_keyword(file, &loader.limits.syntax, loader.names)
            && Some(found as u64) != reported
        {
            loader.reset_merge_state();
            usable = loader.try_chain(found as u64)?;
            if usable {
                used_recovery = true;
                loader.recovery.push(RecoveryEvent::StartXrefRecovered {
                    reported,
                    used: found as u64,
                });
            }
        }
    }

    // --- Trailer resolution / full rebuild --------------------------------
    let mut trailer = usable.then(|| loader.resolve_trailer()).flatten();
    // Rebuild when the xref gave no trailer/`/Root`, or when a *recovered*
    // chain resolved a degenerate document — a stub page tree the recovery
    // stopped at (a linearized/incremental-update placeholder whose real page
    // tree lives in a later revision). A full rebuild's last-occurrence-wins
    // then recovers the real pages.
    let degenerate = used_recovery
        && trailer
            .as_ref()
            .is_some_and(|t| loader.page_tree_looks_empty(t));
    // A trailer that names a `/Root` the xref cannot resolve (missing entry or a
    // stale offset that no longer parses) is corruption invisible to the chain
    // walk — the trailer looks complete. Escalate to a full rebuild, which finds
    // the catalog by scanning `N G obj` headers and object streams. Unlike
    // `degenerate`, this applies to reported chains too: a healthy `/Root`
    // always resolves (directly or via an object stream), so a well-formed
    // document — incremental updates included — never triggers it.
    let root_unresolved = trailer.as_ref().is_some_and(|t| !loader.root_resolves(t));
    // A *recovered* chain whose entries no longer point at their objects is a
    // file whose byte offsets have shifted wholesale: the `/Root` may still
    // land (low object numbers often survive) while page and content objects
    // do not, which renders as a blank page rather than an open failure.
    // PDFium never uses such a table at all — a `startxref` that misses sends
    // it straight to `RebuildCrossRef` — so validate before trusting a table we
    // only found by scanning. Reported chains are left alone: their offsets are
    // as authoritative as the file gets, and PDFium keeps them too.
    let offsets_stale = used_recovery && !loader.xref_offsets_are_consistent();
    if trailer.is_none() || degenerate || root_unresolved || offsets_stale {
        // Snapshot the chain-derived state so a rebuild that fails to improve
        // matters (e.g. a minimal file whose `/Root` is intentionally external,
        // or a synthetic xref-stream fixture) can be rolled back instead of
        // clobbering usable entries with a sparser scan.
        let saved_entries = loader.entries.clone();
        let saved_sections = loader.sections.clone();
        let saved_recovery_len = loader.recovery.len();

        // Full-file reconstruction (PDFium `RebuildCrossRef`).
        loader.reset_merge_state();
        loader.rebuild();
        let rebuilt = loader.resolve_trailer();
        if loader.entries.is_empty() {
            return Err(StructureError::NoUsableXref);
        }
        // A rebuild is worth keeping when it yields a `/Root` that actually
        // resolves, or when we had no trailer at all (any catalog is progress).
        // Otherwise — the rebuild found no better catalog than the chain did —
        // roll back to the parsed xref rather than degrade it.
        let rebuilt_improves = rebuilt.as_ref().is_some_and(|t| loader.root_resolves(t));
        if rebuilt_improves || (trailer.is_none() && rebuilt.is_some()) {
            trailer = rebuilt;
        } else if trailer.is_some() {
            loader.entries = saved_entries;
            loader.sections = saved_sections;
            loader.recovery.truncate(saved_recovery_len);
        } else if rebuilt.is_some() {
            trailer = rebuilt;
        }
    }
    let trailer = trailer.ok_or(StructureError::NoCatalog)?;

    let xref = loader.build_xref_map(&trailer);
    Ok(DocumentStructure {
        version,
        header_offset: header_offset as u64,
        xref,
        trailer,
        sections: loader.sections.into_boxed_slice(),
        recovery: loader.recovery.into_boxed_slice(),
    })
}

/// Load a document's structure by going **straight to a full-file
/// reconstruction** (PDFium `RebuildCrossRef`), bypassing the reported xref
/// chain. This is a document-level escalation for a file whose chain loads
/// "cleanly" (resolvable `/Root`, consistent offsets) yet whose page-tree walk
/// still recovers zero pages — because a `/Kids` reference resolves to a null
/// the xref points at a wrong offset, corruption invisible to `load_structure`'s
/// own trailer/root-level gates. The rebuild's last-occurrence-wins scan and its
/// object-stream member re-indexing recover the page objects the stale entries
/// missed. The caller adopts the result only if it yields strictly more pages.
pub fn load_structure_rebuilt(
    source: &dyn PdfSource,
    names: &NameTable,
    limits: &StructureLimits,
) -> Result<DocumentStructure, StructureError> {
    let len = source.len();
    let bytes: Cow<'_, [u8]> = source.read_range(0..len)?;
    let bytes: &[u8] = &bytes;

    let header_offset = find_header(bytes).ok_or(StructureError::NoHeader)?;
    let file = &bytes[header_offset..];
    let mut recovery: Vec<RecoveryEvent> = Vec::new();
    let version = parse_version(file, &mut recovery);

    let mut loader = Loader {
        file,
        names,
        limits,
        budget: DecodeBudget::new(limits.max_decoded_bytes),
        entries: HashMap::new(),
        sections: Vec::new(),
        visited: HashSet::new(),
        recovery,
    };

    loader.reset_merge_state();
    loader.rebuild();
    if loader.entries.is_empty() {
        return Err(StructureError::NoUsableXref);
    }
    let trailer = loader.resolve_trailer().ok_or(StructureError::NoCatalog)?;
    let xref = loader.build_xref_map(&trailer);
    Ok(DocumentStructure {
        version,
        header_offset: header_offset as u64,
        xref,
        trailer,
        sections: loader.sections.into_boxed_slice(),
        recovery: loader.recovery.into_boxed_slice(),
    })
}

/// Find `%PDF` within the first `MAX_HEADER_GARBAGE` bytes.
fn find_header(bytes: &[u8]) -> Option<usize> {
    let window_end = bytes.len().min(MAX_HEADER_GARBAGE + 4);
    bytes[..window_end].windows(4).position(|w| w == b"%PDF")
}

/// Parse `-M.N` after `%PDF`. Malformed versions default to 1.7 with a
/// recovery note — the header's presence, not its version, gates parsing.
fn parse_version(file: &[u8], recovery: &mut Vec<RecoveryEvent>) -> PdfVersion {
    let rest = &file[4..];
    let parsed = (|| {
        let rest = rest.strip_prefix(b"-")?;
        let major = rest
            .first()
            .filter(|b| b.is_ascii_digit())
            .map(|b| b - b'0')?;
        let rest = rest.get(1..)?.strip_prefix(b".")?;
        let minor = rest
            .first()
            .filter(|b| b.is_ascii_digit())
            .map(|b| b - b'0')?;
        Some(PdfVersion { major, minor })
    })();
    parsed.unwrap_or_else(|| {
        recovery.push(RecoveryEvent::Other(
            "malformed %PDF version; assuming 1.7".into(),
        ));
        PdfVersion { major: 1, minor: 7 }
    })
}

/// Locate the *last* `startxref` in the tail and read its operand.
fn find_startxref(file: &[u8], syntax: &SyntaxLimits) -> Option<u64> {
    let scan_start = file.len().saturating_sub(STARTXREF_TAIL_SCAN);
    let pos = scan_start + find_last_subslice(&file[scan_start..], b"startxref")?;
    let mut lexer = Lexer::new(file, 0, syntax);
    lexer.set_pos(pos);
    let kw = lexer.next_token().ok()?;
    if !matches!(&kw.value, Token::Keyword(k) if k == b"startxref") {
        return None;
    }
    match lexer.next_token().ok()?.value {
        Token::Integer(v) if v >= 0 => Some(v as u64),
        _ => None,
    }
}

/// Last occurrence of `needle` in `haystack`.
fn find_last_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    (0..=haystack.len() - needle.len())
        .rev()
        .find(|&i| &haystack[i..i + needle.len()] == needle)
}

/// How much of the end of the file is searched backwards for the `xref`
/// keyword before the rest is scanned forwards (see
/// [`find_last_xref_keyword`]). A classic table sits just before its trailer,
/// so the last megabyte finds it unless a megabyte of something else follows.
const XREF_KEYWORD_TAIL_SCAN: usize = 1 << 20;

/// Whether `file[i..]` starts with keyword `kw` as a whole word (not embedded
/// in a longer regular-character run — `xref` inside `startxref` must not
/// match).
fn keyword_at(file: &[u8], i: usize, kw: &[u8]) -> bool {
    file.get(i..i + kw.len()) == Some(kw)
        && (i == 0 || !crate::syntax::classify::is_regular(file[i - 1]))
        && file
            .get(i + kw.len())
            .is_none_or(|&b| !crate::syntax::classify::is_regular(b))
}

/// Last whole-word `xref` keyword in the file: the fallback for a `startxref`
/// that is missing or wrong.
///
/// The end of the file is searched backwards, which finds a classic table at
/// once. Only when it holds none is the rest searched, forwards, stepping over
/// stream bodies whose `/Length` is verified ([`verified_stream_body`]). The
/// search used to run backwards over every byte: for a file with no classic
/// table at all (cross-reference streams only) that read the whole file, image
/// data included, to find nothing, before the rebuild read it again. A
/// keyword-shaped run inside verified stream data is no longer a candidate; it
/// could only ever have named a table that is not one.
fn find_last_xref_keyword(file: &[u8], syntax: &SyntaxLimits, names: &NameTable) -> Option<usize> {
    const KW: &[u8] = b"xref";
    let tail_start = file.len().saturating_sub(XREF_KEYWORD_TAIL_SCAN);
    if let Some(found) = (tail_start..file.len().saturating_sub(KW.len() - 1))
        .rev()
        .find(|&i| keyword_at(file, i, KW))
    {
        return Some(found);
    }
    let mut last = None;
    let mut body: Option<(usize, usize)> = None;
    let mut i = 0usize;
    while i < tail_start {
        if let Some((from, to)) = body
            && i >= from
        {
            body = None;
            if to > i {
                i = to;
                continue;
            }
        }
        if keyword_at(file, i, b"obj") && backtrack_obj_header(file, i).is_some() {
            body = verified_stream_body(file, i + 3, syntax, names);
            i += 3;
            continue;
        }
        if keyword_at(file, i, KW) {
            last = Some(i);
            i += KW.len();
            continue;
        }
        i += 1;
    }
    last
}

/// Working state for one load.
struct Loader<'a> {
    file: &'a [u8],
    names: &'a NameTable,
    limits: &'a StructureLimits,
    budget: DecodeBudget,
    /// Merged view, **first write wins**: revisions are processed newest →
    /// oldest, so the first location recorded for an object number is the
    /// live one; older revisions (and older entries in hybrid files) are
    /// shadowed. Free entries occupy their number like any other write.
    entries: HashMap<u32, (u16, ObjectLocation)>,
    sections: Vec<XrefSection>,
    visited: HashSet<u64>,
    recovery: Vec<RecoveryEvent>,
}

impl<'a> Loader<'a> {
    fn reset_merge_state(&mut self) {
        self.entries.clear();
        self.sections.clear();
        self.visited.clear();
    }

    /// Snapshot the recovery events recorded since `start` (a `recovery.len()`
    /// taken when section parsing began) for one section's own log. The
    /// global log keeps everything; the section carries its attributable
    /// subset.
    fn section_recovery(&self, start: usize) -> Arc<[RecoveryEvent]> {
        self.recovery.get(start..).unwrap_or(&[]).to_vec().into()
    }

    /// Record an entry unless the number is already live (first-write-wins).
    fn record(&mut self, number: u32, generation: u16, location: ObjectLocation) {
        if number >= self.limits.max_objects {
            return;
        }
        self.entries.entry(number).or_insert((generation, location));
    }

    /// Follow a chain and report whether it yielded a usable view.
    ///
    /// Limit violations (revision count, decode budget) are **fatal** —
    /// malicious files must terminate with errors, not silently continue
    /// into the rebuild path. Ordinary corruption is non-fatal: the caller
    /// falls back to scanning/rebuilding.
    fn try_chain(&mut self, start: u64) -> Result<bool, StructureError> {
        match self.follow_chain(start) {
            Ok(()) => Ok(!self.entries.is_empty()),
            Err(e @ StructureError::LimitExceeded(_)) => Err(e),
            Err(
                e @ StructureError::Decode(crate::structure::decode::DecodeError::BudgetExceeded),
            ) => Err(e),
            Err(_) => Ok(false),
        }
    }

    /// Follow the `/Prev` chain from `start` (header-relative offset).
    fn follow_chain(&mut self, start: u64) -> Result<(), StructureError> {
        let mut next = Some(start);
        while let Some(offset) = next {
            if offset as usize >= self.file.len() {
                self.recovery.push(RecoveryEvent::Other(format!(
                    "xref offset {offset} outside file; chain truncated"
                )));
                break;
            }
            if !self.visited.insert(offset) {
                // A /Prev cycle is not fatal — everything before the
                // repeat is already merged (PDFium stops the same way).
                self.recovery.push(RecoveryEvent::Other(format!(
                    "xref chain cycle at offset {offset}"
                )));
                break;
            }
            if self.sections.len() >= self.limits.max_revisions {
                return Err(StructureError::LimitExceeded("max_revisions"));
            }
            next = self.parse_section(offset)?;
        }
        Ok(())
    }

    /// Parse one xref section (classic table or xref stream); returns the
    /// `/Prev` offset if any.
    fn parse_section(&mut self, offset: u64) -> Result<Option<u64>, StructureError> {
        let mut lexer = Lexer::new(self.file, 0, &self.limits.syntax);
        lexer.set_pos(offset as usize);
        let first = lexer.peek_token()?;
        match &first.value {
            Token::Keyword(kw) if kw == b"xref" => self.parse_classic_table(lexer, offset),
            Token::Integer(_) => self.parse_xref_stream(offset, None),
            _ => Err(StructureError::NoUsableXref),
        }
    }

    /// Classic `xref` table. Entries are read token-wise, which naturally
    /// tolerates the 19/21-byte CR/LF-sloppy variants PDFium accepts.
    /// Collect per-section entries on the audit path; an empty slice on the
    /// fast render path (no per-entry retention there).
    fn preserved_entries(
        &self,
        entries: impl Iterator<Item = RevisionXrefEntry>,
    ) -> Arc<[RevisionXrefEntry]> {
        if self.limits.preserve_section_entries {
            entries.collect::<Vec<_>>().into()
        } else {
            Vec::new().into()
        }
    }

    fn parse_classic_table(
        &mut self,
        mut lexer: Lexer<'a>,
        offset: u64,
    ) -> Result<Option<u64>, StructureError> {
        let recovery_start = self.recovery.len();
        let _ = lexer.next_token()?; // consume `xref`
        let mut staged: Vec<(u32, u16, ObjectLocation)> = Vec::new();
        let trailer_dict: Option<Dictionary> = loop {
            let tok = lexer.next_token()?;
            match tok.value {
                Token::Integer(start) => {
                    let count_tok = lexer.next_token()?;
                    let Token::Integer(count) = count_tok.value else {
                        break None; // malformed subsection header
                    };
                    let (Ok(start), Ok(count)) = (u32::try_from(start), u32::try_from(count))
                    else {
                        break None;
                    };
                    // A subsection declared as starting at object 1 whose first
                    // entry is the free-list head (`0000000000 65535 f`) is a
                    // producer that wrote `1 N` where it meant `0 N`: object 0
                    // is *always* that head. Taken literally every entry lands
                    // one object number too high, so the real object 1 is
                    // recorded free and every reference to it dies — in
                    // pdfjs/issue7229 that is the page's only image, and the
                    // page renders blank. PDFium and pdf.js both correct this.
                    let mut start = start;
                    if start == 1 && count > 0 {
                        let probe = lexer.pos();
                        let head = (
                            lexer.next_token().map(|t| t.value),
                            lexer.next_token().map(|t| t.value),
                            lexer.next_token().map(|t| t.value),
                        );
                        if let (
                            Ok(Token::Integer(0)),
                            Ok(Token::Integer(65535)),
                            Ok(Token::Keyword(k)),
                        ) = head
                            && k.as_slice() == b"f"
                        {
                            start = 0;
                        }
                        lexer.set_pos(probe);
                    }
                    for i in 0..count {
                        let save_entry = lexer.pos();
                        let (o, g, k) = (
                            lexer.next_token()?,
                            lexer.next_token()?,
                            lexer.next_token()?,
                        );
                        let (
                            Token::Integer(entry_off),
                            Token::Integer(entry_gen),
                            Token::Keyword(kind),
                        ) = (o.value, g.value, k.value)
                        else {
                            // Subsection shorter than declared: stop here,
                            // keep what parsed (count lies are common).
                            lexer.set_pos(save_entry);
                            break;
                        };
                        let number = start.saturating_add(i);
                        let generation = u16::try_from(entry_gen.clamp(0, i64::from(u16::MAX)))
                            .unwrap_or(u16::MAX);
                        match kind.as_slice() {
                            b"n" if entry_off >= 0 => staged.push((
                                number,
                                generation,
                                ObjectLocation::Offset(entry_off as u64),
                            )),
                            b"f" => staged.push((number, generation, ObjectLocation::Free)),
                            _ => {
                                lexer.set_pos(save_entry);
                                break;
                            }
                        }
                    }
                }
                Token::Keyword(kw) if kw == b"trailer" => {
                    let mut parser = ObjectParser::from_lexer(lexer.clone(), self.names);
                    match parser.parse_object() {
                        Ok(PdfObject::Dictionary(d)) => break Some(Arc::unwrap_or_clone(d)),
                        _ => break None,
                    }
                }
                _ => break None,
            }
        };

        let Some(trailer_dict) = trailer_dict else {
            // A classic table without a readable trailer is unusable as a
            // revision (no /Prev, no /Root contribution).
            return Err(StructureError::NoUsableXref);
        };

        // Table entries first (they take precedence over the hybrid
        // /XRefStm entries of the same revision — PDFium's merge order).
        for (n, g, loc) in &staged {
            self.record(*n, *g, *loc);
        }
        let trailer_dict = Arc::new(trailer_dict);
        let prev = trailer_dict
            .get(self.names.known.prev)
            .and_then(PdfObject::as_int)
            .and_then(|v| u64::try_from(v).ok());
        let entries =
            self.preserved_entries(staged.iter().map(|&(number, generation, location)| {
                RevisionXrefEntry {
                    id: ObjectId::new(number, generation),
                    location,
                }
            }));
        let classic_idx = self.sections.len();
        let recovery = self.section_recovery(recovery_start);
        let mut entry_counts = crate::structure::XrefEntryCounts::default();
        for &(_, _, location) in &staged {
            entry_counts.tally(location);
        }
        self.sections.push(XrefSection {
            offset,
            kind: XrefSectionKind::Classic,
            entry_counts,
            entries,
            trailer: Arc::clone(&trailer_dict),
            prev,
            auxiliary_of: None,
            recovery,
        });

        // Hybrid-reference hop: /XRefStm within this revision.
        if let Some(stm_off) = trailer_dict
            .get(self.names.known.xref_stm)
            .and_then(PdfObject::as_int)
            .and_then(|v| u64::try_from(v).ok())
            && (stm_off as usize) < self.file.len()
            && self.visited.insert(stm_off)
        {
            // Failures in the hybrid stream are tolerated: the classic
            // table alone may still be a usable view.
            let auxiliary_of = u32::try_from(classic_idx).ok();
            if let Err(e) = self.parse_xref_stream(stm_off, auxiliary_of) {
                self.recovery.push(RecoveryEvent::Other(format!(
                    "hybrid /XRefStm at {stm_off} unusable: {e}"
                )));
                // The failure note belongs to this revision too: re-attach
                // the section's recovery log now that it exists.
                let recovery = self.section_recovery(recovery_start);
                if let Some(classic) = self.sections.get_mut(classic_idx) {
                    classic.recovery = recovery;
                }
            }
        }

        Ok(prev)
    }

    /// Cross-reference stream (ISO 32000-1 §7.5.8). `auxiliary_of` carries
    /// the hybrid-reference pairing: the classic table's section index when
    /// this stream was reached via `/XRefStm`, `None` on the primary chain.
    fn parse_xref_stream(
        &mut self,
        offset: u64,
        auxiliary_of: Option<u32>,
    ) -> Result<Option<u64>, StructureError> {
        let recovery_start = self.recovery.len();
        let window = &self.file[offset as usize..];
        let mut parser = ObjectParser::new(window, offset, &self.limits.syntax, self.names);
        // /Length can in principle be indirect; unresolvable pre-xref, so
        // the parser falls back to scanning for `endstream`.
        let parsed = parser.parse_indirect(&mut |_| None)?;
        let PdfObject::Stream(stream) = parsed.object else {
            return Err(StructureError::NoUsableXref);
        };
        for repair in &parsed.repairs {
            match repair {
                crate::object::parser::IndirectRepair::StreamLengthRepaired {
                    declared,
                    actual,
                } => self.recovery.push(RecoveryEvent::StreamLengthRepaired {
                    id: parsed.id,
                    declared: *declared,
                    actual: *actual,
                }),
                crate::object::parser::IndirectRepair::MissingReferenceGeneration {
                    number,
                    offset,
                } => self
                    .recovery
                    .push(RecoveryEvent::ReferenceGenerationRepaired {
                        id: parsed.id,
                        referenced: *number,
                        offset: *offset,
                    }),
                crate::object::parser::IndirectRepair::MissingEndObj => {}
            }
        }
        let dict = &stream.dict;
        let raw: &[u8] = match &stream.data {
            StreamData::InSource { offset, len } => {
                let (start, end) = (*offset as usize, (*offset + *len) as usize);
                self.file
                    .get(start..end)
                    .ok_or(StructureError::NoUsableXref)?
            }
            StreamData::Owned(bytes) => bytes,
        };
        let data = decode_stream(raw, dict, self.names, &mut self.budget)?;

        let get_int = |key: crate::object::NameId| dict.get(key).and_then(PdfObject::as_int);
        let size = get_int(self.names.known.size).unwrap_or(0).max(0);

        // /W: at least 3 field widths; extras pad the stride but are
        // ignored (PDFium tolerates and so do we).
        let widths: Vec<u64> = match dict.get(self.names.known.w) {
            Some(PdfObject::Array(a)) => a
                .iter()
                .map(|o| o.as_int().and_then(|v| u64::try_from(v).ok()))
                .collect::<Option<Vec<u64>>>()
                .ok_or(StructureError::NoUsableXref)?,
            _ => return Err(StructureError::NoUsableXref),
        };
        if widths.len() < 3 || widths.iter().any(|&w| w > 8) {
            return Err(StructureError::NoUsableXref);
        }
        let total_width: u64 = widths.iter().sum();
        if total_width == 0 {
            return Err(StructureError::NoUsableXref);
        }

        // /Index: subsection pairs; default [0 Size].
        let mut indices: Vec<(u32, u32)> = Vec::new();
        if let Some(PdfObject::Array(a)) = dict.get(self.names.known.index) {
            for pair in a.chunks(2) {
                if let [s, c] = pair
                    && let (Some(s), Some(c)) = (s.as_int(), c.as_int())
                    && let (Ok(s), Ok(c)) = (u32::try_from(s), u32::try_from(c))
                {
                    indices.push((s, c));
                }
            }
        }
        if indices.is_empty() {
            indices.push((0, u32::try_from(size).unwrap_or(0)));
        }

        let stride = usize::try_from(total_width).unwrap_or(usize::MAX);
        let mut seg_start = 0usize;
        // Audit path only: retain what this section declared. `None` on the
        // fast path, where no per-section allocation happens at all. The
        // counters below run on both paths: the facts layer reports counts,
        // never entries.
        let mut staged: Option<Vec<RevisionXrefEntry>> = if self.limits.preserve_section_entries {
            Some(Vec::new())
        } else {
            None
        };
        let mut entry_counts = crate::structure::XrefEntryCounts::default();
        for (start_num, count) in indices {
            let count_usize = count as usize;
            let Some(seg_len) = count_usize.checked_mul(stride) else {
                continue;
            };
            let Some(seg_end) = seg_start.checked_add(seg_len) else {
                continue;
            };
            if seg_end > data.len() {
                continue; // segment overruns data: skip pair (PDFium)
            }
            let seg = &data[seg_start..seg_end];
            for i in 0..count_usize {
                let number = start_num.saturating_add(i as u32);
                let entry = &seg[i * stride..(i + 1) * stride];
                if let Some((generation, location)) = Self::decode_stream_entry(entry, &widths) {
                    self.record(number, generation, location);
                    entry_counts.tally(location);
                    if let Some(staged) = staged.as_mut() {
                        staged.push(RevisionXrefEntry {
                            id: ObjectId::new(number, generation),
                            location,
                        });
                    }
                }
            }
            seg_start = seg_end;
        }

        let dict_arc = Arc::new(dict.clone());
        let prev = dict
            .get(self.names.known.prev)
            .and_then(PdfObject::as_int)
            .and_then(|v| u64::try_from(v).ok());
        let entries: Arc<[RevisionXrefEntry]> = match staged {
            Some(staged) => staged.into(),
            None => Vec::new().into(),
        };
        let recovery = self.section_recovery(recovery_start);
        self.sections.push(XrefSection {
            offset,
            kind: XrefSectionKind::Stream,
            entry_counts,
            entries,
            trailer: dict_arc,
            prev,
            auxiliary_of,
            recovery,
        });

        Ok(prev)
    }

    /// Decode one xref-stream entry (ISO 32000-1 Table 18 / PDFium
    /// `ProcessCrossRefStreamEntry`). `None` for unknown entry types and
    /// out-of-range field values: skip the entry, keep the section (PDFium).
    fn decode_stream_entry(entry: &[u8], widths: &[u64]) -> Option<(u16, ObjectLocation)> {
        // Field offsets are a property of `W`, not of the entry, so walk the
        // prefix once here instead of re-summing it inside `field` for each of
        // the three fields of every entry in the table.
        let mut offsets = [0usize; 3];
        let mut at = 0usize;
        for (i, w) in widths.iter().take(3).enumerate() {
            offsets[i] = at;
            at += *w as usize;
        }
        let field = |idx: usize| -> u64 {
            let (start, len) = (offsets[idx], widths[idx] as usize);
            entry[start..start + len]
                .iter()
                .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
        };
        // W[0] = 0 → default entry type 1 (ISO 32000-1 Table 17).
        let entry_type = if widths[0] == 0 { 1 } else { field(0) };
        let f1 = field(1);
        let f2 = field(2);
        match entry_type {
            0 => {
                let generation = u16::try_from(f2).ok()?;
                Some((generation, ObjectLocation::Free))
            }
            1 => {
                let generation = u16::try_from(f2).ok()?;
                Some((generation, ObjectLocation::Offset(f1)))
            }
            2 => {
                let container = u32::try_from(f1).ok()?;
                let index = u32::try_from(f2).ok()?;
                // Generation of in-stream objects is 0 by definition.
                Some((0, ObjectLocation::InObjectStream { container, index }))
            }
            // Unknown types: skip the entry, keep the section (PDFium).
            _ => None,
        }
    }

    /// Resolve the current trailer view from the merged sections:
    /// newest-first, first hit wins per key.
    fn resolve_trailer(&self) -> Option<Trailer> {
        let mut root: Option<ObjectId> = None;
        let mut info: Option<ObjectId> = None;
        let mut encrypt: Option<ObjectId> = None;
        let mut file_id: Option<[PdfString; 2]> = None;
        for section in &self.sections {
            let d = &section.trailer;
            if root.is_none() {
                root = d
                    .get(self.names.known.root)
                    .and_then(PdfObject::as_reference);
            }
            if info.is_none() {
                info = d
                    .get(self.names.known.info)
                    .and_then(PdfObject::as_reference);
            }
            if encrypt.is_none() {
                encrypt = d
                    .get(self.names.known.encrypt)
                    .and_then(PdfObject::as_reference);
            }
            if file_id.is_none()
                && let Some(PdfObject::Array(a)) = d.get(self.names.known.id)
                && let [PdfObject::String(a0), PdfObject::String(a1)] = a.as_ref()
            {
                file_id = Some([a0.clone(), a1.clone()]);
            }
        }
        let root = root?;
        let dict = self
            .sections
            .first()
            .map(|s| Arc::clone(&s.trailer))
            .unwrap_or_else(|| Arc::new(Dictionary::new()));
        Some(Trailer {
            dict,
            root,
            info,
            encrypt,
            file_id,
        })
    }

    /// Full-file reconstruction: index every `N G obj` header (last
    /// occurrence of an object number wins — later bytes are later
    /// revisions), collect `trailer` dictionaries, and fall back to a
    /// `/Type /Catalog` scan for the root (PDFium `RebuildCrossRef`).
    fn rebuild(&mut self) {
        self.recovery.push(RecoveryEvent::XrefRebuilt);
        let file = self.file;
        // number → (effective file position, generation, location). The
        // position orders revisions when an object is defined more than once:
        // an uncompressed body is at its header offset; an object-stream member
        // is at its container's header offset (the revision that wrote it), so
        // a later uncompressed redefinition still wins.
        let mut best: HashMap<u32, (u64, u16, ObjectLocation)> = HashMap::new();
        let mut trailer_dicts: Vec<Dictionary> = Vec::new();
        // `/Type /ObjStm` containers found in the scan (number, header offset),
        // to decompress and index below.
        let mut containers: Vec<(u32, u64)> = Vec::new();
        // `/Type /XRef` cross-reference streams (number, header offset). Their
        // *dict* is the revision trailer — an xref-stream-only file (PDF ≥ 1.5)
        // has no `trailer` keyword, so its /Root lives only here.
        let mut xref_streams: Vec<(u32, u64)> = Vec::new();
        let mut current: Option<(u32, u64)> = None;
        // The body of the stream object being scanned, when its `/Length` is
        // verified: the scan steps over it instead of reading it.
        let mut body: Option<(usize, usize)> = None;

        let mut i = 0usize;
        while i + 3 <= file.len() {
            if let Some((from, to)) = body
                && i >= from
            {
                body = None;
                if to > i {
                    i = to;
                    continue;
                }
            }
            if &file[i..i + 3] == b"obj"
                && (i + 3 == file.len() || !crate::syntax::classify::is_regular(file[i + 3]))
                && let Some((start, number, generation)) = backtrack_obj_header(file, i)
            {
                let start = start as u64;
                // Last occurrence wins (headers are scanned in offset order).
                best.insert(number, (start, generation, ObjectLocation::Offset(start)));
                current = Some((number, start));
                body = verified_stream_body(file, i + 3, &self.limits.syntax, self.names);
                i += 3;
                continue;
            }
            // The `/ObjStm` type name inside an object marks it as a container;
            // remember the enclosing object so its members can be indexed.
            if i + 6 <= file.len()
                && &file[i..i + 6] == b"ObjStm"
                && (i == 0 || !crate::syntax::classify::is_regular(file[i - 1]))
                && (i + 6 == file.len() || !crate::syntax::classify::is_regular(file[i + 6]))
            {
                if let Some(c) = current.take() {
                    containers.push(c);
                }
                i += 6;
                continue;
            }
            // A `/XRef` type name marks a cross-reference stream. Remember the
            // enclosing object so its dict (the revision trailer, carrying
            // /Root) is parsed after the scan.
            if i + 4 <= file.len()
                && &file[i..i + 4] == b"XRef"
                && (i == 0 || !crate::syntax::classify::is_regular(file[i - 1]))
                && (i + 4 == file.len() || !crate::syntax::classify::is_regular(file[i + 4]))
            {
                if let Some(c) = current {
                    xref_streams.push(c);
                }
                i += 4;
                continue;
            }
            if i + 7 <= file.len()
                && &file[i..i + 7] == b"trailer"
                && (i == 0 || !crate::syntax::classify::is_regular(file[i - 1]))
                && (i + 7 == file.len() || !crate::syntax::classify::is_regular(file[i + 7]))
            {
                let mut parser = ObjectParser::new(
                    &file[i + 7..],
                    (i + 7) as u64,
                    &self.limits.syntax,
                    self.names,
                );
                if let Ok(PdfObject::Dictionary(d)) = parser.parse_object() {
                    trailer_dicts.push(Arc::unwrap_or_clone(d));
                }
                i += 7;
                continue;
            }
            i += 1;
        }

        // Decompress each object-stream container and index its members. A
        // corrupted modern PDF keeps most objects (pages, fonts, content)
        // inside `/Type /ObjStm`, invisible to the `N G obj` scan; without this
        // the rebuild silently loses them (PDFium's `RebuildCrossRef` parses
        // object streams the same way). A member is overridden only by a
        // *later* uncompressed definition.
        for (container, offset) in containers {
            let Some(members) = self.read_objstm_members(offset) else {
                continue;
            };
            for (index, member) in members.into_iter().enumerate() {
                let overridden_by_later =
                    matches!(best.get(&member), Some(&(pos, _, _)) if pos > offset);
                if !overridden_by_later {
                    best.insert(
                        member,
                        (
                            offset,
                            0,
                            ObjectLocation::InObjectStream {
                                container,
                                index: index as u32,
                            },
                        ),
                    );
                }
            }
        }

        // A cross-reference stream's dict *is* the revision trailer for an
        // xref-stream file (PDF ≥ 1.5, no `trailer` keyword). Parse each so its
        // /Root (and /Encrypt, /Info) is recovered; otherwise a corrupted
        // modern PDF whose catalog lives inside an object stream has no findable
        // root, and `find_catalog` — which only inspects offset objects — misses
        // it. Pushed after the keyword trailers so the newest xref stream wins
        // the newest-first ordering below.
        for (_num, offset) in xref_streams {
            let Some(window) = self.file.get(offset as usize..) else {
                continue;
            };
            let mut parser = ObjectParser::new(window, offset, &self.limits.syntax, self.names);
            if let Ok(parsed) = parser.parse_indirect(&mut |_| None)
                && let PdfObject::Stream(stream) = &parsed.object
            {
                trailer_dicts.push(stream.dict.clone());
            }
        }

        for (n, (_, g, loc)) in best {
            self.record(n, g, loc);
        }
        // Later trailers are later revisions: iterate newest-last →
        // register newest first for the first-hit-wins trailer resolution.
        // These sections are synthesized (offset 0, no entries): a scan has
        // no section structure, only trailer dictionaries to resolve.
        for dict in trailer_dicts.into_iter().rev() {
            self.sections.push(XrefSection {
                offset: 0,
                kind: XrefSectionKind::Classic,
                entry_counts: crate::structure::XrefEntryCounts::default(),
                entries: Vec::new().into(),
                trailer: Arc::new(dict),
                prev: None,
                auxiliary_of: None,
                recovery: Vec::new().into(),
            });
        }

        // No trailer with /Root anywhere: hunt for a /Type /Catalog object.
        let root_known = self
            .sections
            .iter()
            .any(|s| s.trailer.get(self.names.known.root).is_some());
        if !root_known && let Some((id, _)) = self.find_catalog() {
            let dict = Dictionary::from_pairs([(self.names.known.root, PdfObject::Reference(id))]);
            self.sections.insert(
                0,
                XrefSection {
                    offset: 0,
                    kind: XrefSectionKind::Classic,
                    entry_counts: crate::structure::XrefEntryCounts::default(),
                    entries: Vec::new().into(),
                    trailer: Arc::new(dict),
                    prev: None,
                    auxiliary_of: None,
                    recovery: Vec::new().into(),
                },
            );
        }
    }

    /// Scan indexed objects for a `/Type /Catalog` dictionary.
    fn find_catalog(&mut self) -> Option<(ObjectId, Arc<Dictionary>)> {
        let catalog = self.names.intern(b"Catalog");
        let mut numbers: Vec<u32> = self.entries.keys().copied().collect();
        numbers.sort_unstable();
        for n in numbers {
            let (generation, ObjectLocation::Offset(off)) = self.entries[&n] else {
                continue;
            };
            let window = self.file.get(off as usize..)?;
            let mut parser = ObjectParser::new(window, off, &self.limits.syntax, self.names);
            let Ok(parsed) = parser.parse_indirect(&mut |_| None) else {
                continue;
            };
            if let Some(dict) = parsed.object.as_dict()
                && dict
                    .get(self.names.known.type_)
                    .and_then(PdfObject::as_name)
                    == Some(catalog)
            {
                return Some((ObjectId::new(n, generation), Arc::new(dict.clone())));
            }
        }
        None
    }

    /// Parse the object at `offset` as a `/Type /ObjStm` container and return
    /// its member object numbers in index order. `None` if it is not a
    /// (decodable) object stream.
    fn read_objstm_members(&mut self, offset: u64) -> Option<Vec<u32>> {
        let file = self.file;
        let names = self.names;
        let limits = self.limits;

        let window = file.get(offset as usize..)?;
        let mut parser = ObjectParser::new(window, offset, &limits.syntax, names);
        let parsed = parser.parse_indirect(&mut |_| None).ok()?;
        let PdfObject::Stream(stream) = &parsed.object else {
            return None;
        };
        if stream
            .dict
            .get(names.known.type_)
            .and_then(PdfObject::as_name)
            != Some(names.known.obj_stm)
        {
            return None;
        }
        let raw: &[u8] = match &stream.data {
            StreamData::InSource { offset, len } => {
                file.get(*offset as usize..(*offset + *len) as usize)?
            }
            StreamData::Owned(bytes) => bytes,
        };
        let data = decode_stream(raw, &stream.dict, names, &mut self.budget).ok()?;
        let n = stream
            .dict
            .get(names.known.n)
            .and_then(PdfObject::as_int)
            .unwrap_or(0);
        let first = stream
            .dict
            .get(names.known.first)
            .and_then(PdfObject::as_int)
            .unwrap_or(0);
        let layout = parse_object_stream_layout(&data, n, first, &limits.syntax).ok()?;
        Some(layout.members.iter().map(|m| m.number).collect())
    }

    /// Whether the document reached through `trailer` has a *degenerate* page
    /// tree — a root `/Pages` node with `/Count ≤ 0` and no `/Kids`. This is
    /// the signature of a stub first revision (linearized files begin with an
    /// empty `<</Count 0/Kids[]/Type/Pages>>` placeholder that a later revision
    /// overrides); if the recovered xref stopped at that stub, the whole
    /// document reads as zero pages. Seeing it, `load_structure` escalates to a
    /// full rebuild, where last-occurrence-wins picks up the real page tree.
    ///
    /// Conservative: returns `false` whenever the catalog or `/Pages` node
    /// cannot be resolved from a file offset (e.g. it lives in an object
    /// stream), so a healthy document is never needlessly rebuilt.
    fn page_tree_looks_empty(&self, trailer: &Trailer) -> bool {
        let Some(catalog) = self.fetch_offset_dict(trailer.root) else {
            return false;
        };
        let Some(pages) = self.resolve_dict_value(catalog.get(self.names.known.pages)) else {
            return false;
        };
        let count_nonpositive = pages
            .get(self.names.known.count)
            .and_then(PdfObject::as_int)
            .unwrap_or(0)
            <= 0;
        let kids_empty = match pages.get(self.names.known.kids) {
            Some(PdfObject::Array(kids)) => kids.is_empty(),
            None => true,
            // An indirect /Kids is not evidence of emptiness.
            _ => false,
        };
        count_nonpositive && kids_empty
    }

    /// Whether the trailer's `/Root` reference resolves to a catalog the xref
    /// chain can actually reach. A `/Root` that is absent from the merged xref,
    /// or whose recorded offset no longer parses as a dictionary, is corruption
    /// the chain itself cannot detect (the trailer still names a `/Root`); it
    /// warrants escalating to a full rebuild, which relocates the catalog by
    /// scanning object headers and object streams.
    ///
    /// A `/Root` that lives in an object stream is trusted without decoding it
    /// here — object-stream membership is normal for healthy modern PDFs, and
    /// the offset-only fetch below cannot read it, so treating it as unresolved
    /// would needlessly rebuild every compressed document.
    fn root_resolves(&self, trailer: &Trailer) -> bool {
        match self.entries.get(&trailer.root.number) {
            None => false,
            Some((_, ObjectLocation::InObjectStream { .. })) => true,
            Some((_, ObjectLocation::Offset(_))) => self.fetch_offset_dict(trailer.root).is_some(),
            Some((_, ObjectLocation::Free)) => false,
        }
    }

    /// Whether every offset entry in the merged view actually points at the
    /// object header it claims (PDFium `CPDF_Parser::VerifyCrossRefTable`).
    ///
    /// Only meaningful for a chain reached by *recovering* the `startxref`
    /// offset: a file whose `startxref` is wrong is a file whose byte offsets
    /// have shifted, and the table sitting at the recovered location is then
    /// usually stale in the same way. PDFium never even looks at such a table —
    /// a `startxref` that does not land on `xref`/an xref stream sends it
    /// straight to `RebuildCrossRef` — so validating here is how we reach the
    /// same rebuild from a scan-based recovery that PDFium does not perform.
    ///
    /// Entries in object streams and free entries have no offset to check and
    /// are skipped. A single mismatch condemns the table: partial staleness is
    /// what makes these files render half-empty rather than fail outright.
    fn xref_offsets_are_consistent(&self) -> bool {
        self.entries.iter().all(|(&number, &(_, location))| {
            let ObjectLocation::Offset(off) = location else {
                return true;
            };
            self.object_header_number_at(off) == Some(number)
        })
    }

    /// Parse `N G obj` at `off` and return `N`. `None` when the bytes there are
    /// not an object header.
    fn object_header_number_at(&self, off: u64) -> Option<u32> {
        let window = self.file.get(off as usize..)?;
        let mut i = 0usize;
        let skip_ws = |w: &[u8], i: &mut usize| {
            while w.get(*i).is_some_and(|b| b.is_ascii_whitespace()) {
                *i += 1;
            }
        };
        let take_digits = |w: &[u8], i: &mut usize| -> Option<u64> {
            let start = *i;
            let mut v: u64 = 0;
            while let Some(&b) = w.get(*i) {
                if !b.is_ascii_digit() {
                    break;
                }
                // Saturate rather than wrap: an absurd run of digits is not an
                // object number we could match anyway.
                v = v.saturating_mul(10).saturating_add(u64::from(b - b'0'));
                *i += 1;
            }
            (*i > start).then_some(v)
        };
        skip_ws(window, &mut i);
        let number = take_digits(window, &mut i)?;
        skip_ws(window, &mut i);
        take_digits(window, &mut i)?; // generation
        skip_ws(window, &mut i);
        window.get(i..i + 3).filter(|w| *w == b"obj")?;
        u32::try_from(number).ok()
    }

    /// Fetch and parse an indirect object located at a file offset, returning
    /// its dictionary. `None` for free/compressed/unparsable objects.
    fn fetch_offset_dict(&self, id: ObjectId) -> Option<Dictionary> {
        let &(_, ObjectLocation::Offset(off)) = self.entries.get(&id.number)? else {
            return None;
        };
        let window = self.file.get(off as usize..)?;
        let mut parser = ObjectParser::new(window, off, &self.limits.syntax, self.names);
        let parsed = parser.parse_indirect(&mut |_| None).ok()?;
        parsed.object.as_dict().cloned()
    }

    /// Resolve a dictionary value that is either a direct dictionary or a
    /// one-level reference to one.
    fn resolve_dict_value(&self, value: Option<&PdfObject>) -> Option<Dictionary> {
        match value? {
            PdfObject::Reference(id) => self.fetch_offset_dict(*id),
            PdfObject::Dictionary(d) => Some((**d).clone()),
            _ => None,
        }
    }

    /// Freeze the merged entries into the dense `XrefMap`.
    fn build_xref_map(&mut self, trailer: &Trailer) -> XrefMap {
        let max_num = self.entries.keys().copied().max().unwrap_or(0);
        let size = (max_num as usize) + 1;
        let mut locations = vec![ObjectLocation::Free; size];
        let mut generations = vec![0u16; size];
        for (&n, &(g, loc)) in &self.entries {
            locations[n as usize] = loc;
            generations[n as usize] = g;
        }
        // Object 0 is the free-list head; never a real object.
        locations[0] = ObjectLocation::Free;

        // /Size disagreement is informational (PDFium ignores wrong sizes;
        // we record the repair for observability).
        if let Some(declared) = trailer
            .dict
            .get(self.names.known.size)
            .and_then(PdfObject::as_int)
            && declared != size as i64
        {
            self.recovery.push(RecoveryEvent::SizeRepaired {
                declared,
                actual: size as u32,
            });
        }
        XrefMap::from_parts(locations.into_boxed_slice(), generations.into_boxed_slice())
    }
}

/// Scan `window` for an `N G obj` header whose object number is `number`,
/// returning `(header start relative to window, generation)`. Used by the
/// document layer to repair xref entries whose declared offset does not
/// land on the declared object (PDFium re-scans the same way).
pub fn scan_for_object_header(window: &[u8], number: u32) -> Option<(usize, u16)> {
    let mut i = 0usize;
    while i + 3 <= window.len() {
        if &window[i..i + 3] == b"obj"
            && (i + 3 == window.len() || !crate::syntax::classify::is_regular(window[i + 3]))
            && let Some((start, n, generation)) = backtrack_obj_header(window, i)
            && n == number
        {
            return Some((start, generation));
        }
        i += 1;
    }
    None
}

/// From an `obj` keyword at `kw_pos`, backtrack over `<num> <gen>` and
/// return (header start, number, generation).
/// The body of the stream object whose `obj` keyword ends at `after_obj`, as
/// `(first byte, one past the last)`, when it can be trusted: the object is a
/// dictionary followed by `stream`, its `/Length` is a direct number, and
/// `endstream` is the next token after that many bytes. These are the object
/// parser's own conditions for taking `/Length` at its word
/// (`ObjectParser::read_stream_body`), so the range is exactly what every
/// later read of the object treats as opaque stream data.
///
/// The rebuild scan steps over such a body. Reading it found nothing that
/// belongs to the document — bytes inside a stream are not objects, and a
/// header-shaped run in compressed data (or the objects of an embedded PDF
/// stored uncompressed) could only displace a real object — and it read the
/// whole file: a 781 MB scanned book whose `startxref` was 13 KB off took
/// 1.9 s to open and had every page of its mapping resident before the first
/// page was rendered, though its dictionaries are a few megabytes. PDFium's
/// rebuild reads stream bodies by `/Length` the same way. A stream whose
/// `/Length` is missing, indirect or wrong is scanned through as before.
fn verified_stream_body(
    file: &[u8],
    after_obj: usize,
    syntax: &SyntaxLimits,
    names: &NameTable,
) -> Option<(usize, usize)> {
    // Only a dictionary can head a stream; do not parse anything else.
    let mut at = after_obj;
    while file
        .get(at)
        .is_some_and(|&b| crate::syntax::classify::is_whitespace(b))
    {
        at += 1;
    }
    if file.get(at..at + 2) != Some(b"<<".as_slice()) {
        return None;
    }
    let mut parser = ObjectParser::new(file.get(after_obj..)?, after_obj as u64, syntax, names);
    let PdfObject::Dictionary(dict) = parser.parse_object().ok()? else {
        return None;
    };
    let lexer = parser.lexer_mut();
    let keyword = lexer.next_token().ok()?;
    if !matches!(&keyword.value, Token::Keyword(kw) if kw == b"stream") {
        return None;
    }
    // The same end-of-line rule as the object parser: optional blanks, then
    // CRLF, LF or a lone CR.
    let mut pos = after_obj + lexer.pos();
    while matches!(file.get(pos), Some(b' ') | Some(b'\t')) {
        pos += 1;
    }
    if file.get(pos) == Some(&b'\r') {
        pos += 1;
        if file.get(pos) == Some(&b'\n') {
            pos += 1;
        }
    } else if file.get(pos) == Some(&b'\n') {
        pos += 1;
    }
    let declared = match dict.get(names.known.length) {
        Some(PdfObject::Integer(n)) => *n,
        Some(PdfObject::Real(r)) => *r as i64,
        _ => return None,
    };
    let len = usize::try_from(declared).ok()?;
    let end = pos.checked_add(len).filter(|&end| end <= file.len())?;
    let mut check = Lexer::new(file, 0, syntax);
    check.set_pos(end);
    matches!(check.next_token(),
        Ok(t) if matches!(&t.value, Token::Keyword(kw) if kw == b"endstream"))
    .then_some((pos, end))
}

fn backtrack_obj_header(file: &[u8], kw_pos: usize) -> Option<(usize, u32, u16)> {
    let mut j = kw_pos;
    // whitespace between gen and `obj` (required)
    let ws_end = j;
    while j > 0 && crate::syntax::classify::is_whitespace(file[j - 1]) {
        j -= 1;
    }
    if j == ws_end {
        return None;
    }
    // generation digits
    let gen_end = j;
    while j > 0 && file[j - 1].is_ascii_digit() {
        j -= 1;
    }
    if j == gen_end {
        return None;
    }
    let generation: u16 = std::str::from_utf8(&file[j..gen_end]).ok()?.parse().ok()?;
    // whitespace between num and gen (required)
    let ws2_end = j;
    while j > 0 && crate::syntax::classify::is_whitespace(file[j - 1]) {
        j -= 1;
    }
    if j == ws2_end {
        return None;
    }
    // object-number digits
    let num_end = j;
    while j > 0 && file[j - 1].is_ascii_digit() {
        j -= 1;
    }
    if j == num_end {
        return None;
    }
    // Word boundary before the number ("x12 0 obj" is not a header).
    if j > 0 && crate::syntax::classify::is_regular(file[j - 1]) {
        return None;
    }
    let number: u32 = std::str::from_utf8(&file[j..num_end]).ok()?.parse().ok()?;
    if number == 0 {
        return None;
    }
    Some((j, number, generation))
}