Skip to main content

pdfcer_model/writer/
save.rs

1//! # The two save paths (ISO 32000-1 §7.5.4–§7.5.8)
2//!
3//! [`save_incremental`] appends a revision (§7.5.6); [`save_full`]
4//! rewrites the file with one cross-reference section. Both are pure
5//! byte producers — they build a `Vec<u8>` and never touch the
6//! filesystem, which is what lets the round-trip harness and the fuzz
7//! target compare outputs without I/O.
8//!
9//! Read [`super`]'s module docs first: they carry the two contracts,
10//! the never-normalize rule (R33), the `/ID` reasoning (R39), the
11//! redaction-forbids-incremental rule (R35) and the fingerprint rule
12//! (R41). This file is the enactment.
13//!
14//! ## `save_incremental`, step by step (§7.5.6)
15//!
16//! 1. **Copy the base file. Never open it for writing.** Nothing below
17//!    the original EOF may change — that is §7.5.6's *"changes shall be
18//!    appended to the end of the file, leaving its original contents
19//!    intact"*, and it is simultaneously what makes the signature claim
20//!    (§12.8.1 NOTE 1) and the round-trip claim true.
21//! 2. **Empty dirty set ⇒ stop.** Zero edits means zero bytes, not
22//!    "the input plus an empty revision".
23//! 3. **If the base's last byte is not an EOL, write one.** §7.2.3: a
24//!    comment runs *"up to but not including the end of the line"* — so
25//!    an appended `12 0 obj` token fused onto an unterminated `%%EOF`
26//!    line is swallowed by that comment and the file silently loses its
27//!    entire update. The spec states no rule here (a recorded NEGATIVE
28//!    RESULT); §7.5.1's general line discipline supplies it in
29//!    practice, and this handles the files where it did not.
30//! 4. **Append each dirty object's definition**, recording its offset.
31//! 5. **Append one cross-reference section** in the base file's own
32//!    form, carrying entries *only* for the dirty set — plus object 0
33//!    (see below).
34//! 6. **Append the trailer**: every entry of the previous trailer
35//!    *except* `Prev`, then a new `Prev` = the offset the base file's
36//!    own `startxref` named. Copying the old `Prev` **and** adding a
37//!    new one is a duplicate key, which §7.3.7 prohibits — the trap
38//!    §7.5.6 requirement 3 sets for naive implementations.
39//! 7. **`startxref` + `%%EOF`.**
40//!
41//! ### Why object 0 is always in the update section
42//!
43//! §7.5.6 requirement 1 says an update section *"shall contain entries
44//! **only for** objects that have been changed, replaced, or deleted"*
45//! — a restriction, not merely permission to omit. Read literally, an
46//! unchanged object 0 does not belong there.
47//!
48//! **The standard's own worked example violates that reading.** Annex
49//! H.7 stage 2 emits a `0 1` subsection carrying object 0's free-list
50//! head even though it is byte-identical to stage 1's. pdfcer follows
51//! the example, not the literal text: the entry costs 20 bytes, keeps
52//! the free-list head unambiguous for readers that merge sections
53//! rather than probe them, and cannot be wrong for any reader. The
54//! spec-vs-own-example tension is recorded in
55//! `iso32000__annex__h7.md`; this is the resolution.
56//!
57//! ## Applying real edits (Pass 3.1)
58//!
59//! A [`DirtySet`] entry may now carry a **replacement value**. Where the
60//! Pass 3.0 loop had one decision (verbatim bytes, or re-serialize a
61//! compressed object), it now has three:
62//!
63//! | dirty entry | base object | what is written | counted as |
64//! |---|---|---|---|
65//! | re-emission | `Provenance::File` | its source bytes, verbatim | `objects_verbatim` |
66//! | re-emission | `Provenance::RecoveredFile` | re-serialized from values | `objects_reserialized` (no promotion) |
67//! | re-emission | `Provenance::ObjectStream` | re-serialized from values | `objects_reserialized` + **promotion** |
68//! | replacement | `Provenance::File` | the new value, serialized | `objects_reserialized` |
69//! | replacement | `Provenance::ObjectStream` | the new value, serialized | `objects_reserialized` + **promotion** |
70//! | replacement | *absent from the base* | the new value, serialized | `objects_reserialized` (a **created** object) |
71//!
72//! ### Promotion, and the stale copy it leaves (R38, decision 007 W3)
73//!
74//! A compressed object has no contiguous file bytes, so an edit to one
75//! cannot be a patch. The two available moves are *rewrite the whole
76//! container* — which perturbs every **other** object inside it, a
77//! minimal-diff violation by proxy — or *promote the edited object out*,
78//! writing it as an ordinary file-level object whose new type-1
79//! cross-reference entry supersedes the type-2 one. R38 chooses
80//! promotion, and the supersession is sound in both section forms:
81//! §7.5.6 makes the most recent copy win for a classic or stream update
82//! section, and §7.5.8.4's search order consults the newest classic
83//! section *before* a forwarded `/XRefStm`, so a hybrid file behaves the
84//! same way.
85//!
86//! ⚠️ **Promotion leaves the object's previous value inside its old
87//! container, and a full rewrite does not change that** — the container
88//! is itself a `Provenance::File` stream copied through verbatim. For an
89//! ordinary edit this is exactly the same "superseded content survives"
90//! property that §7.5.6 gives incremental save by construction, and it is
91//! harmless. **It is not harmless for redaction.** `ARCHITECTURE.md` §5.2
92//! (from decision 007 W3) records that R35's full-rewrite requirement
93//! "closes the stale-copy path"; with object streams carried through
94//! intact, it does not — the Redaction Pass must additionally rewrite
95//! (or decompose) any container holding a redacted object, and must have
96//! a test that greps the saved bytes. Recorded here, at the code that
97//! creates the condition, so that Pass cannot inherit the gap silently.
98//!
99//! Every promotion is pushed onto [`SaveReport::promoted`] — counted
100//! *and named*, because it is a byte-level change to an object the
101//! operator did not edit the *representation* of.
102//!
103//! ### Created objects and the trailer patch
104//!
105//! A replacement whose id the base document does not define is a created
106//! object: it is appended, gets a fresh type-1 entry, and raises `/Size`
107//! through the same [`bump_size`] path as any other entry. Its only Pass
108//! 3.1 use is an operator metadata edit on a file with no `/Info`
109//! dictionary, which also needs the trailer to gain `/Info N 0 R` — hence
110//! [`DirtySet::patch_trailer`], applied over the §7.5.6-copied base
111//! trailer *before* the writer's own `/Prev` and `/Size` are set, so a
112//! patch can never displace those.
113//!
114//! ## `save_full`, and the one thing it must not do
115//!
116//! A full rewrite re-emits every `Provenance::File` object **from its
117//! retained source bytes**, byte for byte. It does *not* re-serialize
118//! them from values — §5's contract is byte identity for untouched
119//! content, and PDF syntax is non-canonical enough that re-serializing
120//! would change bytes on every second object (`crate::span`'s module
121//! docs work the three cases).
122//!
123//! The **one** file-level exception is `Provenance::RecoveredFile`, and it
124//! is not a weakening of the rule but a precondition of it: those bytes
125//! contradict the value pdfcer parsed from them (a stream whose extent
126//! recovery re-derived from `endstream`, leaving the old `/Length` in the
127//! source text). Copying them verbatim would emit a stream whose declared
128//! length does not match its data — a file pdfcer would refuse to reload,
129//! i.e. "save then reopen" would lose the operator's document. §5 promises
130//! byte identity for content pdfcer did not touch; pdfcer *did* touch this
131//! object's length, deliberately and disclosed, which is exactly the
132//! condition under which §5 does not bind.
133//!
134//! ### Object streams survive a full rewrite intact
135//!
136//! A compressed object (`Provenance::ObjectStream`) has no file-level
137//! bytes of its own, so a naive full rewrite would have to promote it
138//! out of its container — perturbing every *other* object in that
139//! container, a minimal-diff violation by proxy (decision 007 W3).
140//!
141//! pdfcer does not do that, and the reason is worth stating because it
142//! is not obvious: a type-2 cross-reference entry's fields are the
143//! **container's object number and the index within it** — neither is a
144//! byte offset. So re-emitting the container verbatim (it is itself an
145//! ordinary `Provenance::File` stream object) leaves every type-2 entry
146//! *still correct*. Object streams are carried through untouched, with
147//! zero promotions, and the only thing that changes is the container's
148//! own offset in its type-1 entry.
149//!
150//! ### Hybrid-reference files are REWRITTEN, in their own form
151//!
152//! ~~"Hybrid-reference files are refused, by name."~~ True until
153//! `Pass 281.0`, and struck rather than deleted because a reader who
154//! remembers it needs to see that it moved.
155//!
156//! A full rewrite of a §7.5.8.4 file emits the three-part unit the clause
157//! describes: a main classic table where the file's **hidden** objects are free
158//! with generation 65535, the cross-reference stream that gives their real
159//! locations, and an update section whose trailer names it through `/XRefStm`.
160//! Which objects are hidden is not re-derived — the loader retains it
161//! (`Document::hybrid_partition`), because §7.5.8.4's visibility rule says what
162//! a producer *may* hide and this writer must reproduce what the file *did*
163//! hide.
164//!
165//! [`WriteError::HybridFullRewrite`] survives for the one case that is still a
166//! guess: an `/XRefStm` pdfcer could not parse. Incremental save of a hybrid
167//! file is unchanged (form A, a classic update section carrying `/XRefStm`
168//! forward).
169
170use std::collections::{BTreeMap, BTreeSet};
171
172use crate::document::Document;
173use crate::object::{Dict, IndirectObject, Name, ObjId, Object, Provenance};
174use crate::xref::{SectionShape, XrefEntry};
175
176use super::encoder::{IdentityEncoder, ObjectEncoder};
177use super::{DirtySet, ProducerPolicy, SaveOptions, WriteError, serialize, xref_out};
178
179/// Largest object number [`save_full`] will build a cross-reference
180/// table up to before refusing (ISO 32000-1 Annex C, Table C.1).
181///
182/// # Why a bound is structurally necessary here
183///
184/// §7.5.4's completeness requirement makes a single-section full rewrite
185/// emit one entry per object number from 0 to the highest one **defined
186/// in the file** — "even if one or more of the object numbers in this
187/// range do not actually occur". The cost is therefore driven by the
188/// largest object NUMBER, not by the object COUNT, and the largest
189/// number is chosen by whoever wrote the input.
190///
191/// # Where the value comes from — sourced, not guessed
192///
193/// Annex C Table C.1 gives **8,388,607 (2²³ − 1) maximum indirect
194/// objects**, a legacy Acrobat architectural limit. A file whose highest
195/// object number exceeds that cannot have a conforming object *count*
196/// either, so the bound refuses nothing a conforming producer can make.
197///
198/// The same table caps an integer at 2,147,483,647 (2³¹ − 1), which is
199/// worth knowing for the file that prompted this: pdfium's
200/// `bug_455199.pdf` names `2147483648 0 obj` — one MORE than the largest
201/// integer the spec permits, so the object number is not merely
202/// implausible, it is unrepresentable as a conforming PDF integer.
203///
204/// Deliberately **not** clamped to the object count: a sparse-but-small
205/// file with one high number is exactly the adversarial shape this
206/// guards, and a count-based bound would let it through.
207///
208/// Sized in the spirit of `pdfcer_core::forms::MAX_FORM_FIELDS` and
209/// [`crate::annot::MAX_ANNOTS_PER_PAGE`] — far above any conformant
210/// corpus, so the veraPDF §6.1.12 implementation-limits suite keeps
211/// comfortable headroom.
212pub const MAX_REWRITE_OBJECT_NUMBER: u32 = 8_388_607;
213
214/// What a save actually did — the honest report the CLI, the GUI and
215/// the corpus harness all print.
216///
217/// Counters exist for the things that would otherwise be invisible: a
218/// save that quietly promoted objects out of an object stream, or that
219/// spent a document's Fast Web View property, has changed something the
220/// operator cares about and must say so ("fuzzy, never sneaky").
221#[derive(Debug, Clone, PartialEq, Eq)]
222#[non_exhaustive]
223pub struct SaveReport {
224    /// Total bytes in the produced file.
225    pub bytes_written: usize,
226    /// Bytes appended past the base file's original length. Exactly
227    /// `0` for an empty-dirty-set incremental save, and equal to
228    /// [`SaveReport::bytes_written`] for a full rewrite.
229    pub bytes_appended: usize,
230    /// Number of object definitions emitted in this save.
231    pub objects_written: usize,
232    /// Objects re-emitted **verbatim** from their retained source
233    /// bytes — the §5 invariant's numerator.
234    pub objects_verbatim: usize,
235    /// Objects that had to be re-serialized from values because they
236    /// had no file-level bytes (compressed in an object stream) or
237    /// because a policy deliberately rewrote them (`/Producer`).
238    ///
239    /// Every one of these is a byte-level divergence from the input,
240    /// and each is counted rather than rounded away (R20-style).
241    pub objects_reserialized: usize,
242    /// Whether the output is byte-identical to the input. Only ever
243    /// true for an empty-dirty-set [`save_incremental`](super::save_incremental).
244    pub byte_identical: bool,
245    /// Whether this save spent the input's live Fast Web View property
246    /// (Annex F.1; R36). Reported, never repaired.
247    pub delinearized: bool,
248    /// Objects that were **promoted out of an object stream** (R38) —
249    /// counted *and named*, per decision 007 W3's mitigation.
250    ///
251    /// A compressed object cannot be written in place, so touching one
252    /// moves it to file level. That is a representation change to an
253    /// object whose *value* the operator may not have edited at all
254    /// (an identity re-emission promotes too), and it leaves the old
255    /// value behind inside the untouched container — see this module's
256    /// "Promotion, and the stale copy it leaves". Both facts are things
257    /// an operator can act on, so neither is rounded away.
258    ///
259    /// `promoted.len()` is the count; there is deliberately no separate
260    /// counter field to fall out of step with the list.
261    pub promoted: Vec<ObjId>,
262    /// Objects given a type-0 (free) cross-reference entry by this save
263    /// — the Pass 3.2 deletion path (§7.5.4, decision 007 W9).
264    ///
265    /// Counted rather than named, unlike [`SaveReport::promoted`],
266    /// because a deletion is something the **operator asked for** and
267    /// already knows about, whereas a promotion is a representation
268    /// change pdfcer made on its own initiative. The honesty obligation
269    /// differs accordingly.
270    pub objects_deleted: usize,
271    /// `Some(n)` when this save appended under an RC4 handler
272    /// ([`Rc4Append::Preserve`](super::Rc4Append::Preserve)): `n` edited
273    /// objects were re-encrypted under the number and generation, and so the
274    /// RC4 keystream, of their previous revision. XOR-ing the two
275    /// ciphertexts cancels the keystream. `None` for every other save.
276    pub rc4_keystream_reused: Option<usize>,
277}
278
279impl SaveReport {
280    /// The report of a save that wrote nothing: `len` bytes, byte-identical.
281    pub(super) fn unchanged(len: usize) -> Self {
282        Self {
283            bytes_written: len,
284            bytes_appended: 0,
285            objects_written: 0,
286            objects_verbatim: 0,
287            objects_reserialized: 0,
288            byte_identical: true,
289            delinearized: false,
290            promoted: Vec::new(),
291            objects_deleted: 0,
292            rc4_keystream_reused: None,
293        }
294    }
295}
296
297/// Rewrite `doc` as a single-revision file, applying `dirty`, and return
298/// the bytes.
299///
300/// Every `Provenance::File` object the dirty set does **not** name is
301/// re-emitted from its retained source bytes verbatim; only the header
302/// prefix, object offsets, the cross-reference section and the trailer
303/// are newly generated. Byte identity is therefore asserted **per object
304/// definition**, never per file (R32 — see [`super`]'s contract table).
305///
306/// Pass `&DirtySet::empty()` for a pure identity rewrite; that is what
307/// the corpus round-trip gate and the fuzz target do, and it makes the
308/// no-edit path a strict subset of the edit path rather than a separate
309/// one that could drift.
310///
311/// ⚠️ **A full rewrite destroys every existing digital signature**
312/// (§12.8.1) and, unlike incremental save, does **not** by itself remove
313/// the superseded value of a promoted compressed object — see this
314/// module's "Promotion, and the stale copy it leaves", which the
315/// Redaction Pass must read.
316///
317/// # Errors
318///
319/// [`WriteError`] — notably [`WriteError::HybridFullRewrite`], which since
320/// `Pass 281.0` fires only for a §7.5.8.4 hybrid-reference input whose
321/// `/XRefStm` pdfcer could not parse. A hybrid file whose partition is known is
322/// rewritten **as a hybrid**, never normalized away.
323pub fn save_full(
324    doc: &Document,
325    dirty: &DirtySet,
326    options: &SaveOptions,
327) -> Result<(Vec<u8>, SaveReport), WriteError> {
328    let base = doc.bytes();
329    // Resolve `EOL-A1` against the FILE BEING SAVED, once, here.
330    //
331    // This is the only layer that has both the operator's setting and the
332    // base file's bytes, which is exactly why the default can now be
333    // "match the source" at all. Resolving once rather than at each
334    // `write_classic_table` call keeps an incremental save and a full
335    // rewrite of the same document from ever disagreeing about its form.
336    let entry_eol = options.xref_entry_eol.resolve(base);
337
338    // R45: authored appearance streams live in the staging buffer past the
339    // base file; replacement/created objects serialize against `base ++
340    // staging`. `base` alone (zero-copy) when nothing was authored.
341    let combined = dirty.combined_source(base);
342
343    // A HYBRID FILE IS NOW REWRITTEN, NOT REFUSED (`Pass 281.0`). The
344    // refusal here used to be unconditional, with the reasoning that
345    // "rebuilding the three-part unit from a merged view is Pass 3.2 work".
346    // The merged view is not the obstacle it was taken to be — the LOADER now
347    // retains which objects the `/XRefStm` established
348    // (`Document::hybrid_partition`), which is the one fact the merge
349    // destroyed — and `write_hybrid_tail` emits the unit §7.5.8.4 describes.
350    //
351    // What still refuses: a file that SAYS it hides objects and whose stream
352    // pdfcer could not parse. There the partition is unknown rather than
353    // absent, and either half would be a guess.
354    //
355    // Why this mattered beyond tidiness: redaction is forced to a full
356    // rewrite by `R35` — an incremental save leaves the un-redacted bytes in a
357    // prior revision — so this refusal made REDACTION UNREACHABLE on every
358    // hybrid file, and the refusal's own advice ("use incremental save") was
359    // the one thing a redaction may not do. Reported by `pdfcer-gui` on the
360    // operator's own SolidWorks drawing, which he had asked about three times.
361    if doc.is_hybrid() && !doc.hybrid_partition().is_reproducible() {
362        return Err(WriteError::HybridFullRewrite);
363    }
364
365    // 7.6: same refusal as the incremental path, and for the same reason --
366    // a full rewrite re-emits untouched objects from their source span too.
367    if doc.encryption().is_some() {
368        return Err(WriteError::EncryptedSaveUnsupported);
369    }
370
371    // The header region.
372    //
373    // Normal path: copied verbatim FROM THE `%PDF-` MARKER, so the
374    // `%PDF-M.N` line is preserved exactly (never re-derived — re-deriving
375    // would normalize a `%PDF-1.4 ` with trailing space) along with the
376    // §7.5.2 binary-comment line. Any bytes BEFORE the marker are dropped;
377    // see `header_span` for the measurement that forced that, and for why
378    // only a full rewrite is allowed to do it.
379    //
380    // Recovered path (decision 013): a recovered file's base cross-reference
381    // was invalid, so §5.6's "never normalize" does not bind it — and its
382    // header may be absent or buried behind >1 KiB of leading junk (the
383    // offset-start case, where `header_span` finds no marker in its
384    // window and would copy nothing, yielding a headerless rewrite that
385    // re-triggers recovery on reload). Emit a fresh, clean `%PDF-<version>`
386    // header + binary marker so the rewrite loads via the STRICT path.
387    let mut out = if doc.loaded_via_recovery() {
388        let mut h = format!("%PDF-{}\n", doc.version()).into_bytes();
389        h.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n"); // §7.5.2 binary marker
390        h
391    } else {
392        let mut h = base
393            .get(header_span(base))
394            .unwrap_or(b"%PDF-1.7\n")
395            .to_vec();
396        if !matches!(h.last(), Some(b'\n' | b'\r')) {
397            h.push(b'\n');
398        }
399        h
400    };
401
402    // The object number the new cross-reference stream will occupy, if
403    // the base file uses that form. Its old definition is NOT re-emitted
404    // as a body object — it *is* the section.
405    //
406    // A HYBRID FILE HAS ONE TOO (`Pass 281.0`), and it is found the same way
407    // a reader finds it: the object whose entry gives the offset the trailer's
408    // `/XRefStm` names. Reusing that number rather than allocating a fresh one
409    // keeps the rewritten file's object numbering as close to the input's as
410    // this Pass can — and a fresh number would raise `/Size` on a file where
411    // nothing was added.
412    let xref_stream_id = match doc.section_shape() {
413        SectionShape::Stream { id, .. } => Some(id),
414        SectionShape::Classic {
415            xref_stm: Some(off),
416        } => hybrid_stream_object(doc, off),
417        SectionShape::Classic { xref_stm: None } => None,
418    };
419    let base_widths = match doc.section_shape() {
420        SectionShape::Stream { widths, .. } => widths,
421        _ => [1, 4, 2],
422    };
423
424    // The `/Info` object, when a policy is going to rewrite it.
425    let info_id = match options.producer {
426        ProducerPolicy::Set => doc.trailer().get(b"Info").and_then(Object::as_reference),
427        ProducerPolicy::Preserve => None,
428    };
429
430    let body_start = out.len();
431    let mut entries: BTreeMap<u32, XrefEntry> = BTreeMap::new();
432    let mut verbatim = 0usize;
433    let mut reserialized = 0usize;
434    let mut promoted: Vec<ObjId> = Vec::new();
435
436    // Ascending object-number order. Not required by §7.5.4 (which lets
437    // subsections appear in any order) but it is what makes the emitted
438    // table a single contiguous subsection, and it keeps the output
439    // deterministic across runs — a precondition for byte-comparison
440    // testing at all.
441    //
442    // The dirty set's own ids are folded in so a **created** object (one
443    // the base document does not define) is emitted too. `BTreeSet`
444    // rather than sort+dedup because the two sources overlap for every
445    // ordinary edit.
446    let mut numbers: BTreeSet<u32> = doc.xref().iter().map(|(num, _)| num).collect();
447    numbers.extend(dirty.iter().map(|id| id.num));
448
449    for num in numbers {
450        // A replacement for this object number, if the dirty set has
451        // one. Looked up by number rather than by full id because the
452        // base file's generation is authoritative here — an edit never
453        // changes a generation in this Pass (deletion, which is what
454        // increments one, is Pass 3.2).
455        let entry = doc.xref().get(num);
456        let generation = match entry {
457            Some(XrefEntry::InUse { generation, .. }) => generation,
458            // A compressed object's generation is always 0 (§7.5.7), and
459            // a created object is allocated at generation 0.
460            _ => 0,
461        };
462        let id = ObjId::new(num, generation);
463
464        // A deleted object contributes no body. Its type-0 entry is
465        // written by `apply_free_list` below, together with the rest of
466        // the chain — `continue` here rather than inserting a
467        // placeholder, because a placeholder is exactly the kind of
468        // half-written free entry decision 007 W9 warns about.
469        if dirty.is_deleted(id) {
470            continue;
471        }
472        let replacement = dirty.replacement(id);
473
474        match entry {
475            // A free entry carries no bytes; it is copied through
476            // exactly as the base recorded it, which preserves the
477            // base file's free list without pdfcer inventing one. A
478            // replacement for a free number would be a resurrection,
479            // which needs the generation rules deletion brings — Pass
480            // 3.2 — so it is left alone here.
481            Some(free @ XrefEntry::Free { .. }) => {
482                entries.insert(num, free);
483            }
484            // A compressed object needs no body emission at all *unless
485            // it was edited*: its type-2 entry names a container and an
486            // index, neither of which is a byte offset, and the
487            // container is re-emitted verbatim below (module docs). An
488            // edited one must be promoted out (R38), because the
489            // container it lives in is about to be copied through with
490            // its OLD contents.
491            Some(XrefEntry::InStream { .. }) => match replacement {
492                None => {
493                    if xref_stream_id.is_none() {
494                        // The output section is a CLASSIC table, which
495                        // cannot express a type-2 entry. This is only
496                        // reachable for a **recovered** document (decision
497                        // 013): a normal xref-stream file has a `Stream`
498                        // section shape (`xref_stream_id.is_some()`) and
499                        // carries type-2 entries through untouched; a
500                        // recovered document is fixed to
501                        // `Classic { xref_stm: None }`, so its compressed
502                        // objects must be PROMOTED out to file level (R38).
503                        // The old container is re-emitted verbatim too, so
504                        // this is a superseding file-level definition, not a
505                        // move — but a classic table can only name the
506                        // file-level copy.
507                        let io = doc.get(id).ok_or(WriteError::MissingObject { num })?;
508                        let offset = out.len() as u64;
509                        serialize::write_indirect(
510                            &mut out,
511                            id,
512                            &io.value,
513                            &combined,
514                            &IdentityEncoder,
515                        );
516                        reserialized += 1;
517                        promoted.push(id);
518                        entries.insert(num, XrefEntry::InUse { offset, generation });
519                    } else if let Some(e) = entry {
520                        entries.insert(num, e);
521                    }
522                }
523                Some(value) => {
524                    let offset = out.len() as u64;
525                    serialize::write_indirect(&mut out, id, value, &combined, &IdentityEncoder);
526                    reserialized += 1;
527                    promoted.push(id);
528                    entries.insert(num, XrefEntry::InUse { offset, generation });
529                }
530            },
531            Some(XrefEntry::InUse { .. }) => {
532                if xref_stream_id.is_some_and(|sid| sid.num == num) {
533                    // Placeholder; the real offset is filled in once
534                    // the body is complete.
535                    continue;
536                }
537                let offset = out.len() as u64;
538                match (replacement, Some(id) == info_id) {
539                    // An operator metadata edit AND a `/Producer`
540                    // policy on the same object. Both apply: the policy
541                    // is layered over the edited value, not instead of
542                    // it. Doing otherwise would make an unrelated
543                    // authorship setting silently discard the
544                    // operator's own edit.
545                    (Some(value), true) => {
546                        write_with_producer(&mut out, id, value, &combined);
547                        reserialized += 1;
548                    }
549                    (Some(value), false) => {
550                        serialize::write_indirect(&mut out, id, value, &combined, &IdentityEncoder);
551                        reserialized += 1;
552                    }
553                    (None, true) => {
554                        let io = doc.get(id).ok_or(WriteError::MissingObject { num })?;
555                        write_with_producer(&mut out, id, &io.value, base);
556                        reserialized += 1;
557                    }
558                    (None, false) => {
559                        let io = doc.get(id).ok_or(WriteError::MissingObject { num })?;
560                        match emit_object(&mut out, io, (base, base), &IdentityEncoder)? {
561                            Emission::Verbatim => verbatim += 1,
562                            // See the matching arm in `save_incremental`.
563                            Emission::RecoveredReserialized => reserialized += 1,
564                            Emission::Promoted => {
565                                reserialized += 1;
566                                promoted.push(id);
567                            }
568                        }
569                    }
570                }
571                entries.insert(num, XrefEntry::InUse { offset, generation });
572            }
573            // The base document does not define this number at all: it
574            // is a created object, and only a replacement can supply a
575            // value for it. A bare re-emission request for an unknown
576            // id is the same named refusal as on the incremental path.
577            None => {
578                let Some(value) = replacement else {
579                    return Err(WriteError::UnknownDirtyObject { id });
580                };
581                let offset = out.len() as u64;
582                serialize::write_indirect(&mut out, id, value, &combined, &IdentityEncoder);
583                reserialized += 1;
584                entries.insert(num, XrefEntry::InUse { offset, generation });
585            }
586        }
587    }
588    let body_end = out.len();
589
590    // §7.5.4: "The cross-reference table … shall contain one entry for
591    // each object number from 0 to the maximum object number defined in
592    // the file." A full rewrite is ONE section, so that obligation
593    // lands entirely on it: holes must be filled with free entries.
594    //
595    // The fill value is §7.5.4's second, "detached" free form — links
596    // back to object 0, generation 65535 — which the clause explicitly
597    // permits ("the table may contain other free entries that link back
598    // to object number 0 and have a generation number of 65,535, even
599    // though these entries are not in the linked list itself"). Using
600    // it avoids re-deriving a free-list chain pdfcer has no business
601    // inventing in a Pass with no deletion.
602    let highest = entries
603        .keys()
604        .copied()
605        .max()
606        .max(xref_stream_id.map(|id| id.num))
607        .unwrap_or(0);
608    // THE HOLE-FILLING LOOP BELOW IS O(highest), AND `highest` IS CHOSEN
609    // BY THE INPUT FILE. Guard it before it runs.
610    //
611    // The completeness obligation above is real and is why the loop
612    // exists — but it makes the writer's cost a function of the largest
613    // object NUMBER in the file, not of how many objects the file
614    // actually contains. A 1.2 KB document naming one object
615    // `2147483648 0 obj` therefore asks pdfcer to emit 2,147,483,649
616    // cross-reference entries: measured at ~27 MB/s of steady allocation
617    // with the CPU pinned, which is roughly an hour of grinding before
618    // the allocator gives up. Not an infinite loop — worse in one
619    // respect, because it looks like progress.
620    //
621    // That is a real corpus file (pdfium's `bug_455199.pdf`), and the
622    // consequence in the GUI is an unrecoverable freeze: no error, no
623    // cancel, no save.
624    //
625    // So this refuses by name (R27) rather than grinding. Refusal is the
626    // honest outcome: complying literally would emit a ~40 GB
627    // cross-reference table for a 1.2 KB input, and quietly emitting a
628    // SPARSE table instead would violate §7.5.4's completeness
629    // requirement for a single-section full rewrite — trading a hang for
630    // a malformed file.
631    if highest > MAX_REWRITE_OBJECT_NUMBER {
632        return Err(WriteError::ObjectNumberTooLarge {
633            num: highest,
634            max: MAX_REWRITE_OBJECT_NUMBER,
635        });
636    }
637    entries.entry(0).or_insert(XrefEntry::Free {
638        next_free: 0,
639        generation: 65_535,
640    });
641    for num in 0..=highest {
642        entries.entry(num).or_insert(XrefEntry::Free {
643            next_free: 0,
644            generation: 65_535,
645        });
646    }
647    // Deletions get their real type-0 entries last, so the hole-filling
648    // loop above cannot leave a deleted object wearing a detached free
649    // entry with the wrong generation.
650    let deleted = apply_free_list(&mut entries, doc, dirty);
651
652    let mut trailer = copy_trailer_without_prev(doc.trailer());
653    // Operator trailer changes first; the writer's own keys below win.
654    dirty.apply_trailer_changes(&mut trailer);
655    // A single section has no predecessor and no hybrid companion.
656    trailer.0.retain(|(k, _)| k.as_bytes() != b"XRefStm");
657    bump_size(&mut trailer, highest);
658    if dirty.changes_content() {
659        refresh_changing_identifier(
660            &mut trailer,
661            base.len(),
662            out.get(body_start..body_end).unwrap_or(&[]),
663        );
664    }
665
666    let section_offset = out.len() as u64;
667    // Three tails, and which one runs is decided by the INPUT's form (R33) —
668    // never by preference. A hybrid input is the only one that emits more than
669    // one section, because §7.5.8.4 forbids `/XRefStm` in a main section and a
670    // single-section file has only a main one.
671    let hybrid_rewritten = doc.is_hybrid();
672    match (hybrid_rewritten, xref_stream_id) {
673        (true, Some(stm_id)) => {
674            write_hybrid_tail(
675                &mut out,
676                &HybridTail {
677                    entries: &entries,
678                    hidden: &doc.hybrid_partition().hidden,
679                    stm_id,
680                    trailer: &trailer,
681                    base_widths,
682                    entry_eol,
683                    trailing: options.trailing_eol,
684                },
685            )?;
686        }
687        // A hybrid whose stream object could not be located is refused above;
688        // reaching here would mean that guard and this match disagree, and
689        // emitting a NON-hybrid file for a hybrid input is exactly the silent
690        // normalization R33 forbids. Refuse rather than "fall back".
691        (true, None) => return Err(WriteError::HybridFullRewrite),
692        (false, None) => {
693            xref_out::write_classic_table(&mut out, &entries, entry_eol)?;
694            xref_out::write_classic_tail(&mut out, &trailer, section_offset, options.trailing_eol);
695        }
696        (false, Some(id)) => {
697            entries.insert(
698                id.num,
699                XrefEntry::InUse {
700                    offset: section_offset,
701                    generation: id.generation,
702                },
703            );
704            let widths = xref_out::Widths::fit(&entries, base_widths);
705            let stream = xref_out::build_xref_stream(id, &entries, widths, &trailer)?;
706            out.extend_from_slice(&stream.bytes);
707            xref_out::write_stream_tail(&mut out, section_offset, options.trailing_eol);
708        }
709    }
710
711    let report = SaveReport {
712        bytes_written: out.len(),
713        bytes_appended: out.len(),
714        objects_written: verbatim + reserialized,
715        objects_verbatim: verbatim,
716        objects_reserialized: reserialized,
717        byte_identical: false,
718        delinearized: doc.linearization().save_invalidates_fast_web_view(),
719        promoted,
720        objects_deleted: deleted,
721        rc4_keystream_reused: None,
722    };
723    Ok((out, report))
724}
725
726/// The values a full **encrypting** rewrite needs beyond the ordinary
727/// [`save_full`] inputs: the file key, the object the `/Encrypt` dictionary
728/// occupies, that dictionary's value, and the two-element `/ID`.
729///
730/// At `/V` 5 `/ID` plays **no** part in key derivation (unlike `/R` 4), so a
731/// freshly generated pair is written verbatim; it exists because §7.5.5 makes
732/// `/ID` mandatory whenever `/Encrypt` is present.
733#[derive(Debug, Clone)]
734pub struct EncryptParams {
735    /// The 32-byte file encryption key (never serialised; drives the encoder).
736    pub file_key: [u8; 32],
737    /// The object number and generation the `/Encrypt` dictionary is written
738    /// at — its own strings/streams are exempt from encryption (§7.6).
739    pub encrypt_dict: ObjId,
740    /// The `/Encrypt` dictionary as a value ready to serialise (`/V 5 /R 6
741    /// /CFM AESV3`, with the byte-string `/O`/`/U`/`/OE`/`/UE`/`/Perms`).
742    pub encrypt_dict_value: Object,
743    /// The `/ID` array's two byte strings.
744    pub file_id: [Vec<u8>; 2],
745    /// `/EncryptMetadata` — when false, `/Metadata` streams are left in clear.
746    pub encrypt_metadata: bool,
747}
748
749/// Rewrite the whole document as one **encrypted** revision (`Pass 5.4`,
750/// ISO 32000-2:2020 §7.6 + Algorithm 1.A).
751///
752/// # Why this is a separate function, not a flag on [`save_full`]
753///
754/// Encryption is decision 007 **W8**'s canonical "touches EVERY string and
755/// EVERY stream" transformation, so the minimal-diff invariant
756/// (`ARCHITECTURE.md` §5) is *deliberately* waived here: no object is emitted
757/// verbatim from its source span, because a verbatim copy would leave the
758/// object's strings and streams in clear. Every object is re-serialised
759/// through the `EncryptingEncoder`, which is the ONLY difference from a
760/// plaintext rewrite — the serializer recomputes `/Length` from the encrypted
761/// bytes (§7.3.8.2, IV + ciphertext + PKCS#7 pad), so nothing else needs to
762/// change.
763///
764/// # Structural normalisation this DOES perform, and why it is sanctioned
765///
766/// The output is always a **classic cross-reference table** with every
767/// compressed object promoted to file level and every `/Type /ObjStm`
768/// container dropped. This is the same normalisation a recovered document
769/// gets (decision 013), sanctioned here for the same reason it is sanctioned
770/// there: the operation is a whole-file rewrite by nature, so §5's "never
771/// normalise gratuitously" does not bind it — and a classic table sidesteps
772/// the special-case exemptions an xref STREAM would need (its own bytes must
773/// stay in clear, §7.6.2). An object stream's exemption is moot once it is
774/// gone.
775///
776/// # What is left in clear
777///
778/// The `/Encrypt` dictionary itself (it is what a reader needs *before* it can
779/// decrypt anything), and `/Metadata` streams when `encrypt_metadata` is
780/// false (§7.6.2). A signed document is refused UPSTREAM by the caller
781/// (`pdfcer_core::EditSession`) — the write path never sees one — so the
782/// per-string `/Contents` exemption (N13) is not expressed here.
783///
784/// # Errors
785///
786/// - [`WriteError::HybridFullRewrite`] for a hybrid-reference input (R33).
787/// - [`WriteError::EncryptedSaveUnsupported`] if the document is ALREADY
788///   encrypted — re-encryption decrypts first, which is the caller's job.
789/// - [`WriteError::ObjectNumberTooLarge`] (R27) as [`save_full`].
790/// - [`WriteError::MissingObject`] / [`WriteError::UnknownDirtyObject`] for a
791///   dangling reference, as [`save_full`].
792pub fn save_full_encrypted(
793    doc: &Document,
794    dirty: &DirtySet,
795    options: &SaveOptions,
796    enc: &EncryptParams,
797) -> Result<(Vec<u8>, SaveReport), WriteError> {
798    full_reencode(doc, dirty, options, Some(enc))
799}
800
801/// Rewrite the whole document as one revision, re-serialising EVERY string and
802/// stream through an identity encoder — the plaintext sibling of
803/// [`save_full_encrypted`] (`Pass 5.4`, `EditSession::remove_encryption`).
804///
805/// # Why this is distinct from [`save_full`]
806///
807/// [`save_full`] copies an untouched object's DEFINITION BYTES verbatim from
808/// the source. That is wrong for a document that was **decrypted in place**:
809/// decryption shortened each stream's `data_span` (AES strips the 16-byte IV
810/// and padding) but left the dictionary's `/Length` and the trailing bytes in
811/// the source buffer, so a verbatim copy would emit a stale `/Length` over
812/// plaintext-plus-leftover-ciphertext. Re-serialising every object recomputes
813/// `/Length` from the shortened span, which is exactly what removing
814/// encryption needs — and is why saving a decrypted document through the
815/// verbatim path is refused (`WriteError::EncryptedSaveUnsupported`).
816///
817/// The caller must have already dropped the `/Encrypt` state
818/// (`Document::clear_encryption`); this function does not write
819/// `/Encrypt` or force `/ID`.
820///
821/// # Errors
822///
823/// As [`save_full_encrypted`].
824pub fn save_full_decrypted(
825    doc: &Document,
826    dirty: &DirtySet,
827    options: &SaveOptions,
828) -> Result<(Vec<u8>, SaveReport), WriteError> {
829    full_reencode(doc, dirty, options, None)
830}
831
832/// The shared body of [`save_full_encrypted`] (`enc = Some`) and
833/// [`save_full_decrypted`] (`enc = None`): a full rewrite that re-serialises
834/// every object through an [`ObjectEncoder`], never verbatim. See both public
835/// wrappers for the contract.
836fn full_reencode(
837    doc: &Document,
838    dirty: &DirtySet,
839    options: &SaveOptions,
840    enc: Option<&EncryptParams>,
841) -> Result<(Vec<u8>, SaveReport), WriteError> {
842    use super::encoder::{EncryptingEncoder, IdentityEncoder, ObjectEncoder};
843
844    let base = doc.bytes();
845    let entry_eol = options.xref_entry_eol.resolve(base);
846    let combined = dirty.combined_source(base);
847
848    if matches!(
849        doc.section_shape(),
850        SectionShape::Classic { xref_stm: Some(_) }
851    ) {
852        return Err(WriteError::HybridFullRewrite);
853    }
854    if doc.encryption().is_some() {
855        // Encrypting requires plaintext; re-encryption decrypts first (the
856        // caller clears `/Encrypt` after decrypt-in-place). A document still
857        // reporting encryption here has not been through that, and its source
858        // bytes are ciphertext.
859        return Err(WriteError::EncryptedSaveUnsupported);
860    }
861
862    // The set of stream objects whose DATA is exempt from encryption
863    // (§7.6.2). Empty when not encrypting. With a classic output table there
864    // is no xref stream to exempt; the remaining categories are clear
865    // `/Metadata` and external (`/F`) streams. Resolved into object numbers so
866    // the encoder — which sees only bytes and an owner id — can consult it.
867    let mut clear_streams: std::collections::HashSet<u32> = std::collections::HashSet::new();
868    if let Some(enc) = enc {
869        for (num, _) in doc.xref().iter() {
870            let id = ObjId::new(num, 0);
871            if let Some(io) = doc.get(id)
872                && let Object::Stream(st) = &io.value
873            {
874                let ty = st.dict.get(b"Type").and_then(Object::as_name);
875                let is_metadata = ty.is_some_and(|n| n.0 == b"Metadata");
876                let external = st.dict.get(b"F").is_some();
877                if (is_metadata && !enc.encrypt_metadata) || external {
878                    clear_streams.insert(num);
879                }
880            }
881        }
882    }
883    let encrypting;
884    let identity = IdentityEncoder;
885    let encoder: &dyn ObjectEncoder = match enc {
886        Some(enc) => {
887            encrypting = EncryptingEncoder::new(enc.file_key, enc.encrypt_dict, clear_streams);
888            &encrypting
889        }
890        None => &identity,
891    };
892
893    // A clean header copied from the source marker so an encrypted rewrite
894    // always loads via the strict path.
895    let mut out = {
896        let mut h = base
897            .get(header_span(base))
898            .unwrap_or(b"%PDF-1.7\n")
899            .to_vec();
900        if !matches!(h.last(), Some(b'\n' | b'\r')) {
901            h.push(b'\n');
902        }
903        h
904    };
905
906    // The base file's old xref stream, if any, is NOT re-emitted as a body
907    // object — the output is a classic table, so the container disappears.
908    let old_xref_stream = match doc.section_shape() {
909        SectionShape::Stream { id, .. } => Some(id.num),
910        _ => None,
911    };
912
913    let body_start = out.len();
914    let _ = body_start;
915    let mut entries: BTreeMap<u32, XrefEntry> = BTreeMap::new();
916    let mut reserialized = 0usize;
917    let mut promoted: Vec<ObjId> = Vec::new();
918
919    let mut numbers: BTreeSet<u32> = doc.xref().iter().map(|(num, _)| num).collect();
920    numbers.extend(dirty.iter().map(|id| id.num));
921    if let Some(enc) = enc {
922        numbers.insert(enc.encrypt_dict.num);
923    }
924
925    for num in numbers {
926        if old_xref_stream == Some(num) {
927            continue;
928        }
929        let entry = doc.xref().get(num);
930        let generation = match entry {
931            Some(XrefEntry::InUse { generation, .. }) => generation,
932            _ => 0,
933        };
934        let id = ObjId::new(num, generation);
935
936        if dirty.is_deleted(id) {
937            continue;
938        }
939
940        // The value to serialise: the /Encrypt dict for its number, else a
941        // dirty replacement, else the base object. A free base entry carries
942        // no body.
943        let value_owned;
944        let value: &Object = if let Some(e) = enc.filter(|e| num == e.encrypt_dict.num) {
945            &e.encrypt_dict_value
946        } else if let Some(v) = dirty.replacement(id) {
947            v
948        } else {
949            match entry {
950                Some(XrefEntry::Free { .. }) => {
951                    entries.insert(
952                        num,
953                        entry.unwrap_or(XrefEntry::Free {
954                            next_free: 0,
955                            generation: 65_535,
956                        }),
957                    );
958                    continue;
959                }
960                _ => {
961                    let io = doc.get(id).ok_or(WriteError::MissingObject { num })?;
962                    value_owned = io.value.clone();
963                    &value_owned
964                }
965            }
966        };
967
968        // A dropped object stream leaves no body; its members are emitted at
969        // file level by their own numbers.
970        if let Object::Stream(st) = value
971            && st
972                .dict
973                .get(b"Type")
974                .and_then(Object::as_name)
975                .is_some_and(|n| n.0 == b"ObjStm")
976        {
977            continue;
978        }
979
980        let offset = out.len() as u64;
981        serialize::write_indirect(&mut out, id, value, &combined, encoder);
982        reserialized += 1;
983        if matches!(entry, Some(XrefEntry::InStream { .. })) {
984            promoted.push(id);
985        }
986        entries.insert(num, XrefEntry::InUse { offset, generation });
987    }
988
989    let highest = entries.keys().copied().max().unwrap_or(0);
990    if highest > MAX_REWRITE_OBJECT_NUMBER {
991        return Err(WriteError::ObjectNumberTooLarge {
992            num: highest,
993            max: MAX_REWRITE_OBJECT_NUMBER,
994        });
995    }
996    entries.entry(0).or_insert(XrefEntry::Free {
997        next_free: 0,
998        generation: 65_535,
999    });
1000    for num in 0..=highest {
1001        entries.entry(num).or_insert(XrefEntry::Free {
1002            next_free: 0,
1003            generation: 65_535,
1004        });
1005    }
1006    let deleted = apply_free_list(&mut entries, doc, dirty);
1007
1008    let mut trailer = copy_trailer_without_prev(doc.trailer());
1009    dirty.apply_trailer_changes(&mut trailer);
1010    trailer.0.retain(|(k, _)| k.as_bytes() != b"XRefStm");
1011    if let Some(enc) = enc {
1012        // §7.5.5: /Encrypt names the security handler dictionary; /ID is
1013        // mandatory when /Encrypt is present. Both are set explicitly here —
1014        // never derived — because encryption owns them.
1015        trailer.insert(Name::from(b"Encrypt"), Object::Reference(enc.encrypt_dict));
1016        trailer.insert(
1017            Name::from(b"ID"),
1018            Object::Array(vec![
1019                Object::String(enc.file_id[0].clone()),
1020                Object::String(enc.file_id[1].clone()),
1021            ]),
1022        );
1023    }
1024    bump_size(&mut trailer, highest);
1025
1026    let section_offset = out.len() as u64;
1027    xref_out::write_classic_table(&mut out, &entries, entry_eol)?;
1028    xref_out::write_classic_tail(&mut out, &trailer, section_offset, options.trailing_eol);
1029
1030    let report = SaveReport {
1031        bytes_written: out.len(),
1032        bytes_appended: out.len(),
1033        objects_written: reserialized,
1034        objects_verbatim: 0,
1035        objects_reserialized: reserialized,
1036        byte_identical: false,
1037        delinearized: doc.linearization().save_invalidates_fast_web_view(),
1038        promoted,
1039        objects_deleted: deleted,
1040        rc4_keystream_reused: None,
1041    };
1042    Ok((out, report))
1043}
1044
1045/// The cross-reference **stream object** of a hybrid-reference file, found the
1046/// way a reader finds it (`Pass 281.0`).
1047///
1048/// The trailer's `/XRefStm` gives a byte offset (§7.5.8.4 Table 19); the object
1049/// living at that offset is the stream. It is named by the update section's own
1050/// classic table — §7.5.8.3 requires an entry for it to exist "in a
1051/// cross-reference table (in hybrid-reference files)" — so a lookup by offset
1052/// over the merged table finds it.
1053///
1054/// `None` when nothing in the table claims that offset: the file names a stream
1055/// pdfcer's table does not account for, and inventing a number for it would be
1056/// a guess. The caller refuses instead.
1057fn hybrid_stream_object(doc: &Document, xref_stm_offset: u64) -> Option<ObjId> {
1058    doc.xref().iter().find_map(|(num, entry)| match entry {
1059        XrefEntry::InUse { offset, generation } if offset == xref_stm_offset => {
1060            Some(ObjId::new(num, generation))
1061        }
1062        _ => None,
1063    })
1064}
1065
1066/// The inputs [`write_hybrid_tail`] needs, bundled so the seam stays inside
1067/// clippy's seven-argument limit — and, more usefully, so the three-part unit's
1068/// ingredients are named in one place rather than spread over a call.
1069#[derive(Clone, Copy)]
1070struct HybridTail<'a> {
1071    /// The finished entry map for the whole file, before concealment.
1072    entries: &'a BTreeMap<u32, XrefEntry>,
1073    /// The object numbers this file hides — see `Document::hybrid_partition`.
1074    hidden: &'a BTreeSet<u32>,
1075    /// The object number the cross-reference stream occupies.
1076    stm_id: ObjId,
1077    /// The trailer both sections are built from.
1078    trailer: &'a Dict,
1079    /// The `/W` widths to fit the stream's rows into.
1080    base_widths: [usize; 3],
1081    /// `EOL-A1`, resolved against the file being saved.
1082    entry_eol: crate::writer::XrefEntryEol,
1083    /// `EOL-A2`, the file's last byte.
1084    trailing: crate::writer::TrailingEol,
1085}
1086
1087/// Emit the §7.5.8.4 three-part unit that makes a rewritten file
1088/// **hybrid-reference** again (`Pass 281.0`).
1089///
1090/// # What a hybrid file physically is, and why one section cannot be one
1091///
1092/// §7.5.8.4 is explicit: *"the `XRefStm` entry shall **not** be used in the
1093/// trailer dictionary of the main cross-reference section but only in an
1094/// update cross-reference section."* A hybrid file therefore has **at least
1095/// two** sections by construction, and a full rewrite that emitted a single
1096/// section could not be hybrid whatever else it did. That is the fact the
1097/// refusal this replaces was really about — not, as its comment claimed, that
1098/// rebuilding the unit was impossible.
1099///
1100/// So the emitted tail is, in order:
1101///
1102/// ```text
1103/// <main classic table>     every object 0..=highest; the HIDDEN ones and the
1104///                          stream object itself marked free, generation 65535
1105/// trailer << … >>          no /XRefStm, no /Prev — this IS the main section
1106/// startxref <main_at> %%EOF
1107/// <the cross-reference stream object>   real entries for the hidden objects
1108/// <update classic table>   one entry: the stream object, at its real offset
1109/// trailer << … /XRefStm <stm_at> /Prev <main_at> >>
1110/// startxref <upd_at> %%EOF
1111/// ```
1112///
1113/// # Why the hidden objects are marked free with generation 65535
1114///
1115/// That is the concealment mechanism itself, quoted from §7.5.8.4: *"The free
1116/// entry shall have a next-generation number of 65535 so that the object
1117/// number shall not be reused."* A pre-1.5 reader resolves such a reference to
1118/// null (§7.3.10) and renders the file without the optional structure; a 1.5+
1119/// reader finds the object through `/XRefStm` first, because §7.5.8.4's search
1120/// order consults the stream **before** `/Prev`.
1121///
1122/// # Why the stream object is free in the main table too
1123///
1124/// It is not part of the pre-1.5 view — a pre-1.5 reader has no business
1125/// resolving a reference to a cross-reference stream — and §7.5.8.3 says an
1126/// entry for it *"shall exist in … a cross-reference table (in
1127/// hybrid-reference files)"*, which is the **update** table below. Marking it
1128/// in-use in both would be two answers to one question.
1129///
1130/// # Completeness
1131///
1132/// §7.5.8.4: *"to allow random access, a main cross-reference section shall
1133/// contain entries for **all** objects numbered 0 through `Size` − 1."* The
1134/// main table therefore covers `0..=highest` with no holes — the same
1135/// obligation the non-hybrid path already meets, applied to the same entry map
1136/// before the hidden objects are masked out of it.
1137fn write_hybrid_tail(out: &mut Vec<u8>, plan: &HybridTail<'_>) -> Result<(), WriteError> {
1138    let HybridTail {
1139        entries,
1140        hidden,
1141        stm_id,
1142        trailer,
1143        base_widths,
1144        entry_eol,
1145        trailing,
1146    } = *plan;
1147    // ---- the main section: the visible view, and only it.
1148    let mut main_entries = entries.clone();
1149    let concealed = XrefEntry::Free {
1150        next_free: 0,
1151        generation: 65_535,
1152    };
1153    for num in hidden {
1154        main_entries.insert(*num, concealed);
1155    }
1156    main_entries.insert(stm_id.num, concealed);
1157
1158    let main_at = out.len() as u64;
1159    xref_out::write_classic_table(out, &main_entries, entry_eol)?;
1160    let mut main_trailer = trailer.clone();
1161    main_trailer.0.retain(|(k, _)| {
1162        // The main section names neither companion: `/XRefStm` is forbidden
1163        // here by §7.5.8.4, and there is no earlier section for `/Prev`.
1164        //
1165        // MEASURED REDUNDANT FOR `/XRefStm`, AND KEPT. The caller already
1166        // strips that key before building this trailer ("a single section has
1167        // no predecessor and no hybrid companion"), so a sabotage that removes
1168        // it here stays GREEN — a guarantee enforced elsewhere, which is one of
1169        // this project's three recorded reasons a sabotage survives.
1170        //
1171        // It stays because §7.5.8.4's requirement is owed BY THIS FUNCTION: the
1172        // caller's strip exists for the single-section case and would be
1173        // perfectly reasonable to change, at which point the clause would be
1174        // violated forty lines from the code that knows about it. `/Prev` is
1175        // NOT redundant — nothing else removes it — and the two are stripped
1176        // together because they are one rule about one section.
1177        !matches!(k.as_bytes(), b"XRefStm" | b"Prev")
1178    });
1179    xref_out::write_classic_tail(out, &main_trailer, main_at, trailing);
1180
1181    // ---- the cross-reference stream: the hidden view, and only it.
1182    let hidden_entries: BTreeMap<u32, XrefEntry> = hidden
1183        .iter()
1184        .filter_map(|num| entries.get(num).map(|e| (*num, *e)))
1185        .collect();
1186    let stm_at = out.len() as u64;
1187    let widths = xref_out::Widths::fit(&hidden_entries, base_widths);
1188    let stream = xref_out::build_xref_stream(stm_id, &hidden_entries, widths, &main_trailer)?;
1189    out.extend_from_slice(&stream.bytes);
1190
1191    // ---- the update section: one real entry, for the stream object.
1192    let mut upd_entries: BTreeMap<u32, XrefEntry> = BTreeMap::new();
1193    upd_entries.insert(
1194        stm_id.num,
1195        XrefEntry::InUse {
1196            offset: stm_at,
1197            generation: stm_id.generation,
1198        },
1199    );
1200    let upd_at = out.len() as u64;
1201    xref_out::write_classic_table(out, &upd_entries, entry_eol)?;
1202    let mut upd_trailer = main_trailer;
1203    upd_trailer.insert(
1204        Name::from(b"XRefStm"),
1205        Object::Integer(i64::try_from(stm_at).unwrap_or(0)),
1206    );
1207    upd_trailer.insert(
1208        Name::from(b"Prev"),
1209        Object::Integer(i64::try_from(main_at).unwrap_or(0)),
1210    );
1211    xref_out::write_classic_tail(out, &upd_trailer, upd_at, trailing);
1212    Ok(())
1213}
1214
1215/// Give every deleted object a conforming type-0 entry and splice them
1216/// onto the head of the file's free list. Returns how many were freed.
1217///
1218/// This function is decision 007 **W9** in executable form:
1219///
1220/// > A malformed type-0 free chain produces files Acrobat tolerates and
1221/// > stricter readers reject — the worst failure shape, because the
1222/// > obvious test passes.
1223///
1224/// Three rules, each from §7.5.4, each easy to get wrong:
1225///
1226/// 1. **The 10-digit field of a free entry is an object number, not an
1227///    offset** — *"the object number of the next free object"*. The
1228///    entries therefore form a **linked list**, and one that terminates
1229///    at 0.
1230/// 2. **A free entry's generation is the generation the number would get
1231///    if reused** — *"the generation number to be used if the object is
1232///    ever reused"* — i.e. one more than the object being freed. It
1233///    saturates at 65,535, which §7.5.4 defines as the marker for a
1234///    number that *"shall not be reused"*: an object already at the
1235///    maximum generation cannot be recycled, and pretending otherwise
1236///    would hand out an identity a stale reference could match.
1237/// 3. **Object 0 is the list head**, always free, always generation
1238///    65,535 — *"the head of the linked list of free objects"*.
1239///
1240/// ## Splicing rather than rebuilding, and why
1241///
1242/// The new entries are pushed onto the **front** of the existing list:
1243/// `0 → d₁ → d₂ → … → dₙ → (whatever object 0 used to point at)`. The
1244/// alternative — walking the base file's chain and appending to its tail
1245/// — would need to read entries this update section does not carry and
1246/// would rewrite free entries pdfcer was not asked to touch (§5). Front
1247/// insertion touches exactly the head plus the new entries, and §7.5.4
1248/// imposes no ordering on the list, so it is fully conforming.
1249///
1250/// Note what is deliberately **not** done: pre-existing "detached" free
1251/// entries (`next_free 0`, generation 65,535 — a form §7.5.4 explicitly
1252/// permits) are left exactly as the base file wrote them. Re-deriving a
1253/// tidy chain across them would be pdfcer inventing structure nobody
1254/// asked for, which R33 forbids for the same reason it forbids
1255/// normalizing anything else.
1256pub(super) fn apply_free_list(
1257    entries: &mut BTreeMap<u32, XrefEntry>,
1258    doc: &Document,
1259    dirty: &DirtySet,
1260) -> usize {
1261    let freed: Vec<ObjId> = dirty.deletions().collect();
1262    if freed.is_empty() {
1263        return 0;
1264    }
1265
1266    // Where the current head points, so the tail of the new run can be
1267    // spliced in front of it without losing the old list.
1268    let old_next_free = match entries.get(&0) {
1269        Some(XrefEntry::Free { next_free, .. }) => *next_free,
1270        // Object 0 is not free (a malformed file — §7.5.4 makes it
1271        // "always free"). Terminating the new list at 0 is the only
1272        // safe reading; chaining into a live object would be worse.
1273        _ => 0,
1274    };
1275
1276    for (position, id) in freed.iter().enumerate() {
1277        // The next link: the following deleted object, or the old head's
1278        // target once the run is exhausted.
1279        let next_free = freed
1280            .get(position + 1)
1281            .map_or(old_next_free, |next| next.num);
1282        // Rule 2. The generation to record is the *deleted object's*
1283        // generation plus one — read from the cross-reference table
1284        // rather than from the id, because a caller could name a stale
1285        // generation and the table is what the file actually asserts.
1286        let current = match doc.xref().get(id.num) {
1287            Some(XrefEntry::InUse { generation, .. }) => generation,
1288            // A compressed object has no generation field at all
1289            // (§7.5.7 fixes it at 0), and an object the base does not
1290            // define starts at 0 too.
1291            _ => id.generation,
1292        };
1293        entries.insert(
1294            id.num,
1295            XrefEntry::Free {
1296                next_free,
1297                generation: current.saturating_add(1),
1298            },
1299        );
1300    }
1301
1302    // Rule 3, applied last so it cannot be overwritten by the loop above
1303    // (an operator cannot delete object 0 — nothing hands out that id —
1304    // but the writer should not depend on that being true).
1305    let head = freed.first().map_or(old_next_free, |first| first.num);
1306    entries.insert(
1307        0,
1308        XrefEntry::Free {
1309            next_free: head,
1310            generation: 65_535,
1311        },
1312    );
1313    freed.len()
1314}
1315
1316/// Re-list every object a forwarded `/XRefStm` would otherwise shadow.
1317///
1318/// §7.5.8.4's search order is, per section, *classic table → that section's
1319/// `/XRefStm` → `/Prev`*. Form A copies `/XRefStm` into the new section, so the
1320/// stream is consulted before every older update section. An object the
1321/// stream lists that a later update changed (or freed) but this save does not
1322/// touch would resolve to the stream's stale entry: a second incremental save
1323/// of a hybrid file would silently undo the first. The forwarded key stays
1324/// (§7.5.6 requirement 3); this section additionally carries the base file's
1325/// current entry for each such object. No object bytes are written — the
1326/// entry points where the object already is.
1327///
1328/// A stream that does not parse re-lists nothing: the loader ignored it too,
1329/// so nothing in pdfcer's view of the base depends on it.
1330pub(super) fn relist_shadowed_by_xref_stm(
1331    entries: &mut BTreeMap<u32, XrefEntry>,
1332    doc: &Document,
1333    base: &[u8],
1334) {
1335    let SectionShape::Classic {
1336        xref_stm: Some(offset),
1337    } = doc.section_shape()
1338    else {
1339        return;
1340    };
1341    let Some(stream) = crate::xref::xref_stream_entries(base, offset) else {
1342        return;
1343    };
1344    for (num, stale) in stream {
1345        if entries.contains_key(&num) {
1346            continue;
1347        }
1348        if let Some(current) = doc.xref().get(num)
1349            && current != stale
1350        {
1351            entries.insert(num, current);
1352        }
1353    }
1354}
1355
1356/// How an object's definition reached the output — the distinction the
1357/// §5 invariant is measured on.
1358pub(super) enum Emission {
1359    /// Copied byte-for-byte from the retained source buffer.
1360    Verbatim,
1361    /// Rebuilt from the value tree because there were no file-level
1362    /// bytes to copy — which, for [`emit_object`], can only mean the
1363    /// object lived inside an object stream and has now been **promoted**
1364    /// out of it (R38). The variant is named for the consequence rather
1365    /// than the mechanism because the consequence is what gets reported.
1366    Promoted,
1367    /// Rebuilt from the value tree because the object's file-level bytes,
1368    /// though present, contradict its parsed value
1369    /// ([`Provenance::RecoveredFile`] — a stream whose extent recovery
1370    /// re-derived from `endstream`). Distinct from [`Emission::Promoted`]
1371    /// because nothing was promoted out of an object stream: the object
1372    /// was and remains file-level, so it must not appear in
1373    /// [`SaveReport::promoted`]. Counted as re-serialized.
1374    RecoveredReserialized,
1375}
1376
1377/// Replace `ID[1]` with a fresh changing identifier (§14.4).
1378///
1379/// Called **only** when the save writes at least one changed object —
1380/// that condition lives at the call sites, not here, so this function
1381/// cannot accidentally become "regenerate on every save".
1382///
1383/// Three no-op cases, each a deliberate refusal to invent document
1384/// identity (see [`super`]'s "`/ID` on save"):
1385///
1386/// - **no `/ID` in the base trailer** — nothing is synthesized;
1387/// - **`/ID` is an indirect reference** — legal in an unencrypted file,
1388///   but rewriting it would mean editing an object the operator did not
1389///   touch and adding it to the dirty set behind their back;
1390/// - **`/ID` is malformed** (not an array of exactly two strings) —
1391///   §14.4 states no recovery rule, so the operator's value is passed
1392///   through exactly as found.
1393///
1394/// `ID[0]` is always preserved: §14.4 says it *"shall not change when the
1395/// file is incrementally updated"*, and §7.6.3.3 Algorithm 2 step (e)
1396/// feeds it into the encryption key, so a change here would surface in
1397/// Pass 5 as a decryption failure that looks like a crypto bug.
1398pub(super) fn refresh_changing_identifier(trailer: &mut Dict, base_len: usize, appended: &[u8]) {
1399    let Some(Object::Array(items)) = trailer.get(b"ID") else {
1400        return;
1401    };
1402    let (Some(Object::String(permanent)), Some(Object::String(changing)), 2) =
1403        (items.first(), items.get(1), items.len())
1404    else {
1405        return;
1406    };
1407    let fresh = super::fileid::changing_identifier(changing, base_len, appended);
1408    let replacement = Object::Array(vec![
1409        Object::String(permanent.clone()),
1410        Object::String(fresh.to_vec()),
1411    ]);
1412    trailer.insert(Name::from(b"ID"), replacement);
1413}
1414
1415/// Emit one object definition, preferring its verbatim source bytes.
1416///
1417/// The `Provenance` enum makes this a total function with no sentinel:
1418/// `File` has bytes, `ObjectStream` does not, and there is no third
1419/// "might have bytes" state to guess about (see
1420/// `crate::object::Provenance`'s type docs).
1421pub(super) fn emit_object(
1422    out: &mut Vec<u8>,
1423    io: &IndirectObject,
1424    (source, values): (&[u8], &[u8]),
1425    encoder: &dyn ObjectEncoder,
1426) -> Result<Emission, WriteError> {
1427    match io.provenance {
1428        Provenance::File(span) => {
1429            let bytes = span
1430                .slice(source)
1431                .ok_or(WriteError::SpanOutOfRange { id: io.id, span })?;
1432            out.extend_from_slice(bytes);
1433            // §7.5.1 line discipline: terminate the `endobj` line so
1434            // the next definition starts cleanly. The span ends at the
1435            // last byte of `endobj`, by the Provenance::File contract.
1436            out.push(b'\n');
1437            Ok(Emission::Verbatim)
1438        }
1439        // The bytes exist but contradict the value (a recovered stream
1440        // extent), so copying them would emit a file whose `/Length`
1441        // under- or over-runs its own data — one pdfcer would then refuse
1442        // to reload. Re-serializing regenerates `/Length` from the actual
1443        // data (`serialize`'s "always recomputed, never trusted"), which
1444        // is the only way a recovered document's full rewrite can be a
1445        // valid PDF.
1446        Provenance::RecoveredFile(_) => {
1447            serialize::write_indirect(out, io.id, &io.value, values, encoder);
1448            Ok(Emission::RecoveredReserialized)
1449        }
1450        // R38: promote-to-uncompressed. Reached in Pass 3.0 only via
1451        // an explicit identity re-emission of a compressed object; a
1452        // full rewrite never takes this branch, because it carries
1453        // object streams through intact (module docs).
1454        Provenance::ObjectStream { .. } => {
1455            serialize::write_indirect(out, io.id, &io.value, values, encoder);
1456            Ok(Emission::Promoted)
1457        }
1458    }
1459}
1460
1461/// Re-serialize the document information dictionary with pdfcer's
1462/// `/Producer` (§14.3.3 Table 317), under [`ProducerPolicy::Set`].
1463///
1464/// This is the **only** object a full rewrite deliberately makes
1465/// non-verbatim, it happens only when the policy asks for it, and it is
1466/// counted in [`SaveReport::objects_reserialized`] so it can never be
1467/// mistaken for a passthrough. If the value is not a dictionary the
1468/// object is emitted verbatim instead — a `/Info` pointing at a
1469/// non-dictionary is a malformed file, and mangling it further is not
1470/// an improvement.
1471fn write_with_producer(out: &mut Vec<u8>, id: ObjId, value: &Object, source: &[u8]) {
1472    let Object::Dict(dict) = value else {
1473        // A `/Info` pointing at a non-dictionary is a malformed file,
1474        // and mangling it further is not an improvement — emit the
1475        // value unchanged.
1476        serialize::write_indirect(out, id, value, source, &IdentityEncoder);
1477        return;
1478    };
1479    let mut updated = dict.clone();
1480    updated.insert(
1481        Name::from(b"Producer"),
1482        Object::String(super::producer_string().into_bytes()),
1483    );
1484    serialize::write_indirect(out, id, &Object::Dict(updated), source, &IdentityEncoder);
1485}
1486
1487/// Copy a trailer dictionary, dropping `Prev`.
1488///
1489/// §7.5.6 requirement 3 in one function: *"The added trailer shall
1490/// contain all the entries **except** the `Prev` entry (if present)
1491/// from the previous trailer, whether modified or not."* Keys that
1492/// describe the *physical* shape of the previous cross-reference stream
1493/// (`/Type`, `/W`, `/Index`, `/Filter`, `/DecodeParms`, `/Length`) are
1494/// dropped too: when the base file's newest section was a stream, its
1495/// dictionary IS the trailer, and forwarding those keys would emit a
1496/// dictionary that contradicts the bytes beneath it.
1497/// [`xref_out::build_xref_stream`] also drops them, belt and braces.
1498pub(super) fn copy_trailer_without_prev(trailer: &Dict) -> Dict {
1499    let mut out = Dict::new();
1500    for (key, value) in trailer.iter() {
1501        if matches!(
1502            key.as_bytes(),
1503            b"Prev" | b"Type" | b"W" | b"Index" | b"Filter" | b"DecodeParms" | b"Length"
1504        ) {
1505            continue;
1506        }
1507        out.insert(key.clone(), value.clone());
1508    }
1509    out
1510}
1511
1512/// Raise `/Size` to cover `highest`, never lowering it.
1513///
1514/// Table 15: `/Size` is *"1 greater than the highest object number
1515/// defined in the file"*, across the **whole `/Prev` chain** — not a
1516/// count of this section's entries. It is also a hard reader-side
1517/// filter (§7.5.5: objects numbered at or above it *"shall be ignored
1518/// and defined to be missing"*), so under-reporting it silently deletes
1519/// objects from every reader's view. Never lowering it is what keeps a
1520/// small update section on a large file correct.
1521pub(super) fn bump_size(trailer: &mut Dict, highest: u32) {
1522    let needed = i64::from(highest) + 1;
1523    let current = trailer.get(b"Size").and_then(Object::as_int).unwrap_or(0);
1524    trailer.insert(Name::from(b"Size"), Object::Integer(current.max(needed)));
1525}
1526
1527/// Byte range of the header region to copy verbatim into a full rewrite:
1528/// from the `%PDF-M.N` marker through that line, plus the §7.5.2
1529/// binary-comment line if one follows.
1530///
1531/// §7.5.2: *"If a PDF file contains binary data, as most do, the header
1532/// line shall be immediately followed by a comment line containing at
1533/// least four binary characters — that is, characters whose codes are
1534/// 128 or greater."* Dropping that line would make a binary file look
1535/// like a text file to transfer tools that inspect it, which is exactly
1536/// what it exists to prevent.
1537///
1538/// # Bytes BEFORE the marker are deliberately DROPPED (changed 2026-08-07)
1539///
1540/// This used to return a length from byte 0, carrying any leading junk
1541/// through, on the reasoning that pdfcer's probe tolerates a preamble and
1542/// §5 says not to normalize what the operator did not ask about. That was
1543/// wrong, and the measurement that settled it is worth keeping:
1544///
1545/// **veraPDF cannot open ANY file that has a preamble and spec-literal
1546/// offsets** — not merely one whose producer wrote header-relative
1547/// offsets. A minimal 3-object file, offsets absolute from byte 0 exactly
1548/// as §7.5.4/§7.5.5 require, with 19 bytes of junk ahead of `%PDF-`:
1549/// *"can not locate xref table"*. The identical file with the junk removed
1550/// parses clean. So an independent, conformance-focused reader treats
1551/// offsets as **header-relative** whenever a preamble exists.
1552///
1553/// That makes preamble preservation a defect generator rather than a
1554/// courtesy. `iso32000__s__7.5.md` records the ambiguity as real and
1555/// **unresolved by ISO 32000-1** — the spec position is byte 0, but the
1556/// spec gives no guidance for readers that disagree, and a file pdfcer
1557/// writes has to be readable by the readers that exist.
1558///
1559/// Dropping the preamble makes the two interpretations **coincide**:
1560/// with the header at byte 0, absolute and header-relative are the same
1561/// number, and every reader agrees. It also stops re-emitting a §7.5.2
1562/// violation ("The first line of a PDF file shall be a header") that the
1563/// operator never asked pdfcer to preserve.
1564///
1565/// # Why only a FULL rewrite may do this
1566///
1567/// `save_full` promises per-object-definition byte identity, a reloadable
1568/// file and an identical raster — explicitly **not** whole-file identity,
1569/// because offsets legitimately move. Removing a preamble is inside that
1570/// contract. Incremental and identity-append saves promise byte identity
1571/// or byte-prefix behaviour and **must** carry the preamble through; they
1572/// do not call this function.
1573fn header_span(buf: &[u8]) -> core::ops::Range<usize> {
1574    let window = buf
1575        .get(..buf.len().min(crate::HEADER_SCAN_WINDOW))
1576        .unwrap_or(buf);
1577    let Some(marker) = window.windows(5).position(|w| w == b"%PDF-") else {
1578        return 0..0;
1579    };
1580    let mut pos = marker;
1581    // End of the header line.
1582    while !matches!(buf.get(pos), None | Some(b'\r' | b'\n')) {
1583        pos += 1;
1584    }
1585    pos = skip_eol(buf, pos);
1586    // An immediately-following comment line, if any (§7.5.2).
1587    if matches!(buf.get(pos), Some(b'%')) {
1588        while !matches!(buf.get(pos), None | Some(b'\r' | b'\n')) {
1589            pos += 1;
1590        }
1591        pos = skip_eol(buf, pos);
1592    }
1593    marker..pos
1594}
1595
1596/// Advance past one EOL marker (CR, LF, or CRLF — §7.2.2's rule that
1597/// CRLF is *one* marker, not two).
1598fn skip_eol(buf: &[u8], pos: usize) -> usize {
1599    match buf.get(pos) {
1600        Some(b'\r') => {
1601            if matches!(buf.get(pos + 1), Some(b'\n')) {
1602                pos + 2
1603            } else {
1604                pos + 1
1605            }
1606        }
1607        Some(b'\n') => pos + 1,
1608        _ => pos,
1609    }
1610}
1611
1612#[cfg(test)]
1613#[allow(
1614    clippy::unwrap_used,
1615    clippy::expect_used,
1616    clippy::panic,
1617    clippy::indexing_slicing
1618)]
1619mod tests {
1620    use super::*;
1621    use crate::writer::SaveOptions;
1622    use crate::writer::save_incremental;
1623
1624    /// A small, offset-consistent classic PDF.
1625    fn classic_pdf() -> Vec<u8> {
1626        let mut buf = b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n".to_vec();
1627        let bodies = [
1628            "<< /Type /Catalog /Pages 2 0 R >>",
1629            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
1630            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << >> >>",
1631            "<< /Producer (Somebody Else) /Title (Original) >>",
1632        ];
1633        let mut offsets = Vec::new();
1634        for (i, body) in bodies.iter().enumerate() {
1635            offsets.push(buf.len());
1636            buf.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
1637        }
1638        let xref_at = buf.len();
1639        buf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f \n");
1640        for off in &offsets {
1641            buf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
1642        }
1643        buf.extend_from_slice(
1644            format!(
1645                "trailer\n<< /Size 5 /Root 1 0 R /Info 4 0 R >>\nstartxref\n{xref_at}\n%%EOF\n"
1646            )
1647            .as_bytes(),
1648        );
1649        buf
1650    }
1651
1652    fn doc() -> Document {
1653        Document::from_bytes(classic_pdf()).unwrap()
1654    }
1655
1656    #[test]
1657    fn empty_dirty_set_incremental_save_is_byte_identical() {
1658        // THE headline contract of Pass 3.0. Zero edits, zero bytes.
1659        let bytes = classic_pdf();
1660        let d = Document::from_bytes(bytes.clone()).unwrap();
1661        let (out, report) =
1662            save_incremental(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1663        assert_eq!(out, bytes);
1664        assert!(report.byte_identical);
1665        assert_eq!(report.bytes_appended, 0);
1666        assert_eq!(report.objects_written, 0);
1667    }
1668
1669    #[test]
1670    fn incremental_save_never_rewrites_info_r41() {
1671        // R41 / decision 001 §6.1 obligation 6, at its enforcement
1672        // point. The /Info object's bytes must be findable, unchanged,
1673        // and must appear exactly once — no appended replacement.
1674        let bytes = classic_pdf();
1675        let d = Document::from_bytes(bytes.clone()).unwrap();
1676        let (out, _) = save_incremental(&d, &DirtySet::empty(), &SaveOptions::default()).unwrap();
1677        let needle = b"/Producer (Somebody Else)";
1678        assert_eq!(count_occurrences(&out, needle), 1);
1679        assert_eq!(count_occurrences(&out, b"pdfcer "), 0);
1680        // And with a real append that does not touch /Info.
1681        let (out, _) = save_incremental(
1682            &d,
1683            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1684            &SaveOptions::default(),
1685        )
1686        .unwrap();
1687        assert_eq!(count_occurrences(&out, needle), 1);
1688        assert_eq!(count_occurrences(&out, b"pdfcer "), 0);
1689    }
1690
1691    #[test]
1692    fn incremental_append_preserves_every_prior_byte() {
1693        // §7.5.6: "changes shall be appended to the end of the file,
1694        // leaving its original contents intact". This is also the
1695        // signature-safety claim (§12.8.1 NOTE 1) in one assertion.
1696        let bytes = classic_pdf();
1697        let d = Document::from_bytes(bytes.clone()).unwrap();
1698        let (out, report) = save_incremental(
1699            &d,
1700            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1701            &SaveOptions::identity(),
1702        )
1703        .unwrap();
1704        assert!(out.starts_with(&bytes));
1705        assert!(report.bytes_appended > 0);
1706        assert_eq!(report.objects_verbatim, 1);
1707        assert_eq!(report.objects_reserialized, 0);
1708        assert!(!report.byte_identical);
1709    }
1710
1711    #[test]
1712    fn appended_revision_reloads_to_an_equivalent_document() {
1713        let d = doc();
1714        let (out, _) = save_incremental(
1715            &d,
1716            &DirtySet::identity_reemission([ObjId::new(1, 0), ObjId::new(3, 0)]),
1717            &SaveOptions::identity(),
1718        )
1719        .unwrap();
1720        let back = Document::from_bytes(out).unwrap();
1721        assert_eq!(back.object_count(), d.object_count());
1722        for io in d.objects() {
1723            assert_eq!(
1724                back.get(io.id).map(|b| &b.value),
1725                Some(&io.value),
1726                "object {} differs after round trip",
1727                io.id
1728            );
1729        }
1730    }
1731
1732    #[test]
1733    fn appended_trailer_has_prev_and_exactly_one_of_it() {
1734        // §7.5.6 requirement 3's trap: copying the old Prev AND adding
1735        // a new one is a duplicate key, which §7.3.7 prohibits and
1736        // pdfcer's own parser rejects at parse time.
1737        let d = doc();
1738        let (out, _) = save_incremental(
1739            &d,
1740            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1741            &SaveOptions::identity(),
1742        )
1743        .unwrap();
1744        let back = Document::from_bytes(out.clone()).unwrap();
1745        // Prev must name the base file's own startxref, not its /Prev.
1746        assert_eq!(
1747            back.trailer().get(b"Prev").and_then(Object::as_int),
1748            Some(i64::try_from(d.base_startxref()).unwrap())
1749        );
1750        // Two revisions, two %%EOF markers (§7.5.6 requirement 4).
1751        assert_eq!(count_occurrences(&out, b"%%EOF"), 2);
1752    }
1753
1754    #[test]
1755    fn a_second_append_chains_prev_correctly() {
1756        // Chain shape after k updates: startxref -> Sk, Sk.Prev -> Sk-1.
1757        // Getting this wrong loses a whole revision silently.
1758        let d = doc();
1759        let (once, _) = save_incremental(
1760            &d,
1761            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1762            &SaveOptions::identity(),
1763        )
1764        .unwrap();
1765        let d2 = Document::from_bytes(once).unwrap();
1766        let (twice, _) = save_incremental(
1767            &d2,
1768            &DirtySet::identity_reemission([ObjId::new(1, 0)]),
1769            &SaveOptions::identity(),
1770        )
1771        .unwrap();
1772        assert_eq!(count_occurrences(&twice, b"%%EOF"), 3);
1773        let d3 = Document::from_bytes(twice).unwrap();
1774        assert_eq!(d3.object_count(), d.object_count());
1775        assert_eq!(
1776            d3.trailer().get(b"Prev").and_then(Object::as_int),
1777            Some(i64::try_from(d2.base_startxref()).unwrap())
1778        );
1779    }
1780
1781    #[test]
1782    fn update_section_carries_object_zero_and_only_dirty_objects() {
1783        // §7.5.6 requirement 1 ("only for") plus Annex H.7's own
1784        // object-0 convention. The update table must have exactly two
1785        // entries: object 0 and object 3.
1786        let d = doc();
1787        let (out, _) = save_incremental(
1788            &d,
1789            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1790            &SaveOptions::identity(),
1791        )
1792        .unwrap();
1793        let tail = &out[classic_pdf().len()..];
1794        let text = String::from_utf8_lossy(tail).into_owned();
1795        assert!(text.contains("xref\n0 1\n"), "{text}");
1796        assert!(text.contains("\n3 1\n"), "{text}");
1797        assert!(!text.contains("\n0 5\n"), "full table re-emitted: {text}");
1798    }
1799
1800    #[test]
1801    fn missing_final_eol_gets_one_before_the_append() {
1802        // §7.2.3: a comment runs to end of line, so an appended token
1803        // fused onto an unterminated %%EOF is swallowed entirely.
1804        let mut bytes = classic_pdf();
1805        while matches!(bytes.last(), Some(b'\n' | b'\r')) {
1806            bytes.pop();
1807        }
1808        let d = Document::from_bytes(bytes.clone()).unwrap();
1809        let (out, _) = save_incremental(
1810            &d,
1811            &DirtySet::identity_reemission([ObjId::new(3, 0)]),
1812            &SaveOptions::identity(),
1813        )
1814        .unwrap();
1815        assert!(out.starts_with(&bytes));
1816        assert_eq!(out[bytes.len()], b'\n');
1817        // And the result must actually load.
1818        assert!(Document::from_bytes(out).is_ok());
1819    }
1820
1821    #[test]
1822    fn full_rewrite_reemits_every_object_definition_verbatim() {
1823        // R32's per-OBJECT assertion — never per file.
1824        let d = doc();
1825        let (out, report) = save_full(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1826        assert!(!report.byte_identical);
1827        assert_eq!(report.objects_reserialized, 0);
1828        assert_eq!(report.objects_verbatim, 4);
1829        for io in d.objects() {
1830            let want = io.file_span().unwrap().slice(d.bytes()).unwrap();
1831            assert!(
1832                out.windows(want.len()).any(|w| w == want),
1833                "object {} definition bytes missing from the rewrite",
1834                io.id
1835            );
1836        }
1837    }
1838
1839    #[test]
1840    fn full_rewrite_reloads_to_an_equivalent_document() {
1841        let d = doc();
1842        let (out, _) = save_full(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1843        let back = Document::from_bytes(out).unwrap();
1844        assert_eq!(back.object_count(), d.object_count());
1845        for io in d.objects() {
1846            assert_eq!(back.get(io.id).map(|b| &b.value), Some(&io.value));
1847        }
1848        assert_eq!(back.version().to_string(), d.version().to_string());
1849    }
1850
1851    #[test]
1852    fn full_rewrite_preserves_the_binary_comment_line() {
1853        // §7.5.2: dropping it makes a binary file look textual to
1854        // transfer tools — the exact thing the line exists to prevent.
1855        let d = doc();
1856        let (out, _) = save_full(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1857        assert!(out.starts_with(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"));
1858    }
1859
1860    #[test]
1861    fn producer_policy_is_suppressible_and_effective() {
1862        // The R41 acceptance criterion, from the pdfcer-core side.
1863        let d = doc();
1864        let (preserved, rep) = save_full(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1865        assert_eq!(count_occurrences(&preserved, b"pdfcer "), 0);
1866        assert_eq!(count_occurrences(&preserved, b"Somebody Else"), 1);
1867        assert_eq!(rep.objects_reserialized, 0);
1868
1869        let (stamped, rep) = save_full(&d, &DirtySet::empty(), &SaveOptions::default()).unwrap();
1870        assert_eq!(count_occurrences(&stamped, b"Somebody Else"), 0);
1871        assert_eq!(rep.objects_reserialized, 1);
1872        let back = Document::from_bytes(stamped).unwrap();
1873        let info = back
1874            .resolve(back.trailer().get(b"Info").unwrap())
1875            .as_dict()
1876            .unwrap()
1877            .clone();
1878        let Object::String(p) = info.get(b"Producer").unwrap() else {
1879            panic!("producer is not a string");
1880        };
1881        assert_eq!(p, super::super::producer_string().as_bytes());
1882        // Other /Info keys survive.
1883        assert!(info.contains_key(b"Title"));
1884    }
1885
1886    #[test]
1887    fn producer_set_creates_nothing_when_info_is_absent() {
1888        // The deliberate narrowing recorded on ProducerPolicy::Set:
1889        // manufacturing an /Info on a file that had none is the
1890        // fingerprinting behavior R41 exists to prevent.
1891        let mut bytes = classic_pdf();
1892        let at = bytes
1893            .windows(11)
1894            .position(|w| w == b" /Info 4 0 R")
1895            .or_else(|| bytes.windows(12).position(|w| w == b" /Info 4 0 R"));
1896        if let Some(pos) = at {
1897            bytes.splice(pos..pos + 12, std::iter::repeat_n(b' ', 12));
1898        }
1899        let d = Document::from_bytes(bytes).unwrap();
1900        assert!(d.trailer().get(b"Info").is_none());
1901        let (out, rep) = save_full(&d, &DirtySet::empty(), &SaveOptions::default()).unwrap();
1902        assert_eq!(count_occurrences(&out, b"pdfcer "), 0);
1903        assert_eq!(rep.objects_reserialized, 0);
1904    }
1905
1906    #[test]
1907    fn full_rewrite_fills_object_number_holes_with_free_entries() {
1908        // §7.5.4: a single section must cover 0..max with no holes.
1909        let mut buf = b"%PDF-1.4\n".to_vec();
1910        let mut offsets = Vec::new();
1911        for (num, body) in [
1912            (1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
1913            (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
1914            // Deliberate hole at 3-4.
1915            (5, "<< /Note (sparse) >>"),
1916        ] {
1917            offsets.push((num, buf.len()));
1918            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
1919        }
1920        let xref_at = buf.len();
1921        buf.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n");
1922        for num in 1..=5u32 {
1923            match offsets.iter().find(|(n, _)| *n == num) {
1924                Some((_, off)) => {
1925                    buf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
1926                }
1927                None => buf.extend_from_slice(b"0000000000 65535 f \n"),
1928            }
1929        }
1930        buf.extend_from_slice(
1931            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
1932        );
1933        let d = Document::from_bytes(buf).unwrap();
1934        let (out, _) = save_full(&d, &DirtySet::empty(), &SaveOptions::identity()).unwrap();
1935        let back = Document::from_bytes(out.clone()).unwrap();
1936        assert_eq!(back.object_count(), 3);
1937        // One contiguous subsection covering 0..=5.
1938        let text = String::from_utf8_lossy(&out).into_owned();
1939        assert!(text.contains("xref\n0 6\n"), "{text}");
1940    }
1941
1942    #[test]
1943    fn size_never_shrinks_on_an_update() {
1944        // Table 15: /Size is a high-water mark across the whole chain,
1945        // not a count of this section's entries. Under-reporting it
1946        // silently deletes objects from every reader's view.
1947        let d = doc();
1948        let (out, _) = save_incremental(
1949            &d,
1950            &DirtySet::identity_reemission([ObjId::new(1, 0)]),
1951            &SaveOptions::identity(),
1952        )
1953        .unwrap();
1954        let back = Document::from_bytes(out).unwrap();
1955        assert_eq!(
1956            back.trailer().get(b"Size").and_then(Object::as_int),
1957            Some(5)
1958        );
1959    }
1960
1961    #[test]
1962    fn header_span_handles_all_three_shapes() {
1963        assert_eq!(header_span(b"%PDF-1.7\nrest"), 0..9);
1964        assert_eq!(header_span(b"%PDF-1.7\r\n%\x80\x81\x82\x83\r\nrest"), 0..17);
1965        // No header at all: copy nothing rather than guessing.
1966        assert_eq!(header_span(b"not a pdf"), 0..0);
1967        // A non-comment second line is not swallowed.
1968        assert_eq!(header_span(b"%PDF-1.4\n1 0 obj\n"), 0..9);
1969    }
1970
1971    /// The span STARTS at the marker, so a preamble is excluded.
1972    ///
1973    /// This is the unit-level statement of the 2026-08-07 change. Without
1974    /// it the only coverage would be the end-to-end rewrite test, and a
1975    /// regression that reintroduced `..end` would still satisfy every
1976    /// assertion above — all four of those cases have the marker at byte
1977    /// 0, where `0..end` and `..end` are indistinguishable.
1978    #[test]
1979    fn header_span_excludes_bytes_before_the_marker() {
1980        assert_eq!(header_span(b" %PDF-1.4\nrest"), 1..10);
1981        assert_eq!(header_span(b"JUNK\n%PDF-1.4\nrest"), 5..14);
1982        // With the binary-comment line, still measured from the marker.
1983        // 3-byte BOM, then `%PDF-1.7\n` (9) and `%\x80\x81\x82\x83\n` (6).
1984        assert_eq!(
1985            header_span(b"\xEF\xBB\xBF%PDF-1.7\n%\x80\x81\x82\x83\n"),
1986            3..18
1987        );
1988    }
1989
1990    #[test]
1991    fn unknown_dirty_object_is_a_named_refusal() {
1992        let d = doc();
1993        let err = save_incremental(
1994            &d,
1995            &DirtySet::identity_reemission([ObjId::new(99, 0)]),
1996            &SaveOptions::identity(),
1997        )
1998        .unwrap_err();
1999        assert!(matches!(err, WriteError::UnknownDirtyObject { .. }));
2000    }
2001
2002    fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
2003        if needle.is_empty() || haystack.len() < needle.len() {
2004            return 0;
2005        }
2006        haystack
2007            .windows(needle.len())
2008            .filter(|w| *w == needle)
2009            .count()
2010    }
2011}