Skip to main content

pdfcer_model/
linearization.rs

1//! # Linearization (Fast Web View) detection — ISO 32000-1 Annex F
2//!
3//! **Detection only.** pdfcer does not write linearized files, and this
4//! module deliberately implements nothing that would be needed to:
5//! no hint-table parsing (Annex F.4), no part-ordering validation
6//! (F.3.5, F.3.7–F.3.10). Producing a linearized file needs all of
7//! that; recognizing one, and stating honestly what a save does to it,
8//! needs only Table F.1's parameter dictionary. Spec source:
9//! `iso32000__annex__f.md` in the PDF-spec RAG.
10//!
11//! ## Why pdfcer detects something it cannot produce
12//!
13//! Decision 007 W5 and R36. An incremental save appends past the
14//! first-page cross-reference table and the hint streams, so the
15//! linearization is stale afterwards. F.1 is normative and blunt about
16//! it: *"Incremental update shall still be permitted, but the resulting
17//! PDF is **no longer linearized** and subsequently shall be treated as
18//! ordinary PDF."*
19//!
20//! That is spec-sanctioned and unavoidable — but it is also an
21//! observable property change the operator did not ask for (the file
22//! opens more slowly over a network afterwards). `CLAUDE.md` rule 4,
23//! "fuzzy, never sneaky", makes silently degrading it the wrong
24//! behavior. So: detect on load, name it, warn on save.
25//!
26//! ## What this module refuses to do, and why
27//!
28//! - **It never strips a stale `/Linearized` dictionary.** Removing it
29//!   would be a normalization (R33) and Annex G.7's reader-side
30//!   revalidation path depends on the dictionary still being there.
31//! - **It never patches `L`.** `L` is not the property — the object
32//!   ordering and hint validity are. A file whose `L` was "fixed" after
33//!   an append *claims* to be linearized while its hints point into a
34//!   stale layout, which is strictly worse for a network reader than an
35//!   honestly de-linearized file. (It is also impossible in an
36//!   append-only save, since `L` lives at the front.)
37//!
38//! ## The detection recipe (F.3.3 + Table F.1)
39//!
40//! 1. The parameter dictionary *"shall be entirely contained within the
41//!    first 1024 bytes of the PDF file"* — so the scan is bounded, and
42//!    that bound exists precisely so a reader can decide cheaply.
43//! 2. It is *"the first object in the body of the file"*, an indirect
44//!    dictionary, and *"all values in this dictionary shall be direct
45//!    objects"* — so detection needs no cross-reference table and can
46//!    run before the xref is parsed at all.
47//! 3. `/Linearized` present ⇒ **candidate**.
48//! 4. `L` (required) *"shall be exactly equal to the actual length of
49//!    the PDF file. A mismatch indicates that the file is not
50//!    linearized and shall be treated as ordinary PDF."* This is the
51//!    **liveness check**, and it is why step 3 alone is not enough: a
52//!    stale `/Linearized` dictionary survives any append.
53
54use crate::object::Object;
55use crate::parser::Parser;
56
57/// How far into the file the linearization parameter dictionary is
58/// searched for.
59///
60/// F.3.3, verbatim: *"The linearization parameter dictionary shall be
61/// entirely contained within the first 1024 bytes of the PDF file.
62/// This limits the amount of data a conforming reader must read before
63/// deciding whether the file is linearized."* The bound is the spec's,
64/// not a pdfcer policy guard.
65pub const LINEARIZATION_SCAN_WINDOW: usize = 1024;
66
67/// What Annex F detection concluded about a loaded file.
68///
69/// Three states, not two, because "was linearized and then updated" is
70/// operationally different from both "is linearized" and "never was":
71/// it is the state in which a *previous* save already spent the Fast
72/// Web View property, so pdfcer has nothing left to warn about.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74#[non_exhaustive]
75pub enum Linearization {
76    /// No `/Linearized` parameter dictionary in the first
77    /// [`LINEARIZATION_SCAN_WINDOW`] bytes.
78    #[default]
79    None,
80    /// `/Linearized` present **and** `L` equals the actual file length:
81    /// the hint tables are trustworthy and Fast Web View is live.
82    ///
83    /// This is the state a save must warn about (R36).
84    Live {
85        /// The declared file length (`L`), which equals the real one.
86        declared_length: u64,
87    },
88    /// `/Linearized` present but `L` disagrees with the file length.
89    ///
90    /// Per F.1 the file *"shall be treated as ordinary PDF"*. The two
91    /// sub-cases are distinguished because they mean different things:
92    /// a file **longer** than `L` had an update appended (G.7's case);
93    /// a file **shorter** than `L` is truncated, i.e. damaged.
94    Stale {
95        /// The `L` value the dictionary declares.
96        declared_length: u64,
97        /// The file's real length.
98        actual_length: u64,
99    },
100}
101
102impl Linearization {
103    /// Whether a save would destroy a *live* Fast Web View property —
104    /// i.e. whether the operator is owed a warning (R36).
105    ///
106    /// False for [`Linearization::Stale`]: the property was already
107    /// spent by whoever appended the previous update, and warning about
108    /// a loss that already happened is noise, not honesty.
109    #[must_use]
110    pub const fn save_invalidates_fast_web_view(self) -> bool {
111        matches!(self, Self::Live { .. })
112    }
113
114    /// Whether the file carries a `/Linearized` dictionary at all,
115    /// live or stale — the fact worth reporting as a diagnostic.
116    #[must_use]
117    pub const fn is_marked(self) -> bool {
118        !matches!(self, Self::None)
119    }
120}
121
122/// Detect Annex F linearization in `buf`.
123///
124/// Follows the F.3.3 recipe in the module docs. Never allocates beyond
125/// the parsed dictionary, never touches the cross-reference table, and
126/// never fails: every malformed shape is simply "not linearized",
127/// because F.1 already prescribes exactly that outcome for a file whose
128/// linearization information does not check out.
129///
130/// # Examples
131///
132/// ```
133/// use pdfcer_model::linearization::{detect, Linearization};
134///
135/// // A file with no parameter dictionary is simply not linearized.
136/// assert_eq!(detect(b"%PDF-1.7\n1 0 obj\n<</Type /Catalog>>\nendobj\n"),
137///            Linearization::None);
138/// ```
139#[must_use]
140pub fn detect(buf: &[u8]) -> Linearization {
141    let window_len = buf.len().min(LINEARIZATION_SCAN_WINDOW);
142    let window = buf.get(..window_len).unwrap_or(buf);
143
144    let Some(obj_start) = find_first_object(window) else {
145        return Linearization::None;
146    };
147
148    // F.3.3: all values are direct, so a null `/Length` resolver is not
149    // merely adequate — resolving anything would be a bug, since no
150    // cross-reference table has been read at this point.
151    let Ok(io) = Parser::at(window, obj_start).parse_indirect_object(&mut |_| None) else {
152        // "If parsing runs past 1024 bytes without a complete
153        // dictionary → not linearized" (F.3.3's bound, enforced by the
154        // window slice rather than by a byte count).
155        return Linearization::None;
156    };
157    let Some(dict) = io.value.as_dict() else {
158        return Linearization::None;
159    };
160    // Table F.1: `/Linearized` is required; "its mere presence is the
161    // detection marker".
162    if dict.get(b"Linearized").is_none() {
163        return Linearization::None;
164    }
165
166    let actual_length = buf.len() as u64;
167    // `L` is required and is the liveness check. A `/Linearized`
168    // dictionary with no usable `L` cannot be validated, and F.1's
169    // "treat as ordinary PDF" is the prescribed outcome — reported as
170    // Stale with a declared length of 0 so the marker is still visible
171    // to diagnostics.
172    let declared = dict
173        .get(b"L")
174        .and_then(Object::as_int)
175        .and_then(|v| u64::try_from(v).ok())
176        .unwrap_or(0);
177
178    if declared == actual_length {
179        Linearization::Live {
180            declared_length: declared,
181        }
182    } else {
183        Linearization::Stale {
184            declared_length: declared,
185            actual_length,
186        }
187    }
188}
189
190/// Find the offset of the first `N G obj` header in `window`.
191///
192/// F.3.3 puts the parameter dictionary at *"the first object in the
193/// body of the file (part 2)"*, immediately after the header line and
194/// its optional binary-comment line. Rather than model that layout,
195/// this skips comment lines and blank lines and stops at the first line
196/// that begins with a digit — which is the same thing, and tolerates
197/// the leading-junk case pdfcer's header probe already allows.
198fn find_first_object(window: &[u8]) -> Option<usize> {
199    let mut pos = 0usize;
200    while pos < window.len() {
201        // Skip leading whitespace on the line.
202        while matches!(window.get(pos), Some(b' ' | b'\t' | b'\r' | b'\n' | b'\0')) {
203            pos += 1;
204        }
205        match window.get(pos) {
206            None => return None,
207            // A comment (`%PDF-…`, the binary marker line, or any
208            // other) runs to the end of the line (§7.2.3).
209            Some(b'%') => {
210                while !matches!(window.get(pos), None | Some(b'\r' | b'\n')) {
211                    pos += 1;
212                }
213            }
214            Some(b) if b.is_ascii_digit() => return Some(pos),
215            // Anything else at the start of a line is not the body's
216            // first object; F.3.3's guarantee has already failed.
217            Some(_) => return None,
218        }
219    }
220    None
221}
222
223#[cfg(test)]
224#[allow(
225    clippy::unwrap_used,
226    clippy::expect_used,
227    clippy::panic,
228    clippy::indexing_slicing
229)]
230mod tests {
231    use super::*;
232
233    /// Build a file whose linearization dictionary declares `l`, padded
234    /// to `total` bytes so the real length is controllable.
235    fn linearized_file(l: u64, total: usize) -> Vec<u8> {
236        let mut buf =
237            format!("%PDF-1.4\n%\u{80}\u{81}\u{82}\u{83}\n1 0 obj\n<< /Linearized 1.0 /L {l} /H [100 200] /O 5 /E 900 /N 3 /T 1000 >>\nendobj\n")
238                .into_bytes();
239        while buf.len() < total {
240            buf.push(b' ');
241        }
242        buf
243    }
244
245    #[test]
246    fn absent_dictionary_is_not_linearized() {
247        assert_eq!(detect(b""), Linearization::None);
248        assert_eq!(detect(b"%PDF-1.7\n"), Linearization::None);
249        assert_eq!(
250            detect(b"%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n"),
251            Linearization::None
252        );
253    }
254
255    #[test]
256    fn live_linearization_requires_l_to_match_the_file_length() {
257        // Table F.1: L "shall be exactly equal to the actual length of
258        // the PDF file".
259        let probe = linearized_file(0, 400);
260        let total = probe.len() as u64;
261        let buf = linearized_file(total, 400);
262        assert_eq!(buf.len() as u64, total);
263        assert_eq!(
264            detect(&buf),
265            Linearization::Live {
266                declared_length: total
267            }
268        );
269        assert!(detect(&buf).save_invalidates_fast_web_view());
270        assert!(detect(&buf).is_marked());
271    }
272
273    #[test]
274    fn appended_update_makes_the_marker_stale_not_absent() {
275        // The G.7 case: file longer than L. Still *marked*, so the
276        // diagnostic reports it, but no warning is owed — a previous
277        // save already spent the property.
278        let probe = linearized_file(0, 400);
279        let mut buf = linearized_file(probe.len() as u64, 400);
280        let declared = probe.len() as u64;
281        buf.extend_from_slice(b"\n% appended update\n");
282        let got = detect(&buf);
283        assert!(
284            matches!(got, Linearization::Stale { declared_length, .. } if declared_length == declared)
285        );
286        assert!(!got.save_invalidates_fast_web_view());
287        assert!(got.is_marked());
288    }
289
290    #[test]
291    fn truncated_file_is_stale_too() {
292        let probe = linearized_file(0, 400);
293        let buf = linearized_file(probe.len() as u64 + 5_000, 400);
294        assert!(matches!(detect(&buf), Linearization::Stale { .. }));
295    }
296
297    #[test]
298    fn dictionary_beyond_the_1024_byte_window_is_not_detected() {
299        // F.3.3's bound is normative: a "linearization" dictionary that
300        // does not fit in the first 1024 bytes is not one, and pdfcer
301        // must not scan further looking for it.
302        let mut buf = b"%PDF-1.4\n".to_vec();
303        buf.extend(std::iter::repeat_n(b'%', 1_100));
304        buf.push(b'\n');
305        buf.extend_from_slice(b"1 0 obj\n<< /Linearized 1.0 /L 9 >>\nendobj\n");
306        assert_eq!(detect(&buf), Linearization::None);
307    }
308
309    #[test]
310    fn missing_l_is_marked_but_never_live() {
311        // A dictionary that cannot be validated: F.1's "treat as
312        // ordinary PDF" applies, but the marker is still reportable.
313        let buf = b"%PDF-1.4\n1 0 obj\n<< /Linearized 1.0 /O 5 >>\nendobj\n".to_vec();
314        let got = detect(&buf);
315        assert!(matches!(
316            got,
317            Linearization::Stale {
318                declared_length: 0,
319                ..
320            }
321        ));
322        assert!(!got.save_invalidates_fast_web_view());
323    }
324
325    #[test]
326    fn first_object_scan_skips_the_binary_comment_line() {
327        // The header's mandatory-if-binary comment line (§7.5.2 A5)
328        // sits between the header and part 2; a scanner that stops at
329        // the first `%` line finds nothing.
330        let buf = b"%PDF-1.5\n%\xE2\xE3\xCF\xD3\n1 0 obj\n<< /Linearized 1.0 /L 0 >>\nendobj\n";
331        assert!(detect(buf).is_marked());
332    }
333
334    #[test]
335    fn a_non_object_first_line_is_not_linearized() {
336        assert_eq!(detect(b"%PDF-1.4\nxref\n0 1\n"), Linearization::None);
337    }
338}