pdfcer_model/writer/mod.rs
1//! # The writer — save paths for `ARCHITECTURE.md` §5
2//!
3//! Two save modes, two **different** correctness contracts, and a
4//! deliberate absence of any third thing.
5//!
6//! | Mode | Contract | Assertion shape |
7//! |---|---|---|
8//! | [`save_incremental`] with an empty dirty set | output is **byte-identical to the input**, whole file | `output == input` |
9//! | [`save_incremental`] with a dirty set | prior bytes untouched; only an update revision appended (§7.5.6) | `output.starts_with(input)` |
10//! | [`save_full`] | every `Provenance::File` object's **definition bytes** re-emitted verbatim; offsets, xref and trailer regenerated | **per object**, never per file |
11//!
12//! Decision 007 W1 names conflating the last two rows *"the single
13//! likeliest source of a false green or a false red in this Pass"*. A
14//! full rewrite **cannot** be byte-identical file-wide — object offsets
15//! move, so the cross-reference section must differ. A test that asserts
16//! file-level identity for [`save_full`] fails universally; a test that
17//! asserts only reloadability passes vacuously. Hence R32: two
18//! assertions, never one.
19//!
20//! ## Pass 3.0 scope: an *identity* writer, on purpose
21//!
22//! Pass 3.0 shipped **no editing capability of any kind** (decision 007
23//! `explicit_non_goals`). What it built is:
24//!
25//! - the serializer ([`serialize`]), complete for every `Object`
26//! variant;
27//! - both cross-reference forms ([`xref_out`]), selected by the input,
28//! never normalized (R33);
29//! - the encryption seam ([`encoder`]), identity implementation (R37);
30//! - the §7.5.6 append machinery, exercised through
31//! [`DirtySet::identity_reemission`] — a **verification** entry point
32//! that re-emits chosen objects *unchanged*, so the append path was
33//! corpus-proven before Pass 3.1 put real edits through it.
34//!
35//! ## Pass 3.1 scope: the mutation writer
36//!
37//! Pass 3.1 adds exactly one thing to the writer: a [`DirtySet`] may now
38//! carry **replacement values** and **trailer-entry patches** as well as
39//! bare re-emission requests. Three consequences, each of which was
40//! unreachable before and is now a live code path:
41//!
42//! 1. **`/ID[1]` regeneration becomes reachable** (§14.4, R39). It fires
43//! exactly when a save writes at least one *changed* object — see
44//! [`DirtySet::changes_content`] and [`fileid`]. An identity
45//! re-emission is not a change, so the Pass 3.0 corpus gate is
46//! unperturbed by construction.
47//! 2. **R38 promotion becomes reachable** (decision 007 W3). An edited
48//! object whose provenance is `ObjectStream` has no verbatim bytes to
49//! re-emit and cannot be patched in place, so it is *promoted* to an
50//! uncompressed file-level object; the old container is left
51//! untouched and the new type-1 cross-reference entry supersedes the
52//! type-2 one (§7.5.6 requirement: most recent copy wins; and for a
53//! hybrid file §7.5.8.4's search order puts the newest classic
54//! section ahead of `/XRefStm`). Every promotion is counted **and
55//! named** in [`SaveReport::promoted`] — it is a byte-level
56//! divergence the operator did not ask for, so it is disclosed.
57//! 3. **New objects can be appended.** A `DirtySet` replacement whose id
58//! is absent from the base document is a *created* object (Pass 3.1's
59//! only user is "the operator set metadata on a file that had no
60//! `/Info` dictionary"). Creating one is not a fingerprint — see
61//! [`ProducerPolicy`]'s contrast note.
62//!
63//! Still deliberately absent, each for a stated reason: object deletion
64//! and free-list writing (they need a real mutation to be tested
65//! against — decision 007 W9; Pass 3.2), generation increments,
66//! structural page operations, content-stream re-emission, cross-document
67//! object renumbering, linearization writing, optimization, object-stream
68//! authoring, and encryption.
69//!
70//! ## The three things a save must never do
71//!
72//! 1. **Never normalize** (R33, W4). Not the cross-reference form, not
73//! the header version, not number formatting, not object-stream
74//! membership. §7.5.6 does not *require* an appended section to
75//! match the base file's form — that is a recorded spec silence —
76//! which is precisely why pdfcer has to impose the rule itself.
77//! 2. **Never leave a fingerprint** (R41, decision 001 §6.1
78//! obligation 6). [`save_incremental`] does not rewrite `/Info`, and
79//! does not regenerate `/ID`, on a save that changed nothing. See
80//! [`ProducerPolicy`] for the full-rewrite rule and the reasoning.
81//! 3. **Never re-serialize a signature dictionary** (§12.8). A
82//! signature's `Contents` is a fixed-width placeholder covered by a
83//! `/ByteRange`; re-emitting it *even identically* is a byte-offset
84//! hazard. pdfcer's structural answer is that signed objects are, by
85//! construction, `Provenance::File` objects on the verbatim path —
86//! they are copied, never decomposed.
87//!
88//! ## `/ID` on save (§14.4, R39, W6)
89//!
90//! §14.4 says `ID[0]` *"shall not change when the file is incrementally
91//! updated"* and `ID[1]` is *"a changing identifier based on the file's
92//! contents at the time it was last updated."* Taken naively that
93//! conflicts head-on with byte-identical round-tripping.
94//!
95//! It does not actually conflict, and the reasoning is worth stating
96//! because it will be re-litigated: **if nothing changed, nothing was
97//! "updated"**, so §14.4's trigger never fired. `/ID` is
98//! `should`-strength for unencrypted files and **no `shall` anywhere
99//! requires regeneration** — §14.4 states what `ID[1]` *is*, not when a
100//! writer must recompute it. So pdfcer regenerates `ID[1]` exactly when
101//! a save writes at least one changed object, and never otherwise; and
102//! `ID[0]` changes only when pdfcer creates a document it regards as
103//! new, which no save mode in this Pass does. A gratuitously
104//! regenerated `/ID` is an observable "pdfcer touched this file" signal
105//! on a file pdfcer did not change — R41 territory.
106//!
107//! Pass 3.1 makes that rule executable. [`DirtySet::changes_content`] is
108//! the trigger; [`fileid::changing_identifier`] is the value; and three
109//! sub-rules are enforced, each recorded because each is a judgement
110//! call the spec does not make for us:
111//!
112//! - **A base file with no `/ID` gets none.** §14.4 is `should`-strength
113//! and the spec RAG's own analysis calls synthesizing one on an append
114//! *"a judgement call … recommend matching the base file (add
115//! nothing)"*. Adding `/ID` to a file that never had one changes the
116//! document's identity semantics on behalf of an operator who asked
117//! for a metadata edit. pdfcer adds nothing, in **both** save modes.
118//! (The RAG does recommend synthesizing on a full rewrite; pdfcer
119//! declines even there for now, because a full rewrite of an unchanged
120//! document must stay fingerprint-free under R41 and the two rules
121//! would then have to disagree by save mode. Revisit when a genuine
122//! from-scratch / "Save As new document" path exists — that is the
123//! context in which `ID[0]` legitimately changes too.)
124//! - **A malformed `/ID` is left exactly as found.** §14.4 states no
125//! recovery rule for a 1- or 3-element array or a non-string element.
126//! Rewriting one would be pdfcer inventing document identity; passing
127//! it through preserves the operator's file.
128//! - **`ID[0]` is never touched by either mode.** It is an input to
129//! §7.6.3.3 Algorithm 2 step (e), so an error here surfaces in Pass 5
130//! as a decryption failure that presents as a crypto bug.
131//!
132//! ## Redaction forbids incremental save (R35, W2)
133//!
134//! Recorded here because this module is where it will be enforced, and
135//! because it is trust-critical and was undocumented before Pass 3.0.
136//! Incremental save **structurally preserves superseded content**: the
137//! old bytes of every edited object remain in the file by construction
138//! (§7.5.6: *"changes shall be appended … leaving its original contents
139//! intact"*). A redaction saved incrementally therefore leaves the
140//! redacted content trivially recoverable — and incremental is the
141//! **default** save mode. Any operation whose contract is *removal*
142//! must force [`save_full`] and refuse [`save_incremental`]. See
143//! `ARCHITECTURE.md` §5.
144//!
145//! ## Signatures interact with both modes, in opposite directions (R36, W7)
146//!
147//! §12.8.1 NOTE 1: *"If a signed document is modified and saved by
148//! incremental update, the data corresponding to the byte range of the
149//! original signature is preserved."* A full rewrite destroys every
150//! signature. So signature presence forces incremental — which collides
151//! head-on with R35's redaction rule. "Redact a signed document" is a
152//! genuine either/or that must be surfaced to the operator, never
153//! resolved silently. It belongs to the Redaction and Signatures
154//! Passes; it is named here so neither Pass can claim surprise.
155
156pub mod content;
157pub mod encoder;
158pub mod fileid;
159mod incremental;
160mod rebuild;
161mod save;
162pub mod serialize;
163pub mod xref_out;
164
165use std::collections::BTreeMap;
166
167pub use encoder::{EncryptingEncoder, IdentityEncoder, ObjectEncoder};
168pub use incremental::save_incremental;
169pub use rebuild::{RebuildOptions, RebuildReport, rebuild, rebuild_declaring};
170pub use save::{EncryptParams, SaveReport, save_full, save_full_decrypted, save_full_encrypted};
171pub use xref_out::XrefOutError;
172
173use crate::object::{Dict, Name, ObjId, Object};
174
175/// The set of objects a save must write into the new revision.
176///
177/// ## The bug this type exists to make impossible
178///
179/// `ARCHITECTURE.md` §11.1 and decision 007: the dirty set is a **diff
180/// against the base revision, computed at save time** — never the union
181/// of every command run during the session. The difference is not
182/// academic. An object edited and then *undone* is in the union but not
183/// in the diff; including it appends a revision that silently re-states
184/// the object's original value, bloating every save after any undo and
185/// breaking the "objects pdfcer didn't logically touch are omitted"
186/// half of the §5 invariant. §7.5.6 requirement 1 is the spec-side
187/// reason: *"A cross-reference section for an incremental update shall
188/// contain entries **only for** objects that have been changed,
189/// replaced, or deleted."* Read the modality carefully — "only for" is
190/// a restriction, not merely permission to omit.
191///
192/// ## Two kinds of entry, and why both live in one type
193///
194/// - A **re-emission** ([`DirtySet::identity_reemission`]) asks the
195/// writer to write an object's *existing* value into the new
196/// revision. It is a verification device, not an edit.
197/// - A **replacement** ([`DirtySet::replace`]) carries a new value.
198/// This is what an actual operator edit produces, and it is the only
199/// entry kind that counts as "changed" for
200/// [`DirtySet::changes_content`] — the `/ID[1]` trigger (§14.4).
201///
202/// Plus a **trailer patch** ([`DirtySet::patch_trailer`]): entries the
203/// new revision's trailer must carry with a different value than the
204/// base trailer had. The trailer is part of a revision, not an object,
205/// so it cannot be expressed as an entry — but it *is* part of the same
206/// save-time diff, and threading a second parameter through every save
207/// signature would only hide that.
208///
209/// ## Building one
210///
211/// Nothing here computes the diff; `pdfcer_core::edit::EditSession` does,
212/// and it is the only thing that should. This type is the *result* of
213/// that computation and the writer's input. Constructing one by hand is
214/// legitimate for tests and for the verification modes, and is exactly
215/// how the "union of every command ever run" bug would be reintroduced
216/// if an edit path ever built one directly — so don't.
217#[derive(Debug, Clone, Default, PartialEq)]
218pub struct DirtySet {
219 entries: BTreeMap<ObjId, Change>,
220 trailer_patch: Dict,
221 /// Trailer keys the new revision must NOT carry; applied after
222 /// [`Self::trailer_patch`].
223 trailer_removals: Vec<Name>,
224 /// Authored stream bytes the session staged (R45, Pass 6.1). Empty
225 /// for every pre-6.1 edit, which keeps their save path byte-for-byte
226 /// unchanged (the combined-source construction below is skipped when
227 /// this is empty).
228 ///
229 /// ## The combined coordinate system (R45, X5)
230 ///
231 /// A `Change::Replace` value may be — for the first time as of
232 /// Pass 6.1 — a [`Stream`](crate::object::Stream) whose `data_span`
233 /// points not into the base file but into *this* buffer: an authored
234 /// appearance stream. To keep [`crate::object::Stream`]'s span model
235 /// (R45 forbids an owned-bytes `Stream` variant), authored spans are
236 /// expressed in a **single combined coordinate system** — an absolute
237 /// offset of `base.len() + local`, where `local` is the byte offset
238 /// within this staging buffer. At save time the writer serializes
239 /// replacement objects against `base ++ staging`, in which a base span
240 /// (`< base.len()`) resolves in the prefix and an authored span
241 /// resolves in the suffix. See [`DirtySet::combined_source`].
242 staging: Vec<u8>,
243}
244
245/// What the writer must do with one named object. Private: the public
246/// surface is [`DirtySet::replacement`] / [`DirtySet::contains`] /
247/// [`DirtySet::is_deleted`], which is exactly why adding the `Delete`
248/// variant in Pass 3.2 was not a breaking change — the note that
249/// predicted it is left above as evidence the encapsulation paid for
250/// itself.
251#[derive(Debug, Clone, PartialEq)]
252enum Change {
253 /// Write the object's existing value into the new revision.
254 Reemit,
255 /// Write this value instead of the object's existing one. Also used
256 /// for an object that does not exist in the base document at all.
257 Replace(Object),
258 /// **Delete** the object: emit no body at all, and give it a type-0
259 /// (free) cross-reference entry (§7.5.4) so every later reference to
260 /// it resolves to `null` (§7.3.10).
261 ///
262 /// Pass 3.2's addition, and the one that decision 007 W9 warns about:
263 /// *"A malformed type-0 free chain produces files Acrobat tolerates
264 /// and stricter readers reject — the worst failure shape, because
265 /// the obvious test passes."* See [`save`]'s free-list section for
266 /// the discipline this variant obliges.
267 Delete,
268}
269
270impl DirtySet {
271 /// The empty dirty set — "this document has no unsaved changes".
272 ///
273 /// With this, [`save_incremental`] produces a file **byte-identical
274 /// to the input**: zero edits means zero bytes, not "the input plus
275 /// an empty revision".
276 #[must_use]
277 pub fn empty() -> Self {
278 Self::default()
279 }
280
281 /// Build a dirty set that asks the writer to **re-emit the named
282 /// objects unchanged**.
283 ///
284 /// This is a **verification** constructor, not an editing API, and
285 /// the distinction is worth being precise about. It changes no
286 /// object's value; it drives the §7.5.6 append machinery — object
287 /// re-emission, update-section construction, `/Prev` chaining,
288 /// trailer copying, `startxref` placement — over real files so that
289 /// path is corpus-proven *before* genuine edits go through it. The
290 /// resulting file is semantically identical to the input by
291 /// construction, which gives the round-trip harness a strong oracle:
292 /// it must reload to the same object graph and re-render to the same
293 /// pixels.
294 ///
295 /// Without this, Pass 3.0's headline gate (an empty dirty set
296 /// producing a byte-identical file) would exercise a `memcpy` and
297 /// nothing else, and the append writer would have shipped untested.
298 ///
299 /// Because it changes nothing, a set built this way answers `false`
300 /// to [`DirtySet::changes_content`] and therefore does **not**
301 /// regenerate `/ID[1]`.
302 #[must_use]
303 pub fn identity_reemission(ids: impl IntoIterator<Item = ObjId>) -> Self {
304 Self {
305 entries: ids.into_iter().map(|id| (id, Change::Reemit)).collect(),
306 trailer_patch: Dict::new(),
307 trailer_removals: Vec::new(),
308 staging: Vec::new(),
309 }
310 }
311
312 /// Record that `id` must be written with `value` instead of whatever
313 /// it holds in the base revision.
314 ///
315 /// `id` need not exist in the base document: an id the base does not
316 /// define is a **created** object, which the writer appends and
317 /// gives a fresh cross-reference entry. That is how a metadata edit
318 /// on a file with no `/Info` dictionary reaches the file.
319 ///
320 /// Replacing supersedes a previously recorded re-emission for the
321 /// same id, and a second replacement supersedes the first — so N
322 /// edits to one object produce exactly **one** entry in the update
323 /// section, never N. That coalescing is structural (a map keyed by
324 /// id), not a special case.
325 pub fn replace(&mut self, id: ObjId, value: Object) {
326 self.entries.insert(id, Change::Replace(value));
327 }
328
329 /// Record that `id` must be **deleted**: no body in the new
330 /// revision, and a type-0 (free) cross-reference entry that makes
331 /// every reference to it resolve to `null` (§7.3.10, §7.5.4).
332 ///
333 /// ## Deleting is not redacting, and this method is not a shortcut
334 ///
335 /// A deletion recorded here is a *structural* removal — the object
336 /// leaves the document graph. Under [`save_incremental`] its
337 /// previous bytes remain in the file by construction (§7.5.6 appends,
338 /// it does not erase), and under [`save_full`] they are simply not
339 /// re-emitted. Neither is redaction, and `ARCHITECTURE.md` §5.7
340 /// records why full rewrite is not sufficient there either
341 /// (object-stream containers carry through verbatim in both modes).
342 /// Front ends must say so — pdfce-gui's delete tooltip does.
343 ///
344 /// ## Generation numbers are the writer's business, not the caller's
345 ///
346 /// §7.5.4 makes a free entry's generation *"the generation number to
347 /// be used if the object … is reused"*, i.e. one more than the
348 /// deleted object's. The caller supplies only the id it wants gone;
349 /// the increment (and its 65,535 saturation, which marks a number
350 /// permanently unreusable) happens in [`save`], once, where the
351 /// free-list chain is built. Letting callers pass a generation would
352 /// be an invitation to get that arithmetic wrong in three places.
353 ///
354 /// A delete supersedes any previously recorded change for the same
355 /// id, and vice versa — the map is keyed by id, so the last word
356 /// wins, which is what an editing session's save-time diff means.
357 pub fn delete(&mut self, id: ObjId) {
358 self.entries.insert(id, Change::Delete);
359 }
360
361 /// Whether `id` is recorded for deletion.
362 #[must_use]
363 pub fn is_deleted(&self, id: ObjId) -> bool {
364 matches!(self.entries.get(&id), Some(Change::Delete))
365 }
366
367 /// Every id recorded for deletion, ascending.
368 ///
369 /// Ascending because the free-list chain the writer builds from this
370 /// runs in increasing object-number order — not a `shall` (§7.5.4
371 /// only requires a well-formed linked list) but the form Annex H's
372 /// examples use, and the one that keeps output deterministic and
373 /// therefore byte-comparison-testable.
374 pub fn deletions(&self) -> impl Iterator<Item = ObjId> + '_ {
375 self.entries
376 .iter()
377 .filter(|(_, change)| matches!(change, Change::Delete))
378 .map(|(id, _)| *id)
379 }
380
381 /// Record that the new revision's trailer must carry `key` with
382 /// `value`.
383 ///
384 /// §7.5.6 requirement 3 makes an update trailer carry *"all the
385 /// entries except the `Prev` entry … from the previous trailer,
386 /// whether modified or not"*, so the writer starts from the base
387 /// trailer and applies this patch over it. Only genuinely changed
388 /// keys belong here — a patch that restates a base value is a
389 /// no-op that would still flip [`DirtySet::changes_content`], and
390 /// therefore would regenerate `/ID[1]` on a document nothing
391 /// changed in.
392 pub fn patch_trailer(&mut self, key: Name, value: Object) {
393 self.trailer_patch.insert(key, value);
394 }
395
396 /// Record that the new revision's trailer must not carry `key`, which
397 /// the base trailer has. Like [`Self::patch_trailer`], only for a key
398 /// the session genuinely removed; it counts as a content change.
399 pub fn remove_trailer_key(&mut self, key: Name) {
400 if !self.trailer_removals.contains(&key) {
401 self.trailer_removals.push(key);
402 }
403 }
404
405 /// The trailer keys [`Self::remove_trailer_key`] recorded.
406 #[must_use]
407 pub fn trailer_removals(&self) -> &[Name] {
408 &self.trailer_removals
409 }
410
411 /// Apply [`Self::trailer_patch`] then [`Self::trailer_removals`] to a
412 /// trailer copied from the base.
413 pub(super) fn apply_trailer_changes(&self, trailer: &mut Dict) {
414 for (key, value) in self.trailer_patch.iter() {
415 trailer.insert(key.clone(), value.clone());
416 }
417 trailer
418 .0
419 .retain(|(k, _)| !self.trailer_removals.contains(k));
420 }
421
422 /// Whether the set names nothing at all — the condition under which
423 /// [`save_incremental`] guarantees whole-file byte identity.
424 #[must_use]
425 pub fn is_empty(&self) -> bool {
426 self.entries.is_empty() && self.trailer_patch.is_empty() && self.trailer_removals.is_empty()
427 }
428
429 /// How many object definitions the next revision will carry.
430 ///
431 /// Deliberately excludes the trailer patch: the trailer is not an
432 /// object and does not get a cross-reference entry.
433 #[must_use]
434 pub fn len(&self) -> usize {
435 self.entries.len()
436 }
437
438 /// Whether this save writes at least one **changed** thing — the
439 /// §14.4 / R39 trigger for regenerating `/ID[1]`.
440 ///
441 /// A pure identity re-emission answers `false`: it writes objects,
442 /// but it changes none of them, so §14.4's *"at the time it was last
443 /// updated"* trigger never fired. Keeping these two questions
444 /// separate is what lets Pass 3.0's `append-identity` corpus mode
445 /// stay byte-stable while a real edit correctly refreshes `/ID[1]`.
446 #[must_use]
447 pub fn changes_content(&self) -> bool {
448 !self.trailer_patch.is_empty()
449 || !self.trailer_removals.is_empty()
450 || self
451 .entries
452 .values()
453 .any(|c| matches!(c, Change::Replace(_) | Change::Delete))
454 }
455
456 /// The replacement value recorded for `id`, or `None` if this id is
457 /// absent or is a bare re-emission.
458 #[must_use]
459 pub fn replacement(&self, id: ObjId) -> Option<&Object> {
460 match self.entries.get(&id) {
461 Some(Change::Replace(value)) => Some(value),
462 _ => None,
463 }
464 }
465
466 /// Whether `id` is named at all (as a replacement or a re-emission).
467 #[must_use]
468 pub fn contains(&self, id: ObjId) -> bool {
469 self.entries.contains_key(&id)
470 }
471
472 /// The trailer entries the new revision must carry with a value
473 /// different from the base trailer's.
474 #[must_use]
475 pub const fn trailer_patch(&self) -> &Dict {
476 &self.trailer_patch
477 }
478
479 /// Iterate the named objects in ascending `(num, generation)`
480 /// order.
481 ///
482 /// Ascending order is not cosmetic: it is what lets the
483 /// cross-reference emitters group entries into runs, which
484 /// §7.5.8.2 turns into a `shall` for cross-reference streams
485 /// (*"The array shall be sorted in ascending order by object
486 /// number"*).
487 pub fn iter(&self) -> impl Iterator<Item = ObjId> + '_ {
488 self.entries.keys().copied()
489 }
490
491 /// Attach the session's authored-stream staging buffer (R45).
492 ///
493 /// Called by `pdfcer_core::edit::EditSession::dirty_set` when the session
494 /// carries authored streams. The buffer's bytes are the raw
495 /// (still-filter-encoded, but Pass 6.1 authors raw appearances)
496 /// payloads that replacement `Stream` values' spans index into, in the
497 /// `base.len() + local` combined coordinate system documented on the
498 /// field.
499 pub fn set_staging(&mut self, staging: Vec<u8>) {
500 self.staging = staging;
501 }
502
503 /// The authored-stream staging buffer (empty for a pre-6.1 edit).
504 #[must_use]
505 pub fn staging(&self) -> &[u8] {
506 &self.staging
507 }
508
509 /// The serialization source a replacement object's stream spans index
510 /// into (R45): `base` alone when nothing was authored (zero-copy, the
511 /// unchanged pre-6.1 path), or `base ++ staging` when authored streams
512 /// are present.
513 ///
514 /// The combined buffer is sound because a base span (`< base.len()`)
515 /// resolves in the prefix — identical to `base` — while an authored
516 /// span (`>= base.len()`, i.e. `base.len() + local`) resolves in the
517 /// appended suffix. `base` **must** be the same buffer the session's
518 /// authored offsets were computed against, i.e. the document passed to
519 /// the save function; the writer guarantees this by passing
520 /// `doc.bytes()`.
521 #[must_use]
522 pub fn combined_source<'a>(&'a self, base: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
523 if self.staging.is_empty() {
524 std::borrow::Cow::Borrowed(base)
525 } else {
526 let mut combined = Vec::with_capacity(base.len() + self.staging.len());
527 combined.extend_from_slice(base);
528 combined.extend_from_slice(&self.staging);
529 std::borrow::Cow::Owned(combined)
530 }
531 }
532}
533
534/// What [`save_full`] does with `/Producer` (§14.3.3 Table 317).
535///
536/// ## Why this is a policy knob and not a constant
537///
538/// Decision 001 §6.1 obligation 6 — restated as decision 007's R41 at
539/// its actual enforcement point, which is this module — requires that
540/// pdfcer leave **no non-suppressible output fingerprint**. No build
541/// hash, no edition marker, no producer id the operator cannot turn
542/// off. This is the structural prevention of the specific behavior that
543/// disqualified `oxidize-pdf` as a foundation for pdfcer.
544///
545/// [`save_incremental`] has no such knob **by construction**: it never
546/// rewrites `/Info` at all, because doing so would mean appending a
547/// revision to a document the operator did not change.
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
549#[non_exhaustive]
550pub enum ProducerPolicy {
551 /// Emit `/Producer (pdfcer <version>)` into an existing document
552 /// information dictionary. The default for a full rewrite, which is
553 /// an operator-initiated act of authorship rather than a
554 /// passthrough.
555 ///
556 /// **Only rewrites an `/Info` that already exists.** If the base
557 /// document has no information dictionary, none is created. That is
558 /// a deliberate narrowing of "sets `/Producer`": manufacturing an
559 /// `/Info` object on a file that had none is exactly the
560 /// stamp-our-name-on-everything behavior R41 exists to prevent, in
561 /// miniature. The narrowing is recorded rather than silent.
562 ///
563 /// ## Contrast with an operator metadata edit (Pass 3.1)
564 ///
565 /// `pdfcer_core::edit::EditSession::set_info_field` **does** create an
566 /// `/Info` dictionary when the base file has none, and that is not
567 /// an inconsistency. R41 forbids pdfcer writing *its own* identity
568 /// into a file the operator did not ask it to mark. An operator who
569 /// types a document title has asked, explicitly, for exactly that
570 /// dictionary to exist and to say exactly that. The distinction the
571 /// rule actually draws is **who authored the value**, not whether
572 /// the object is new:
573 ///
574 /// | | writes `/Info` | creates `/Info` | why |
575 /// |---|---|---|---|
576 /// | `ProducerPolicy::Set` | yes | **no** | pdfcer authored it; creating a whole object to hold a producer id is a fingerprint |
577 /// | operator metadata edit | yes | **yes** | the operator authored it and asked for it by name |
578 /// | `save_incremental`, no edit | **no** | no | nothing changed, so nothing is written |
579 #[default]
580 Set,
581 /// Leave `/Info` byte-untouched. Required for any byte-comparison
582 /// harness, and available to operators who want a rewrite that is
583 /// as close to a passthrough as a rewrite can be.
584 Preserve,
585}
586
587/// The producer string [`ProducerPolicy::Set`] writes.
588///
589/// Deliberately just the crate name and version: **no build hash, no
590/// timestamp, no edition marker, no host identifier** (R41). Anything
591/// that varies between two builds of the same version would make
592/// pdfcer's output non-reproducible and would be a fingerprint.
593#[must_use]
594pub fn producer_string() -> String {
595 format!("pdfcer {}", env!("CARGO_PKG_VERSION"))
596}
597
598/// Whether an incremental save of an RC4-encrypted document keeps the
599/// document's RC4 handler. Set with
600/// [`Document::set_rc4_append`](crate::document::Document::set_rc4_append).
601///
602/// RC4 is deprecated in ISO 32000-2 (§7.6.2) and pdfcer never chooses it;
603/// this only decides whether an existing RC4 document can take an
604/// incremental edit. Decision 190.
605#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
606#[non_exhaustive]
607pub enum Rc4Append {
608 /// Refuse the save with [`WriteError::Rc4AppendRefused`]. The default.
609 #[default]
610 Refuse,
611 /// Append under the document's RC4 key. Existing signatures stay valid;
612 /// the save reports how many objects reused a keystream in
613 /// [`SaveReport::rc4_keystream_reused`].
614 Preserve,
615}
616
617/// Options controlling a save.
618#[derive(Debug, Clone, Default)]
619#[non_exhaustive]
620pub struct SaveOptions {
621 /// `/Producer` handling for [`save_full`]. Ignored by
622 /// [`save_incremental`], which never touches `/Info`.
623 pub producer: ProducerPolicy,
624 /// Which of §7.5.4's three permitted two-byte terminators ends a
625 /// classic cross-reference **entry** (spec ambiguity `EOL-A1`, R169).
626 ///
627 /// Default [`XrefEntryEol::SpaceLf`] — the form pdfcer has always
628 /// emitted. **Evidence tier (c), downgrade pending**: the spec RAG
629 /// calls `SP LF` *"the common choice"* but the register's §11.3 flags
630 /// that the claim carries no citation and should either gain one or
631 /// drop to tier (d).
632 ///
633 /// Applies to **newly written** cross-reference entries only, so an
634 /// incremental save changes nothing about the base revision's bytes.
635 pub xref_entry_eol: XrefEntryEol,
636 /// Whether an end-of-line byte follows the final `%%EOF` (spec
637 /// ambiguity `EOL-A2`, R169).
638 ///
639 /// Default [`TrailingEol::Lf`] — what pdfcer has always emitted.
640 /// **Evidence tier (d)**, a reasoned guess and the safe side of one:
641 /// §7.2.3 needs an EOL before a following `N G obj` on the append
642 /// path anyway, and a trailing EOL never breaks a backward `%%EOF`
643 /// scan.
644 pub trailing_eol: TrailingEol,
645 /// How an **edited** stream whose source was `/FlateDecode` is written.
646 ///
647 /// Default [`EditedStreamCompression::KeepSourceFilter`]: edit routes
648 /// stage decoded bytes, so without this a 1.6 MB compressed content
649 /// stream is saved as 14 MB of plain text.
650 pub edited_stream_compression: EditedStreamCompression,
651}
652
653/// How a save writes an edited stream whose base-revision value was
654/// compressed with `/FlateDecode` (§7.4.4) and whose edited value carries
655/// no filter.
656///
657/// Applies only to that case: untouched streams are copied as they were,
658/// an edited stream that still declares a filter is written as it is, and
659/// a stream with no base value (created by the session) is written as
660/// authored.
661#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
662pub enum EditedStreamCompression {
663 /// Re-apply `/FlateDecode` (no predictor), keeping the producer's
664 /// choice to compress. **The default.**
665 #[default]
666 KeepSourceFilter,
667 /// Write the edited bytes unfiltered — larger, but readable in a text
668 /// editor.
669 AsAuthored,
670}
671
672impl SaveOptions {
673 /// Options that leave every byte pdfcer did not have to change
674 /// exactly as it was — the settings the round-trip harness and the
675 /// per-object byte-identity gate run under.
676 ///
677 /// The two §7.5 end-of-line knobs stay at their **defaults** here
678 /// rather than tracking the operator's persisted choice, and that is
679 /// deliberate: `identity()` names a byte-comparison posture, and a
680 /// harness whose expected bytes depend on a settings file is a harness
681 /// that fails on one machine and passes on another. An operator-facing
682 /// save path applies the persisted values explicitly; this one does
683 /// not, and says so.
684 #[must_use]
685 pub fn identity() -> Self {
686 Self {
687 producer: ProducerPolicy::Preserve,
688 xref_entry_eol: XrefEntryEol::default(),
689 trailing_eol: TrailingEol::default(),
690 edited_stream_compression: EditedStreamCompression::default(),
691 }
692 }
693
694 /// Set how an edited, formerly Flate-compressed stream is written,
695 /// consuming and returning `self`.
696 #[must_use]
697 pub const fn with_edited_stream_compression(mut self, c: EditedStreamCompression) -> Self {
698 self.edited_stream_compression = c;
699 self
700 }
701
702 /// Set the classic cross-reference entry terminator (`EOL-A1`),
703 /// consuming and returning `self`.
704 ///
705 /// **BYTES blast radius.** Every value §7.5.4 permits is conforming,
706 /// so this changes bytes and nothing else; it exists so an operator
707 /// matching another tool's output byte-for-byte can.
708 #[must_use]
709 pub const fn with_xref_entry_eol(mut self, eol: XrefEntryEol) -> Self {
710 self.xref_entry_eol = eol;
711 self
712 }
713
714 /// Set whether a trailing end-of-line follows `%%EOF` (`EOL-A2`),
715 /// consuming and returning `self`.
716 #[must_use]
717 pub const fn with_trailing_eol(mut self, eol: TrailingEol) -> Self {
718 self.trailing_eol = eol;
719 self
720 }
721
722 /// Set the `/Producer` policy, consuming and returning `self`.
723 ///
724 /// A setter rather than a struct-literal field because
725 /// `SaveOptions` is `#[non_exhaustive]`: downstream crates
726 /// (`pdfcer`, `pdfce-gui`, the round-trip harness) cannot use a
727 /// struct expression at all, and adding an option in a later Pass
728 /// must not be a breaking change for them.
729 #[must_use]
730 pub const fn with_producer(mut self, producer: ProducerPolicy) -> Self {
731 self.producer = producer;
732 self
733 }
734}
735
736/// Why a save could not be completed.
737///
738/// Every variant is a **named, counted refusal** rather than a
739/// best-effort degradation — the R27 fail-clean posture applied to the
740/// write side. A writer that guesses produces a plausible, working,
741/// wrong file, which is the worst possible failure shape for this
742/// subsystem (decision 007 W4).
743#[derive(Debug, thiserror::Error)]
744#[non_exhaustive]
745pub enum WriteError {
746 /// File I/O failed.
747 #[error("I/O error writing PDF: {0}")]
748 Io(#[from] std::io::Error),
749 /// A cross-reference section could not be emitted.
750 #[error(transparent)]
751 Xref(#[from] XrefOutError),
752 /// An object's retained `ByteSpan` does not lie inside the
753 /// document's buffer — a provenance bug, and one that must never be
754 /// papered over by emitting a truncated object.
755 #[error("object {id}: retained byte span {span} lies outside the source buffer")]
756 SpanOutOfRange {
757 /// The object whose provenance is broken.
758 id: ObjId,
759 /// The span that could not be sliced.
760 span: crate::span::ByteSpan,
761 },
762 /// A save was requested on a session that has a **deferred redaction
763 /// pending** (`pdfcer_core::edit::EditSession::apply_redactions_deferred`,
764 /// `Pass 250.2`).
765 ///
766 /// A deferred redaction leaves the un-redacted content in the live
767 /// session so the operator's undo history is preserved; the removal is
768 /// carried out only by
769 /// `pdfcer_core::edit::EditSession::save_applying_redaction`, which runs the
770 /// surgery over the current state and emits clean bytes. Both ordinary
771 /// save modes are refused meanwhile: an **incremental** save would append
772 /// a delta over the un-redacted base and leak the content via `/Prev`
773 /// (`ARCHITECTURE.md` §5.2), and a **full** rewrite would emit the marks
774 /// with the content still present (an unapplied redaction — a footgun, not
775 /// a leak). Refusing by name, and pointing at the verb that is safe, is the
776 /// honest outcome.
777 #[error(
778 "a deferred redaction is pending; ordinary saves are refused to avoid \
779 leaking (incremental) or silently not applying it (full rewrite) — \
780 use EditSession::save_applying_redaction, or cancel_pending_redaction first"
781 )]
782 RedactionPending,
783 /// A full rewrite was requested for a **hybrid-reference** file
784 /// (§7.5.8.4) whose `/XRefStm` pdfcer could not parse (`Pass 281.0`).
785 ///
786 /// # NARROWED. This used to fire for EVERY hybrid file.
787 ///
788 /// The original reasoning is kept verbatim, because it is instructive about
789 /// how a refusal outlives its cause:
790 ///
791 /// > ~~"Rebuilding that unit from a merged view requires re-deriving which
792 /// > objects were hidden and re-checking §7.5.8.4's recursive visibility
793 /// > rule, which is Pass 3.2 work at the earliest. Normalizing the file to
794 /// > a single non-hybrid section instead would destroy its pre-1.5
795 /// > readability, which R33 forbids outright."~~
796 ///
797 /// Both halves were true and the conclusion did not follow. **The merged
798 /// view was the obstacle, and the merge is pdfcer's own**: the loader now
799 /// retains which objects the `/XRefStm` established
800 /// ([`crate::document::Document::hybrid_partition`]), which is the single
801 /// fact `merge_first_wins` destroyed. Nothing has to be re-derived — and
802 /// re-deriving would have been *wrong*, because §7.5.8.4's visibility rule
803 /// says what a producer **may** hide while a rewrite must reproduce what
804 /// this file **did** hide.
805 ///
806 /// Nor is the file normalized: `save_full` emits the same three-part unit —
807 /// main table with the hidden objects free at generation 65535, the stream,
808 /// and an update section naming it — so the pre-1.5 view survives and `R33`
809 /// is honoured rather than waived.
810 ///
811 /// # What it cost while it stood
812 ///
813 /// `R35` forces a redaction to a full rewrite — an incremental save leaves
814 /// the un-redacted bytes in a prior revision — so this refusal made
815 /// **redaction unreachable on every hybrid file**, and the remedy it named
816 /// ("use incremental save") was the one thing a redaction may not take.
817 /// Reported by `pdfcer-gui` on the operator's own SolidWorks drawing, which
818 /// he had asked about three times.
819 ///
820 /// # What still refuses
821 ///
822 /// A file whose trailer names an `/XRefStm` that does not parse. The file
823 /// says it hides objects; pdfcer cannot say which; either partition would
824 /// be a guess, and a wrong guess yields a file that opens with an outline
825 /// or a structure tree silently missing. A broken `/XRefStm` is
826 /// deliberately non-fatal to *loading* (§7.5.8.4 guarantees the visible
827 /// graph resolves without it) and is fatal to a *rewrite*.
828 #[error(
829 "full rewrite of a hybrid-reference file (§7.5.8.4) whose /XRefStm could not be parsed is not supported: the file hides objects and pdfcer cannot tell which, so either partition would be a guess -- use incremental save, which appends a conforming classic update section and carries the stream forward untouched"
830 )]
831 HybridFullRewrite,
832 /// A full rewrite was asked to build a cross-reference table up to an
833 /// object number beyond [`save::MAX_REWRITE_OBJECT_NUMBER`].
834 ///
835 /// §7.5.4 requires a single-section full rewrite to carry one entry
836 /// per object number from 0 to the highest defined in the file, so
837 /// the writer's cost is set by the largest object NUMBER rather than
838 /// by how many objects the file contains. A small file naming one
839 /// enormous number therefore asks for an enormous table: pdfium's
840 /// `bug_455199.pdf` is 1.2 KB, names `2147483648 0 obj`, and would
841 /// require 2,147,483,649 entries — measured at ~27 MB/s of steady
842 /// allocation with the CPU pinned, i.e. about an hour of apparent
843 /// progress before the allocator gives up.
844 ///
845 /// Refusing by name is the honest outcome, and the alternatives are
846 /// both worse: grinding is an unrecoverable freeze in the GUI, and
847 /// emitting a sparse table instead would break §7.5.4's completeness
848 /// requirement — trading a hang for a malformed file.
849 ///
850 /// **Reading such a file is unaffected**; this bounds the writer
851 /// only. `inspect` and `extract-text` both succeed on the file above.
852 #[error(
853 "object number {num} exceeds the largest a full rewrite will build a \
854 cross-reference table up to ({max}, ISO 32000-1 Annex C Table C.1 \
855 maximum indirect objects); §7.5.4 requires one entry per number from \
856 0, so this file would need a table of {} entries",
857 u64::from(*num) + 1
858 )]
859 ObjectNumberTooLarge {
860 /// The highest object number the document defines.
861 num: u32,
862 /// The bound that was exceeded.
863 max: u32,
864 },
865 /// The document's cross-reference table names an object the loader
866 /// did not parse — the table and the object map disagree.
867 #[error("cross-reference entry for object {num} has no corresponding parsed object")]
868 MissingObject {
869 /// The object number with no parsed definition.
870 num: u32,
871 },
872 /// An object named in the dirty set is not present in the document.
873 #[error("object {id} is named in the dirty set but is not present in the document")]
874 UnknownDirtyObject {
875 /// The object that could not be re-emitted.
876 id: ObjId,
877 },
878 /// [`save_incremental`] was requested for a document loaded via
879 /// **cross-reference recovery** (decision 013).
880 ///
881 /// A recovered document had a **broken** base cross-reference table, so
882 /// an incremental append is not merely undesirable but structurally
883 /// impossible: the appended section's `/Prev` would have to point at a
884 /// cross-reference section that does not correctly exist, and the
885 /// preserved base bytes are not a valid revision to build on. Its save
886 /// is therefore a mandatory **full rewrite** ([`save_full`], which
887 /// emits a fresh valid classic cross-reference); incremental is refused
888 /// by name here.
889 ///
890 /// This is the recovered-base-forces-full-rewrite standing rule
891 /// **R67** (decision 013 §9; librarian-assigned — "R59" was proposed
892 /// but R59/R60/R61 were already taken, so R67 is the assigned number).
893 /// It is a sibling of R35 (redaction forces full rewrite) and R58
894 /// (removal/scrub forces full rewrite): §5.6's "never normalize" does
895 /// not bind a recovered file, because its base was already invalid.
896 #[error(
897 "incremental save of a recovered document is refused; its base cross-reference \
898 was invalid, so its save must be a full rewrite (save_full)"
899 )]
900 RecoveredBaseForbidsIncremental,
901
902 /// A **full rewrite** was asked of a document loaded from an encrypted
903 /// file (§7.6).
904 ///
905 /// Load decrypts stream data in the retained buffer and strings in the
906 /// parsed objects, so a full rewrite's verbatim copies would emit a file
907 /// whose `/Encrypt` claims encryption its content no longer has — one no
908 /// reader can open. Save incrementally (which appends under the existing
909 /// handler), or re-encrypt / remove encryption, which re-serialise every
910 /// object.
911 #[error(
912 "this document was loaded from an encrypted file, and a full rewrite would copy \
913 decrypted bytes under its encryption dictionary; save incrementally instead, or \
914 change or remove the encryption"
915 )]
916 EncryptedSaveUnsupported,
917
918 /// An incremental save of an **RC4**-encrypted document under the
919 /// default [`Rc4Append::Refuse`]. The routes: opt in with
920 /// [`Document::set_rc4_append`](crate::document::Document::set_rc4_append)
921 /// (the CLI's `--allow-rc4-append`), re-encrypt with AES-256, or remove
922 /// the encryption. Decision 190.
923 #[error(
924 "this document is encrypted with RC4, which pdfcer does not write by default; \
925 pass --allow-rc4-append to keep its RC4 encryption (weak; existing signatures stay \
926 valid), or re-encrypt it with AES-256 or remove its encryption before saving an edit"
927 )]
928 Rc4AppendRefused,
929
930 /// The operating system's random-number source was unreachable, so no
931 /// fresh AES initialisation vector (§7.6.2) could be made. Nothing was
932 /// written.
933 #[error("no secure random source is available to encrypt the saved objects")]
934 EntropyUnavailable,
935
936 /// pdfcer could not reload a full rewrite it had just produced, so a
937 /// step that needs the rewrite as a document (an optimize rebuild)
938 /// stopped. A writer bug; nothing was written.
939 #[error("pdfcer could not reload its own full rewrite: {0}")]
940 RewriteReload(#[source] Box<crate::document::DocError>),
941 /// Linearizing (Annex F) needs a catalog with at least one page, and
942 /// the document has neither. Nothing was written.
943 #[error("cannot linearize: the document has no catalog or no page")]
944 NothingToLinearize,
945}
946
947#[cfg(test)]
948#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
949mod tests {
950 use super::*;
951
952 #[test]
953 fn empty_dirty_set_is_the_default() {
954 assert!(DirtySet::default().is_empty());
955 assert!(DirtySet::empty().is_empty());
956 assert_eq!(DirtySet::empty().len(), 0);
957 }
958
959 #[test]
960 fn dirty_set_iterates_in_ascending_order() {
961 // §7.5.8.2 makes ascending order a `shall` for xref-stream
962 // /Index; sourcing it from a BTreeSet makes it structural.
963 let d =
964 DirtySet::identity_reemission([ObjId::new(9, 0), ObjId::new(2, 1), ObjId::new(2, 0)]);
965 let got: Vec<ObjId> = d.iter().collect();
966 assert_eq!(
967 got,
968 vec![ObjId::new(2, 0), ObjId::new(2, 1), ObjId::new(9, 0)]
969 );
970 assert_eq!(d.len(), 3);
971 }
972
973 #[test]
974 fn producer_string_carries_no_build_fingerprint() {
975 // R41: no hash, no timestamp, no host. Two builds of the same
976 // version must produce identical bytes.
977 let p = producer_string();
978 assert!(p.starts_with("pdfcer "));
979 assert!(!p.contains('+'), "build metadata leaked: {p}");
980 assert!(
981 p.chars().all(|c| c.is_ascii_graphic() || c == ' '),
982 "non-ASCII in producer string: {p}"
983 );
984 }
985
986 #[test]
987 fn identity_options_preserve_the_information_dictionary() {
988 assert_eq!(SaveOptions::identity().producer, ProducerPolicy::Preserve);
989 assert_eq!(SaveOptions::default().producer, ProducerPolicy::Set);
990 }
991}
992
993/// Which of §7.5.4's three permitted two-byte terminators ends a classic
994/// cross-reference **entry** (spec ambiguity `EOL-A1`).
995///
996/// # The choice being made
997///
998/// §7.5.4 fixes the entry at exactly 20 bytes and permits three, and only
999/// three, forms for bytes 18–19. `LF CR`, a bare `LF`, a bare `CR`,
1000/// `SP SP` and `SP CR LF` are **not** legal and are deliberately not
1001/// offered here — a settings file is not a licence to emit a
1002/// non-conforming file.
1003///
1004/// # Default: [`Self::MatchSource`] — the register's own recommendation
1005///
1006/// **Changed on the operator's ruling of 2026-08-08** ("change the shipped
1007/// default so that we match the file's existing 2-byte EOL"), replacing a
1008/// fixed `SP LF`.
1009///
1010/// `iso32000__ref__ambiguity_settings_register.md` §5.11 recommended
1011/// exactly this and pdfcer shipped the fixed form anyway, because
1012/// implementing "match the source" needed an observation of the base
1013/// file's bytes that no channel carried. The register said plainly that
1014/// the shipped default was *"arguably wrong on pdfcer's own invariant"*,
1015/// and it was right: **rule 3 says objects pdfcer did not logically touch
1016/// are re-emitted byte-identical, and a full rewrite of a `CR LF` file
1017/// under a fixed `SP LF` changes two bytes in every entry of the table.**
1018/// On a 5,000-object file that is a 10,000-byte diff in a document nobody
1019/// edited — the exact diff minimal-diff editing exists to prevent.
1020///
1021/// The channel now exists: [`crate::xref::observed_entry_eol`] reads the
1022/// form back out of the base file, and the writer resolves
1023/// [`Self::MatchSource`] against it. This is the same idea
1024/// `Document::section_shape` already served at a coarser grain — *the base
1025/// file's own form* (R33) — one level finer.
1026///
1027/// **Evidence tier is no longer (d)-shaped at all**, which is the quiet
1028/// win here. The old default rested on the RAG's uncited claim that
1029/// `SP LF` is *"the common choice"* — flagged in the register's §11.3 as
1030/// carrying no source and pending a downgrade. The new default rests on
1031/// nothing external: it derives the answer from the file in front of it,
1032/// so there is no guess left to grade. The uncited claim now governs only
1033/// the fallback, where there is genuinely nothing to match.
1034///
1035/// **BYTES blast radius, zero render effect.** Every value is conforming,
1036/// so no operator disclosure is needed when one is chosen.
1037#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1038pub enum XrefEntryEol {
1039 /// Write whichever of the three forms the file being saved already
1040 /// used, falling back to `SP LF` when there is nothing to match.
1041 ///
1042 /// **The shipped default.** "Nothing to match" means a
1043 /// cross-reference *stream* file (§7.5.8 is binary and has no entry
1044 /// EOL), a file whose table is non-conforming at that position, or a
1045 /// document pdfcer assembled from nothing — see
1046 /// [`crate::xref::observed_entry_eol`].
1047 #[default]
1048 MatchSource,
1049 /// Always `SP LF` (`20 0A`), whatever the source used.
1050 SpaceLf,
1051 /// Always `SP CR` (`20 0D`).
1052 SpaceCr,
1053 /// Always `CR LF` (`0D 0A`).
1054 CrLf,
1055}
1056
1057impl XrefEntryEol {
1058 /// The concrete two bytes to emit, resolving [`Self::MatchSource`]
1059 /// against the file being saved.
1060 ///
1061 /// `base` is the bytes of the document this save is derived from —
1062 /// empty for a document assembled from nothing. Kept as a method on
1063 /// the setting rather than a branch in the writer so that every
1064 /// caller resolves it the same way; a second resolution site is how
1065 /// an incremental save and a full rewrite would come to disagree
1066 /// about the same file.
1067 #[must_use]
1068 pub fn resolve(self, base: &[u8]) -> Self {
1069 match self {
1070 Self::MatchSource => crate::xref::observed_entry_eol(base).unwrap_or(Self::SpaceLf),
1071 other => other,
1072 }
1073 }
1074
1075 /// The two bytes themselves. [`Self::MatchSource`] resolves to the
1076 /// fallback here, so callers that have a base file must call
1077 /// [`Self::resolve`] first.
1078 #[must_use]
1079 pub const fn bytes(self) -> [u8; 2] {
1080 match self {
1081 Self::SpaceLf | Self::MatchSource => *b" \n",
1082 Self::SpaceCr => *b" \r",
1083 Self::CrLf => *b"\r\n",
1084 }
1085 }
1086}
1087
1088/// Whether the writer puts an end-of-line byte after the final `%%EOF`
1089/// (spec ambiguity `EOL-A2`).
1090///
1091/// # The disagreement being resolved
1092///
1093/// §7.5.1 requires every line to be EOL-terminated; §7.5.5 says the last
1094/// line *"contains only"* `%%EOF`. **Both readings are self-consistent and
1095/// the standard does not choose between them.**
1096///
1097/// # Default: [`Self::Lf`] — **EVIDENCE TIER (d)**
1098///
1099/// Tier (d) — **a guess**, and the safe side of one: §7.2.3 requires the
1100/// incremental-append path to have an EOL before a following `12 0 obj`
1101/// anyway, and a trailing EOL never breaks a reader's backward `%%EOF`
1102/// scan. Low value as a knob; it exists because the choice is currently
1103/// hard-coded, is labelled in the source as a recorded spec ambiguity, and
1104/// an engineer who finds that label will ask where the switch is.
1105///
1106/// **BYTES blast radius — one byte.** No disclosure needed.
1107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1108pub enum TrailingEol {
1109 /// Terminate the `%%EOF` line with `LF`. **The shipped default.**
1110 #[default]
1111 Lf,
1112 /// End the file at the final `F` of `%%EOF`.
1113 None,
1114}