pdfcer_model/xref.rs
1//! # Cross-reference machinery (ISO 32000-1 §7.5.4–§7.5.8)
2//!
3//! Locates and parses every kind of cross-reference section a PDF can
4//! have — classic `xref` tables (§7.5.4), PDF 1.5 cross-reference
5//! **streams** (§7.5.8), and the hybrid-reference combination of both
6//! (§7.5.8.4) — producing the merged object-number → entry map the
7//! document layer resolves through, plus the document's trailer.
8//!
9//! Spec sources in the PDF-spec RAG: `iso32000__s__7.5.4.md` (the
10//! 20-byte entry format, subsections, free-list), `iso32000__s__7.5.5.md`
11//! (trailer, `startxref`, `%%EOF`, the nine-step load algorithm),
12//! `iso32000__s__7.5.6.md` (incremental updates / most-recent-copy
13//! rule), `iso32000__s__7.5.8.md` (Tables 17/18/19 — xref-stream
14//! dictionary, entry types, `XRefStm`), `iso32000__s__7.5.7.md` (object
15//! streams, the targets of type-2 entries). Clause numbers are
16//! ISO 32000-1:2008.
17//!
18//! ## The chain walk (§7.5.5's load algorithm, steps 1–9)
19//!
20//! 1. Scan **backward** from EOF for the last `startxref` keyword
21//! (§7.5.5: readers "should read a PDF file from its end"; the
22//! marker may be followed by trailing bytes — the scan window
23//! [`STARTXREF_SCAN_WINDOW`] is pdfcer policy, not spec).
24//! 2. Seek to the offset and classify what is there by its first token:
25//! the `xref` keyword → a classic section (§7.5.4); an integer (the
26//! `N` of an `N G obj` header) → a cross-reference **stream**
27//! (§7.5.8.1 amends `startxref` to point at the stream object
28//! itself). Anything else is malformed.
29//! 3. Parse the section. Its "trailer" is either the literal `trailer`
30//! dictionary (classic) or the xref stream's own dictionary
31//! (§7.5.8.1: the stream dictionary "carries what a trailer would
32//! carry"). **Both forms may appear at different links of the same
33//! chain** — a file may be updated from classic to stream form or
34//! vice versa, and each link is classified independently.
35//! 4. Merge entries **first-wins**: the newest section is parsed first,
36//! and §7.5.6's most-recent-copy rule is exactly "an entry already
37//! established by a newer section is never overwritten."
38//! 5. If the section's trailer carries `/XRefStm` this is a
39//! **hybrid-reference file** (§7.5.8.4): parse the cross-reference
40//! stream at that offset and merge it **before** following `/Prev` —
41//! see the dedicated section below.
42//! 6. Follow `/Prev` (which despite Table 15's wording MUST be direct —
43//! a flagged ISO 32000-1 defect, see the RAG) and repeat, with a
44//! cycle guard ([`MAX_XREF_SECTIONS`], pdfcer policy).
45//! 7. The **newest** trailer is the document's trailer (its `/Root`,
46//! `/Size`, …).
47//!
48//! `/Size` is then a hard filter (Table 15): entries with object
49//! number ≥ `Size` are "ignored and defined to be missing."
50//!
51//! ## Cross-reference streams (§7.5.8) — what makes bootstrap possible
52//!
53//! An xref stream is an ordinary indirect stream object whose data,
54//! once run through its `/Filter` chain, is a packed array of
55//! fixed-width big-endian rows. Decoding it therefore needs `/Filter`,
56//! `/DecodeParms` and `/W` **before any cross-reference exists** —
57//! which is exactly why §7.5.8.2 requires every Table 17 entry, every
58//! element of the `Index`/`W` arrays, and `Filter`/`DecodeParms` to be
59//! **direct** objects. pdfcer relies on that: the stream is parsed with
60//! a null `/Length` resolver, so an (illegal, unbootstrappable)
61//! indirect `/Length` surfaces as a clean
62//! [`XrefErrorKind::BadXrefStream`] rather than a wrong parse.
63//!
64//! Row decoding follows Table 18 exactly:
65//!
66//! | field 1 (type) | field 2 | field 3 |
67//! |---|---|---|
68//! | 0 — free | next free object number | generation for reuse |
69//! | 1 — in use, uncompressed | byte offset in file | generation (default 0) |
70//! | 2 — **compressed** | object stream's object number | index within it |
71//!
72//! `/W` gives each field's byte width; **a width of 0 means the field
73//! is absent and its Table 18 default applies** — and if `W[0]` is 0
74//! the type itself defaults to 1. Multi-byte fields are big-endian
75//! ("high-order byte first"). Any type value other than 0/1/2 "shall be
76//! interpreted as a reference to the null object" — pdfcer records those
77//! rows as free entries, which is precisely that semantics (§7.5.4
78//! free ⇒ §7.3.10 null) while still letting the row shadow an older
79//! section's entry, as a newest-wins entry must.
80//!
81//! ## Hybrid-reference files (§7.5.8.4) — the search-order rule
82//!
83//! A hybrid file has a classic table (so a pre-1.5 reader can open it)
84//! *plus* an xref stream, named by the trailer's `/XRefStm`, that
85//! defines additional objects the classic table deliberately marks
86//! **free**. The operative reader rule is:
87//!
88//! > if an entry is not found in any given standard cross-reference
89//! > section, the search shall proceed to a cross-reference stream
90//! > specified by the `XRefStm` entry **before** looking in the
91//! > previous cross-reference section (the `Prev` entry).
92//!
93//! Implemented as a merge, that is: for each link of the chain, merge
94//! `classic entries`, then `XRefStm entries`, then move to `/Prev`.
95//! First-wins insertion then reproduces the search order exactly — the
96//! `XRefStm` stream cannot override its own section's classic table,
97//! but it does override everything older, which is what makes hidden
98//! objects visible to a 1.5+ reader and invisible (free ⇒ null) to a
99//! 1.4 reader.
100//!
101//! Two deliberate refinements, both spec-sourced:
102//!
103//! - The `XRefStm` stream's own `/Prev` is **not** followed. Table 17
104//! states `Prev` is "not meaningful in hybrid-reference files"; chain
105//! continuation belongs to the *trailer's* `/Prev`, and the
106//! `XRefStm` target is a leaf lookup, not a chain link.
107//! - A **broken `XRefStm` is not fatal.** §7.5.8.4 guarantees that
108//! everything reachable from the root is visible in the classic
109//! tables (the catalog, page tree, fonts and anything required "shall
110//! not be hidden"), so ignoring an unparseable `XRefStm` degrades
111//! exactly to what a conforming pre-1.5 reader sees — a documented,
112//! safe fallback rather than a guess. A broken *primary* section is
113//! still fatal.
114//!
115//! ## Encryption is detected here and handled one layer up (§7.6)
116//!
117//! If the newest trailer has `/Encrypt`, strings and stream data in the
118//! file are encrypted and every downstream layer would silently decode
119//! garbage.
120//!
121//! **This module used to refuse such a document outright.** It no longer
122//! does: [`crate::crypto`] implements the `/Standard` handler for RC4, so
123//! the decision is no longer "encrypted or not" but "which configuration,
124//! and does a password open it" — and neither question can be answered
125//! from the cross-reference layer, which has no objects yet and so cannot
126//! resolve an indirect `/O`, `/U` or `/CF`.
127//!
128//! So this layer *detects* and reports; [`crate::document::Document`]
129//! decides. [`XrefErrorKind::EncryptionUnsupported`] survives for the one
130//! case that genuinely belongs here — a document whose cross-reference
131//! machinery is broken **and** which is encrypted, where rebuild-by-scan
132//! would have to parse ciphertext to find objects (see
133//! [`crate::recover`]).
134//!
135//! ## Entry format enforced strictly (§7.5.4)
136//!
137//! Classic entries are exactly 20 bytes: 10-digit offset, SP, 5-digit
138//! generation, SP, `n`/`f`, and a 2-byte EOL that is one of `SP CR`,
139//! `SP LF`, `CR LF`. Real-world 19/21-byte deviants exist; pdfcer
140//! refuses them (fail-clean) — tolerance is a later, corpus-evidenced
141//! addition recorded in `C:\personal_rag\pdf\` first.
142
143use std::collections::{BTreeSet, HashMap};
144
145use crate::filters::{self, FilterError};
146use crate::object::{Dict, ObjId, Object};
147use crate::parser::{ParseError, Parser};
148use crate::span::ByteSpan;
149
150/// How many trailing bytes are scanned backward for the last
151/// `startxref` keyword.
152///
153/// pdfcer policy, not spec: §7.5.5 places `startxref` on the
154/// third-to-last line but says nothing about trailing bytes after
155/// `%%EOF`, and real files accumulate them. 4 KiB is far beyond any
156/// legitimate trailer tail while keeping the scan O(1) in file size.
157pub const STARTXREF_SCAN_WINDOW: usize = 4096;
158
159/// Maximum number of cross-reference sections followed through `/Prev`
160/// before the chain is declared cyclic/hostile.
161///
162/// pdfcer policy (ARCHITECTURE.md §10): each legitimate section is one
163/// incremental update; a document with thousands is implausible, and an
164/// unguarded `Prev` cycle is an infinite loop.
165pub const MAX_XREF_SECTIONS: usize = 1024;
166
167/// Maximum total xref entries accepted across all sections.
168///
169/// pdfcer policy (ARCHITECTURE.md §10.1): bounds allocation against a
170/// hostile subsection header claiming billions of entries. 10 million
171/// objects is far beyond any legitimate document.
172pub const MAX_XREF_ENTRIES: usize = 10_000_000;
173
174/// Maximum byte width accepted for a single `/W` field of a
175/// cross-reference stream (§7.5.8.2).
176///
177/// pdfcer policy: the spec puts no ceiling on `W`'s elements, but a
178/// field wider than 8 bytes cannot be represented in the `u64` the
179/// decoder reads into, and no legitimate producer emits one (real files
180/// use 1–4). A wider field is malformed, not merely large.
181pub const MAX_W_FIELD_WIDTH: usize = 8;
182
183/// Maximum total row width (the sum of `/W`) accepted for a
184/// cross-reference stream.
185///
186/// pdfcer policy: bounds the per-row read for a hostile `W` array such
187/// as `[8 8 8 8 8 …]`. PDF 1.5's `W` "always contains three integers"
188/// and 32 bytes is four maximal fields — far past anything real.
189pub const MAX_XREF_STREAM_ROW: usize = 32;
190
191/// One cross-reference entry: §7.5.4's classic `n`/`f` types plus
192/// §7.5.8.3 Table 18's type-2 compressed-object entry.
193///
194/// `#[non_exhaustive]`: §7.5.8.3 explicitly reserves further entry
195/// types ("any other value shall be interpreted as a reference to the
196/// null object, thus permitting new entry types to be defined in the
197/// future"), so downstream matches must stay open.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199#[non_exhaustive]
200pub enum XrefEntry {
201 /// Classic type `n` / stream type **1**: the object lives at
202 /// `offset` (from the beginning of the file) with generation
203 /// `generation`.
204 InUse {
205 /// Byte offset of the object's `N G obj` header.
206 offset: u64,
207 /// Generation that a reference must match to resolve.
208 generation: u16,
209 },
210 /// Classic type `f` / stream type **0**: the object number is free.
211 /// Kept (not dropped!) — free-with-generation-65535 entries are how
212 /// hybrid files hide objects, and a free entry shadows an older
213 /// in-use entry during the first-wins merge (deletion via
214 /// incremental update).
215 Free {
216 /// Object number of the next free object (the linked list).
217 next_free: u32,
218 /// Generation to assign when this number is next reused.
219 generation: u16,
220 },
221 /// Stream type **2** (§7.5.8.3 Table 18): the object is
222 /// **compressed** inside an object stream (§7.5.7).
223 ///
224 /// Note what this variant deliberately does *not* carry: a
225 /// generation. A type-2 entry has no generation field at all — its
226 /// field 3 is the index within the container — because §7.3.10/
227 /// §7.5.7 fix the generation of every compressed object, and of the
228 /// container itself, at **0**. Storing a generation here would
229 /// invent information the file does not contain.
230 InStream {
231 /// Object number of the object stream holding this object. Its
232 /// generation is implicitly 0.
233 stream_num: u32,
234 /// 0-based index of this object within that object stream's
235 /// pair table.
236 index: u32,
237 },
238}
239
240/// The merged cross-reference map for a document: object number →
241/// newest entry, plus the newest trailer.
242#[derive(Debug, Clone, Default)]
243pub struct XrefTable {
244 /// Object number → the entry from the NEWEST section that defines
245 /// it (§7.5.6 most-recent-copy, enforced by first-wins insertion
246 /// during the newest-to-oldest walk).
247 entries: HashMap<u32, XrefEntry>,
248}
249
250impl XrefTable {
251 /// Build a table directly from a synthesized object-number → entry
252 /// map — the cross-reference **recovery** path (`crate::recover`).
253 ///
254 /// The normal load path never uses this: it fills `entries` by walking
255 /// real cross-reference sections ([`load_xref_chain`]). Recovery, by
256 /// contrast, *reconstructs* the map from a full-file object scan when
257 /// no trustworthy section exists (decision 013 §3.3), then hands the
258 /// document layer a table shaped exactly as a normal load would have
259 /// produced — so every downstream layer (object parse, §7.5.7
260 /// resolution, the writer) is unchanged. `pub(crate)` because building
261 /// an arbitrary table outside the crate would let a caller assert
262 /// cross-references the bytes do not support.
263 #[must_use]
264 pub(crate) fn from_entries(entries: HashMap<u32, XrefEntry>) -> Self {
265 Self { entries }
266 }
267
268 /// The newest entry for `num`, if any section defined one (and it
269 /// survived the `/Size` filter).
270 #[must_use]
271 pub fn get(&self, num: u32) -> Option<XrefEntry> {
272 self.entries.get(&num).copied()
273 }
274
275 /// Iterate `(object number, entry)` pairs (unordered).
276 pub fn iter(&self) -> impl Iterator<Item = (u32, XrefEntry)> + '_ {
277 self.entries.iter().map(|(&n, &e)| (n, e))
278 }
279
280 /// Number of merged entries.
281 #[must_use]
282 pub fn len(&self) -> usize {
283 self.entries.len()
284 }
285
286 /// Whether the table is empty.
287 #[must_use]
288 pub fn is_empty(&self) -> bool {
289 self.entries.is_empty()
290 }
291}
292
293/// A cross-reference-level structural error.
294#[derive(Debug, Clone, PartialEq, thiserror::Error)]
295#[error("xref error at byte {offset}: {kind}")]
296pub struct XrefError {
297 /// Byte offset where the problem was detected.
298 pub offset: usize,
299 /// What was wrong.
300 pub kind: XrefErrorKind,
301}
302
303/// Classification of cross-reference errors.
304#[derive(Debug, Clone, PartialEq, thiserror::Error)]
305#[non_exhaustive]
306pub enum XrefErrorKind {
307 /// No `startxref` keyword found in the trailing scan window.
308 #[error("no startxref found in the last {STARTXREF_SCAN_WINDOW} bytes")]
309 StartxrefNotFound,
310 /// `startxref` found but not followed by a usable integer offset,
311 /// or the offset points outside the file.
312 #[error("startxref offset missing or out of range")]
313 BadStartxrefOffset,
314 /// Neither an `xref` keyword nor an `N G obj` header at the target
315 /// offset — the section cannot be classified at all (§7.5.5 step 3
316 /// / §7.5.8.1).
317 #[error("expected an xref keyword or a cross-reference stream object at this offset")]
318 NotAnXrefSection,
319 /// A cross-reference stream (§7.5.8) was located but its
320 /// dictionary, `/W`, `/Index` or packed data violated §7.5.8.2/
321 /// §7.5.8.3. The payload is a static description of which rule.
322 #[error("malformed cross-reference stream: {0}")]
323 BadXrefStream(&'static str),
324 /// The cross-reference stream's `/Filter` chain failed to decode
325 /// (§7.5.8.2 forbids a `Crypt` filter here, so this is genuinely a
326 /// damaged or unsupported-filter stream).
327 #[error("cross-reference stream could not be decoded: {0}")]
328 XrefStreamDecode(#[from] FilterError),
329 /// The document is encrypted (§7.6) **and** its cross-reference
330 /// machinery could not be read, so rebuild-by-scan would have to find
331 /// objects in ciphertext.
332 ///
333 /// **No longer raised for a merely encrypted document.** Since
334 /// [`crate::crypto`] implements the `/Standard` handler, an encrypted
335 /// file with an intact cross-reference table is loaded and decrypted
336 /// (or refused with a *specific* reason — a named cipher, a named
337 /// handler, a password prompt). This variant now means exactly what its
338 /// name says in the recovery context: encryption that blocks
339 /// *recovery*, raised by [`crate::document`] when
340 /// [`crate::recover::RecoverError::Encrypted`] comes back.
341 #[error(
342 "encrypted documents (\u{a7}7.6) cannot be recovered by scanning: object bodies are ciphertext"
343 )]
344 EncryptionUnsupported,
345 /// A subsection header line wasn't `first count` (two
346 /// non-negative integers).
347 #[error("malformed xref subsection header")]
348 BadSubsectionHeader,
349 /// An entry violated the exact 20-byte §7.5.4 format.
350 #[error("malformed 20-byte xref entry")]
351 BadEntry,
352 /// Total entries exceeded [`MAX_XREF_ENTRIES`] (pdfcer guard).
353 #[error("xref entry count exceeds MAX_XREF_ENTRIES")]
354 TooManyEntries,
355 /// `trailer` keyword or its dictionary missing/malformed after a
356 /// section's subsections.
357 #[error("missing or malformed trailer: {0}")]
358 BadTrailer(&'static str),
359 /// The `/Prev` chain revisited an offset or exceeded
360 /// [`MAX_XREF_SECTIONS`] (cycle guard, pdfcer policy).
361 #[error("xref /Prev chain is cyclic or too long")]
362 PrevChainCycle,
363 /// Structural parse failure inside the trailer dictionary.
364 #[error(transparent)]
365 Parse(#[from] ParseError),
366}
367
368impl XrefError {
369 const fn new(offset: usize, kind: XrefErrorKind) -> Self {
370 Self { offset, kind }
371 }
372}
373
374/// The physical form of one cross-reference section — the fact a
375/// minimal-diff writer needs in order to **match** rather than
376/// normalize (`ARCHITECTURE.md` §5; decision 007 R33).
377///
378/// ## Why this is load-bearing and not diagnostic trivia
379///
380/// §7.5.6 nowhere requires an appended update section to use the same
381/// form as the section it supersedes (recorded as a NEGATIVE RESULT in
382/// `iso32000__s__7.5.6.md`). A writer is therefore *free* to answer a
383/// classic `xref` table with an appended cross-reference stream — and
384/// doing so is precisely the "silent normalization" failure decision
385/// 007 W4 names: the result is a plausible, working, WRONG file that
386/// silently raises a PDF 1.4 document's effective version to 1.5.
387///
388/// pdfcer's rule is to emit whatever the base file's **newest** section
389/// already used, which means the load path has to remember it.
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum SectionShape {
392 /// A classic §7.5.4 `xref` table with a §7.5.5 `trailer` dictionary.
393 Classic {
394 /// The section's `/XRefStm` offset (§7.5.8.4 Table 19) when the
395 /// file is **hybrid-reference**. `Some` here is what makes an
396 /// append a form-A hybrid append: §7.5.6 requirement 3 obliges
397 /// the new trailer to carry every previous-trailer entry except
398 /// `Prev`, and `/XRefStm` is such an entry.
399 xref_stm: Option<u64>,
400 },
401 /// A §7.5.8 cross-reference **stream**: an ordinary indirect stream
402 /// object that also carries the trailer's keys.
403 Stream {
404 /// The stream object's own identifier. A new section written in
405 /// this form re-uses this object number, because the base file
406 /// already spends it on exactly this role and allocating a fresh
407 /// one would grow `/Size` for no reason.
408 id: ObjId,
409 /// The base stream's `/W` field widths. Re-used verbatim when
410 /// the new section's values still fit (they usually do); widened
411 /// only when an offset no longer fits, which is a value change
412 /// forced by the data, not a normalization.
413 widths: [usize; 3],
414 },
415}
416
417/// Result of a successful chain load: the merged table, the newest
418/// trailer dictionary, and the physical facts a minimal-diff writer
419/// needs about the newest section.
420#[derive(Debug, Clone)]
421#[non_exhaustive]
422pub struct LoadedXref {
423 /// Merged object-number → entry map (newest wins, `/Size`-filtered).
424 pub table: XrefTable,
425 /// The trailer dictionary of the NEWEST section — the one whose
426 /// `/Root`/`/Info`/`/Encrypt` govern the document (§7.5.5 load
427 /// algorithm step 9).
428 pub trailer: Dict,
429 /// The byte offset the file's own `startxref` names (§7.5.5).
430 ///
431 /// This is the **exact value an appended update's `/Prev` must
432 /// carry** — §7.5.6 Q2: "the location of the previous
433 /// cross-reference section", i.e. the section this update
434 /// supersedes, which is the one `startxref` currently points at.
435 /// Deriving it from the base trailer's own `/Prev` instead is the
436 /// classic off-by-one-revision bug.
437 pub startxref: u64,
438 /// The physical form of the newest section — see [`SectionShape`].
439 pub newest_shape: SectionShape,
440 /// The highest object number the chain mentions **before** the
441 /// `/Size` filter runs.
442 ///
443 /// ## Why the unfiltered number has to be kept
444 ///
445 /// `/Size` is a hard reader-side filter (Table 15, §7.5.5), so a
446 /// file whose `/Size` under-reports loads with those entries
447 /// *invisible* — and a writer that allocates a "new" object number
448 /// from the filtered view will happily pick a number the file
449 /// already defines. The result is an update section whose entry
450 /// collides with a live one, which is the worst failure shape
451 /// available: a file that looks fine and resolves an object to the
452 /// wrong bytes.
453 ///
454 /// Found by the `writer_roundtrip` fuzz target on a corpus file
455 /// carrying `/Size 3` over six real entries.
456 pub highest_object_number: u32,
457 /// How many entries the `/Size` filter removed.
458 ///
459 /// Non-zero means the file is **hiding** cross-reference entries
460 /// behind an under-reported `/Size`. That matters to the writer
461 /// beyond diagnostics: raising `/Size` — which any object creation
462 /// does — would *expose* every one of them, resurrecting objects
463 /// the operator never touched and which may not even parse. See
464 /// [`crate::document::Document::suppressed_object_count`].
465 pub suppressed_by_size: usize,
466 /// The object numbers whose winning cross-reference entry came from a
467 /// hybrid file's `/XRefStm` stream rather than from any classic table
468 /// (§7.5.8.4) — the file's **hidden** objects (`Pass 281.0`).
469 ///
470 /// # Why this has to be retained rather than re-derived
471 ///
472 /// §7.5.8.4 describes a three-part unit a writer "creates … at the same
473 /// time": a main classic table where the hidden objects are **free with
474 /// generation 65535**, an update section, and a cross-reference stream
475 /// that gives their real locations. To *rewrite* such a file, a writer
476 /// must know which objects belong on which side.
477 ///
478 /// The alternative — re-deriving hiddenness from §7.5.8.4's recursive
479 /// visibility rule ("the root … shall not be hidden, nor any object that
480 /// is visible from the root") — answers a **different question**. That
481 /// rule says what a producer is *allowed* to hide; this set records what
482 /// this file *did* hide. A file may legally hide less than it could, and a
483 /// rewrite that re-derived the maximum would move objects the operator
484 /// never touched from one side of the partition to the other, which is
485 /// precisely the "plausible, working, wrong file" `R33` exists to prevent.
486 ///
487 /// Empty for every non-hybrid file, and empty for a hybrid file whose
488 /// `/XRefStm` did not parse — the writer distinguishes those two cases,
489 /// because the second one means the partition is **unknown** rather than
490 /// absent.
491 pub hidden_objects: BTreeSet<u32>,
492 /// Whether the newest section named an `/XRefStm` that pdfcer could not
493 /// parse (`Pass 281.0`).
494 ///
495 /// A broken `/XRefStm` is deliberately **not fatal** to loading — the
496 /// module docs explain why (§7.5.8.4 guarantees the visible graph is
497 /// resolvable without it), and every hidden object is optional by
498 /// construction. It *is* fatal to a full rewrite: the file says it hides
499 /// objects, pdfcer cannot say which, and emitting either partition would
500 /// be a guess. [`crate::writer::WriteError::HybridFullRewrite`] keeps that
501 /// case.
502 pub hybrid_stream_unreadable: bool,
503}
504
505/// Which objects a hybrid-reference file hides, and whether pdfcer could tell
506/// (`Pass 281.0`).
507///
508/// Travels from [`load_xref_chain`] to the writer as one value because the two
509/// facts are only meaningful together: an empty `hidden` set means *"nothing is
510/// hidden"* when `stream_unreadable` is `false`, and *"something is hidden and
511/// pdfcer cannot say what"* when it is `true`. Those two demand opposite
512/// behaviour from a full rewrite — proceed, and refuse — so a caller handed
513/// only the set would have to guess.
514#[derive(Debug, Clone, Default, PartialEq, Eq)]
515pub struct HybridPartition {
516 /// Object numbers whose winning entry came from the `/XRefStm` stream —
517 /// see [`LoadedXref::hidden_objects`].
518 pub hidden: BTreeSet<u32>,
519 /// Whether an `/XRefStm` was named and could not be parsed — see
520 /// [`LoadedXref::hybrid_stream_unreadable`].
521 pub stream_unreadable: bool,
522}
523
524impl HybridPartition {
525 /// Whether a full rewrite can reproduce this file's §7.5.8.4 partition.
526 ///
527 /// `false` for a file that says it hides objects and whose stream pdfcer
528 /// could not read: emitting either side of the partition would be a guess,
529 /// and a wrong guess produces a file that opens and is missing an outline
530 /// tree or a structure tree with nothing to say so.
531 #[must_use]
532 pub fn is_reproducible(&self) -> bool {
533 !self.stream_unreadable
534 }
535}
536
537/// Locate `startxref` (§7.5.5) and load the full cross-reference chain
538/// from `buf` — classic tables, cross-reference streams, and
539/// hybrid-reference `XRefStm` lookups, in the spec's search order.
540///
541/// See the module docs for the step-by-step mapping onto §7.5.5's load
542/// algorithm, the §7.5.8.4 hybrid rule, and the deliberate
543/// encryption refusal.
544///
545/// # Errors
546///
547/// [`XrefError`] — see [`XrefErrorKind`] for every case.
548pub fn load_xref_chain(buf: &[u8]) -> Result<LoadedXref, XrefError> {
549 let first_offset = find_startxref(buf)?;
550
551 let mut table = XrefTable::default();
552 let mut newest_trailer: Option<Dict> = None;
553 let mut newest_shape: Option<SectionShape> = None;
554 let mut visited: Vec<usize> = Vec::new();
555 let mut next_offset = Some(first_offset);
556 let mut hidden_objects: BTreeSet<u32> = BTreeSet::new();
557 let mut hybrid_stream_unreadable = false;
558
559 while let Some(offset) = next_offset {
560 if visited.contains(&offset) || visited.len() >= MAX_XREF_SECTIONS {
561 return Err(XrefError::new(offset, XrefErrorKind::PrevChainCycle));
562 }
563 visited.push(offset);
564
565 let section = parse_section_at(buf, offset, table.entries.len())?;
566 merge_first_wins(&mut table, section.entries);
567
568 // §7.5.8.4 hybrid-reference lookup: the `XRefStm` stream is
569 // consulted BEFORE `/Prev`, and merged first-wins so it can
570 // override older sections but not this section's own classic
571 // table. See the module docs for why a failure here is
572 // non-fatal and why its own `/Prev` is not followed.
573 if let Some(Object::Integer(v)) = section.trailer.get(b"XRefStm")
574 && let Ok(stm_offset) = usize::try_from(*v)
575 && stm_offset < buf.len()
576 && !visited.contains(&stm_offset)
577 && visited.len() < MAX_XREF_SECTIONS
578 {
579 visited.push(stm_offset);
580 match parse_xref_stream_section(buf, stm_offset, table.entries.len()) {
581 Ok(hidden) => {
582 // WHICH numbers this stream ESTABLISHED, not which it
583 // mentioned. `merge_first_wins` is first-wins, so a number
584 // a newer classic table already defined is not hidden even
585 // though the stream names it — and the writer needs the
586 // set that would be LOST if the stream were dropped, which
587 // is exactly the set that was inserted here.
588 let before: Vec<u32> = hidden.entries.iter().map(|(n, _)| *n).collect();
589 let already: BTreeSet<u32> = before
590 .iter()
591 .copied()
592 .filter(|n| table.entries.contains_key(n))
593 .collect();
594 merge_first_wins(&mut table, hidden.entries);
595 for num in before {
596 if !already.contains(&num) {
597 hidden_objects.insert(num);
598 }
599 }
600 }
601 // Non-fatal to LOADING (see the module docs) and fatal to a
602 // full rewrite: the file says it hides objects and pdfcer
603 // cannot say which.
604 Err(_) => hybrid_stream_unreadable = true,
605 }
606 }
607
608 // `/Prev` — required-direct (Table 15 defect noted in module
609 // docs); a non-integer is malformed.
610 next_offset = match section.trailer.get(b"Prev") {
611 None => None,
612 Some(Object::Integer(v)) => match usize::try_from(*v) {
613 Ok(o) if o < buf.len() => Some(o),
614 _ => {
615 return Err(XrefError::new(
616 offset,
617 XrefErrorKind::BadTrailer("Prev offset out of range"),
618 ));
619 }
620 },
621 Some(_) => {
622 return Err(XrefError::new(
623 offset,
624 XrefErrorKind::BadTrailer("Prev is not a direct integer"),
625 ));
626 }
627 };
628
629 if newest_trailer.is_none() {
630 newest_shape = Some(section.shape);
631 newest_trailer = Some(section.trailer);
632 }
633 }
634
635 let trailer = newest_trailer.ok_or(XrefError::new(
636 first_offset,
637 XrefErrorKind::NotAnXrefSection,
638 ))?;
639 let newest_shape = newest_shape.ok_or(XrefError::new(
640 first_offset,
641 XrefErrorKind::NotAnXrefSection,
642 ))?;
643
644 // §7.6: encryption is NOT refused here any more. The trailer is where
645 // the fact is discovered, but not where it can be acted on — resolving
646 // an `/O`, `/U` or `/CF` entry that is an indirect reference needs
647 // objects, and there are none yet. `Document::assemble` authenticates
648 // and decrypts; see `crate::crypto`.
649
650 // Captured BEFORE the filter: the writer needs to know what the
651 // file physically mentions, not what a reader is allowed to see.
652 let highest_object_number = table.entries.keys().copied().max().unwrap_or(0);
653 let before_filter = table.entries.len();
654
655 // `/Size` hard filter (Table 15): entries numbered >= Size are
656 // "ignored and defined to be missing."
657 if let Some(Object::Integer(size)) = trailer.get(b"Size")
658 && let Ok(size) = u32::try_from(*size)
659 {
660 table.entries.retain(|&num, _| num < size);
661 }
662 let suppressed_by_size = before_filter.saturating_sub(table.entries.len());
663
664 // Computed BEFORE `table` moves into the struct, and filtered by the same
665 // `/Size` rule that just ran: a hidden object above `/Size` is invisible to
666 // a reader and must not be re-emitted as though it were there.
667 let hidden_objects: BTreeSet<u32> = hidden_objects
668 .into_iter()
669 .filter(|n| table_has(&table, *n))
670 .collect();
671
672 Ok(LoadedXref {
673 table,
674 trailer,
675 highest_object_number,
676 suppressed_by_size,
677 startxref: first_offset as u64,
678 newest_shape,
679 hidden_objects,
680 hybrid_stream_unreadable,
681 })
682}
683
684impl LoadedXref {
685 /// This file's §7.5.8.4 partition, as one value for the writer
686 /// (`Pass 281.0`).
687 #[must_use]
688 pub fn hybrid_partition(&self) -> HybridPartition {
689 HybridPartition {
690 hidden: self.hidden_objects.clone(),
691 stream_unreadable: self.hybrid_stream_unreadable,
692 }
693 }
694}
695
696/// The entries of the cross-reference stream at `offset`, or `None` when it
697/// does not parse. The writer uses this to find which objects a forwarded
698/// `/XRefStm` would shadow (§7.5.8.4 search order).
699pub(crate) fn xref_stream_entries(buf: &[u8], offset: u64) -> Option<Vec<(u32, XrefEntry)>> {
700 let offset = usize::try_from(offset).ok().filter(|o| *o < buf.len())?;
701 parse_xref_stream_section(buf, offset, 0)
702 .ok()
703 .map(|s| s.entries)
704}
705
706/// Whether the merged table still holds an entry for `num` after the
707/// `/Size` filter — the predicate that keeps a hidden object above `/Size`
708/// out of the writer's partition (`Pass 281.0`).
709fn table_has(table: &XrefTable, num: u32) -> bool {
710 table.entries.contains_key(&num)
711}
712
713/// Merge one section's entries into `table` **first-wins**: an entry
714/// already established by a newer section (or by this section's own
715/// classic table, when merging a hybrid `XRefStm`) is never
716/// overwritten. That single rule implements both §7.5.6's
717/// most-recent-copy semantics and §7.5.8.4's search order — see the
718/// module docs.
719fn merge_first_wins(table: &mut XrefTable, entries: Vec<(u32, XrefEntry)>) {
720 for (num, entry) in entries {
721 table.entries.entry(num).or_insert(entry);
722 }
723}
724
725/// Scan the trailing [`STARTXREF_SCAN_WINDOW`] bytes for the LAST
726/// `startxref` keyword and parse the offset on the following line.
727///
728/// "Last" matters: each incremental update appends its own
729/// `startxref`/`%%EOF` (§7.5.6), and the newest one wins (§7.5.5).
730fn find_startxref(buf: &[u8]) -> Result<usize, XrefError> {
731 const KEYWORD: &[u8] = b"startxref";
732 let window_start = buf.len().saturating_sub(STARTXREF_SCAN_WINDOW);
733 let window = buf.get(window_start..).unwrap_or(buf);
734
735 let pos_in_window = window
736 .windows(KEYWORD.len())
737 .rposition(|w| w == KEYWORD)
738 .ok_or(XrefError::new(buf.len(), XrefErrorKind::StartxrefNotFound))?;
739 let after_kw = window_start + pos_in_window + KEYWORD.len();
740
741 // The offset is the next token; lexing is exactly right here (it
742 // skips the EOL and reads the integer).
743 let mut lx = crate::lexer::Lexer::at(buf, after_kw);
744 let offset = match lx.next_token() {
745 Ok(Some(t)) => match t.kind {
746 crate::lexer::TokenKind::Integer(v) => usize::try_from(v).ok(),
747 _ => None,
748 },
749 _ => None,
750 };
751 match offset {
752 Some(o) if o < buf.len() => Ok(o),
753 _ => Err(XrefError::new(after_kw, XrefErrorKind::BadStartxrefOffset)),
754 }
755}
756
757/// One parsed cross-reference section: its entries and the dictionary
758/// that plays the trailer role for it — the literal `trailer` dict for
759/// a classic section, or the stream dictionary for a cross-reference
760/// stream (§7.5.8.1).
761struct Section {
762 entries: Vec<(u32, XrefEntry)>,
763 trailer: Dict,
764 /// The section's physical form — carried up to [`LoadedXref`] for
765 /// the newest section only, where the writer needs it (R33).
766 shape: SectionShape,
767}
768
769/// Classify and parse one cross-reference section at `offset`
770/// (§7.5.5 load-algorithm step 3).
771///
772/// Classification is by the first token, per §7.5.5/§7.5.8.1: the
773/// `xref` keyword means a classic section; an integer means the start
774/// of an `N G obj` header, i.e. a cross-reference stream. Each link of
775/// a `/Prev` chain is classified independently, because a file may
776/// legitimately mix the two forms across incremental updates.
777///
778/// `already_merged` feeds the [`MAX_XREF_ENTRIES`] guard across the
779/// whole chain, not per-section.
780fn parse_section_at(
781 buf: &[u8],
782 offset: usize,
783 already_merged: usize,
784) -> Result<Section, XrefError> {
785 let mut lx = crate::lexer::Lexer::at(buf, offset);
786 let first = match lx.next_token() {
787 Ok(Some(t)) => t,
788 _ => return Err(XrefError::new(offset, XrefErrorKind::NotAnXrefSection)),
789 };
790 match first.kind {
791 crate::lexer::TokenKind::Keyword if first.span.slice(buf) == Some(b"xref") => {}
792 crate::lexer::TokenKind::Integer(_) => {
793 return parse_xref_stream_section(buf, offset, already_merged);
794 }
795 _ => return Err(XrefError::new(offset, XrefErrorKind::NotAnXrefSection)),
796 }
797
798 // After `xref`: an EOL, then subsections. Entry parsing is BYTE
799 // EXACT (20-byte records), so from here the code works on raw
800 // offsets, using the lexer only for the variable-width subsection
801 // headers and the trailer.
802 let mut cursor = first.span.end();
803 let mut entries: Vec<(u32, XrefEntry)> = Vec::new();
804
805 loop {
806 // Peek the next token to decide: subsection header (integer),
807 // or `trailer`.
808 let mut peek_lx = crate::lexer::Lexer::at(buf, cursor);
809 let tok = match peek_lx.next_token() {
810 Ok(Some(t)) => t,
811 _ => {
812 return Err(XrefError::new(
813 cursor,
814 XrefErrorKind::BadTrailer("input ended inside xref section"),
815 ));
816 }
817 };
818
819 match tok.kind {
820 crate::lexer::TokenKind::Keyword if tok.span.slice(buf) == Some(b"trailer") => {
821 // Parse the trailer dictionary with the object parser.
822 let mut parser = Parser::at(buf, tok.span.end());
823 let dict = match parser.parse_object() {
824 Ok(Object::Dict(d)) => d,
825 Ok(_) => {
826 return Err(XrefError::new(
827 tok.span.end(),
828 XrefErrorKind::BadTrailer("trailer value is not a dictionary"),
829 ));
830 }
831 Err(e) => return Err(XrefError::new(e.offset, XrefErrorKind::Parse(e))),
832 };
833 // §7.5.8.4 Table 19: `/XRefStm` marks this a
834 // hybrid-reference section. Captured here (rather than
835 // re-read from the trailer later) so the writer's
836 // form-A append has the offset without re-deriving it.
837 let xref_stm = dict
838 .get(b"XRefStm")
839 .and_then(Object::as_int)
840 .and_then(|v| u64::try_from(v).ok());
841 return Ok(Section {
842 entries,
843 trailer: dict,
844 shape: SectionShape::Classic { xref_stm },
845 });
846 }
847 crate::lexer::TokenKind::Integer(first_num) => {
848 // Subsection header: `first count`.
849 let count_tok = match peek_lx.next_token() {
850 Ok(Some(t)) => t,
851 _ => {
852 return Err(XrefError::new(cursor, XrefErrorKind::BadSubsectionHeader));
853 }
854 };
855 let crate::lexer::TokenKind::Integer(count) = count_tok.kind else {
856 return Err(XrefError::new(
857 count_tok.span.start,
858 XrefErrorKind::BadSubsectionHeader,
859 ));
860 };
861 let (Ok(first_num), Ok(count)) = (u32::try_from(first_num), usize::try_from(count))
862 else {
863 return Err(XrefError::new(
864 tok.span.start,
865 XrefErrorKind::BadSubsectionHeader,
866 ));
867 };
868 if already_merged + entries.len() + count > MAX_XREF_ENTRIES {
869 return Err(XrefError::new(
870 tok.span.start,
871 XrefErrorKind::TooManyEntries,
872 ));
873 }
874
875 // Entries begin after the header line's EOL. §7.5.4's
876 // fixed format starts each entry at a known offset;
877 // skip the single EOL (CR, LF, or CRLF) after the
878 // count token.
879 let mut entry_pos = skip_one_eol(buf, count_tok.span.end());
880 for k in 0..count {
881 let record = buf
882 .get(entry_pos..entry_pos + 20)
883 .ok_or(XrefError::new(entry_pos, XrefErrorKind::BadEntry))?;
884 let span = ByteSpan::new(entry_pos, 20);
885 let entry = parse_entry(record)
886 .ok_or(XrefError::new(span.start, XrefErrorKind::BadEntry))?;
887 // Object number = subsection first + index; a
888 // number defined twice IN THE SAME SECTION is
889 // spec-invalid but across subsections we just take
890 // the first occurrence (consistent with the
891 // section-level "shall not" being writer-side).
892 let num = first_num.saturating_add(u32::try_from(k).unwrap_or(u32::MAX));
893 if !entries.iter().any(|(n, _)| *n == num) {
894 entries.push((num, entry));
895 }
896 entry_pos += 20;
897 }
898 cursor = entry_pos;
899 }
900 _ => {
901 return Err(XrefError::new(
902 tok.span.start,
903 XrefErrorKind::BadTrailer("expected subsection header or trailer keyword"),
904 ));
905 }
906 }
907 }
908}
909
910// ---------------------------------------------------------------------------
911// Cross-reference streams (§7.5.8)
912// ---------------------------------------------------------------------------
913
914/// The resolved `/W` field-width specification of one cross-reference
915/// stream (§7.5.8.2).
916#[derive(Debug, Clone, Copy)]
917struct WidthSpec {
918 /// Byte widths of Table 18's fields 1, 2 and 3. A `0` means the
919 /// field is **absent from the data** and its Table 18 default
920 /// applies; it consumes no bytes.
921 fields: [usize; 3],
922 /// Total bytes per row — the sum of **every** element of `/W`,
923 /// including any beyond the third. Spec: "the sum of the items =
924 /// total length of each entry", and §7.5.8.3 says fields are
925 /// written in increasing field order, so trailing fields pdfcer does
926 /// not interpret still occupy their bytes and must be skipped.
927 row: usize,
928}
929
930/// Parse one cross-reference stream section (§7.5.8) at `offset`: the
931/// indirect stream object, its Table 17 dictionary, and the packed
932/// entry rows in its decoded data.
933///
934/// The returned [`Section::trailer`] is the stream's own dictionary —
935/// §7.5.8.1: it "carries what a trailer would carry", so `/Root`,
936/// `/Size`, `/Prev`, `/Info`, `/Encrypt` and `/ID` are read from it
937/// exactly as from a classic `trailer` dict.
938fn parse_xref_stream_section(
939 buf: &[u8],
940 offset: usize,
941 already_merged: usize,
942) -> Result<Section, XrefError> {
943 // The null `/Length` resolver is correct-by-spec, not a shortcut:
944 // §7.5.8.2 makes every entry a reader needs in order to decode the
945 // xref direct, precisely because no xref exists yet. A file with an
946 // indirect `/Length` on its xref stream is unbootstrappable, and
947 // surfaces here as a parse error rather than a wrong guess.
948 let io = Parser::at(buf, offset)
949 .parse_indirect_object(&mut |_| None)
950 .map_err(|e| XrefError::new(e.offset, XrefErrorKind::Parse(e)))?;
951 let Object::Stream(stream) = io.value else {
952 return Err(XrefError::new(
953 offset,
954 XrefErrorKind::BadXrefStream("startxref target is not a stream object"),
955 ));
956 };
957 let dict = stream.dict;
958
959 // Table 17: `/Type` shall be `/XRef`. A *wrong* type means the
960 // offset led somewhere else entirely and nothing here can be
961 // trusted; a *missing* type is tolerated, because `/W` + `/Size`
962 // are what actually drive decoding and refusing on the strength of
963 // a redundant tag would reject files that decode perfectly. The
964 // deviation is deliberate and recorded here.
965 if let Some(ty) = dict.get(b"Type")
966 && ty.as_name().map(crate::object::Name::as_bytes) != Some(b"XRef")
967 {
968 return Err(XrefError::new(
969 offset,
970 XrefErrorKind::BadXrefStream("/Type is present but is not /XRef"),
971 ));
972 }
973
974 let raw = stream.data_span.slice(buf).ok_or(XrefError::new(
975 offset,
976 XrefErrorKind::BadXrefStream("stream data span outside the buffer"),
977 ))?;
978 let data = filters::decode_stream(&dict, raw)
979 .map_err(|e| XrefError::new(offset, XrefErrorKind::XrefStreamDecode(e)))?;
980
981 let spec = width_spec(&dict).ok_or(XrefError::new(
982 offset,
983 XrefErrorKind::BadXrefStream("/W missing, not a direct integer array, or out of range"),
984 ))?;
985
986 // Table 15/17 `/Size`: required, direct. It is also the default
987 // `/Index` upper bound.
988 let size = dict
989 .get(b"Size")
990 .and_then(Object::as_int)
991 .and_then(|v| u32::try_from(v).ok())
992 .ok_or(XrefError::new(
993 offset,
994 XrefErrorKind::BadXrefStream("/Size missing or not a direct non-negative integer"),
995 ))?;
996
997 let index = index_pairs(&dict, size).ok_or(XrefError::new(
998 offset,
999 XrefErrorKind::BadXrefStream("/Index is not an array of direct integer pairs"),
1000 ))?;
1001
1002 let mut entries: Vec<(u32, XrefEntry)> = Vec::new();
1003 let mut pos = 0usize;
1004 for (first_num, count) in index {
1005 if already_merged
1006 .saturating_add(entries.len())
1007 .saturating_add(count)
1008 > MAX_XREF_ENTRIES
1009 {
1010 return Err(XrefError::new(offset, XrefErrorKind::TooManyEntries));
1011 }
1012 for k in 0..count {
1013 let row = data
1014 .get(pos..)
1015 .and_then(|rest| rest.get(..spec.row))
1016 .ok_or(XrefError::new(
1017 offset,
1018 XrefErrorKind::BadXrefStream("decoded data is shorter than /Index requires"),
1019 ))?;
1020 pos = pos.saturating_add(spec.row);
1021 let num = first_num.saturating_add(u32::try_from(k).unwrap_or(u32::MAX));
1022 // A row whose field values fall outside the spec's ranges
1023 // (a generation above 65,535, an object number above
1024 // `u32`) describes no representable object; it is dropped
1025 // rather than failing the load, exactly as §7.5.8.3's
1026 // unknown-type rule drops forward-incompatible rows.
1027 if let Some(entry) = decode_row(row, spec)
1028 && !entries.iter().any(|(n, _)| *n == num)
1029 {
1030 entries.push((num, entry));
1031 }
1032 }
1033 }
1034
1035 // Field widths beyond the third are not pdfcer's to reproduce (PDF
1036 // 1.5's `/W` "always contains three integers"); the first three are
1037 // what a re-emitted section needs. A shorter `/W` reads as
1038 // zero-width trailing fields, which is exactly Table 17's rule.
1039 let widths = [
1040 spec.fields.first().copied().unwrap_or(0),
1041 spec.fields.get(1).copied().unwrap_or(0),
1042 spec.fields.get(2).copied().unwrap_or(0),
1043 ];
1044
1045 Ok(Section {
1046 entries,
1047 trailer: dict,
1048 shape: SectionShape::Stream { id: io.id, widths },
1049 })
1050}
1051
1052/// Read and validate `/W` (§7.5.8.2) into a [`WidthSpec`].
1053///
1054/// Returns `None` if `/W` is absent, is not a direct array of direct
1055/// non-negative integers, has no elements, or violates
1056/// [`MAX_W_FIELD_WIDTH`] / [`MAX_XREF_STREAM_ROW`]. A row width of 0
1057/// is also rejected: it would make the row loop consume no data and
1058/// every entry identical.
1059fn width_spec(dict: &Dict) -> Option<WidthSpec> {
1060 let items = dict.get(b"W")?.as_array()?;
1061 if items.is_empty() {
1062 return None;
1063 }
1064 let mut row = 0usize;
1065 let mut fields = [0usize; 3];
1066 for (i, item) in items.iter().enumerate() {
1067 let w = usize::try_from(item.as_int()?).ok()?;
1068 if w > MAX_W_FIELD_WIDTH {
1069 return None;
1070 }
1071 row = row.checked_add(w)?;
1072 if let Some(slot) = fields.get_mut(i) {
1073 *slot = w;
1074 }
1075 }
1076 if row == 0 || row > MAX_XREF_STREAM_ROW {
1077 return None;
1078 }
1079 Some(WidthSpec { fields, row })
1080}
1081
1082/// Read `/Index` (§7.5.8.2) as `(first object number, count)` pairs,
1083/// defaulting to the spec's `[0 Size]` when absent.
1084///
1085/// Returns `None` for a malformed `/Index` (not an array, an odd
1086/// number of elements, a non-integer or negative element, or a count
1087/// that does not fit `usize`).
1088fn index_pairs(dict: &Dict, size: u32) -> Option<Vec<(u32, usize)>> {
1089 let Some(items) = dict.get(b"Index") else {
1090 // Table 17 default value: `[0 Size]` — the data then holds
1091 // exactly `Size` rows covering every object number.
1092 return Some(vec![(0, usize::try_from(size).unwrap_or(usize::MAX))]);
1093 };
1094 let items = items.as_array()?;
1095 if items.len() % 2 != 0 {
1096 return None;
1097 }
1098 let mut pairs = Vec::with_capacity(items.len() / 2);
1099 for pair in items.chunks_exact(2) {
1100 let (Some(first), Some(count)) = (pair.first(), pair.get(1)) else {
1101 return None;
1102 };
1103 let first = u32::try_from(first.as_int()?).ok()?;
1104 let count = usize::try_from(count.as_int()?).ok()?;
1105 pairs.push((first, count));
1106 }
1107 Some(pairs)
1108}
1109
1110/// Decode one packed cross-reference-stream row into an [`XrefEntry`]
1111/// per §7.5.8.3 Table 18.
1112///
1113/// Field semantics, defaults and the big-endian rule are all spelled
1114/// out in the module docs. `None` means the row does not describe a
1115/// representable entry (a type-1 row with no offset field, or a field
1116/// value outside the spec's ranges) and should be skipped.
1117fn decode_row(row: &[u8], spec: WidthSpec) -> Option<XrefEntry> {
1118 let mut cursor = 0usize;
1119 // Reads the next `width` bytes as an unsigned big-endian integer
1120 // ("fields requiring more than one byte are stored with the
1121 // high-order byte first"). Width 0 → the field is not present and
1122 // consumes nothing; the caller substitutes the Table 18 default.
1123 let mut read = |width: usize| -> Option<u64> {
1124 if width == 0 {
1125 return None;
1126 }
1127 let bytes = row.get(cursor..cursor.checked_add(width)?)?;
1128 cursor = cursor.saturating_add(width);
1129 let mut value: u64 = 0;
1130 for &b in bytes {
1131 value = value.checked_mul(256)?.checked_add(u64::from(b))?;
1132 }
1133 Some(value)
1134 };
1135
1136 // "If the first element is zero, the type field shall not be
1137 // present, and shall default to type 1."
1138 let ty = read(spec.fields[0]).unwrap_or(1);
1139 let field2 = read(spec.fields[1]);
1140 let field3 = read(spec.fields[2]);
1141
1142 match ty {
1143 0 => Some(XrefEntry::Free {
1144 // Table 18 states no default for a zero-width field here;
1145 // 0 (the free-list terminator) is the only sensible value
1146 // and is noted as such in the spec RAG's gotchas.
1147 next_free: u32::try_from(field2.unwrap_or(0)).ok()?,
1148 generation: u16::try_from(field3.unwrap_or(0)).ok()?,
1149 }),
1150 1 => Some(XrefEntry::InUse {
1151 // No default exists for a type-1 offset: without it the
1152 // entry points nowhere, so the row is unusable.
1153 offset: field2?,
1154 // Table 18: "Default value: 0."
1155 generation: u16::try_from(field3.unwrap_or(0)).ok()?,
1156 }),
1157 2 => Some(XrefEntry::InStream {
1158 stream_num: u32::try_from(field2?).ok()?,
1159 index: u32::try_from(field3.unwrap_or(0)).ok()?,
1160 }),
1161 // §7.5.8.3: "Any other value shall be interpreted as a
1162 // reference to the null object, thus permitting new entry types
1163 // to be defined in the future." A free entry IS that reading
1164 // (§7.5.4 free ⇒ §7.3.10 null), and — unlike simply dropping
1165 // the row — it still shadows older sections, which is what a
1166 // newest-wins entry saying "this object is null" must do.
1167 _ => Some(XrefEntry::Free {
1168 next_free: 0,
1169 generation: 0,
1170 }),
1171 }
1172}
1173
1174/// Skip exactly one EOL marker (CR, LF, or CRLF) at `pos`, plus any
1175/// spaces before it (the subsection-header line may have trailing
1176/// spaces in the wild — but entry alignment needs us at the next line,
1177/// and anything other than spaces/EOL here is malformed enough to
1178/// surface at entry parse instead).
1179fn skip_one_eol(buf: &[u8], mut pos: usize) -> usize {
1180 while buf.get(pos) == Some(&b' ') {
1181 pos += 1;
1182 }
1183 match (buf.get(pos), buf.get(pos + 1)) {
1184 (Some(b'\r'), Some(b'\n')) => pos + 2,
1185 (Some(b'\r' | b'\n'), _) => pos + 1,
1186 _ => pos,
1187 }
1188}
1189
1190/// Parse one exact 20-byte entry record (§7.5.4):
1191/// `nnnnnnnnnn ggggg t ee` where `t` ∈ {`n`,`f`} and `ee` is one of
1192/// `SP CR`, `SP LF`, `CR LF`. Returns `None` on any deviation.
1193fn parse_entry(record: &[u8]) -> Option<XrefEntry> {
1194 if record.len() != 20 {
1195 return None;
1196 }
1197 let field1 = record.get(0..10)?;
1198 let sp1 = record.get(10)?;
1199 let field2 = record.get(11..16)?;
1200 let sp2 = record.get(16)?;
1201 let ty = record.get(17)?;
1202 let eol = record.get(18..20)?;
1203
1204 if *sp1 != b' ' || *sp2 != b' ' {
1205 return None;
1206 }
1207 if !matches!(eol, b" \r" | b" \n" | b"\r\n") {
1208 return None;
1209 }
1210 let field1 = parse_fixed_decimal(field1)?;
1211 let field2 = parse_fixed_decimal(field2)?;
1212 let generation = u16::try_from(field2).ok()?;
1213
1214 match ty {
1215 b'n' => Some(XrefEntry::InUse {
1216 offset: field1,
1217 generation,
1218 }),
1219 b'f' => Some(XrefEntry::Free {
1220 next_free: u32::try_from(field1).ok()?,
1221 generation,
1222 }),
1223 _ => None,
1224 }
1225}
1226
1227/// Parse a fixed-width, zero-padded decimal field (all bytes must be
1228/// ASCII digits).
1229fn parse_fixed_decimal(field: &[u8]) -> Option<u64> {
1230 let mut value: u64 = 0;
1231 for &b in field {
1232 if !b.is_ascii_digit() {
1233 return None;
1234 }
1235 value = value.checked_mul(10)?.checked_add(u64::from(b - b'0'))?;
1236 }
1237 Some(value)
1238}
1239
1240// ---------------------------------------------------------------------------
1241// Observing the base file's own entry EOL (§7.5.4, spec ambiguity EOL-A1)
1242// ---------------------------------------------------------------------------
1243
1244/// Read back the 2-byte entry EOL a file's own classic cross-reference
1245/// table used (§7.5.4).
1246///
1247/// # Why this exists
1248///
1249/// §7.5.4 fixes the entry at *"exactly 20 bytes long, including the
1250/// end-of-line marker"* and then permits **three** spellings of those two
1251/// bytes — `SP CR`, `SP LF`, `CR LF` — with no rule preferring any of
1252/// them. That is the ambiguity catalogued as `EOL-A1`, and until this
1253/// function existed pdfcer answered it by always writing `SP LF`.
1254///
1255/// Always writing one form is wrong on pdfcer's **own** invariant. Rule 3
1256/// says objects pdfcer did not logically touch are re-emitted
1257/// byte-identical; a full rewrite of a `CR LF` file under a fixed `SP LF`
1258/// changes two bytes in **every entry of the table** — a 10,000-byte diff
1259/// on a 5,000-object file nobody edited. Minimal-diff editing exists to
1260/// prevent exactly that, so the setting's default is now
1261/// [`XrefEntryEol::MatchSource`](crate::writer::XrefEntryEol::MatchSource) and this is what resolves it.
1262///
1263/// It is the same principle `Document::section_shape` already serves at a
1264/// coarser grain — *the base file's own form* (R33). This is that idea one
1265/// level finer: not merely "was it a table or a stream", but "which of the
1266/// three legal spellings did it use".
1267///
1268/// # How it decides, and why it reads only the first entry
1269///
1270/// Finds the **last** `xref` keyword in the file (the newest section in an
1271/// incrementally-updated file, which is the form a rewrite should match),
1272/// steps over the subsection header, and reads bytes 18..20 of the first
1273/// 20-byte record.
1274///
1275/// One entry, not a survey, because §7.5.4's fixed width means a file that
1276/// mixed forms *within* a table would already be malformed in a way the
1277/// entry parser rejects — so the first entry either speaks for all of them
1278/// or the file does not load at all. Sampling more would cost a scan to
1279/// answer a question the format has already answered.
1280///
1281/// # When it returns `None`
1282///
1283/// - The file has no classic `xref` table (a cross-reference **stream**
1284/// file — §7.5.8 has no entry EOL at all, being binary).
1285/// - The bytes at the expected position are not one of the three legal
1286/// pairs, i.e. the file is non-conforming here.
1287/// - There is no file yet: a document pdfcer assembles from nothing has no
1288/// base form to match.
1289///
1290/// In every one of those cases the caller falls back to `SP LF`, which is
1291/// what pdfcer emitted before this existed — so a file with nothing to
1292/// match is written exactly as it always was.
1293#[must_use]
1294pub fn observed_entry_eol(buf: &[u8]) -> Option<crate::writer::XrefEntryEol> {
1295 use crate::writer::XrefEntryEol;
1296
1297 // The LAST `xref` keyword: in an incrementally-updated file the newest
1298 // section is the one a rewrite is replacing, so it is the one whose
1299 // form should carry forward.
1300 let at = last_xref_keyword(buf)?;
1301
1302 // `xref` then an EOL, then the subsection header `first count`, then
1303 // its EOL, then the entries.
1304 let mut pos = skip_one_eol(buf, at + 4);
1305 // Step over the subsection header line. Deliberately tolerant: it is
1306 // digits and spaces, and anything else means this is not a table the
1307 // entry parser would have accepted either.
1308 let header_start = pos;
1309 while matches!(buf.get(pos), Some(b'0'..=b'9' | b' ')) {
1310 pos += 1;
1311 }
1312 if pos == header_start {
1313 return None;
1314 }
1315 pos = skip_one_eol(buf, pos);
1316
1317 let record = buf.get(pos..pos + 20)?;
1318 // Confirm it really is an entry before trusting its last two bytes —
1319 // otherwise a file whose table starts unexpectedly would have its
1320 // trailing bytes read as an EOL and silently set the output's form.
1321 parse_entry(record)?;
1322 match (record.get(18), record.get(19)) {
1323 (Some(b' '), Some(b'\n')) => Some(XrefEntryEol::SpaceLf),
1324 (Some(b' '), Some(b'\r')) => Some(XrefEntryEol::SpaceCr),
1325 (Some(b'\r'), Some(b'\n')) => Some(XrefEntryEol::CrLf),
1326 _ => None,
1327 }
1328}
1329
1330/// Byte offset of the last `xref` keyword that begins a line.
1331///
1332/// Anchored to a line start so the `startxref` keyword — which ends in the
1333/// same four letters — cannot be mistaken for a table header. That is not
1334/// hypothetical: `startxref` appears in every classic file, *after* the
1335/// table, so a naive search for `xref` would find it first when scanning
1336/// backwards and land on the offset digits instead of an entry.
1337fn last_xref_keyword(buf: &[u8]) -> Option<usize> {
1338 let mut found = None;
1339 let mut i = 0usize;
1340 while let Some(rel) = buf.get(i..).and_then(|tail| find_subslice(tail, b"xref")) {
1341 let at = i + rel;
1342 // A line start, and NOT the tail of `startxref` — which ends in the
1343 // same four letters and appears in every classic file, *after* the
1344 // table. Without that exclusion this would return the offset digits
1345 // following it instead of an entry.
1346 //
1347 // Deliberately strict about the preceding byte. An earlier version
1348 // also tolerated leading spaces on the line; it was both panicky (it
1349 // sliced) and pointless, because a table whose `xref` keyword is
1350 // indented is not one the entry parser above would have accepted
1351 // either — so tolerating it here could only ever produce an EOL
1352 // reading for a file that does not load.
1353 let at_line_start = at == 0 || matches!(buf.get(at - 1), Some(b'\r' | b'\n'));
1354 let is_startxref = at >= 5 && buf.get(at - 5..at) == Some(b"start");
1355 if at_line_start && !is_startxref {
1356 found = Some(at);
1357 }
1358 i = at + 4;
1359 }
1360 found
1361}
1362
1363/// First index of `needle` in `haystack`.
1364fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1365 haystack
1366 .windows(needle.len())
1367 .position(|window| window == needle)
1368}
1369
1370#[cfg(test)]
1371#[allow(
1372 clippy::unwrap_used,
1373 clippy::expect_used,
1374 clippy::panic,
1375 clippy::indexing_slicing
1376)]
1377mod tests {
1378 use super::*;
1379
1380 /// Build a minimal classic PDF tail: xref section + trailer +
1381 /// startxref, positioned so offsets are self-consistent. Returns
1382 /// the full buffer with `body` at the front.
1383 fn with_xref_tail(body: &[u8], xref_block: &str, trailer: &str) -> Vec<u8> {
1384 let mut buf = body.to_vec();
1385 let xref_at = buf.len();
1386 buf.extend_from_slice(xref_block.as_bytes());
1387 buf.extend_from_slice(trailer.as_bytes());
1388 buf.extend_from_slice(format!("startxref\n{xref_at}\n%%EOF\n").as_bytes());
1389 buf
1390 }
1391
1392 #[test]
1393 fn parses_spec_example_2_section() {
1394 // §7.5.4 EXAMPLE 2: one subsection, six entries.
1395 let buf = with_xref_tail(
1396 b"",
1397 "xref\n0 6\n\
1398 0000000003 65535 f\r\n\
1399 0000000017 00000 n\r\n\
1400 0000000081 00000 n\r\n\
1401 0000000000 00007 f\r\n\
1402 0000000331 00000 n\r\n\
1403 0000000409 00000 n\r\n",
1404 "trailer\n<< /Size 6 /Root 1 0 R >>\n",
1405 );
1406 let loaded = load_xref_chain(&buf).unwrap();
1407 assert_eq!(loaded.table.len(), 6);
1408 assert_eq!(
1409 loaded.table.get(0),
1410 Some(XrefEntry::Free {
1411 next_free: 3,
1412 generation: 65535
1413 })
1414 );
1415 assert_eq!(
1416 loaded.table.get(1),
1417 Some(XrefEntry::InUse {
1418 offset: 17,
1419 generation: 0
1420 })
1421 );
1422 assert_eq!(
1423 loaded.table.get(3),
1424 Some(XrefEntry::Free {
1425 next_free: 0,
1426 generation: 7
1427 })
1428 );
1429 }
1430
1431 #[test]
1432 fn parses_spec_example_3_multiple_subsections() {
1433 // §7.5.4 EXAMPLE 3: four subsections; object 23 at gen 2.
1434 let buf = with_xref_tail(
1435 b"",
1436 "xref\n0 1\n\
1437 0000000000 65535 f\r\n\
1438 3 1\n\
1439 0000025325 00000 n\r\n\
1440 23 2\n\
1441 0000025518 00002 n\r\n\
1442 0000025635 00000 n\r\n\
1443 30 1\n\
1444 0000025777 00000 n\r\n",
1445 "trailer\n<< /Size 31 /Root 1 0 R >>\n",
1446 );
1447 let loaded = load_xref_chain(&buf).unwrap();
1448 assert_eq!(loaded.table.len(), 5);
1449 assert_eq!(
1450 loaded.table.get(23),
1451 Some(XrefEntry::InUse {
1452 offset: 25518,
1453 generation: 2
1454 })
1455 );
1456 assert_eq!(
1457 loaded.table.get(24),
1458 Some(XrefEntry::InUse {
1459 offset: 25635,
1460 generation: 0
1461 })
1462 );
1463 assert!(loaded.table.get(2).is_none());
1464 }
1465
1466 #[test]
1467 fn all_three_legal_entry_eols_accepted() {
1468 for eol in [" \r", " \n", "\r\n"] {
1469 let entry = format!("0000000017 00000 n{eol}");
1470 assert!(
1471 parse_entry(entry.as_bytes()).is_some(),
1472 "EOL {eol:?} rejected"
1473 );
1474 }
1475 }
1476
1477 #[test]
1478 fn nineteen_byte_entry_rejected() {
1479 // A 10+1+5+1+1+1 = 19-byte record (single-char EOL) is a
1480 // real-world deviation Pass 1 refuses (module docs).
1481 assert!(parse_entry(b"0000000017 00000 n\n").is_none());
1482 // And a wrong type byte:
1483 assert!(parse_entry(b"0000000017 00000 x \n").is_none());
1484 }
1485
1486 // ---- decision 013 Pass A: strict-§7.5.4 rejections, corpus-evidenced ----
1487 //
1488 // Pass A (the xref-recovery MEASUREMENT step) classified the CRLF-
1489 // correlated real-world load failures in the acquired corpus. The
1490 // dominant cause was OFFSET-SHIFT (stale stored offsets from LF->CRLF
1491 // byte growth — a Pass B rebuild-by-scan job, not a parser bug), and
1492 // ZERO cases were a genuine rejection of a spec-CONFORMANT classic
1493 // table. The tests below pin the three distinct GENUINELY-MALFORMED
1494 // shapes that Pass A confirmed pdfcer correctly fail-cleans on, so a
1495 // future "tolerate deviant tables" change is a deliberate, evidenced
1496 // decision (module docs: tolerance is corpus-evidenced and recorded in
1497 // C:\personal_rag\pdf\ first) rather than an accidental regression.
1498
1499 #[test]
1500 fn generation_beyond_spec_max_is_rejected() {
1501 // Corpus finding (17 files: pdfium XFA + pdfbox eu-001 + qpdf
1502 // numeric-and-string/i3/fax-decode-parms): the free-list head — or
1503 // an in-use placeholder — is written `0000000000 65536 f` /
1504 // `... 65536 n`, i.e. a well-formed 20-byte record whose GENERATION
1505 // is 65536. §7.5.4 fixes the maximum generation at 65,535 (and
1506 // object 0 "shall have a generation number of 65,535"), so 65536 is
1507 // spec-NON-conformant DATA in a structurally-valid record. pdfcer
1508 // rejects it (u16 range) => the whole load fails clean. This is the
1509 // intended strict behaviour, NOT a class-(b) Pass-A bug: the table
1510 // is not spec-valid. It is also NOT the CRLF story — 14 of the 17
1511 // files are LF. A tolerance broadening (clamp/accept 65536) is a
1512 // separate decision, out of Pass A's scope.
1513 assert!(parse_entry(b"0000000000 65536 f \n").is_none());
1514 assert!(parse_entry(b"0000000000 65536 n \n").is_none());
1515 // The legal boundary value still parses.
1516 assert_eq!(
1517 parse_entry(b"0000000000 65535 f \n"),
1518 Some(XrefEntry::Free {
1519 next_free: 0,
1520 generation: 65535,
1521 })
1522 );
1523 }
1524
1525 #[test]
1526 fn sp_cr_lf_mangled_entry_reads_as_sp_cr_and_desyncs() {
1527 // Corpus finding (minimal-linearize-pass1.pdf): an LF->CRLF
1528 // conversion turns an `SP LF` (20 0A) entry terminator into
1529 // `SP CR LF` (20 0D 0A), a 21-byte line. Reading exactly 20 bytes,
1530 // the parser sees bytes 18-19 = `SP CR` — a LEGAL §7.5.4 EOL — so
1531 // entry 0 is ACCEPTED and the trailing LF becomes a 1-byte
1532 // desync that pushes later entries off alignment until one fails
1533 // BadEntry. So a `SP CR LF`-mangled table still fails clean, just
1534 // not at byte 0. Documented here so the 20-byte fast path's
1535 // interaction with the 21-byte deviant is a known, pinned fact
1536 // (recovery of such files is Pass B / a future tolerance, not this).
1537 let first20 = b"0000000000 00000 n \r"; // first 20 of `... n \r\n`
1538 assert_eq!(
1539 parse_entry(first20),
1540 Some(XrefEntry::InUse {
1541 offset: 0,
1542 generation: 0,
1543 }),
1544 "SP CR is a legal EOL, so the 21-byte SP CR LF entry's first 20 bytes parse"
1545 );
1546 // The full 21-byte record handed in whole is NOT 20 bytes -> None,
1547 // confirming the exact-length invariant (guard: assert 20-byte
1548 // length in unit tests, never rely on round-trip reload).
1549 assert!(parse_entry(b"0000000000 00000 n \r\n").is_none());
1550 }
1551
1552 #[test]
1553 fn prev_chain_merges_newest_wins() {
1554 // Base section defines objects 0-3; update redefines object 2
1555 // and frees object 3. Newest must win for both.
1556 let base_xref = "xref\n0 4\n\
1557 0000000000 65535 f\r\n\
1558 0000000010 00000 n\r\n\
1559 0000000020 00000 n\r\n\
1560 0000000030 00000 n\r\n";
1561 let mut buf: Vec<u8> = b"%PDF-1.4\n".to_vec();
1562 let base_at = buf.len();
1563 buf.extend_from_slice(base_xref.as_bytes());
1564 buf.extend_from_slice(b"trailer\n<< /Size 4 /Root 1 0 R >>\n");
1565 let upd_at = buf.len();
1566 buf.extend_from_slice(
1567 "xref\n2 2\n\
1568 0000000099 00001 n\r\n\
1569 0000000000 65535 f\r\n"
1570 .as_bytes(),
1571 );
1572 buf.extend_from_slice(
1573 format!("trailer\n<< /Size 4 /Root 1 0 R /Prev {base_at} >>\n").as_bytes(),
1574 );
1575 buf.extend_from_slice(format!("startxref\n{upd_at}\n%%EOF\n").as_bytes());
1576
1577 let loaded = load_xref_chain(&buf).unwrap();
1578 // Newest wins: object 2 from the update…
1579 assert_eq!(
1580 loaded.table.get(2),
1581 Some(XrefEntry::InUse {
1582 offset: 99,
1583 generation: 1
1584 })
1585 );
1586 // …object 3 now FREE (shadowing the base in-use entry)…
1587 assert!(matches!(loaded.table.get(3), Some(XrefEntry::Free { .. })));
1588 // …and untouched objects still come from the base.
1589 assert_eq!(
1590 loaded.table.get(1),
1591 Some(XrefEntry::InUse {
1592 offset: 10,
1593 generation: 0
1594 })
1595 );
1596 // Newest trailer governs (it has /Prev; base doesn't).
1597 assert!(loaded.trailer.contains_key(b"Prev"));
1598 }
1599
1600 #[test]
1601 fn prev_cycle_is_detected() {
1602 // A section whose /Prev points at itself.
1603 let mut buf: Vec<u8> = Vec::new();
1604 let at = buf.len();
1605 buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
1606 buf.extend_from_slice(format!("trailer\n<< /Size 1 /Prev {at} >>\n").as_bytes());
1607 buf.extend_from_slice(format!("startxref\n{at}\n%%EOF\n").as_bytes());
1608 let e = load_xref_chain(&buf).unwrap_err();
1609 assert_eq!(e.kind, XrefErrorKind::PrevChainCycle);
1610 }
1611
1612 #[test]
1613 fn size_filter_drops_out_of_range_entries() {
1614 // Table 15: entries numbered >= Size are "ignored and defined
1615 // to be missing."
1616 let buf = with_xref_tail(
1617 b"",
1618 "xref\n0 3\n\
1619 0000000000 65535 f\r\n\
1620 0000000010 00000 n\r\n\
1621 0000000020 00000 n\r\n",
1622 "trailer\n<< /Size 2 /Root 1 0 R >>\n",
1623 );
1624 let loaded = load_xref_chain(&buf).unwrap();
1625 assert!(loaded.table.get(1).is_some());
1626 assert!(loaded.table.get(2).is_none());
1627 }
1628
1629 #[test]
1630 fn encryption_is_reported_to_the_document_layer_not_refused_here() {
1631 // This assertion is the REVERSE of what it was before
1632 // `crate::crypto` existed, and the reversal is the point: an
1633 // encrypted document with an intact cross-reference table now loads
1634 // as far as the trailer, and the decision about ciphers, passwords
1635 // and refusals belongs to `Document::assemble`, which has objects to
1636 // resolve indirect `/O`, `/U` and `/CF` entries with.
1637 //
1638 // What this layer must still do is carry `/Encrypt` through intact —
1639 // silently dropping it would hand ciphertext to the content parser.
1640 let buf = with_xref_tail(
1641 b"",
1642 "xref\n0 1\n0000000000 65535 f\r\n",
1643 "trailer\n<< /Size 1 /Root 1 0 R /Encrypt 9 0 R >>\n",
1644 );
1645 let loaded = load_xref_chain(&buf).expect("encryption is no longer refused here");
1646 assert!(
1647 loaded.trailer.contains_key(b"Encrypt"),
1648 "/Encrypt must survive to the document layer"
1649 );
1650 }
1651
1652 // ---- cross-reference stream row/dictionary decoding (§7.5.8.2-3) ----
1653
1654 /// `W = [1 2 1]`-style spec, built directly (the packed-row layer
1655 /// is unit-testable without assembling a whole file; whole-file
1656 /// coverage lives in `tests/pdf15_streams.rs`).
1657 fn spec_of(w: [usize; 3]) -> WidthSpec {
1658 WidthSpec {
1659 fields: w,
1660 row: w.iter().sum(),
1661 }
1662 }
1663
1664 #[test]
1665 fn multibyte_row_fields_are_big_endian() {
1666 // §7.5.8.3: "Fields requiring more than one byte are stored
1667 // with the high-order byte first."
1668 let spec = spec_of([1, 4, 2]);
1669 let row = [1, 0x00, 0x01, 0x02, 0x03, 0x00, 0x07];
1670 assert_eq!(
1671 decode_row(&row, spec),
1672 Some(XrefEntry::InUse {
1673 offset: 0x0001_0203,
1674 generation: 7
1675 })
1676 );
1677 }
1678
1679 #[test]
1680 fn zero_width_type_field_defaults_to_type_one() {
1681 // §7.5.8.2: "If the first element is zero, the type field shall
1682 // not be present, and shall default to type 1." The type byte
1683 // must also consume NO bytes.
1684 let spec = spec_of([0, 2, 1]);
1685 let row = [0x12, 0x34, 0x05];
1686 assert_eq!(
1687 decode_row(&row, spec),
1688 Some(XrefEntry::InUse {
1689 offset: 0x1234,
1690 generation: 5
1691 })
1692 );
1693 }
1694
1695 #[test]
1696 fn zero_width_generation_field_defaults_to_zero() {
1697 // Table 18, type 1, field 3: "Default value: 0."
1698 let spec = spec_of([1, 2, 0]);
1699 let row = [1, 0x00, 0x99];
1700 assert_eq!(
1701 decode_row(&row, spec),
1702 Some(XrefEntry::InUse {
1703 offset: 0x99,
1704 generation: 0
1705 })
1706 );
1707 }
1708
1709 #[test]
1710 fn type_two_row_is_container_plus_index_never_a_generation() {
1711 // Table 18 type 2: field 2 = object stream number, field 3 =
1712 // index within it. There is no generation field at all.
1713 let spec = spec_of([1, 2, 2]);
1714 let row = [2, 0x00, 0x0A, 0x00, 0x03];
1715 assert_eq!(
1716 decode_row(&row, spec),
1717 Some(XrefEntry::InStream {
1718 stream_num: 10,
1719 index: 3
1720 })
1721 );
1722 }
1723
1724 #[test]
1725 fn type_zero_row_is_a_free_entry() {
1726 let spec = spec_of([1, 2, 2]);
1727 let row = [0, 0x00, 0x00, 0xFF, 0xFF];
1728 assert_eq!(
1729 decode_row(&row, spec),
1730 Some(XrefEntry::Free {
1731 next_free: 0,
1732 generation: 65535
1733 })
1734 );
1735 }
1736
1737 #[test]
1738 fn unknown_row_type_reads_as_the_null_object() {
1739 // §7.5.8.3: "Any other value shall be interpreted as a
1740 // reference to the null object" — recorded as a free entry,
1741 // which IS null (§7.5.4 → §7.3.10) and still shadows older
1742 // sections as a newest-wins entry must.
1743 let spec = spec_of([1, 2, 2]);
1744 let row = [7, 0x12, 0x34, 0x00, 0x01];
1745 assert!(matches!(
1746 decode_row(&row, spec),
1747 Some(XrefEntry::Free { .. })
1748 ));
1749 }
1750
1751 #[test]
1752 fn type_one_row_without_an_offset_field_is_unusable() {
1753 // A zero-width field 2 leaves a type-1 entry pointing nowhere,
1754 // and Table 18 defines no default for it.
1755 let spec = spec_of([1, 0, 1]);
1756 assert_eq!(decode_row(&[1, 0], spec), None);
1757 }
1758
1759 #[test]
1760 fn width_spec_validates_w() {
1761 use crate::object::Name;
1762 let w = |items: Vec<Object>| {
1763 let mut d = Dict::new();
1764 d.insert(Name::from(b"W"), Object::Array(items));
1765 d
1766 };
1767 let ints = |v: &[i64]| v.iter().copied().map(Object::Integer).collect::<Vec<_>>();
1768
1769 let spec = width_spec(&w(ints(&[1, 2, 1]))).unwrap();
1770 assert_eq!(spec.fields, [1, 2, 1]);
1771 assert_eq!(spec.row, 4);
1772
1773 // Trailing elements beyond field 3 are not interpreted but DO
1774 // occupy their bytes (§7.5.8.3: fields in increasing order).
1775 let spec = width_spec(&w(ints(&[1, 2, 1, 3]))).unwrap();
1776 assert_eq!(spec.fields, [1, 2, 1]);
1777 assert_eq!(spec.row, 7);
1778
1779 // Refusals: all-zero row, absurd field width, non-integer, empty.
1780 assert!(width_spec(&w(ints(&[0, 0, 0]))).is_none());
1781 assert!(width_spec(&w(ints(&[1, 99, 1]))).is_none());
1782 assert!(width_spec(&w(vec![Object::Real(1.0)])).is_none());
1783 assert!(width_spec(&w(vec![])).is_none());
1784 assert!(width_spec(&Dict::new()).is_none());
1785 }
1786
1787 #[test]
1788 fn index_defaults_to_zero_size_and_parses_pairs() {
1789 use crate::object::Name;
1790 // Table 17: "Default value: [0 Size]."
1791 assert_eq!(index_pairs(&Dict::new(), 42), Some(vec![(0, 42)]));
1792
1793 let mut d = Dict::new();
1794 d.insert(
1795 Name::from(b"Index"),
1796 Object::Array(vec![
1797 Object::Integer(0),
1798 Object::Integer(1),
1799 Object::Integer(20),
1800 Object::Integer(3),
1801 ]),
1802 );
1803 assert_eq!(index_pairs(&d, 42), Some(vec![(0, 1), (20, 3)]));
1804
1805 // An odd element count is malformed (pairs, per Table 17).
1806 let mut d = Dict::new();
1807 d.insert(
1808 Name::from(b"Index"),
1809 Object::Array(vec![Object::Integer(0)]),
1810 );
1811 assert_eq!(index_pairs(&d, 42), None);
1812 }
1813
1814 #[test]
1815 fn missing_startxref_reported() {
1816 let e = load_xref_chain(b"not a pdf at all").unwrap_err();
1817 assert_eq!(e.kind, XrefErrorKind::StartxrefNotFound);
1818 }
1819
1820 #[test]
1821 fn last_startxref_wins() {
1822 // Two updates → two startxref markers; the LAST one is used
1823 // (§7.5.5 + §7.5.6). The first points at garbage; if the
1824 // scanner picked it, loading would fail.
1825 let mut buf: Vec<u8> = Vec::new();
1826 buf.extend_from_slice(b"startxref\n999999\n%%EOF\n");
1827 let at = buf.len();
1828 buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
1829 buf.extend_from_slice(b"trailer\n<< /Size 1 /Root 1 0 R >>\n");
1830 buf.extend_from_slice(format!("startxref\n{at}\n%%EOF\n").as_bytes());
1831 assert!(load_xref_chain(&buf).is_ok());
1832 }
1833}