Skip to main content

pdfcer_model/
document.rs

1//! # The Document — pdfcer's single object model (load side)
2//!
3//! Ties the layers together: retained source buffer → header probe →
4//! xref chain → eagerly parsed indirect objects → reference resolution.
5//! Spec sources: `iso32000__s__7.5.5.md` (load algorithm),
6//! `iso32000__s__7.3.10.md` (resolution semantics, dangling-ref rule),
7//! `iso32000__s__7.7.2.md` (catalog) in the PDF-spec RAG. Clause
8//! numbers are ISO 32000-1:2008.
9//!
10//! ## THE named invariant: one `Document`, both directions
11//!
12//! [`Document`] is simultaneously the parse result AND (from the first
13//! editing Pass on) the write source
14//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 3). No
15//! separate builder/generation model may ever be introduced — the
16//! audited prior art shows exactly how that bifurcation forecloses
17//! round-trip editing. Write-side machinery (dirty tracking, the
18//! §7.5.6 incremental writer) lands in the first editing Pass and
19//! operates on *this* type.
20//!
21//! ## The retained buffer
22//!
23//! The document owns the complete source bytes for its lifetime. Every
24//! file-level [`IndirectObject`] records a
25//! [`ByteSpan`](crate::span::ByteSpan) into this buffer (its full
26//! `N G obj … endobj` definition), which is what makes
27//! minimal-diff/incremental re-emission mechanical (ARCHITECTURE.md §5;
28//! `crate::span`). Memory cost is the file size — the deliberate price
29//! of the round-trip invariant, and small next to any renderer's
30//! working set.
31//!
32//! Objects that lived **inside an object stream** (§7.5.7) have no span
33//! of their own; they carry [`Provenance::ObjectStream`] instead,
34//! naming the container and index. See [`Provenance`] for why that
35//! distinction is a type and not a sentinel.
36//!
37//! ## Eager parse, strict failure (Pass 1 posture)
38//!
39//! `load`/`from_bytes` parse **every in-use object up front**; any
40//! malformed object fails the whole load with a precise error. Rationale:
41//! fail-clean over partial success (ARCHITECTURE.md §10) — a viewer
42//! that opens a file "successfully" and then errors object-by-object
43//! gives worse diagnostics than one clean refusal naming the offset.
44//! Lazy/tolerant loading (open-what-you-can) is a deliberate later
45//! feature for damaged-file recovery, driven by corpus evidence, not a
46//! default.
47//!
48//! ### Two phases, in this order (§7.5.7 + §7.5.8.3)
49//!
50//! 1. **File-level objects** — every type-1 (`InUse`) xref entry is
51//!    parsed at its offset.
52//! 2. **Compressed objects** — every type-2 (`InStream`) entry is
53//!    resolved through its container.
54//!
55//! The order is forced, not stylistic: a container object stream is
56//! itself an ordinary file-level stream object reached through a
57//! type-1 entry, so phase 2 needs phase 1 to have finished. §7.5.7
58//! guarantees this terminates at two levels — an object stream may not
59//! contain a stream, so a container can never live inside another
60//! container, and the object supplying a container's `/Length` may not
61//! be compressed either. There is no recursion to guard, only an
62//! ordering to respect.
63//!
64//! Each container is decoded **once** and cached for the duration of
65//! the load ([`ObjectStream`]); a container holding 200 objects would
66//! otherwise be inflated 200 times.
67//!
68//! ## Resolution semantics (§7.3.10, §7.5.4)
69//!
70//! [`Document::get`] / [`Document::resolve`] implement, exactly:
71//! - **dangling reference → null** ("shall not be considered an
72//!   error") — including object numbers with no xref entry at all;
73//! - **generation mismatch → null** (a stale reference; the xref
74//!   entry's generation is part of the identity);
75//! - **free entry → null** (§7.5.4 free-list mechanics — how deleted
76//!   and hybrid-hidden objects read as absent);
77//! - **reference chains are depth-guarded** ([`MAX_RESOLVE_DEPTH`],
78//!   pdfcer policy — `5 0 obj 5 0 R endobj` is legal syntax and must
79//!   not loop).
80
81use std::collections::HashMap;
82use std::collections::hash_map::Entry;
83use std::path::Path;
84
85use crate::linearization::{self, Linearization};
86use crate::object::{Dict, IndirectObject, ObjId, Object, Provenance};
87use crate::objstm::{ObjStmError, ObjectStream};
88use crate::parser::{ParseError, Parser, StreamLengthPolicy, TerminatorPolicy};
89use crate::recover::{self, RecoveryReport};
90use crate::view::DocumentView;
91use crate::xref::{self, SectionShape, XrefEntry, XrefError, XrefErrorKind, XrefTable};
92
93mod encryption_refusal;
94use crate::{PdfError, PdfVersion};
95pub use encryption_refusal::EncryptedRefusal;
96
97/// Maximum reference-chain hops [`Document::resolve`] follows before
98/// declaring a cycle and yielding null.
99///
100/// pdfcer policy (ARCHITECTURE.md §10): the spec permits
101/// reference-to-reference chains and does not bound them; legitimate
102/// files use at most a handful of hops. Null (not an error) on
103/// exhaustion keeps the §7.3.10 "references never hard-fail" posture
104/// consistent even for hostile cycles.
105pub const MAX_RESOLVE_DEPTH: usize = 32;
106
107/// Errors from loading a document.
108#[derive(Debug, thiserror::Error)]
109#[non_exhaustive]
110pub enum DocError {
111    /// File I/O failed.
112    #[error("I/O error reading PDF: {0}")]
113    Io(#[from] std::io::Error),
114    /// The document is encrypted with a configuration pdfcer will not decrypt
115    /// (§7.6). The inner error names *which* configuration and why — an
116    /// unimplemented cipher, an unsourced algorithm, a different security
117    /// handler, or a document no conforming reader may open at all.
118    ///
119    /// Those are four different facts with four different next actions, which
120    /// is why this is not one flat "encrypted files are unsupported".
121    #[error("{0}")]
122    Encryption(#[from] crate::crypto::EncryptionUnsupported),
123    /// The document is encrypted with a configuration pdfcer **can** decrypt,
124    /// but no password opened it.
125    ///
126    /// §7.6.3.1 requires trying the empty user password first and silently, so
127    /// reaching this error means the empty password was already tried and
128    /// failed: the document genuinely has a non-empty user password. The
129    /// caller should prompt and retry with
130    /// [`Document::from_bytes_with_password`].
131    ///
132    /// **N6**: ISO 32000-1 states no error model here at all — no retry limit,
133    /// no reporting requirement, nothing about distinguishing a wrong password
134    /// from a malformed one. All of that is pdfcer policy.
135    #[error("this document is password-protected; supply the user or owner password")]
136    PasswordRequired,
137    /// Nothing authenticated, **and** the supplied password contains
138    /// characters `/R` 5's password preprocessing may have changed before
139    /// hashing — so "wrong password" is not the only explanation.
140    ///
141    /// The Adobe supplement's step 1 applies **SASLprep** (RFC 4013) with the
142    /// Normalize and BIDI options before the UTF-8 conversion. pdfcer
143    /// implements the UTF-8 conversion and the 127-byte truncation exactly and
144    /// does **not** implement SASLprep; neither RFC is staged in the project's
145    /// spec corpus, and a stringprep dependency was not taken for a read-only
146    /// increment.
147    ///
148    /// For an all-ASCII password SASLprep is the identity, so this error can
149    /// never arise from one. pdfcer still *attempts* a non-ASCII password —
150    /// SASLprep is the identity for much more than ASCII, and getting it wrong
151    /// cannot open a document with a wrong key, only fail to open one with the
152    /// right password. This variant exists so that failure does not
153    /// masquerade as [`Self::PasswordRequired`]'s "you typed it wrong", which
154    /// would send the operator to re-check a password that was correct.
155    ///
156    /// Reported only at `/R` 5. Password encoding below that is PDFDocEncoding
157    /// (**T8**), a different unimplemented question.
158    #[error(
159        "this document is password-protected; the password supplied contains non-ASCII characters, \
160         and pdfcer does not apply the RFC 4013 (SASLprep) normalisation that /R 5 specifies before \
161         hashing — so a correct password can be rejected here"
162    )]
163    PasswordRequiresNormalisation,
164    /// Authentication failed at handler revision **6** (AES-256 hardened),
165    /// where the failure is **not** unambiguously "wrong password" (`Pass
166    /// 5.4`).
167    ///
168    /// `/R` 6's key derivation (Algorithm 2.B) contains a genuine spec
169    /// ambiguity — **A13**, the loop-exit test, which is internally
170    /// inconsistent between steps (e) and (f) and produces a different digest
171    /// (hence a different key, hence a failed authentication) depending on the
172    /// reading. pdfcer defaults to the reading pypdf and Acrobat write
173    /// ([`crate::crypto::r6::A13Reading::PerformThenTest`]); a document written
174    /// by an implementation that took the other reading would fail here with a
175    /// correct password. This variant names A13 so that failure is not
176    /// reported as "you typed it wrong" (`R169`: a spec ambiguity is disclosed,
177    /// never silently resolved). Raised only at `/R` 6.
178    #[error(
179        "this document is password-protected (AES-256 /R 6); authentication failed. If the password is correct, the cause may be ambiguity A13 in ISO 32000-2 Algorithm 2.B's loop-exit test -- pdfcer uses the reading pypdf and Acrobat write, and a file written under the other reading would not open"
180    )]
181    PasswordRequiredR6,
182    /// The `%PDF-` header probe failed — not a PDF.
183    #[error(transparent)]
184    Header(PdfError),
185    /// The cross-reference machinery failed — a damaged/unreadable
186    /// xref chain, or the deliberate `/Encrypt` capability-gap refusal
187    /// (`XrefErrorKind::EncryptionUnsupported`).
188    #[error(transparent)]
189    Xref(#[from] XrefError),
190    /// An indirect object at an xref-declared offset failed to parse.
191    #[error("object {id} (xref offset {offset}): {source}")]
192    BadObject {
193        /// The object the xref table pointed at.
194        id: ObjId,
195        /// The offset the xref entry gave.
196        offset: u64,
197        /// The underlying structural error.
198        source: ParseError,
199    },
200    /// The object parsed at an offset doesn't match the xref entry
201    /// that pointed there (wrong number or generation) — the table and
202    /// body disagree; strict Pass 1 refuses rather than guessing which
203    /// is right.
204    #[error("object at xref offset {offset} declares {found}, xref expected {expected}")]
205    ObjectIdMismatch {
206        /// What the xref entry promised.
207        expected: ObjId,
208        /// What the bytes at the offset declared.
209        found: ObjId,
210        /// The offset in question.
211        offset: u64,
212    },
213    /// A type-2 cross-reference entry (§7.5.8.3) named an object stream
214    /// that is not present as a loadable file-level object.
215    ///
216    /// §7.5.7: "there shall be an entry for it in a cross-reference
217    /// table or cross-reference stream" — so a missing container means
218    /// the file's own xref contradicts itself.
219    #[error("object {num} is compressed in object stream {container}, which is not present")]
220    ObjectStreamMissing {
221        /// The container the type-2 entry named (generation always 0).
222        container: ObjId,
223        /// The object that was to be read from it.
224        num: u32,
225    },
226    /// An object stream (§7.5.7) could not be decoded or read.
227    #[error("object stream {container}: {source}")]
228    ObjectStream {
229        /// The container object stream.
230        container: ObjId,
231        /// What went wrong inside it.
232        source: ObjStmError,
233    },
234    /// The object number stored in an object stream's pair table
235    /// disagrees with the object number its type-2 cross-reference
236    /// entry promised — the xref and the container contradict each
237    /// other, and the strict loader refuses rather than picking one
238    /// (the same posture as [`DocError::ObjectIdMismatch`] for
239    /// file-level objects).
240    #[error(
241        "object stream {container} index {index} holds object {found}, xref expected object {expected}"
242    )]
243    ObjectStreamIdMismatch {
244        /// The container object stream.
245        container: ObjId,
246        /// The index within it that was read.
247        index: u32,
248        /// The object number the type-2 entry promised.
249        expected: u32,
250        /// The object number the pair table actually stored.
251        found: u32,
252    },
253    /// The trailer has no usable `/Root` (Table 15 requires it; a
254    /// conformant update trailer always repeats it — see the RAG's
255    /// gotcha on why fallback-to-older-trailers is a repair heuristic,
256    /// not Pass 1 behavior).
257    #[error("trailer /Root missing or not a reference to a dictionary")]
258    NoCatalog,
259    /// Cross-reference **recovery** (decision 013) was attempted after the
260    /// strict load failed, but could not produce a document — no
261    /// confirmable objects, no `/Catalog`, or the entry cap. A named
262    /// fail-clean refusal, never a partial/garbage document. (An encrypted
263    /// recovered file is refused as [`XrefErrorKind::EncryptionUnsupported`]
264    /// via [`DocError::Xref`] instead, matching the clean-path capability
265    /// gap.)
266    ///
267    /// [`XrefErrorKind::EncryptionUnsupported`]: crate::xref::XrefErrorKind::EncryptionUnsupported
268    #[error("cross-reference recovery failed: {0}")]
269    Recovery(#[from] crate::recover::RecoverError),
270}
271
272/// A loaded PDF document: retained bytes + parsed structure.
273///
274/// See the module docs for the three design commitments this type
275/// embodies (one model, retained buffer, strict eager load).
276#[derive(Debug, Clone)]
277pub struct Document {
278    /// The complete, untouched source bytes (the provenance substrate —
279    /// every span in `objects` indexes into this).
280    buf: Vec<u8>,
281    /// Header-declared version (`%PDF-M.N`). Catalog `/Version`
282    /// override (§7.5.5) is reconciled by [`Document::version`].
283    header_version: PdfVersion,
284    /// Merged, `/Size`-filtered cross-reference table.
285    xref: XrefTable,
286    /// The newest trailer dictionary.
287    trailer: Dict,
288    /// Every in-use object, parsed. Keyed by full `(num, generation)`
289    /// identity.
290    objects: HashMap<ObjId, IndirectObject>,
291    /// The byte offset this file's own `startxref` names — the value an
292    /// appended update's `/Prev` must carry (§7.5.6). Retained at load
293    /// because it is not recoverable from the merged view.
294    base_startxref: u64,
295    /// The physical form of the newest cross-reference section, so a
296    /// save can match it instead of normalizing (R33).
297    section_shape: SectionShape,
298    /// Annex F linearization state, detected at load (R36).
299    linearization: Linearization,
300    /// Highest object number the cross-reference chain mentions, before
301    /// the `/Size` filter — the number a writer must allocate above.
302    highest_object_number: u32,
303    /// How many cross-reference entries `/Size` suppressed.
304    suppressed_by_size: usize,
305    /// Which objects a hybrid-reference file hides, and whether pdfcer could
306    /// tell (`Pass 281.0`). Default (empty, readable) for every non-hybrid
307    /// file and for a recovered base, where the concept does not apply.
308    hybrid: crate::xref::HybridPartition,
309    /// Every contradiction pdfcer met while loading and decided rather than
310    /// refused (`Pass 283.0`). Empty for a file that says nothing twice.
311    anomalies: Vec<LoadAnomaly>,
312    /// `Some` when this document was loaded via **cross-reference
313    /// recovery** (decision 013): the stored xref could not be parsed and
314    /// the table was rebuilt by scanning. The writer reads this to force a
315    /// full rewrite and refuse incremental save (the recovered-base rule);
316    /// the CLI/GUI read it to disclose. `None` for every cleanly-loaded
317    /// file — recovery lives entirely on the strict-load error path, so a
318    /// clean file's flow never sets it.
319    recovery: Option<RecoveryReport>,
320    /// `Some` when this document was loaded from an **encrypted** file and
321    /// successfully decrypted (§7.6, [`crate::crypto`]).
322    ///
323    /// Holds the configuration, which password opened it, and — privately —
324    /// what an incremental save needs to append under the same handler: the
325    /// file key and the source bytes as they were before decryption.
326    encryption: Option<DocumentEncryption>,
327}
328
329/// What a successfully-decrypted document was protected with.
330///
331/// Reported so the shells can tell the operator the document is encrypted,
332/// which cipher, and what the author's permissions ask for. It is a
333/// **disclosure**, not a gate: §7.6.3.1 states plainly that "there is nothing
334/// inherent in PDF encryption that enforces the document permissions", so
335/// anywhere pdfcer chooses to act on a permission bit it must say so (rule 4).
336/// What decrypts a document on load: a password to authenticate, or an
337/// already-recovered key carried from the document a save descends from.
338#[derive(Clone, Copy)]
339enum Credential<'a> {
340    Password(Option<&'a [u8]>),
341    Reuse(&'a DocumentEncryption),
342}
343
344#[derive(Debug, Clone)]
345pub struct DocumentEncryption {
346    /// The parsed `/Encrypt` dictionary.
347    pub config: crate::crypto::EncryptionConfig,
348    /// Which password opened it. [`AuthKind::EmptyUser`] is the no-prompt
349    /// case — the document had an empty user password, which every
350    /// conforming reader tries silently before prompting.
351    ///
352    /// [`AuthKind::EmptyUser`]: crate::crypto::AuthKind::EmptyUser
353    pub auth: crate::crypto::AuthKind,
354    /// The Algorithm 3.13 `/Perms` verdict — **the only integrity check in
355    /// PDF encryption**, and a `should`, not a `shall`.
356    ///
357    /// [`PermsCheck::NotApplicable`] for every `/R` ≤ 4 document, where the
358    /// entry does not exist. That is the *ordinary* answer, not a failed
359    /// check, and a front end must not render it as one.
360    ///
361    /// # Why it is here rather than acted on
362    ///
363    /// `/Perms` holds an encrypted copy of `/P` and `/EncryptMetadata`. The
364    /// plaintext copies sit in the `/Encrypt` dictionary where anyone can edit
365    /// them, with no integrity protection anywhere else in clause 7.6
366    /// (**N7**). So a disagreement is the one signal PDF gives that a
367    /// document's stated permissions are not the ones its encryptor recorded —
368    /// and no clause says what to do about it.
369    ///
370    /// pdfcer reports it and **prefers neither value**:
371    /// [`EncryptionConfig::permissions`] keeps returning the dictionary's
372    /// `/P`, because that is what the file declares and what every other
373    /// viewer shows, and this field carries the disagreement beside it.
374    /// Silently substituting the decrypted copy would be pdfcer deciding, on an
375    /// inference, what the operator is told — the exact shape project rule 4
376    /// forbids. Refusing the document would reject files nothing else objects
377    /// to, on the strength of a check the standard declines to require. See
378    /// [`PermsCheck`]'s own docs (**T27**).
379    ///
380    /// [`PermsCheck`]: crate::crypto::PermsCheck
381    /// [`PermsCheck::NotApplicable`]: crate::crypto::PermsCheck::NotApplicable
382    /// [`EncryptionConfig::permissions`]: crate::crypto::EncryptionConfig::permissions
383    pub perms: crate::crypto::PermsCheck,
384    /// The recovered file key. Private: [`crate::writer::save_incremental`]
385    /// encrypts appended objects with it (§7.6.2), so a save needs no second
386    /// password prompt. Its `Debug` never prints the key.
387    key: crate::crypto::FileKey,
388    /// The object number of an indirect `/Encrypt` dictionary (`None` when it
389    /// is direct in the trailer).
390    encrypt_dict_id: Option<u32>,
391    /// The file's bytes before decryption. Decryption rewrites stream data in
392    /// the document's buffer, so an append must start from these instead.
393    ciphertext: std::sync::Arc<[u8]>,
394    /// Whether an append may keep an RC4 handler; see [`Document::set_rc4_append`].
395    rc4_append: crate::writer::Rc4Append,
396}
397
398impl DocumentEncryption {
399    /// The recovered file key an append encrypts under.
400    pub(crate) fn file_key(&self) -> &crate::crypto::FileKey {
401        &self.key
402    }
403
404    /// An indirect `/Encrypt` dictionary's object number; an append leaves it in clear.
405    pub(crate) fn encrypt_dict_id(&self) -> Option<u32> {
406        self.encrypt_dict_id
407    }
408
409    /// The source bytes as stored on disk — ciphertext wherever the file
410    /// encrypted something.
411    pub(crate) fn ciphertext(&self) -> &[u8] {
412        &self.ciphertext
413    }
414
415    /// Whether an incremental save can append under this document's key.
416    /// `false` for an RC4 document unless [`Document::set_rc4_append`] opted
417    /// in: pdfcer never chooses RC4 (decision 190), so
418    /// [`crate::writer::save_incremental`] refuses it with
419    /// [`crate::writer::WriteError::Rc4AppendRefused`].
420    #[must_use]
421    pub fn appendable(&self) -> bool {
422        !self.uses_rc4() || self.rc4_append == crate::writer::Rc4Append::Preserve
423    }
424
425    /// Whether strings or streams are encrypted with RC4 (`/V` 1–2, or a
426    /// `/V` 4 crypt filter with `/CFM /V2`; ISO 32000-2 §7.6.2).
427    #[must_use]
428    pub fn uses_rc4(&self) -> bool {
429        use crate::crypto::Cipher;
430        [self.key.string_cipher(), self.key.stream_cipher()].contains(&Cipher::Rc4)
431    }
432
433    /// The RC4 append policy in force; [`Rc4Append::Refuse`] unless
434    /// [`Document::set_rc4_append`] changed it.
435    ///
436    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
437    #[must_use]
438    pub fn rc4_append(&self) -> crate::writer::Rc4Append {
439        self.rc4_append
440    }
441
442    /// Whether `bit` lets the operator who opened the document do what it
443    /// governs (ISO 32000-2 Table 22). The owner password grants everything;
444    /// a user (or empty-user) open is held to the declared `/P`. A bit the
445    /// document's revision does not define is not granted.
446    #[must_use]
447    pub fn grants(&self, bit: crate::crypto::PermissionBit) -> bool {
448        self.auth == crate::crypto::AuthKind::Owner
449            || self.config.permissions().granted(bit) == Some(true)
450    }
451}
452
453impl Document {
454    /// Load a document from a file on disk.
455    ///
456    /// # Errors
457    ///
458    /// [`DocError`] — I/O, header, xref, or object-level failure; every
459    /// variant carries the offending offset/object for diagnostics.
460    pub fn load(path: &Path) -> Result<Self, DocError> {
461        Self::from_bytes(std::fs::read(path)?)
462    }
463
464    /// Load a document from disk, supplying a password for an encrypted file.
465    ///
466    /// `password` is `None` to mean "no password known" — which is **not** the
467    /// same as an empty password. §7.6.3.1 requires a reader to try the empty
468    /// user password first and silently in *either* case, so `None` still
469    /// opens a permissions-only document with no prompt; what `None` means is
470    /// that if that fails, there is nothing else to try and the load returns
471    /// [`DocError::PasswordRequired`].
472    ///
473    /// Either the user or the owner password opens the document
474    /// (§7.6.3.1). Which one it was is reported by
475    /// [`Document::encryption`].
476    ///
477    /// # Errors
478    ///
479    /// [`DocError`] — as [`Document::load`], plus [`DocError::Encryption`] for
480    /// a configuration pdfcer will not decrypt and
481    /// [`DocError::PasswordRequired`] when no supplied password authenticated.
482    pub fn load_with_password(path: &Path, password: Option<&[u8]>) -> Result<Self, DocError> {
483        Self::from_bytes_with_password(std::fs::read(path)?, password)
484    }
485
486    /// Load a document from disk under explicit [`LoadOptions`] — the
487    /// path-shaped twin of [`Document::from_bytes_with_options`].
488    ///
489    /// # Why this exists as well as the bytes form
490    ///
491    /// `Pass 283.0` gave the loader a tolerant posture and gave the operator
492    /// the other choice, but shipped the choice on the **bytes** entry point
493    /// only. Every shell that opens a document opens a **file** — the GUI's
494    /// open-file action, the CLI's path argument — so taking the alternative
495    /// reading meant re-implementing [`Document::load`]'s `std::fs::read`
496    /// at each call site. An intervention route the intended caller can only
497    /// reach by rewriting the route beside it is not offered, it is merely
498    /// present.
499    ///
500    /// The operator's ruling this discharges: *"if the user can intervene in
501    /// a decision that should always be an option along with them not having
502    /// to intervene."* Re-loading the same path under
503    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]
504    /// is the whole intervention; see [`Document::load_anomalies`] for how a
505    /// shell learns there was a decision to intervene in.
506    ///
507    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]: LoadOptions::with_duplicate_keys
508    ///
509    /// # Examples
510    ///
511    /// ```no_run
512    /// use std::path::Path;
513    /// use pdfcer_model::document::{Document, LoadOptions};
514    /// use pdfcer_model::parser::DuplicateKeyPolicy;
515    ///
516    /// let path = Path::new("drawing.pdf");
517    /// let doc = Document::load(path)?;
518    /// if !doc.load_anomalies().is_empty() {
519    ///     // Offer the operator the other reading; nothing forces them to take it.
520    ///     let other = Document::load_with_options(
521    ///         path,
522    ///         None,
523    ///         LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst),
524    ///     )?;
525    ///     let _ = other;
526    /// }
527    /// # Ok::<(), pdfcer_model::document::DocError>(())
528    /// ```
529    ///
530    /// # Errors
531    ///
532    /// [`DocError`] — as [`Document::load_with_password`]. Under
533    /// [`LoadOptions::strict()`] this refuses every malformation `Pass 283.0`
534    /// taught the loader to decide.
535    pub fn load_with_options(
536        path: &Path,
537        password: Option<&[u8]>,
538        options: LoadOptions,
539    ) -> Result<Self, DocError> {
540        Self::from_bytes_with_options(std::fs::read(path)?, password, options)
541    }
542
543    /// Load a document from bytes (takes ownership — the buffer is
544    /// retained for the document's lifetime; see module docs).
545    ///
546    /// # Errors
547    ///
548    /// [`DocError`] — see [`Document::load`].
549    pub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError> {
550        Self::from_bytes_with_password(buf, None)
551    }
552
553    /// Load a COS-family file whose header is NOT `%PDF-` — a `%PPKLITE-`
554    /// address book or a `%FDF-` file — reusing the exact tokenizer, classic-
555    /// xref parser and object assembly the strict PDF path uses (`Pass 10.2`).
556    ///
557    /// `markers` are the accepted first-line tokens (e.g. `[b"%PPKLITE-"]`).
558    /// Only the STRICT path runs: there is no rebuild-by-scan recovery (these
559    /// files are written by Acrobat and well-formed; a malformed one is an
560    /// error, not a file to guess at) and no password (a trust store carries no
561    /// `/Encrypt`). The result is an ordinary [`Document`] — `get`, `trailer`,
562    /// `resolve` and the [`crate::graph::ObjectGraph`] impl all work — so a
563    /// reader (e.g. [`crate::trust_store`]) walks it with the normal object
564    /// model instead of a bespoke parser.
565    ///
566    /// # Errors
567    ///
568    /// [`DocError::Header`] if none of `markers` matches; [`DocError::Xref`] if
569    /// the cross-reference chain does not parse; other [`DocError`] object-level
570    /// failures as [`from_bytes_with_password`](Self::from_bytes_with_password).
571    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
572    pub fn from_cos_bytes(buf: Vec<u8>, markers: &[&[u8]]) -> Result<Self, DocError> {
573        let header_version = crate::probe_cos_header(&buf, markers).map_err(DocError::Header)?;
574        let loaded = xref::load_xref_chain(&buf).map_err(DocError::Xref)?;
575        let hybrid = loaded.hybrid_partition();
576        Self::assemble(
577            buf,
578            header_version,
579            loaded.table,
580            loaded.trailer,
581            loaded.startxref,
582            loaded.newest_shape,
583            loaded.highest_object_number,
584            loaded.suppressed_by_size,
585            hybrid,
586            None,
587            Credential::Password(None),
588            LoadOptions::default(),
589        )
590    }
591
592    /// Load a document from bytes, supplying a password for an encrypted file.
593    ///
594    /// See [`Document::load_with_password`] for what `None` means (it is not
595    /// the empty password).
596    ///
597    /// # Errors
598    ///
599    /// [`DocError`] — see [`Document::load_with_password`].
600    pub fn from_bytes_with_password(
601        buf: Vec<u8>,
602        password: Option<&[u8]>,
603    ) -> Result<Self, DocError> {
604        Self::from_bytes_with_options(buf, password, LoadOptions::default())
605    }
606
607    /// Load a document, choosing how its self-contradictions are decided
608    /// (`Pass 283.0`).
609    ///
610    /// The intervention half of the operator's ruling: a shell that has shown
611    /// the operator what pdfcer chose (via [`Document::load_anomalies`]) and
612    /// been told to take the other value re-loads the same bytes through here.
613    /// Everything else is identical to [`Document::from_bytes_with_password`],
614    /// which is this with the defaults.
615    ///
616    /// # Errors
617    ///
618    /// [`DocError`] — see [`Document::load_with_password`].
619    pub fn from_bytes_with_options(
620        buf: Vec<u8>,
621        password: Option<&[u8]>,
622        options: LoadOptions,
623    ) -> Result<Self, DocError> {
624        Self::from_bytes_inner(buf, Credential::Password(password), options)
625    }
626
627    /// Load `buf` — bytes produced by saving this document incrementally —
628    /// decrypting under this document's file key and access, with no
629    /// password. An unencrypted document loads `buf` like
630    /// [`Document::from_bytes`].
631    ///
632    /// The contract is that `buf` keeps this document's `/Encrypt` and
633    /// `/ID[0]` (an incremental save carries both, ISO 32000-2 §7.6.3); bytes
634    /// from anywhere else decrypt to noise.
635    ///
636    /// # Errors
637    ///
638    /// [`DocError`] — see [`Document::load`].
639    pub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError> {
640        let credential = match &self.encryption {
641            Some(e) => Credential::Reuse(e),
642            None => Credential::Password(None),
643        };
644        Self::from_bytes_inner(buf, credential, LoadOptions::default())
645    }
646
647    fn from_bytes_inner(
648        buf: Vec<u8>,
649        credential: Credential<'_>,
650        options: LoadOptions,
651    ) -> Result<Self, DocError> {
652        // 1. Header (§7.5.2 via the Pass 0 probe).
653        match crate::probe_header(&buf) {
654            // Header OK: try the strict §7.5.5 cross-reference load.
655            Ok(header_version) => match xref::load_xref_chain(&buf) {
656                Ok(loaded) => {
657                    let hybrid = loaded.hybrid_partition();
658                    Self::assemble(
659                        buf,
660                        header_version,
661                        loaded.table,
662                        loaded.trailer,
663                        loaded.startxref,
664                        loaded.newest_shape,
665                        loaded.highest_object_number,
666                        loaded.suppressed_by_size,
667                        hybrid,
668                        None,
669                        credential,
670                        options,
671                    )
672                }
673                // The strict path failed. Decision 013: attempt
674                // rebuild-by-scan recovery, but ONLY on the specific
675                // failure kinds that mean the cross-reference machinery is
676                // unparseable — never on the deliberate `/Encrypt`
677                // capability gap, and never on a future unknown kind
678                // (`recovery_reason_for` returns `None` for both).
679                Err(e) => match recover::recovery_reason_for(&e.kind) {
680                    None => Err(DocError::Xref(e)),
681                    Some(reason) => match recover::recover(&buf, reason) {
682                        Ok(rec) => Self::assemble_recovered(buf, Some(header_version), rec),
683                        // A broken-xref-AND-encrypted file fails clean for
684                        // the RIGHT reason (§7.6), not as a recovery error.
685                        Err(recover::RecoverError::Encrypted) => Err(DocError::Xref(XrefError {
686                            offset: 0,
687                            kind: XrefErrorKind::EncryptionUnsupported,
688                        })),
689                        Err(other) => Err(DocError::Recovery(other)),
690                    },
691                },
692            },
693            // Header probe failed ("not a PDF", offset-start, leading junk).
694            // Rebuild-by-scan is header-independent (absolute offsets), so
695            // it also opens an offset-start file (decision 007 §10 item 6).
696            // Attempt recovery, but succeed ONLY if the scan finds objects
697            // AND a `/Catalog`; otherwise the ORIGINAL header error stands
698            // ("not a PDF").
699            Err(header_err) => match recover::recover(&buf, recover::RecoveryReason::MissingHeader)
700            {
701                Ok(rec) => Self::assemble_recovered(buf, None, rec),
702                Err(_) => Err(DocError::Header(header_err)),
703            },
704        }
705    }
706
707    /// Assemble a [`Document`] from a cross-reference view (table plus
708    /// trailer plus physical facts), running the §7.5.7 two-phase eager
709    /// parse. Shared by the strict load path and the recovery path so the
710    /// object-parse, object-stream resolution, and linearization detection
711    /// are written exactly once.
712    ///
713    /// `recovery` is `Some` only on the rebuild-by-scan path; the writer
714    /// and front ends read it (decision 013).
715    #[allow(clippy::too_many_arguments)] // a private assembly seam; the
716    // alternative (a builder struct) buys nothing for two call sites.
717    fn assemble(
718        mut buf: Vec<u8>,
719        header_version: PdfVersion,
720        table: XrefTable,
721        trailer: Dict,
722        base_startxref: u64,
723        section_shape: SectionShape,
724        highest_object_number: u32,
725        suppressed_by_size: usize,
726        hybrid: crate::xref::HybridPartition,
727        recovery: Option<RecoveryReport>,
728        credential: Credential<'_>,
729        options: LoadOptions,
730    ) -> Result<Self, DocError> {
731        // Phase 1. Eagerly parse every file-level in-use object. Strict on
732        // the clean path; on the recovery path the SAME `/Length`-vs-
733        // `endstream` leniency `crate::recover`'s confirmation step used
734        // must apply here too, or an object recovery accepted would be
735        // rejected on re-parse and cost the whole document (the exact
736        // failure this policy exists to close). Free entries resolve to
737        // null, not to bytes; type-2 entries wait for phase 2 (module docs).
738        // THE CLEAN PATH IS LENIENT TOO SINCE `Pass 283.0`, and the
739        // comment above used to say the opposite.
740        //
741        // `RecoverFromEndstream` re-derives an extent ONLY when the stored
742        // `/Length` cannot be used — absent, non-integer, unresolvable, past
743        // the end of the buffer, or not landing on `endstream`. A usable
744        // `/Length` is still believed, so this changes behaviour for exactly
745        // one class of file: the ones that previously FAILED.
746        //
747        // The operator's ruling: *"we should be making pdfcer so that it opens
748        // pdfs that have errors, and have a way that it manages those errors
749        // such that they aren't fatal."* Losing a 46 KB drawing over a
750        // `/Metadata` stream that omits `/Length` — which is what happened, on
751        // the very next object after the duplicate key that motivated this
752        // Pass — is the failure that ruling names.
753        //
754        // Every recovery is recorded as a `LoadAnomaly` and disclosed. A
755        // caller that wants the old refusal has `LoadOptions`.
756        let length_policy = if recovery.is_some() {
757            StreamLengthPolicy::RecoverFromEndstream
758        } else {
759            options.stream_lengths
760        };
761        // The missing-`endobj` leniency travels with the length leniency,
762        // and for exactly the same stated reason: an object `recover`'s
763        // confirmation step accepted must not be rejected on re-parse
764        // here, or the recovery costs the whole document.
765        let terminator_policy = if recovery.is_some() {
766            TerminatorPolicy::RecoverAtNextHeader
767        } else {
768            options.terminators
769        };
770        let mut anomalies: Vec<LoadAnomaly> = Vec::new();
771        let mut objects: HashMap<ObjId, IndirectObject> = HashMap::new();
772        let mut compressed: Vec<(u32, u32, u32)> = Vec::new();
773        for (num, entry) in table.iter() {
774            match entry {
775                XrefEntry::InUse { offset, generation } => {
776                    let id = ObjId::new(num, generation);
777                    let parsed = parse_object_at(
778                        &buf,
779                        &table,
780                        offset,
781                        length_policy,
782                        terminator_policy,
783                        // THE LOADER OPTS IN; the parser's own default stays
784                        // strict. A duplicate key is a malformed ENTRY in an
785                        // otherwise sound file, and refusing the object cost an
786                        // operator a whole 46 KB drawing every other reader
787                        // opens. Which value wins is the caller's to override
788                        // (`LoadOptions`), and either way it is recorded.
789                        options.duplicate_keys,
790                    );
791                    // ONE UNREADABLE OBJECT NO LONGER COSTS THE DOCUMENT.
792                    //
793                    // §7.3.10 already says what a reference to an object that
794                    // is not there means: it "shall be treated as a reference
795                    // to the null object", and "shall not be considered an
796                    // error". An object whose bytes will not parse IS
797                    // undefined as far as every consumer is concerned, so
798                    // omitting it produces a document the standard describes
799                    // rather than one pdfcer invented.
800                    //
801                    // Under `strict` this is still the refusal it always was.
802                    let (io, repairs) = match parsed {
803                        Ok(pair) => pair,
804                        Err(source) => {
805                            if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
806                                return Err(DocError::BadObject { id, offset, source });
807                            }
808                            anomalies.push(LoadAnomaly::ObjectUnreadable {
809                                object: id,
810                                reason: source.to_string(),
811                            });
812                            continue;
813                        }
814                    };
815                    if repairs.stream_lengths > 0 {
816                        anomalies.push(LoadAnomaly::StreamLengthRecovered { object: id });
817                    }
818                    if repairs.missing_endobj > 0 {
819                        anomalies.push(LoadAnomaly::MissingEndobjRecovered { object: id });
820                    }
821                    anomalies.extend(repairs.duplicate_keys.into_iter().map(|rec| {
822                        LoadAnomaly::DuplicateDictKey {
823                            object: Some(id),
824                            key: rec.key,
825                            kept: rec.kept,
826                            discarded: rec.discarded,
827                        }
828                    }));
829                    if io.id != id {
830                        // The table and the body disagree about which object
831                        // lives here. Neither is more authoritative than the
832                        // other, so pdfcer does not pick: the object the table
833                        // promised is treated as undefined (§7.3.10), which is
834                        // the same answer as "the table pointed at nothing".
835                        if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
836                            return Err(DocError::ObjectIdMismatch {
837                                expected: id,
838                                found: io.id,
839                                offset,
840                            });
841                        }
842                        anomalies.push(LoadAnomaly::ObjectUnreadable {
843                            object: id,
844                            reason: format!(
845                                "the cross-reference table points at offset {offset}, where the file declares {} instead",
846                                io.id
847                            ),
848                        });
849                        continue;
850                    }
851                    objects.insert(id, io);
852                }
853                XrefEntry::InStream { stream_num, index } => {
854                    compressed.push((num, stream_num, index));
855                }
856                // `XrefEntry` is #[non_exhaustive] (§7.5.8.3 reserves
857                // future types); an entry kind this build does not know
858                // resolves to null, which is exactly what the spec
859                // prescribes for unknown types.
860                _ => {}
861            }
862        }
863
864        // Phase 1.5. Decrypt (7.6), if the trailer says so.
865        //
866        // The position of this step is load-bearing, not stylistic. It runs
867        // AFTER phase 1 -- which needs only spans and `/Length`, both of which
868        // are plaintext integers -- and BEFORE phase 2, which inflates object
869        // streams. Decrypting here makes every object stream's data plaintext
870        // by the time phase 2 reads it, and the objects phase 2 parses out of
871        // that data are then correctly left alone: strings inside an object
872        // stream are NOT separately encrypted (TRAP T4). Moving this after
873        // phase 2 would re-apply Algorithm 1 per contained object and corrupt
874        // every string in every modern file.
875        let encryption = Self::decrypt_in_place(&mut buf, &trailer, &mut objects, credential)?;
876
877        // Phase 2. Resolve compressed objects through their containers,
878        // decoding each container at most once. Deterministic order so
879        // that a file with several broken containers always reports the
880        // same one (`iter()` over a HashMap is not ordered).
881        compressed.sort_unstable();
882        Self::load_compressed(
883            &buf,
884            &compressed,
885            &mut objects,
886            options.unreadable_objects,
887            &mut anomalies,
888        )?;
889
890        // Annex F detection runs on the raw buffer and needs no xref
891        // (F.3.3: the parameter dictionary's values are all direct and
892        // it is unreferenced from the document graph), but it is done
893        // here rather than in `load_xref_chain` because it is a
894        // property of the *file*, not of its cross-reference machinery.
895        let linearization = linearization::detect(&buf);
896
897        Ok(Self {
898            buf,
899            header_version,
900            xref: table,
901            trailer,
902            objects,
903            base_startxref,
904            section_shape,
905            linearization,
906            highest_object_number,
907            suppressed_by_size,
908            hybrid,
909            anomalies,
910            recovery,
911            encryption,
912        })
913    }
914
915    /// Authenticate and decrypt the loaded objects in place (7.6).
916    ///
917    /// Returns `Ok(None)` for an unencrypted document -- the overwhelmingly
918    /// common case, and a single `contains_key` away.
919    ///
920    /// # What "in place" means, and its consequence for saving
921    ///
922    /// **Stream data is decrypted in the retained buffer.** RC4 is a stream
923    /// cipher and preserves length exactly, so the plaintext fits precisely
924    /// where the ciphertext was and every span, `/Length` and provenance
925    /// record stays true. That is what lets this increment land without
926    /// touching [`Stream`](crate::object::Stream), which holds a span rather
927    /// than owning bytes. AES will not have that property -- its plaintext is
928    /// shorter than its ciphertext -- so the AES increment has to solve a
929    /// problem this one did not.
930    ///
931    /// **Strings are decrypted in the parsed objects**, because
932    /// [`Object::String`] owns its bytes and a decrypted string cannot
933    /// generally be re-escaped into the same number of source bytes.
934    ///
935    /// So after this runs, the buffer and the parsed objects **disagree**:
936    /// streams are plaintext in both, strings are plaintext only in the
937    /// objects. That is why a full rewrite refuses a decrypted document (its
938    /// verbatim copies would put plaintext under `/Encrypt`), and why the
939    /// pre-decryption bytes are kept: an incremental save appends to them,
940    /// encrypting only what it writes.
941    ///
942    /// # Errors
943    ///
944    /// [`DocError::Encryption`] for a configuration pdfcer will not decrypt;
945    /// [`DocError::PasswordRequired`] when nothing authenticated.
946    fn decrypt_in_place(
947        buf: &mut [u8],
948        trailer: &Dict,
949        objects: &mut HashMap<ObjId, IndirectObject>,
950        credential: Credential<'_>,
951    ) -> Result<Option<DocumentEncryption>, DocError> {
952        use crate::crypto::{EncryptionConfig, EncryptionUnsupported, apply};
953
954        let Some(entry) = trailer.get(b"Encrypt") else {
955            return Ok(None);
956        };
957
958        // The `/Encrypt` dictionary is usually direct in the trailer, but may
959        // be indirect. If it is, its object number must be remembered: its
960        // `/O` and `/U` are the INPUTS to the key derivation, so decrypting
961        // them with a key derived from themselves would authenticate
962        // successfully and then produce a document of noise (E2/E3).
963        let (encrypt_dict, encrypt_dict_id) = match entry {
964            Object::Dict(d) => (d.clone(), None),
965            Object::Reference(id) => match objects.get(id).map(|o| &o.value) {
966                Some(Object::Dict(d)) => (d.clone(), Some(id.num)),
967                _ => {
968                    return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
969                        "/Encrypt names an object that is not a dictionary",
970                    )));
971                }
972            },
973            _ => {
974                return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
975                    "/Encrypt is neither a dictionary nor a reference",
976                )));
977            }
978        };
979
980        // Resolution for indirect `/O`, `/U` and `/CF` entries. Snapshotting
981        // the values a closure needs is simpler than fighting the borrow
982        // checker over `objects`, which is about to be mutated.
983        let snapshot: HashMap<ObjId, Object> = objects
984            .iter()
985            .map(|(id, io)| (*id, io.value.clone()))
986            .collect();
987        let resolve = move |id: ObjId| snapshot.get(&id).cloned();
988
989        let config = EncryptionConfig::parse(&encrypt_dict, &resolve)?;
990
991        // Algorithm 2 step (e) and Algorithm 5 step (c) hash `/ID[0]`.
992        // 7.6.1 E1: trailer `/ID` strings are never encrypted and are direct
993        // objects, so this reads them as-is. A file with no `/ID` hashes
994        // nothing there, which an empty slice expresses exactly -- the
995        // algorithm has no branch for "no ID" (SPEC AMBIGUITY A4).
996        let id0: Vec<u8> = match trailer.get(b"ID") {
997            Some(Object::Array(items)) => match items.first() {
998                Some(Object::String(s)) => s.clone(),
999                _ => Vec::new(),
1000            },
1001            _ => Vec::new(),
1002        };
1003
1004        let authenticated = match credential {
1005            Credential::Password(password) => config.authenticate(password, &id0),
1006            Credential::Reuse(e) => Some((e.key.clone(), e.auth)),
1007        };
1008        let Some((key, auth)) = authenticated else {
1009            // A failed authentication is normally just a wrong password. At
1010            // `/R` 5 with a non-ASCII password it is ambiguous, because the
1011            // SASLprep step pdfcer does not implement may have been the thing
1012            // that mattered -- and telling the operator "wrong password" for a
1013            // password that was right sends them to re-check the one thing
1014            // that is not the problem.
1015            return Err(match credential {
1016                Credential::Password(Some(pw)) if config.password_may_need_normalisation(pw) => {
1017                    DocError::PasswordRequiresNormalisation
1018                }
1019                // At /R 6 a failure is not unambiguously "wrong password": the
1020                // A13 loop-exit ambiguity can reject a correct password for a
1021                // file written under the other reading. Name it (Pass 5.4).
1022                _ if config.revision == 6 => DocError::PasswordRequiredR6,
1023                _ => DocError::PasswordRequired,
1024            });
1025        };
1026
1027        // Algorithm 3.13, run once, immediately after the key is recovered and
1028        // before a single object is decrypted -- the check needs nothing but
1029        // the key, and running it here means the verdict is available to the
1030        // shells for the whole life of the document rather than being
1031        // recomputed on demand from state they would have to keep.
1032        let perms = config.check_perms(&key);
1033        let ciphertext: std::sync::Arc<[u8]> = std::sync::Arc::from(&*buf);
1034
1035        // Decrypt every file-level object. Order within the map does not
1036        // matter: each object's key depends only on its own identity
1037        // (Algorithm 1), never on another object's contents.
1038        for (id, obj) in objects.iter_mut() {
1039            if apply::skip(obj, encrypt_dict_id, config.encrypt_metadata).is_some() {
1040                continue;
1041            }
1042            if key.streams_encrypted()
1043                && let Object::Stream(stream) = &mut obj.value
1044            {
1045                let span = stream.data_span;
1046                let end = span.start.saturating_add(span.len);
1047                // Checked access, not an in-bounds proof: `data_span` comes
1048                // from a `/Length` in an untrusted file, and a stream whose
1049                // declared length runs past the buffer is a real thing a
1050                // malformed (or deliberately hostile) document contains. A
1051                // span that does not fit is left alone -- the object then
1052                // fails to decode later, with an error about the object, which
1053                // is the honest place for it.
1054                if let Some(cipher_text) = buf.get(span.start..end) {
1055                    let plain = key.decrypt_stream(*id, cipher_text);
1056                    // ** The plaintext may be SHORTER than the ciphertext. **
1057                    //
1058                    // Increment 1 asserted the opposite here -- `RC4 must
1059                    // preserve length` -- and guarded the copy on
1060                    // `plain.len() == span.len`. That was true and correct for
1061                    // RC4, and it is the R186 shape: a guard keyed on a
1062                    // property that quietly stopped holding. Under `/AESV2`
1063                    // the ciphertext carries a 16-byte IV plus padding (T5), so
1064                    // the equality is ALWAYS false, the copy would ALWAYS be
1065                    // skipped, and every stream in an AES document would stay
1066                    // ciphertext -- with no test red and no error raised.
1067                    //
1068                    // Shorter is the easy direction: the plaintext still fits
1069                    // at `span.start`, so only the recorded length changes.
1070                    // Nothing re-reads the dictionary's `/Length` after parse
1071                    // (it is consumed once, at parser.rs's stream read), and
1072                    // `data_span` is what every downstream reader actually
1073                    // slices -- content.rs, attachments.rs, the object-stream
1074                    // path, edit.rs. So shortening the span is sufficient and
1075                    // `Stream` needs no new field.
1076                    if plain.len() <= span.len
1077                        && let Some(slot) = buf.get_mut(span.start..span.start + plain.len())
1078                    {
1079                        slot.copy_from_slice(&plain);
1080                        stream.data_span.len = plain.len();
1081                    }
1082                    // A plaintext LONGER than its ciphertext is impossible for
1083                    // both implemented ciphers, so there is no branch for it:
1084                    // it would have to overwrite the following object, and
1085                    // silently declining is the only safe response.
1086                }
1087            }
1088            if key.strings_encrypted() {
1089                apply::decrypt_strings(&mut obj.value, *id, &key);
1090            }
1091        }
1092
1093        Ok(Some(DocumentEncryption {
1094            config,
1095            auth,
1096            perms,
1097            key,
1098            encrypt_dict_id,
1099            ciphertext,
1100            rc4_append: crate::writer::Rc4Append::Refuse,
1101        }))
1102    }
1103
1104    /// How this document was encrypted, if it was -- `None` for a plain file.
1105    ///
1106    /// A **disclosure**, not a gate. See [`DocumentEncryption`].
1107    #[must_use]
1108    pub fn encryption(&self) -> Option<&DocumentEncryption> {
1109        self.encryption.as_ref()
1110    }
1111
1112    /// Choose whether an incremental save of an RC4-encrypted document keeps
1113    /// its RC4 handler ([`Rc4Append::Preserve`]) or is refused
1114    /// ([`Rc4Append::Refuse`], the default). No effect on a plain or AES
1115    /// document.
1116    ///
1117    /// Preserve keeps existing signatures valid, at a cost the save reports
1118    /// in [`SaveReport::rc4_keystream_reused`]: an edited object rewritten
1119    /// under its old number and generation is encrypted with the same RC4
1120    /// keystream as its previous revision. Decision 190.
1121    ///
1122    /// [`Rc4Append::Preserve`]: crate::writer::Rc4Append::Preserve
1123    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
1124    /// [`SaveReport::rc4_keystream_reused`]: crate::writer::SaveReport::rc4_keystream_reused
1125    pub fn set_rc4_append(&mut self, policy: crate::writer::Rc4Append) {
1126        if let Some(enc) = self.encryption.as_mut() {
1127            enc.rc4_append = policy;
1128        }
1129    }
1130
1131    /// Drop this document's encryption, in memory, without re-parsing.
1132    ///
1133    /// Load already decrypted every object's strings (in the parsed values) and
1134    /// every stream's data (in the retained buffer) — see
1135    /// [`Document::decrypt_in_place`]. So a document that WAS encrypted is,
1136    /// object-for-object, already a plaintext document; the only things still
1137    /// asserting encryption are the [`encryption`](Self::encryption) field and
1138    /// the trailer's `/Encrypt` reference. Clearing both is all that
1139    /// "remove encryption" needs at the model level — the writer then emits
1140    /// plaintext because the bytes it re-serialises already are.
1141    ///
1142    /// `Pass 5.4`: used by `pdfcer_core::EditSession::remove_encryption` and
1143    /// `pdfcer_core::EditSession::set_permissions` (which re-keys, so it first
1144    /// clears the old state, then the writer freshly encrypts).
1145    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
1146    pub fn clear_encryption(&mut self) {
1147        self.encryption = None;
1148        self.trailer.remove(b"Encrypt");
1149    }
1150
1151    /// Assemble a [`Document`] from a [`recover::RecoveredXref`].
1152    ///
1153    /// The recovered document is fixed into the shape a save must take
1154    /// (decision 013 §3.3.4, the recovered-base rule): its section shape is
1155    /// a plain classic table (`xref_stm: None`) so a full rewrite emits a
1156    /// fresh valid classic cross-reference, and `base_startxref` is 0
1157    /// because incremental append onto a broken base is refused by the
1158    /// writer. `/Size` suppression is 0 — recovery's synthesized `/Size`
1159    /// already covers every recovered object.
1160    ///
1161    /// `header_override` is the header-probe version when the header parsed
1162    /// (the xref-failure path); `None` on the header-failure path, where
1163    /// the recovery's own whole-buffer version scan is authoritative.
1164    fn assemble_recovered(
1165        buf: Vec<u8>,
1166        header_override: Option<PdfVersion>,
1167        rec: recover::RecoveredXref,
1168    ) -> Result<Self, DocError> {
1169        let version = header_override.unwrap_or(rec.version);
1170        Self::assemble(
1171            buf,
1172            version,
1173            rec.table,
1174            rec.trailer,
1175            0,
1176            SectionShape::Classic { xref_stm: None },
1177            rec.highest_object_number,
1178            0,
1179            // A recovered base is rebuilt by scanning object headers, and the
1180            // scan sees every object equally — the §7.5.8.4 partition is not
1181            // recoverable from it, and `SectionShape::Classic { xref_stm: None }`
1182            // above already says the output is not hybrid. Default, not a
1183            // guess.
1184            crate::xref::HybridPartition::default(),
1185            Some(rec.report),
1186            // The recovery path never carries a password: `recover` refuses an
1187            // encrypted file outright (`RecoverError::Encrypted`), because
1188            // rebuild-by-scan looks for `N G obj` headers in bytes that would
1189            // be ciphertext. So a recovered document is never encrypted, and
1190            // threading a password here would be dead weight that read as
1191            // support.
1192            Credential::Password(None),
1193            LoadOptions::default(),
1194        )
1195    }
1196
1197    /// Load phase 2: resolve every type-2 (`InStream`) cross-reference
1198    /// entry through its object stream, inserting the parsed objects
1199    /// into `objects`.
1200    ///
1201    /// `compressed` is `(object number, container object number, index
1202    /// within container)`, sorted. Containers are looked up in
1203    /// `objects` — which is why this runs strictly after phase 1 (module
1204    /// docs) — decoded once, and cached for the rest of the load. A
1205    /// container that fails is remembered too: its later members are
1206    /// recorded with the first failure's reason, without another decode.
1207    ///
1208    /// Every compressed object is inserted with generation **0**:
1209    /// §7.5.7 fixes the generation of a compressed object at zero, and a
1210    /// type-2 entry carries no generation field to disagree with.
1211    fn load_compressed(
1212        buf: &[u8],
1213        compressed: &[(u32, u32, u32)],
1214        objects: &mut HashMap<ObjId, IndirectObject>,
1215        policy: UnreadableObjectPolicy,
1216        anomalies: &mut Vec<LoadAnomaly>,
1217    ) -> Result<(), DocError> {
1218        let mut cache: HashMap<u32, ObjectStream> = HashMap::new();
1219        // Containers that could not be decoded, with the reason, so a bad
1220        // stream costs one decode per load rather than one per member.
1221        let mut failed: HashMap<u32, String> = HashMap::new();
1222
1223        // A COMPRESSED OBJECT THAT CANNOT BE READ IS UNDEFINED, NOT FATAL
1224        // — the same §7.3.10 reading the file-level loop applies, and for the
1225        // same reason: five of this function's refusals were "one object is
1226        // broken, so you get no document."
1227        //
1228        // Each is recorded with the object it cost and why. Under `strict`
1229        // every one is still the error it was.
1230        macro_rules! give_up_on {
1231            ($num:expr, $reason:expr, $err:expr) => {{
1232                if policy == UnreadableObjectPolicy::Refuse {
1233                    return Err($err);
1234                }
1235                anomalies.push(LoadAnomaly::ObjectUnreadable {
1236                    object: ObjId::new($num, 0),
1237                    reason: $reason,
1238                });
1239                continue;
1240            }};
1241        }
1242
1243        for &(num, stream_num, index) in compressed {
1244            // §7.5.7: "The generation number of an object stream and of
1245            // any compressed object shall be zero."
1246            let container = ObjId::new(stream_num, 0);
1247
1248            // A container that already failed is not decoded again: its
1249            // members get the first failure's reason. Only reachable under
1250            // the lenient policy (strict returned on that first failure).
1251            if let Some(reason) = failed.get(&stream_num) {
1252                anomalies.push(LoadAnomaly::ObjectUnreadable {
1253                    object: ObjId::new(num, 0),
1254                    reason: reason.clone(),
1255                });
1256                continue;
1257            }
1258            let objstm = match cache.entry(stream_num) {
1259                Entry::Occupied(slot) => slot.into_mut(),
1260                Entry::Vacant(slot) => match decode_container(buf, objects, container, num) {
1261                    Ok(parsed) => slot.insert(parsed),
1262                    Err((reason, err)) => {
1263                        failed.insert(stream_num, reason.clone());
1264                        give_up_on!(num, reason, err)
1265                    }
1266                },
1267            };
1268
1269            let value = match member_at(objstm, container, num, index) {
1270                Ok(value) => value,
1271                Err((reason, err)) => give_up_on!(num, reason, err),
1272            };
1273
1274            let id = ObjId::new(num, 0);
1275            objects.insert(
1276                id,
1277                IndirectObject {
1278                    id,
1279                    value,
1280                    provenance: Provenance::ObjectStream { container, index },
1281                },
1282            );
1283        }
1284        Ok(())
1285    }
1286
1287    /// The retained source bytes (the coordinate system every span in
1288    /// this document indexes into).
1289    #[must_use]
1290    pub fn bytes(&self) -> &[u8] {
1291        &self.buf
1292    }
1293
1294    /// A read view of this document for the rasterizer, the vector object
1295    /// model and `pageops` — the file exactly as loaded.
1296    ///
1297    /// The mirror of `EditSession::view`,
1298    /// and the reason every read path can take one parameter type
1299    /// ([`DocumentView`]) instead of two overloads. A `Document` has no
1300    /// overlay and no staging buffer, so its view carries a
1301    /// [`StreamSource::Contiguous`](crate::view::StreamSource::Contiguous)
1302    /// over [`Document::bytes`] — meaning "render the file as it is on
1303    /// disk", which is exactly what `pdfcer` and the round-trip tools
1304    /// want — and why `pdfcer-render`'s `&Document` back-compat wrappers can
1305    /// build one implicitly without changing any caller's behaviour.
1306    ///
1307    /// Cheap: two borrows plus a version probe. Building one per call is
1308    /// the intended usage; there is nothing to cache.
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```
1313    /// use pdfcer_model::document::Document;
1314    /// use pdfcer_model::graph::ObjectGraph;
1315    ///
1316    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1317    /// let doc = Document::from_bytes(
1318    ///     include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
1319    /// )?;
1320    /// let view = doc.view();
1321    /// assert_eq!(view.version(), doc.version());
1322    /// assert_eq!(view.catalog_id(), doc.catalog_id());
1323    /// # Ok(())
1324    /// # }
1325    /// ```
1326    #[must_use]
1327    pub fn view(&self) -> DocumentView<'_> {
1328        DocumentView::new(self, self.bytes(), self.version())
1329    }
1330
1331    /// The newest trailer dictionary (§7.5.5 Table 15).
1332    #[must_use]
1333    pub const fn trailer(&self) -> &Dict {
1334        &self.trailer
1335    }
1336
1337    /// The merged cross-reference table.
1338    #[must_use]
1339    pub const fn xref(&self) -> &XrefTable {
1340        &self.xref
1341    }
1342
1343    /// The document's effective version: the header's `%PDF-M.N`,
1344    /// upgraded by the catalog's `/Version` name if present and higher
1345    /// (§7.5.5: version = max of the two; the catalog entry exists so
1346    /// an incremental update can raise the version without touching
1347    /// byte 0).
1348    #[must_use]
1349    pub fn version(&self) -> PdfVersion {
1350        let catalog_version = self
1351            .catalog()
1352            .ok()
1353            .and_then(|cat| cat.get(b"Version"))
1354            .and_then(Object::as_name)
1355            .and_then(|n| parse_version_name(n.as_bytes()));
1356        match catalog_version {
1357            Some(v) if v > self.header_version => v,
1358            _ => self.header_version,
1359        }
1360    }
1361
1362    /// Look up an indirect object by full identity, applying the
1363    /// §7.3.10/§7.5.4 rules (module docs): dangling, stale-generation,
1364    /// and free all yield `None` here — callers wanting the null-object
1365    /// semantics use [`Document::resolve`], which maps `None` to
1366    /// [`Object::Null`].
1367    #[must_use]
1368    pub fn get(&self, id: ObjId) -> Option<&IndirectObject> {
1369        self.objects.get(&id)
1370    }
1371
1372    /// Resolve `obj` to a non-reference value: follow reference chains
1373    /// (depth-guarded), mapping every unresolvable case to the null
1374    /// object per §7.3.10. Non-reference objects return themselves.
1375    #[must_use]
1376    pub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
1377        const NULL: &Object = &Object::Null;
1378        let mut current = obj;
1379        for _ in 0..MAX_RESOLVE_DEPTH {
1380            match current {
1381                Object::Reference(id) => match self.get(*id) {
1382                    Some(io) => current = &io.value,
1383                    None => return NULL,
1384                },
1385                other => return other,
1386            }
1387        }
1388        // Chain too deep / cyclic: null, not an error (module docs).
1389        NULL
1390    }
1391
1392    /// The document catalog (§7.7.2) — the dictionary the trailer's
1393    /// required `/Root` reference points at.
1394    ///
1395    /// # Errors
1396    ///
1397    /// [`DocError::NoCatalog`] if `/Root` is missing, not a reference,
1398    /// or doesn't resolve to a dictionary.
1399    pub fn catalog(&self) -> Result<&Dict, DocError> {
1400        self.trailer
1401            .get(b"Root")
1402            .map(|root| self.resolve(root))
1403            .and_then(Object::as_dict)
1404            .ok_or(DocError::NoCatalog)
1405    }
1406
1407    /// Number of parsed (in-use) objects.
1408    #[must_use]
1409    pub fn object_count(&self) -> usize {
1410        self.objects.len()
1411    }
1412
1413    /// Iterate all parsed indirect objects (unordered).
1414    pub fn objects(&self) -> impl Iterator<Item = &IndirectObject> {
1415        self.objects.values()
1416    }
1417
1418    /// The byte offset this file's own `startxref` names (§7.5.5).
1419    ///
1420    /// This is the value an appended update's `/Prev` must carry —
1421    /// §7.5.6: *"a `Prev` entry giving the location of the previous
1422    /// cross-reference section"*, which is the section `startxref`
1423    /// currently points at. Taking the base trailer's own `/Prev`
1424    /// instead is the classic off-by-one-revision bug: it would skip a
1425    /// revision and silently resurrect superseded objects.
1426    #[must_use]
1427    pub const fn base_startxref(&self) -> u64 {
1428        self.base_startxref
1429    }
1430
1431    /// The physical form of the newest cross-reference section.
1432    ///
1433    /// The writer matches this rather than choosing (R33): emitting a
1434    /// cross-reference stream where the base file had a classic table
1435    /// silently raises a PDF 1.4 document's effective version to 1.5.
1436    /// §7.5.6 does not require the match — that is a recorded spec
1437    /// silence — which is exactly why pdfcer imposes it.
1438    #[must_use]
1439    pub const fn section_shape(&self) -> SectionShape {
1440        self.section_shape
1441    }
1442
1443    /// Whether this file is a §7.5.8.4 **hybrid-reference** file: a
1444    /// classic cross-reference section whose trailer carries
1445    /// `/XRefStm`.
1446    ///
1447    /// Hybrid files are readable by pre-1.5 readers *and* carry the
1448    /// PDF 1.5 features those readers cannot see. Incremental save
1449    /// preserves that duality (form A: a classic update section
1450    /// carrying `/XRefStm` forward); a full rewrite cannot, and refuses
1451    /// by name rather than flattening it.
1452    #[must_use]
1453    pub const fn is_hybrid(&self) -> bool {
1454        matches!(
1455            self.section_shape,
1456            SectionShape::Classic { xref_stm: Some(_) }
1457        )
1458    }
1459
1460    /// Every contradiction this file contained that pdfcer **decided rather
1461    /// than refused** (`Pass 283.0`).
1462    ///
1463    /// # The three obligations this satisfies at once
1464    ///
1465    /// The operator's ruling: *"we should be making pdfcer so that it opens
1466    /// pdfs that have errors, and have a way that it manages those errors such
1467    /// that they aren't fatal, and if the user can intervene in a decision that
1468    /// should always be an option along with them not having to intervene."*
1469    ///
1470    /// - **Not fatal** — the document is loaded; this list is a report about
1471    ///   it, not a gate in front of it.
1472    /// - **Intervention possible** — each entry names what pdfcer chose *and
1473    ///   what it chose between*, which is what a shell needs to offer the
1474    ///   alternative. Re-load through [`Document::from_bytes_with_options`]
1475    ///   with the other policy to take it.
1476    /// - **Intervention optional** — a caller that never reads this gets a
1477    ///   working document with pdfcer's documented default.
1478    ///
1479    /// Empty for a file that contains no contradiction, which is the
1480    /// overwhelming majority. A non-empty list is not a warning that anything
1481    /// is *wrong with pdfcer's output* — it is the file saying two things.
1482    #[must_use]
1483    pub fn load_anomalies(&self) -> &[LoadAnomaly] {
1484        &self.anomalies
1485    }
1486
1487    /// This file's §7.5.8.4 partition — which objects it **hides** behind
1488    /// `/XRefStm`, and whether pdfcer could read the stream that says so
1489    /// (`Pass 281.0`).
1490    ///
1491    /// # Why a writer needs it, and why re-deriving it would be wrong
1492    ///
1493    /// §7.5.8.4 describes a three-part unit a writer creates "at the same
1494    /// time": a main classic table marking the hidden objects **free with
1495    /// generation 65535**, an update section, and a cross-reference stream
1496    /// giving their real locations. Rewriting such a file means rebuilding
1497    /// that unit, which means knowing which side each object belongs on.
1498    ///
1499    /// §7.5.8.4's visibility rule answers a **different question** — what a
1500    /// producer is *permitted* to hide. This answers what this file *did*
1501    /// hide. A file may legally hide less than it could, and a rewrite that
1502    /// re-derived the maximum would move objects the operator never touched,
1503    /// which is exactly the "plausible, working, wrong file" `R33` guards
1504    /// against.
1505    ///
1506    /// Empty and readable for every non-hybrid file. See
1507    /// [`crate::xref::HybridPartition::is_reproducible`] for the case that
1508    /// still refuses: a file that says it hides objects and whose stream
1509    /// pdfcer could not parse.
1510    #[must_use]
1511    pub const fn hybrid_partition(&self) -> &crate::xref::HybridPartition {
1512        &self.hybrid
1513    }
1514
1515    /// The cross-reference **recovery** record, or `None` for a cleanly
1516    /// loaded file (decision 013).
1517    ///
1518    /// `Some` means the stored cross-reference table could not be parsed
1519    /// and pdfcer rebuilt it by scanning the file for `N G obj` headers
1520    /// (rebuild-by-scan). The returned [`RecoveryReport`] carries the
1521    /// counted disclosure (why the strict path failed, how many objects
1522    /// came from the file-level scan vs. object streams, collisions,
1523    /// trailer source, offset-start). This is a **reviewable fact**
1524    /// (fuzzy-never-sneaky, R20): the CLI prints it and forces a distinct
1525    /// exit status, and the GUI shows a banner. A recovered document also
1526    /// cannot be saved incrementally — see
1527    /// [`Document::save_incremental`]'s refusal.
1528    #[must_use]
1529    pub const fn recovery(&self) -> Option<&RecoveryReport> {
1530        self.recovery.as_ref()
1531    }
1532
1533    /// Whether this document was loaded via cross-reference recovery
1534    /// (decision 013) — the shorthand the writer's incremental-save refusal
1535    /// and the front ends' disclosure branch on.
1536    #[must_use]
1537    pub const fn loaded_via_recovery(&self) -> bool {
1538        self.recovery.is_some()
1539    }
1540
1541    /// Annex F linearization ("Fast Web View") state, detected at load.
1542    ///
1543    /// Reported so a save can warn before spending the property
1544    /// (F.1: an incremental update *"shall"* de-linearize). pdfcer never
1545    /// repairs it and never strips a stale `/Linearized` dictionary —
1546    /// see [`crate::linearization`].
1547    #[must_use]
1548    pub const fn linearization(&self) -> Linearization {
1549        self.linearization
1550    }
1551
1552    /// Save an incremental update (§7.5.6) to `path`.
1553    ///
1554    /// This is pdfcer's **default** save mode (`ARCHITECTURE.md` §5):
1555    /// the existing bytes are copied untouched and a new revision is
1556    /// appended, which is what keeps any pre-existing digital
1557    /// signature's `/ByteRange` digest valid (§12.8.1 NOTE 1).
1558    ///
1559    /// `dirty` is the **save-time diff against the base revision**, and
1560    /// the only thing that should compute one is
1561    /// `pdfcer_core::edit::EditSession::dirty_set` — see
1562    /// `ARCHITECTURE.md` §11.1 for the "union of every command ever run"
1563    /// bug that a hand-built dirty set reintroduces. An empty one gives
1564    /// byte-identical output.
1565    ///
1566    /// ⚠️ **Incremental save structurally preserves superseded
1567    /// content.** The old bytes of every replaced object remain in the
1568    /// file by construction. Any operation whose contract is *removal*
1569    /// — redaction above all — must therefore use
1570    /// [`Document::save_full`] and must refuse this mode (R35).
1571    ///
1572    /// # Errors
1573    ///
1574    /// [`crate::writer::WriteError`] — I/O, a broken provenance span,
1575    /// or a cross-reference form that cannot express an entry.
1576    pub fn save_incremental(
1577        &self,
1578        path: &Path,
1579        dirty: &crate::writer::DirtySet,
1580        options: &crate::writer::SaveOptions,
1581    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
1582        let (bytes, report) = crate::writer::save_incremental(self, dirty, options)?;
1583        std::fs::write(path, &bytes)?;
1584        Ok(report)
1585    }
1586
1587    /// Rewrite the whole document to `path` as a single revision.
1588    ///
1589    /// Every `File`-provenance object is re-emitted from its retained
1590    /// source bytes verbatim; only the header prefix, object offsets,
1591    /// the cross-reference section and the trailer are regenerated. So
1592    /// byte identity holds **per object definition**, never for the
1593    /// file as a whole (R32) — offsets legitimately move.
1594    ///
1595    /// ⚠️ **A full rewrite invalidates every existing digital
1596    /// signature**, because a signature covers a byte range that this
1597    /// mode necessarily disturbs (§12.8.1). That collides with R35's
1598    /// requirement that redaction use this mode; "redact a signed
1599    /// document" is a genuine either/or for the operator to resolve,
1600    /// never something pdfcer decides silently (R36, decision 007 W7).
1601    ///
1602    /// # Errors
1603    ///
1604    /// [`crate::writer::WriteError`], notably
1605    /// [`WriteError::HybridFullRewrite`](crate::writer::WriteError::HybridFullRewrite)
1606    /// for a §7.5.8.4 hybrid-reference input.
1607    pub fn save_full(
1608        &self,
1609        path: &Path,
1610        dirty: &crate::writer::DirtySet,
1611        options: &crate::writer::SaveOptions,
1612    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
1613        let (bytes, report) = crate::writer::save_full(self, dirty, options)?;
1614        std::fs::write(path, &bytes)?;
1615        Ok(report)
1616    }
1617
1618    /// The lowest object number this document does **not** already
1619    /// account for — where a newly created object goes.
1620    ///
1621    /// Four sources are consulted, and taking the maximum of all four
1622    /// is the point:
1623    ///
1624    /// 1. **the highest number the cross-reference chain mentions before
1625    ///    the `/Size` filter runs.** The unfiltered number, deliberately:
1626    ///    `/Size` is a hard reader-side filter, so a file that
1627    ///    under-reports it loads with real entries invisible, and
1628    ///    allocating from the *filtered* view picks a number the file
1629    ///    already defines. That produces an update section whose entry
1630    ///    collides with a live object — a file that looks fine and
1631    ///    resolves to the wrong bytes. Found by the `writer_roundtrip`
1632    ///    fuzz target, on a corpus file carrying `/Size 3` over six
1633    ///    entries.
1634    ///
1635    ///    Free entries count too. A free number is *reusable* in
1636    ///    principle (§7.5.4's free list exists to be consumed), but
1637    ///    reusing one correctly means honouring the generation rules —
1638    ///    a resurrected object takes the free entry's generation — and
1639    ///    pdfcer has no deletion path to have created those entries in
1640    ///    the first place. Allocating past them is always safe;
1641    ///    consuming them is Pass 3.2 work.
1642    /// 2. every parsed object, in case the two disagree;
1643    /// 3. the trailer's `/Size`, so a *stale, oversized* `/Size` cannot
1644    ///    hand out a number that a `/Prev` revision defines and this
1645    ///    merged view dropped.
1646    /// 4. **the newest cross-reference STREAM's own object number**, when
1647    ///    the file has one ([`Document::section_shape`]).
1648    ///
1649    /// ## Why source 4 exists, and the bug it closes
1650    ///
1651    /// A cross-reference stream is an indirect object, and the writer
1652    /// **reuses its number** for the update section it emits (`R33`: match
1653    /// the base's section shape). But it is *the section*, not a body
1654    /// object — the parser never files it in `objects`, and there is no
1655    /// requirement anywhere that it appear in its own `/Index` or be
1656    /// covered by its own `/Size`.
1657    ///
1658    /// So a file can carry `75 0 obj << /Type /XRef /Size 75 /Index [9 1 29
1659    /// 45] >>`: object 75 exists, and every one of sources 1–3 answers 74.
1660    /// This function then handed out **75**, the session wrote its new
1661    /// object there, and the writer wrote *its own cross-reference stream*
1662    /// over the top of it — same object number, later in the file, so the
1663    /// session's object simply vanished and the reader resolved the
1664    /// reference to the xref stream.
1665    ///
1666    /// The failure is silent in the worst way: the file parses, opens, and
1667    /// renders. Only the one thing the edit added is missing. Found by
1668    /// `tools/embed-sweep` over the pdfium corpus
1669    /// (`testing/resources/annotation_stamp_with_ap.pdf`), where an embedded
1670    /// font program came back as a 44-byte cross-reference stream and the
1671    /// text it should have drawn was silently skipped.
1672    ///
1673    /// **This was never specific to font embedding.** Any command that
1674    /// creates an object — adding text, an image, an annotation, a form
1675    /// field — hits it on any file shaped this way. It survived because a
1676    /// collision needs a file whose xref stream is outside its own `/Size`,
1677    /// which no producer pdfcer's fixtures came from emits.
1678    ///
1679    /// Returns `None` only if the document already reaches
1680    /// [`u32::MAX`], which Annex C's implementation limits put far out
1681    /// of reach for any real file — reported rather than wrapped,
1682    /// because silently allocating object 0 would corrupt the free list.
1683    ///
1684    /// ⚠️ A caller must **also** check
1685    /// [`Document::suppressed_object_count`] before creating an object:
1686    /// a valid number is not by itself a licence to write one.
1687    #[must_use]
1688    pub fn next_object_number(&self) -> Option<u32> {
1689        let from_objects = self.objects.keys().map(|id| id.num).max().unwrap_or(0);
1690        let from_size = self
1691            .trailer
1692            .get(b"Size")
1693            .and_then(Object::as_int)
1694            .and_then(|s| u32::try_from(s.saturating_sub(1)).ok())
1695            .unwrap_or(0);
1696        // Source 4 — see this function's docs. The writer reuses this number
1697        // for the section it emits, so handing it out would guarantee a
1698        // collision rather than merely risk one.
1699        let from_section = match self.section_shape {
1700            SectionShape::Stream { id, .. } => id.num,
1701            // A classic table is not an object and spends no number. The
1702            // `_` arm is deliberate: `SectionShape` is `#[non_exhaustive]`,
1703            // and a shape this build does not know must not silently be
1704            // treated as spending a number it might.
1705            _ => 0,
1706        };
1707        self.highest_object_number
1708            .max(from_objects)
1709            .max(from_size)
1710            .max(from_section)
1711            .checked_add(1)
1712            .filter(|n| *n != 0)
1713    }
1714
1715    /// How many cross-reference entries this file's `/Size` is hiding.
1716    ///
1717    /// ## Why anyone cares (and why it blocks object creation)
1718    ///
1719    /// Table 15 / §7.5.5 make `/Size` a hard filter: an object numbered
1720    /// at or above it *"shall be ignored and defined to be missing"*. A
1721    /// file whose `/Size` under-reports is therefore **relying on the
1722    /// filter** — the entries above it are invisible, and the document
1723    /// may only be loadable at all because they are (they can point at
1724    /// bytes that do not parse).
1725    ///
1726    /// Creating an object raises `/Size`. That does not merely add the
1727    /// new object: it **exposes every suppressed entry below the new
1728    /// number**, resurrecting objects the operator never touched. Two
1729    /// separate rules say no — §5's minimal-diff invariant (an edit must
1730    /// not change objects it did not name) and R27's fail-clean posture
1731    /// (name the refusal rather than produce a plausible wrong file).
1732    ///
1733    /// So a non-zero count means *"an edit may modify existing objects
1734    /// in this file, but must not create one"*. The eventual fix is to
1735    /// emit explicit free entries (§7.5.4, generation 65535 — the very
1736    /// mechanism §7.5.8.4 uses to hide an object) for the exposed range,
1737    /// which needs free-list writing that Pass 3.2 brings.
1738    ///
1739    /// Zero for essentially every well-formed file, which is why this is
1740    /// a refusal rather than a feature gap worth blocking on.
1741    #[must_use]
1742    pub const fn suppressed_object_count(&self) -> usize {
1743        self.suppressed_by_size
1744    }
1745}
1746
1747/// Parse the indirect object at `offset`, resolving indirect `/Length`
1748/// values through the xref table (the §7.3.10 EXAMPLE 3 pattern: the
1749/// length object is itself fetched and parsed on demand — it is always
1750/// a plain integer object, so this nested parse cannot recurse).
1751///
1752/// `pub(crate)` so the cross-reference recovery path (`crate::recover`) can
1753/// reuse the exact same object-parse + indirect-`/Length` resolution the
1754/// normal loader uses (rule 13: no new tokenizer) when confirming scanned
1755/// `N G obj` candidates.
1756///
1757/// `policy` selects the `/Length`-vs-`endstream` strictness
1758/// ([`StreamLengthPolicy`]). It is [`StreamLengthPolicy::Strict`] on every
1759/// clean-load call site and [`StreamLengthPolicy::RecoverFromEndstream`]
1760/// only under rebuild-by-scan recovery. Returns the parsed object together
1761/// with the number of stream extents that had to be re-derived (always `0`
1762/// under `Strict`), so the caller can fold it into the counted disclosure.
1763///
1764/// Note the nested `resolve_length` parse stays **strict** regardless: a
1765/// `/Length` object is a plain integer (§7.3.10 EXAMPLE 3), never a stream,
1766/// so the policy has nothing to act on there and holding it strict keeps
1767/// the nested parse from recursing into extent recovery.
1768pub(crate) fn parse_object_at(
1769    buf: &[u8],
1770    table: &XrefTable,
1771    offset: u64,
1772    policy: StreamLengthPolicy,
1773    terminator: TerminatorPolicy,
1774    duplicates: crate::parser::DuplicateKeyPolicy,
1775) -> Result<(IndirectObject, ParseRepairs), ParseError> {
1776    let offset = usize::try_from(offset).unwrap_or(usize::MAX);
1777    let mut resolve_length = |id: ObjId| -> Option<i64> {
1778        let XrefEntry::InUse {
1779            offset: len_offset,
1780            generation,
1781        } = table.get(id.num)?
1782        else {
1783            return None;
1784        };
1785        if generation != id.generation {
1786            return None;
1787        }
1788        let len_offset = usize::try_from(len_offset).ok()?;
1789        let io = Parser::at(buf, len_offset)
1790            .parse_indirect_object(&mut |_| None)
1791            .ok()?;
1792        (io.id == id).then_some(())?;
1793        io.value.as_int()
1794    };
1795    let mut parser = Parser::at(buf, offset)
1796        .with_stream_length_policy(policy)
1797        .with_terminator_policy(terminator)
1798        .with_duplicate_key_policy(duplicates);
1799    let io = parser.parse_indirect_object(&mut resolve_length)?;
1800    Ok((
1801        io,
1802        ParseRepairs {
1803            duplicate_keys: parser.duplicate_keys().to_vec(),
1804            stream_lengths: parser.stream_lengths_recovered(),
1805            missing_endobj: parser.missing_endobj_recovered(),
1806        },
1807    ))
1808}
1809
1810/// How to load a document that contradicts itself (`Pass 283.0`).
1811///
1812/// # Why this type exists rather than a global setting
1813///
1814/// The operator's ruling has two halves that pull in opposite directions:
1815/// a file with errors must open **without intervention**, and intervening must
1816/// **always be possible**. A default plus this struct is how both hold at once
1817/// — [`Default`] is what every existing caller already gets, and a shell that
1818/// wants to offer the operator a choice re-loads the same bytes with a
1819/// different policy and shows the difference.
1820///
1821/// Re-loading rather than patching in place is deliberate: a decision made
1822/// during parsing is not a value that can be edited afterwards, because the
1823/// discarded one was never built into the document. Carrying both would make
1824/// every dictionary lookup ambiguous for the life of the session to serve a
1825/// case that is one keystroke away from being re-read.
1826#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1827#[non_exhaustive]
1828pub struct LoadOptions {
1829    /// Which value wins when one dictionary names a key twice (§7.3.7).
1830    ///
1831    /// Defaults to [`crate::parser::DuplicateKeyPolicy::KeepLast`] — see that
1832    /// type for why last, and [`Document::load_anomalies`] for how a caller
1833    /// learns a choice was made at all.
1834    pub duplicate_keys: crate::parser::DuplicateKeyPolicy,
1835    /// What to do when a stream's `/Length` cannot be used (§7.3.8.2).
1836    ///
1837    /// Defaults to [`StreamLengthPolicy::RecoverFromEndstream`], which only
1838    /// acts when the stored value is unusable. Set
1839    /// [`StreamLengthPolicy::Strict`] to refuse such a file instead.
1840    pub stream_lengths: StreamLengthPolicy,
1841    /// What to do when an indirect object's `endobj` is missing (§7.3.10).
1842    ///
1843    /// Defaults to [`TerminatorPolicy::RecoverAtNextHeader`].
1844    pub terminators: TerminatorPolicy,
1845    /// What to do when one object cannot be loaded at all.
1846    ///
1847    /// Defaults to [`UnreadableObjectPolicy::TreatAsUndefined`] — §7.3.10's
1848    /// own answer for an object that is not there.
1849    pub unreadable_objects: UnreadableObjectPolicy,
1850}
1851
1852/// What to do when one indirect object cannot be loaded (`Pass 283.0`).
1853#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1854#[non_exhaustive]
1855pub enum UnreadableObjectPolicy {
1856    /// Load the document without it, and record a
1857    /// [`LoadAnomaly::ObjectUnreadable`].
1858    ///
1859    /// §7.3.10: an indirect reference to an undefined object *"shall not be
1860    /// considered an error by a conforming reader; it shall be treated as a
1861    /// reference to the null object."* An object whose bytes will not parse is
1862    /// undefined as far as every consumer is concerned, so this is the
1863    /// standard's own answer applied to the state the file is in — not a
1864    /// repair, and nothing invented.
1865    #[default]
1866    TreatAsUndefined,
1867    /// Refuse the document, as pdfcer did before `Pass 283.0`.
1868    Refuse,
1869}
1870
1871impl Default for LoadOptions {
1872    /// NOT the derived default. `DuplicateKeyPolicy`'s own `Default` is
1873    /// `Refuse`, which is right for a parser and wrong for a loader: deriving
1874    /// here would make `LoadOptions::default()` refuse the very files this
1875    /// Pass exists to open, and the two types would silently disagree about
1876    /// what "default" means.
1877    fn default() -> Self {
1878        Self::new()
1879    }
1880}
1881
1882impl LoadOptions {
1883    /// The defaults: open the file, decide the contradictions, report them.
1884    #[must_use]
1885    pub fn new() -> Self {
1886        Self {
1887            duplicate_keys: crate::parser::DuplicateKeyPolicy::KeepLast,
1888            stream_lengths: StreamLengthPolicy::RecoverFromEndstream,
1889            terminators: TerminatorPolicy::RecoverAtNextHeader,
1890            unreadable_objects: UnreadableObjectPolicy::TreatAsUndefined,
1891        }
1892    }
1893
1894    /// Refuse every malformation instead of deciding it — the pre-`Pass 283.0`
1895    /// behaviour, kept reachable.
1896    ///
1897    /// For a caller whose job is to say whether a file is well-formed rather
1898    /// than to open it: a conformance checker, a fuzz harness, a gate.
1899    #[must_use]
1900    pub const fn strict() -> Self {
1901        Self {
1902            duplicate_keys: crate::parser::DuplicateKeyPolicy::Refuse,
1903            stream_lengths: StreamLengthPolicy::Strict,
1904            terminators: TerminatorPolicy::Strict,
1905            unreadable_objects: UnreadableObjectPolicy::Refuse,
1906        }
1907    }
1908
1909    /// Take the OTHER value for every duplicated key — the operator's
1910    /// intervention, applied by re-loading the same bytes.
1911    #[must_use]
1912    pub const fn with_duplicate_keys(mut self, policy: crate::parser::DuplicateKeyPolicy) -> Self {
1913        self.duplicate_keys = policy;
1914        self
1915    }
1916}
1917
1918/// One thing the file said that contradicted itself, and what pdfcer decided
1919/// about it (`Pass 283.0`).
1920///
1921/// # The operator ruling this exists to satisfy
1922///
1923/// > *"We should be making pdfcer so that it opens pdfs that have errors, and
1924/// > have a way that it manages those errors such that they aren't fatal, and
1925/// > if the user can intervene in a decision that should always be an option
1926/// > along with them not having to intervene."*
1927///
1928/// Three obligations in one sentence, and this type carries all three:
1929///
1930/// 1. **Not fatal** — the document loads.
1931/// 2. **Intervention is possible** — the record names the object, the key, the
1932///    value kept and the value discarded, which is everything a shell needs to
1933///    offer the operator the other choice and re-load with it
1934///    ([`crate::parser::DuplicateKeyPolicy`]).
1935/// 3. **Intervention is not required** — pdfcer already picked, the default is
1936///    documented, and a caller that never reads this list gets a working
1937///    document.
1938///
1939/// It is a *disclosure*, not a prompt: project rule 4 as narrowed by decision
1940/// 059 — the inferred value is live document state, and what pdfcer guessed is
1941/// reported off to the side rather than gating the open.
1942#[derive(Debug, Clone, PartialEq)]
1943#[non_exhaustive]
1944pub enum LoadAnomaly {
1945    /// One dictionary named the same key twice (§7.3.7) and pdfcer kept one of
1946    /// the values.
1947    ///
1948    /// Both values are carried, not just the winner. A count would say *that*
1949    /// pdfcer chose; a shell offering the operator the choice needs to show
1950    /// **what it chose between**, and a report that cannot answer "what was the
1951    /// other one?" makes the intervention theoretical.
1952    DuplicateDictKey {
1953        /// The object whose dictionary contradicted itself. `None` when the
1954        /// dictionary is the trailer, which is not an indirect object.
1955        object: Option<ObjId>,
1956        /// The repeated key, e.g. `PageMode`.
1957        key: Vec<u8>,
1958        /// The value pdfcer KEPT — the last occurrence under the default
1959        /// policy.
1960        kept: Object,
1961        /// The value pdfcer DISCARDED. A caller offering the choice presents
1962        /// this as the alternative; a caller re-loading under
1963        /// [`crate::parser::DuplicateKeyPolicy::KeepFirst`] gets it instead.
1964        discarded: Object,
1965    },
1966    /// A stream's `/Length` was absent, non-integer, unresolvable or simply
1967    /// wrong, and pdfcer re-derived the data extent by scanning to
1968    /// `endstream` (§7.3.8.1).
1969    ///
1970    /// `/Length` is REQUIRED by §7.3.8.2 Table 5, so this is a `shall`
1971    /// violation — and one every reader recovers from, because the keyword
1972    /// that ends the data is right there in the file. Refusing costs the whole
1973    /// document to preserve a number the file itself contradicts.
1974    ///
1975    /// There is no operator choice to offer here, and that is not an
1976    /// oversight: the alternative to the scanned extent is **no object at
1977    /// all**. The record exists so the operator learns the file is damaged,
1978    /// not so a decision can be re-taken.
1979    StreamLengthRecovered {
1980        /// The object whose stream extent was re-derived.
1981        object: ObjId,
1982    },
1983    /// An indirect object's `endobj` keyword was missing and pdfcer accepted
1984    /// the definition anyway, ending it at the next object header (§7.3.10).
1985    ///
1986    /// Same shape as [`Self::StreamLengthRecovered`]: a required keyword the
1987    /// file omits, an unambiguous end, and no second reading to choose
1988    /// between.
1989    MissingEndobjRecovered {
1990        /// The object accepted without its terminator.
1991        object: ObjId,
1992    },
1993    /// One object could not be loaded at all, and the document was loaded
1994    /// **without it**.
1995    ///
1996    /// # Why this is continuing rather than guessing
1997    ///
1998    /// §7.3.10 already defines what a reference to an object that is not
1999    /// there means: *"An indirect reference to an undefined object shall not
2000    /// be considered an error by a conforming reader; it shall be treated as
2001    /// a reference to the null object."* An object whose bytes will not parse
2002    /// **is** an undefined object as far as every consumer is concerned — so
2003    /// omitting it is not a liberty pdfcer takes, it is the behaviour the
2004    /// standard prescribes for the state the file is in.
2005    ///
2006    /// That is the whole difference between this and a repair: nothing is
2007    /// invented, and the resulting document is one the standard describes.
2008    ///
2009    /// # What it replaces
2010    ///
2011    /// `DocError::BadObject`, `ObjectIdMismatch`, `ObjectStreamMissing`,
2012    /// `ObjectStream` and `ObjectStreamIdMismatch` — five ways one bad object
2013    /// used to cost the whole document. They survive as errors under
2014    /// [`LoadOptions::strict`].
2015    ///
2016    /// There is no alternative to offer here either. The choice is between
2017    /// this object and no document, and `reason` is carried so the operator
2018    /// can see WHICH object and WHY rather than being told a count.
2019    ObjectUnreadable {
2020        /// The object that could not be loaded.
2021        object: ObjId,
2022        /// Why, in the loader's own words — the error that would have been
2023        /// returned.
2024        reason: String,
2025    },
2026}
2027
2028impl LoadAnomaly {
2029    /// The object this anomaly is about, when it has one.
2030    #[must_use]
2031    pub const fn object(&self) -> Option<ObjId> {
2032        match self {
2033            Self::DuplicateDictKey { object, .. } => *object,
2034            Self::StreamLengthRecovered { object }
2035            | Self::MissingEndobjRecovered { object }
2036            | Self::ObjectUnreadable { object, .. } => Some(*object),
2037        }
2038    }
2039
2040    /// A short stable token for machine-readable output.
2041    #[must_use]
2042    pub const fn kind(&self) -> &'static str {
2043        match self {
2044            Self::DuplicateDictKey { .. } => "duplicate_dict_key",
2045            Self::StreamLengthRecovered { .. } => "stream_length_recovered",
2046            Self::MissingEndobjRecovered { .. } => "missing_endobj_recovered",
2047            Self::ObjectUnreadable { .. } => "object_unreadable",
2048        }
2049    }
2050}
2051
2052/// How much repair a single object's parse needed.
2053///
2054/// Every field counts a place where the file contradicted itself or
2055/// omitted something §7.3.10 requires, and pdfcer chose to continue rather
2056/// than refuse. **All of them are zero under the strict policies**, so a
2057/// non-zero total is proof the file was damaged — which is why these are
2058/// carried out to the recovery report and disclosed (R20,
2059/// fuzzy-never-sneaky) instead of being absorbed silently.
2060#[derive(Debug, Clone, Default, PartialEq)]
2061pub(crate) struct ParseRepairs {
2062    /// Dictionary keys that appeared twice and were resolved to the LAST
2063    /// value rather than refusing the object
2064    /// ([`crate::parser::DuplicateKeyPolicy::KeepLast`], `Pass 283.0`).
2065    ///
2066    /// Unlike its two siblings this one is **non-zero on the clean path**,
2067    /// because the clean loader opts into the tolerant policy — the whole
2068    /// point of the Pass was that a file every other reader opens must not
2069    /// cost pdfcer the whole document. It is still a repair and still
2070    /// disclosed.
2071    pub duplicate_keys: Vec<crate::parser::DuplicateKeyRecord>,
2072    /// Stream extents re-derived from `endstream` because `/Length` was
2073    /// unusable ([`StreamLengthPolicy::RecoverFromEndstream`]).
2074    pub stream_lengths: usize,
2075    /// Definitions accepted with no `endobj` keyword
2076    /// ([`TerminatorPolicy::RecoverAtNextHeader`]).
2077    pub missing_endobj: usize,
2078}
2079
2080/// Parse a catalog `/Version` name (`1.7`, `2.0`) into a version pair.
2081fn parse_version_name(name: &[u8]) -> Option<PdfVersion> {
2082    let text = std::str::from_utf8(name).ok()?;
2083    let (major, minor) = text.split_once('.')?;
2084    Some(PdfVersion {
2085        major: major.parse().ok()?,
2086        minor: minor.parse().ok()?,
2087    })
2088}
2089
2090/// Member `num` at `index` of a decoded object stream, or the anomaly
2091/// reason and the strict-policy error.
2092fn member_at(
2093    objstm: &ObjectStream,
2094    container: ObjId,
2095    num: u32,
2096    index: u32,
2097) -> Result<Object, (String, DocError)> {
2098    let idx = usize::try_from(index).unwrap_or(usize::MAX);
2099    let (found, value) = objstm.object_at(idx).map_err(|source| {
2100        (
2101            format!("index {index} of object stream {container} could not be read: {source}"),
2102            DocError::ObjectStream { container, source },
2103        )
2104    })?;
2105    if found != num {
2106        return Err((
2107            format!(
2108                "object stream {container} stores object {found} at index {index}, where the cross-reference table promised {num}"
2109            ),
2110            DocError::ObjectStreamIdMismatch {
2111                container,
2112                index,
2113                expected: num,
2114                found,
2115            },
2116        ));
2117    }
2118    Ok(value)
2119}
2120
2121/// Decode the object stream `container` for member `num`, or return the
2122/// anomaly reason and the strict-policy error. §7.5.7.
2123fn decode_container(
2124    buf: &[u8],
2125    objects: &HashMap<ObjId, IndirectObject>,
2126    container: ObjId,
2127    num: u32,
2128) -> Result<ObjectStream, (String, DocError)> {
2129    let Some(io) = objects.get(&container) else {
2130        return Err((
2131            format!("its object stream {container} is not in the file"),
2132            DocError::ObjectStreamMissing { container, num },
2133        ));
2134    };
2135    let Object::Stream(stream) = &io.value else {
2136        return Err((
2137            format!("object {container} is named as its container but is not a stream"),
2138            DocError::ObjectStream {
2139                container,
2140                source: ObjStmError::NotAStream,
2141            },
2142        ));
2143    };
2144    let Some(raw) = stream.data_span.slice(buf) else {
2145        return Err((
2146            format!("its object stream {container} declares data outside the file"),
2147            DocError::ObjectStream {
2148                container,
2149                source: ObjStmError::DataOutOfRange,
2150            },
2151        ));
2152    };
2153    #[cfg(test)]
2154    tests::OBJSTM_DECODES.with(|n| n.set(n.get() + 1));
2155    ObjectStream::parse(&stream.dict, raw).map_err(|source| {
2156        (
2157            format!("its object stream {container} could not be decoded: {source}"),
2158            DocError::ObjectStream { container, source },
2159        )
2160    })
2161}
2162
2163#[cfg(test)]
2164#[allow(
2165    clippy::unwrap_used,
2166    clippy::expect_used,
2167    clippy::panic,
2168    clippy::indexing_slicing
2169)]
2170mod tests {
2171    use super::*;
2172
2173    thread_local! {
2174        /// Object-stream decodes attempted on this thread (X039 counter).
2175        pub(super) static OBJSTM_DECODES: std::cell::Cell<usize> =
2176            const { std::cell::Cell::new(0) };
2177    }
2178
2179    /// Build a small, offset-consistent classic PDF from parts: each
2180    /// entry in `objects` is (object number, body text); generation 0.
2181    /// Returns the complete file bytes.
2182    fn build_pdf(objects: &[(u32, &str)], trailer_extra: &str) -> Vec<u8> {
2183        let mut buf = b"%PDF-1.4\n".to_vec();
2184        let mut offsets: Vec<(u32, usize)> = Vec::new();
2185        for (num, body) in objects {
2186            offsets.push((*num, buf.len()));
2187            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
2188        }
2189        let xref_at = buf.len();
2190        let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
2191        buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
2192        buf.extend_from_slice(b"0000000000 65535 f\r\n");
2193        for num in 1..=max_num {
2194            match offsets.iter().find(|(n, _)| *n == num) {
2195                Some((_, off)) => {
2196                    buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
2197                }
2198                None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
2199            }
2200        }
2201        buf.extend_from_slice(
2202            format!(
2203                "trailer\n<< /Size {} /Root 1 0 R {trailer_extra}>>\nstartxref\n{xref_at}\n%%EOF\n",
2204                max_num + 1
2205            )
2206            .as_bytes(),
2207        );
2208        buf
2209    }
2210
2211    fn minimal_doc() -> Vec<u8> {
2212        build_pdf(
2213            &[
2214                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2215                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2216            ],
2217            "",
2218        )
2219    }
2220
2221    #[test]
2222    fn loads_minimal_document() {
2223        let doc = Document::from_bytes(minimal_doc()).unwrap();
2224        assert_eq!(doc.object_count(), 2);
2225        assert_eq!(doc.version().to_string(), "1.4");
2226        let cat = doc.catalog().unwrap();
2227        assert_eq!(
2228            cat.get(b"Type").unwrap().as_name().unwrap().as_bytes(),
2229            b"Catalog"
2230        );
2231    }
2232
2233    #[test]
2234    fn resolve_follows_references_and_nulls_dangling() {
2235        let doc = Document::from_bytes(minimal_doc()).unwrap();
2236        let cat = doc.catalog().unwrap();
2237        // /Pages resolves through the reference to the Pages dict.
2238        let pages = doc.resolve(cat.get(b"Pages").unwrap());
2239        assert_eq!(
2240            pages.as_dict().unwrap().get(b"Count").unwrap().as_int(),
2241            Some(0)
2242        );
2243        // §7.3.10: dangling → null, not an error.
2244        let dangling = Object::Reference(ObjId::new(17, 0));
2245        assert_eq!(*doc.resolve(&dangling), Object::Null);
2246        // Stale generation → null too.
2247        let stale = Object::Reference(ObjId::new(2, 9));
2248        assert_eq!(*doc.resolve(&stale), Object::Null);
2249    }
2250
2251    #[test]
2252    fn reference_cycle_resolves_to_null() {
2253        // `3 0 obj 3 0 R endobj` — legal syntax, must not loop.
2254        let doc = Document::from_bytes(build_pdf(
2255            &[
2256                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2257                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2258                (3, "3 0 R"),
2259            ],
2260            "",
2261        ))
2262        .unwrap();
2263        let cyc = Object::Reference(ObjId::new(3, 0));
2264        assert_eq!(*doc.resolve(&cyc), Object::Null);
2265    }
2266
2267    #[test]
2268    fn provenance_spans_recover_source_bytes() {
2269        // The whole point of the retained buffer: every object's span
2270        // slices back to its exact definition bytes.
2271        let doc = Document::from_bytes(minimal_doc()).unwrap();
2272        let io = doc.get(ObjId::new(1, 0)).unwrap();
2273        let raw = io.file_span().unwrap().slice(doc.bytes()).unwrap();
2274        assert!(raw.starts_with(b"1 0 obj"));
2275        assert!(raw.ends_with(b"endobj"));
2276    }
2277
2278    #[test]
2279    fn catalog_version_upgrades_header() {
2280        // §7.5.5: effective version = max(header, catalog /Version).
2281        let doc = Document::from_bytes(build_pdf(
2282            &[
2283                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.7 >>"),
2284                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2285            ],
2286            "",
2287        ))
2288        .unwrap();
2289        assert_eq!(doc.version().to_string(), "1.7");
2290    }
2291
2292    #[test]
2293    fn catalog_version_cannot_downgrade_header() {
2294        let mut bytes = build_pdf(
2295            &[
2296                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.2 >>"),
2297                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2298            ],
2299            "",
2300        );
2301        // Bump the header to 1.6; catalog says 1.2; max wins.
2302        let pos = bytes.windows(3).position(|w| w == b"1.4").unwrap();
2303        bytes[pos..pos + 3].copy_from_slice(b"1.6");
2304        let doc = Document::from_bytes(bytes).unwrap();
2305        assert_eq!(doc.version().to_string(), "1.6");
2306    }
2307
2308    /// AMENDED BY `Pass 283.0`, and the old assertion is kept as the second
2309    /// half rather than deleted.
2310    ///
2311    /// This test was right for its time: it asserted that a cross-reference
2312    /// entry pointing at the wrong object refuses the whole document, *"rather
2313    /// than guessing which is right"*. pdfcer still does not guess — what
2314    /// changed is that not-guessing no longer means not-opening. The object
2315    /// the table promised is treated as **undefined** (§7.3.10), which is the
2316    /// standard's own answer for an object that is not there, and the operator
2317    /// is told which one was lost.
2318    ///
2319    /// The strict refusal survives by name under [`LoadOptions::strict`], and
2320    /// the second half of this test is the old one unchanged.
2321    #[test]
2322    fn an_object_id_mismatch_is_recorded_by_default_and_refused_under_strict() {
2323        // Corrupt the xref so object 2's entry points at object 1's offset.
2324        let bytes = minimal_doc();
2325        let text = String::from_utf8(bytes.clone()).unwrap();
2326        let obj1_off = text.find("1 0 obj").unwrap();
2327        let obj2_off = text.find("2 0 obj").unwrap();
2328        let entry = format!("{obj2_off:010} 00000 n");
2329        let entry_pos = text.find(&entry).unwrap();
2330        let mut corrupted = bytes;
2331        corrupted[entry_pos..entry_pos + 10].copy_from_slice(format!("{obj1_off:010}").as_bytes());
2332
2333        // Default: the document opens, object 2 is absent, and the loss is
2334        // named.
2335        let doc = Document::from_bytes(corrupted.clone())
2336            .expect("a table/body disagreement about ONE object is not an unreadable file");
2337        assert!(doc.get(ObjId::new(2, 0)).is_none());
2338        assert!(
2339            doc.load_anomalies().iter().any(|a| matches!(
2340                a,
2341                LoadAnomaly::ObjectUnreadable { object, .. } if *object == ObjId::new(2, 0)
2342            )),
2343            "{:?}",
2344            doc.load_anomalies()
2345        );
2346
2347        // Strict: the original assertion, unchanged.
2348        let err =
2349            Document::from_bytes_with_options(corrupted, None, LoadOptions::strict()).unwrap_err();
2350        assert!(matches!(err, DocError::ObjectIdMismatch { .. }));
2351    }
2352
2353    #[test]
2354    fn missing_root_is_no_catalog() {
2355        let mut buf = b"%PDF-1.4\n".to_vec();
2356        let xref_at = buf.len();
2357        buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
2358        buf.extend_from_slice(
2359            format!("trailer\n<< /Size 1 >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
2360        );
2361        let doc = Document::from_bytes(buf).unwrap();
2362        assert!(matches!(doc.catalog(), Err(DocError::NoCatalog)));
2363    }
2364
2365    #[test]
2366    fn stream_with_indirect_length_loads_end_to_end() {
2367        // §7.3.10 EXAMPLE 3 through the full Document path.
2368        let doc = Document::from_bytes(build_pdf(
2369            &[
2370                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2371                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2372                (3, "<< /Length 4 0 R >>\nstream\nhello wo\nendstream"),
2373                (4, "8"),
2374            ],
2375            "",
2376        ))
2377        .unwrap();
2378        let io = doc.get(ObjId::new(3, 0)).unwrap();
2379        let Object::Stream(s) = &io.value else {
2380            panic!("not a stream");
2381        };
2382        assert_eq!(s.data_span.slice(doc.bytes()).unwrap(), b"hello wo");
2383    }
2384
2385    /// A file whose only object stream (object 3, an unknown filter) holds
2386    /// objects 4..=13, all listed in an uncompressed cross-reference stream.
2387    fn bad_objstm_with_ten_members() -> Vec<u8> {
2388        let mut buf = b"%PDF-1.5
2389"
2390        .to_vec();
2391        let bodies = [
2392            (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
2393            (2, "<< /Type /Pages /Kids [] /Count 0 >>".to_string()),
2394            (
2395                3,
2396                "<< /Type /ObjStm /N 10 /First 0 /Filter /NoSuchFilter /Length 4 >>
2397stream
2398xxxx
2399endstream"
2400                    .to_string(),
2401            ),
2402        ];
2403        let mut offsets = Vec::new();
2404        for (num, body) in &bodies {
2405            offsets.push(buf.len());
2406            buf.extend_from_slice(
2407                format!(
2408                    "{num} 0 obj
2409{body}
2410endobj
2411"
2412                )
2413                .as_bytes(),
2414            );
2415        }
2416        let xref_at = buf.len();
2417        // /W [1 4 2]: type, field 2, field 3.
2418        let mut rows: Vec<u8> = Vec::new();
2419        let mut row = |t: u8, f2: u32, f3: u16| {
2420            rows.push(t);
2421            rows.extend_from_slice(&f2.to_be_bytes());
2422            rows.extend_from_slice(&f3.to_be_bytes());
2423        };
2424        row(0, 0, 0xFFFF);
2425        for off in &offsets {
2426            row(1, u32::try_from(*off).unwrap(), 0);
2427        }
2428        for i in 0..10u16 {
2429            row(2, 3, i);
2430        }
2431        row(1, u32::try_from(xref_at).unwrap(), 0);
2432        buf.extend_from_slice(
2433            format!(
2434                "14 0 obj
2435<< /Type /XRef /Size 15 /W [1 4 2] /Root 1 0 R /Length {} >>
2436stream
2437",
2438                rows.len()
2439            )
2440            .as_bytes(),
2441        );
2442        buf.extend_from_slice(&rows);
2443        buf.extend_from_slice(
2444            format!(
2445                "
2446endstream
2447endobj
2448startxref
2449{xref_at}
2450%%EOF
2451"
2452            )
2453            .as_bytes(),
2454        );
2455        buf
2456    }
2457
2458    #[test]
2459    fn a_failed_object_stream_is_decoded_once_per_load() {
2460        OBJSTM_DECODES.with(|n| n.set(0));
2461        let doc = Document::from_bytes(bad_objstm_with_ten_members())
2462            .expect("one bad object stream is not an unreadable file");
2463        assert_eq!(OBJSTM_DECODES.with(std::cell::Cell::get), 1);
2464
2465        let reasons: Vec<(u32, &str)> = doc
2466            .load_anomalies()
2467            .iter()
2468            .filter_map(|a| match a {
2469                LoadAnomaly::ObjectUnreadable { object, reason } => {
2470                    Some((object.num, reason.as_str()))
2471                }
2472                _ => None,
2473            })
2474            .collect();
2475        assert_eq!(
2476            reasons.iter().map(|r| r.0).collect::<Vec<_>>(),
2477            (4..=13).collect::<Vec<_>>(),
2478            "{reasons:?}"
2479        );
2480        assert!(reasons[0].1.contains("could not be decoded"), "{reasons:?}");
2481        assert!(reasons.iter().all(|r| r.1 == reasons[0].1), "{reasons:?}");
2482
2483        // Strict: the first failure is still the error.
2484        let err = Document::from_bytes_with_options(
2485            bad_objstm_with_ten_members(),
2486            None,
2487            LoadOptions::strict(),
2488        )
2489        .unwrap_err();
2490        assert!(matches!(err, DocError::ObjectStream { .. }), "{err:?}");
2491    }
2492}