Skip to main content

pdfcer_model/
content.rs

1//! # Content-stream token model (ISO 32000-1 §7.8.2, §8.9.7)
2//!
3//! The **lossless, byte-span-provenanced token stream** for content
4//! streams, with the semantic operator view as a *projection* over it —
5//! the architecture mandated by
6//! `docs/decisions/001-oxidize-pdf-adopt-vs-build.md` §6.1 item 2.
7//! Spec sources: `iso32000__s__7.8.md` (operand/operator rules,
8//! resource model), `iso32000__s__8.9.7.md` (inline images — the one
9//! lexing exception), `iso32000__s__7.7.3.md` (Contents-array
10//! concatenation) in the PDF-spec RAG.
11//!
12//! ## Why a token stream and not an operator enum
13//!
14//! The audited prior art parses content into a semantic operator model
15//! with **no serializer** — good for text extraction, structurally
16//! wrong for editing (001 §5.3). pdfcer's model answers the question an
17//! editor asks: *"change one operator and leave the other thousands
18//! byte-identical."* Every [`ContentToken`] records its exact span in
19//! the **decoded** content buffer; re-serialization emits verbatim
20//! spans for untouched tokens and re-encodes only edited ones. (Spans
21//! here index the decoded bytes, not the file: editing any token
22//! re-encodes the whole stream *object*, but within the stream the
23//! untouched majority re-emits exactly, which is what keeps diffs
24//! reviewable and content edits minimal.)
25//!
26//! ## What this layer does and doesn't
27//!
28//! It tokenizes and structures; it does **not** interpret. Graphics
29//! semantics (state machine, resource lookup, `BX`/`EX` tolerance,
30//! unknown-operator policy) belong to the interpreter in
31//! `pdfcer-render`. Per §7.8.2 the syntax is the standard §7.2 lexer —
32//! [`crate::lexer`] is reused, never duplicated — with exactly one
33//! divergence: raw image bytes between `ID` and `EI` (§8.9.7),
34//! handled here because they must not reach the lexer at all.
35//!
36//! ## Operand rules enforced at this layer (§7.8.2)
37//!
38//! - Operands are **direct objects only** — the `N G R` reference
39//!   syntax is banned in content streams outright, so this assembler
40//!   has no reference lookahead; an `R` keyword simply becomes an
41//!   (unknown) operator token for the interpreter to reject or skip.
42//! - Dictionaries are legal operand syntax (used by `DP`/`BDC`);
43//!   streams are impossible (no `stream` framing in content).
44//!
45//! ## Inline images (§8.9.7) — the `EI` hazard
46//!
47//! An inline image carries no `/Length`; finding the end of its data
48//! is the most dangerous parse in the grammar. The strategy ladder
49//! (from the RAG's four-case analysis):
50//! 1. **Unfiltered data: compute, don't scan** — exactly
51//!    `ceil(W × colors × BPC / 8) × H` bytes.
52//! 2. **`AHx`/`A85`: scan for the filter's own EOD** (`>` / `~>`),
53//!    which is ASCII-safe.
54//! 3. **Other filters: scan for whitespace-delimited `EI`** — NOT
55//!    spec-sourced, a documented heuristic (real-world divergence gets
56//!    recorded in `C:\personal_rag\pdf\`).
57//!
58//! Abbreviated keys/values (Table 93/94) are normalized to full names
59//! immediately for the semantic view; the raw span still re-emits the
60//! original abbreviated bytes for untouched images (round-trip, §5).
61
62use crate::filters::{self, FilterError};
63// NOTE: `crate::graph::ObjectGraph` is not imported: `from_page` reaches the
64// graph via `DocumentView::graph()`, whose `&dyn ObjectGraph` resolves trait
65// methods without the trait being in scope.
66use crate::lexer::{Lexer, Token, TokenKind};
67/// How deep a chain of form XObjects invoking form XObjects may go before a
68/// walker stops descending (ISO 32000-1 §8.10.1).
69///
70/// # 64, AND THE NUMBER IS CORPUS-CORRECTED RATHER THAN CHOSEN
71///
72/// Real documents nest two or three deep — a page invokes a template, which
73/// invokes a logo — which is exactly what makes a small value *look* safe. But
74/// veraPDF's PDF/A-1b §6.1.12 implementation-limits suite ships a
75/// **conformant** file with a deliberate chain of **32** nested forms, and a
76/// reader that refuses it is wrong. 64 is 2× the deepest conformant structure
77/// anyone has measured, and Annex C sets no form-nesting limit at all.
78///
79/// # It is a backstop, NOT the real defence
80///
81/// The attack it would have to stop is unbounded *recursion*, and that is
82/// caught at any depth by a **cycle guard keyed on the form's object number**
83/// — §8.10.1 does not forbid a form invoking itself, and the same stream is
84/// reachable under different resource names, so a name-keyed guard misses the
85/// cycle entirely. What this value actually bounds is the linear memory a
86/// legitimate-but-absurd chain can pin.
87///
88/// # WHY IT LIVES HERE, WHICH IS THE POINT OF THIS CONSTANT EXISTING
89///
90/// It was written down **twice** independently — `pdfcer-render`'s
91/// `MAX_XOBJECT_DEPTH` and `text_extract`'s `ExtractOptions::max_form_depth`,
92/// the second documented as *"matching `pdfcer-render`'s"* — and a third walker
93/// (the vector decomposer) was about to add a fourth. Three hand-copied
94/// constants that must agree is a disagreement waiting to happen, and the
95/// disagreement would show as **the same file yielding different content
96/// depending on which walker asked**.
97///
98/// `text_extract` and `vector` now both take it from here. `pdfcer-render`'s
99/// copy is a `pub const` in another crate that its own callers name, so
100/// retiring it is a separate, breaking change and is **owed rather than done**.
101pub const MAX_FORM_DEPTH: usize = 64;
102
103use crate::object::{Dict, Name, ObjId, Object};
104use crate::page_tree::Page;
105use crate::span::ByteSpan;
106use crate::view::DocumentView;
107
108mod chunked;
109
110pub use chunked::{ChunkTruncation, ContentChunks};
111
112/// One token of a content stream. `span` indexes the DECODED content
113/// buffer the token was parsed from (see module docs).
114#[derive(Debug, Clone, PartialEq)]
115pub struct ContentToken {
116    /// Classification/content.
117    pub kind: ContentTokenKind,
118    /// Exact bytes in the decoded content buffer.
119    pub span: ByteSpan,
120}
121
122/// Content-token classification.
123#[derive(Debug, Clone, PartialEq)]
124#[non_exhaustive]
125pub enum ContentTokenKind {
126    /// A complete operand: any direct object (scalar, array,
127    /// dictionary), fully assembled. The span covers the whole
128    /// composite (`[` through `]`).
129    Operand(Object),
130    /// An operator keyword (`q`, `cm`, `Tj`, … — also any
131    /// unrecognized keyword; recognizing is the interpreter's job).
132    /// The bytes are the span.
133    Operator,
134    /// A complete `BI … ID … EI` inline image (§8.9.7), as ONE token
135    /// (they're a single indivisible graphics object; span covers
136    /// `BI` through `EI` inclusive).
137    InlineImage {
138        /// Key–value pairs between `BI` and `ID`, keys AND filter/
139        /// colour-space name values normalized from Table 93/94
140        /// abbreviations to their full forms.
141        params: Dict,
142        /// Exact span of the raw (still-encoded) image data bytes.
143        data: ByteSpan,
144    },
145}
146
147/// A parsed content stream: the decoded bytes plus their lossless
148/// token stream.
149#[derive(Debug, Clone, Default)]
150pub struct ContentStream {
151    /// The decoded (defiltered, concatenated) content bytes — the
152    /// buffer every token span indexes.
153    pub buf: Vec<u8>,
154    /// The tokens, in stream order.
155    pub tokens: Vec<ContentToken>,
156}
157
158/// One semantic operation: the projection's unit (module docs).
159#[derive(Debug, Clone, Copy)]
160pub struct Operation<'a> {
161    /// The operand tokens preceding the operator, in order. Their
162    /// `Operand` payloads are the arguments ("all of the operands
163    /// needed by an operator shall immediately precede that
164    /// operator", §7.8.2).
165    pub operands: &'a [ContentToken],
166    /// The operator token ([`ContentTokenKind::Operator`] — read its
167    /// name via [`Operation::operator_name`] — or an
168    /// [`ContentTokenKind::InlineImage`], which is its own complete
169    /// operation).
170    pub operator: &'a ContentToken,
171}
172
173impl<'a> Operation<'a> {
174    /// The operator's keyword bytes (`b"cm"`, `b"Tj"`, …), or `None`
175    /// for an inline image.
176    #[must_use]
177    pub fn operator_name(&self, buf: &'a [u8]) -> Option<&'a [u8]> {
178        match self.operator.kind {
179            ContentTokenKind::Operator => self.operator.span.slice(buf),
180            _ => None,
181        }
182    }
183}
184
185/// Content-stream tokenization errors.
186#[derive(Debug, Clone, PartialEq, thiserror::Error)]
187#[non_exhaustive]
188pub enum ContentError {
189    /// Lexical failure in the decoded bytes.
190    #[error(transparent)]
191    Lex(#[from] crate::lexer::LexError),
192    /// A container (array/dict) operand was malformed or unterminated.
193    #[error("malformed operand at byte {0} of decoded content")]
194    BadOperand(usize),
195    /// Operand nesting exceeded the parser guard.
196    #[error("operand nesting too deep at byte {0}")]
197    TooDeep(usize),
198    /// `BI` without a well-formed key/value section or no `ID`.
199    #[error("malformed inline image parameters at byte {0}")]
200    BadInlineParams(usize),
201    /// The inline image's data end (`EI`) could not be located.
202    #[error("unterminated inline image starting at byte {0}")]
203    UnterminatedInlineImage(usize),
204    /// Decoding a `Contents` stream failed.
205    #[error("content stream decode failed: {0}")]
206    Decode(#[from] FilterError),
207    /// A page `Contents` id didn't resolve to a stream (page-tree
208    /// validation normally prevents this; defensive).
209    #[error("page Contents object is not a stream")]
210    NotAStream,
211}
212
213/// [`ContentStream::parse_from`]'s tokenizer, appending to `tokens`. On an
214/// error, `tokens` holds every token that ended before it.
215fn tokenize(buf: &[u8], tokens: &mut Vec<ContentToken>, from: usize) -> Result<(), ContentError> {
216    // Sized from the stream's own measured density rather than by
217    // doubling -- see `TokenCapacity`, and the 116 MB of slack that
218    // motivated it.
219    let mut capacity = TokenCapacity::default();
220    let total = buf.len();
221    let mut lexer = Lexer::at(buf, from.min(total));
222    while let Some(tok) = lexer.next_token()? {
223        // Exactly one token is pushed per iteration on every branch
224        // below, so one call here covers all of them. Putting it at the
225        // push sites instead would be six copies of one rule.
226        capacity.grow_if_full(tokens, tok.span.start, total);
227        match tok.kind {
228            TokenKind::Keyword => {
229                if tok.lexeme(buf) == Some(b"BI") {
230                    let (token, resume_at) = parse_inline_image(buf, &tok, &mut lexer)?;
231                    tokens.push(token);
232                    lexer = Lexer::at(buf, resume_at);
233                } else {
234                    // true/false/null are OPERANDS even though the
235                    // lexer classes them as keywords; everything
236                    // else is an operator for the interpreter.
237                    match tok.lexeme(buf) {
238                        Some(b"true") => tokens.push(ContentToken {
239                            kind: ContentTokenKind::Operand(Object::Boolean(true)),
240                            span: tok.span,
241                        }),
242                        Some(b"false") => tokens.push(ContentToken {
243                            kind: ContentTokenKind::Operand(Object::Boolean(false)),
244                            span: tok.span,
245                        }),
246                        Some(b"null") => tokens.push(ContentToken {
247                            kind: ContentTokenKind::Operand(Object::Null),
248                            span: tok.span,
249                        }),
250                        _ => tokens.push(ContentToken {
251                            kind: ContentTokenKind::Operator,
252                            span: tok.span,
253                        }),
254                    }
255                }
256            }
257            _ => {
258                let (object, span) = assemble_operand(buf, tok, &mut lexer, 0)?;
259                tokens.push(ContentToken {
260                    kind: ContentTokenKind::Operand(object),
261                    span,
262                });
263            }
264        }
265    }
266    Ok(())
267}
268
269/// Operand container nesting bound (pdfcer policy, ARCHITECTURE.md
270/// §10 — same rationale as [`crate::parser::MAX_NESTING_DEPTH`]).
271const MAX_OPERAND_DEPTH: usize = 64;
272
273impl ContentStream {
274    /// Concatenate, decode, and tokenize a page's `Contents` streams.
275    ///
276    /// Multiple streams concatenate in order with a single LF between
277    /// parts (§7.7.3.3: the split is guaranteed to fall on a token
278    /// boundary, but the boundary itself may carry no whitespace — a
279    /// separator can never merge tokens and its absence could fail to
280    /// separate them).
281    ///
282    /// ## Which document does `view` mean? (decision 018)
283    ///
284    /// This used to take `&Document` — always the file as loaded. It now
285    /// takes a [`DocumentView`], because the answer genuinely differs by
286    /// caller and the type should make the caller say which they meant:
287    ///
288    /// - `&doc.view()` — **the base revision**. What a one-shot
289    ///   `pdfcer` operation, a text/redaction planner, or a save-time
290    ///   walk wants: the bytes on disk, no session overlay.
291    /// - `&session.view()` — **the edited state**. What the rasterizer and
292    ///   the vector object model want, so the operator sees the page they
293    ///   are actually editing.
294    ///
295    /// Getting this wrong is not a crash, it is the Pass 17.0 defect: the
296    /// content parses fine and shows the wrong document. Every caller in
297    /// the tree was audited when this signature changed, and the ones whose
298    /// base-vs-session intent is not obvious from context carry a comment
299    /// saying which they are and why.
300    ///
301    /// # Errors
302    ///
303    /// [`ContentError`] — decode failures or malformed content syntax.
304    pub fn from_page(view: &DocumentView<'_>, page: &Page) -> Result<Self, ContentError> {
305        let mut buf: Vec<u8> = Vec::new();
306        for (i, id) in page.contents.iter().enumerate() {
307            // `graph().value` rather than `doc.get(id).map(|io| &io.value)`:
308            // the graph is the one abstraction both a `Document` and an
309            // `EditSession` overlay answer, and an `IndirectObject`'s
310            // provenance is of no interest to a reader (decision 018 §3).
311            let obj = view.graph().value(*id).ok_or(ContentError::NotAStream)?;
312            let Object::Stream(stream) = obj else {
313                return Err(ContentError::NotAStream);
314            };
315            // `view.slice` rather than `span.slice(doc.bytes())`: a session
316            // view has TWO buffers (base + R45 staging) and a content stream
317            // rewritten this session — by `edit_text`, `format_text`,
318            // `apply_reflow` or a 9c-min vector edit — has its payload in the
319            // staging half. Indexing the base alone is exactly how those
320            // edits stayed invisible.
321            let raw = view
322                .slice(stream.data_span)
323                .ok_or(ContentError::NotAStream)?;
324            let decoded = filters::decode_stream(&stream.dict, raw)?;
325            // A separator only where there is something to separate. An
326            // EMPTY payload is routine here: `EditSession::text_edit_command`
327            // folds a multi-stream page into its first object and empties the
328            // rest IN PLACE (object identity is preserved for minimal-diff
329            // reasons), so a page edited this session concatenates as
330            // "content" + "" + "" ... An unconditional separator would append
331            // one whitespace byte per emptied stream on EVERY re-read, and a
332            // session re-reads its own content on every subsequent edit -- the
333            // staging buffer would grow by a byte per extra stream per edit,
334            // forever. Skipping it also makes a re-read of an already-folded
335            // page byte-identical to what was staged.
336            if i > 0 && !decoded.is_empty() {
337                buf.push(b'\n');
338            }
339            buf.extend_from_slice(&decoded);
340        }
341        Self::parse(buf)
342    }
343
344    /// One **form XObject's** own decoded content (`Pass 119.0`).
345    ///
346    /// A form XObject is a content stream in its own right (§8.10.1) — a
347    /// separate object with separate bytes, its own `/Resources` and its own
348    /// coordinate space. It is emphatically **not** part of the page's
349    /// concatenated `/Contents`, which is why [`Self::from_page`] cannot reach
350    /// the text inside one and why the edit surgery needed this door opened.
351    ///
352    /// The `view` argument carries the same base-versus-session meaning as
353    /// [`Self::from_page`], and it is *more* load-bearing here: once a session
354    /// can edit a form's content, a second edit to the same form must compose
355    /// on top of the first, and only a session view resolves the staged value.
356    ///
357    /// # Errors
358    ///
359    /// [`ContentError::NotAStream`] when the object is absent or is not a
360    /// stream; a decode or syntax error otherwise. The `/Subtype` is **not**
361    /// checked here: this decodes whatever stream it is pointed at, and
362    /// deciding what counts as an editable form belongs to the caller that
363    /// found it (`crate::text_edit::forms`).
364    pub fn from_form(view: &DocumentView<'_>, id: ObjId) -> Result<Self, ContentError> {
365        let Some(Object::Stream(stream)) = view.graph().value(id) else {
366            return Err(ContentError::NotAStream);
367        };
368        let raw = view
369            .slice(stream.data_span)
370            .ok_or(ContentError::NotAStream)?;
371        Self::parse(filters::decode_stream(&stream.dict, raw)?)
372    }
373
374    /// Tokenize decoded content bytes into the lossless token stream.
375    ///
376    /// # Errors
377    ///
378    /// [`ContentError`] — malformed syntax; offsets are into `buf`.
379    pub fn parse(buf: Vec<u8>) -> Result<Self, ContentError> {
380        Self::parse_from(buf, Vec::new(), 0)
381    }
382
383    /// Tokenize `buf` from byte `from` onward, appending to `tokens` -- the
384    /// tokens already read from `buf[..from]`.
385    ///
386    /// Equal to [`Self::parse`] of the same `buf` when `from` is a token
387    /// boundary of it and `tokens` is exactly what `parse` produced before
388    /// that boundary; that is how a caller re-tokenizes only the part of a
389    /// concatenated `/Contents` that changed. A `from` past the end reads
390    /// nothing more.
391    ///
392    /// # Errors
393    ///
394    /// [`ContentError`] -- malformed syntax at or after `from`; offsets are
395    /// into `buf`.
396    pub fn parse_from(
397        buf: Vec<u8>,
398        mut tokens: Vec<ContentToken>,
399        from: usize,
400    ) -> Result<Self, ContentError> {
401        tokenize(&buf, &mut tokens, from)?;
402        Ok(Self { buf, tokens })
403    }
404
405    /// The semantic projection: iterate operations (operand run +
406    /// operator, or a standalone inline image). Purely a VIEW over
407    /// the token stream — never a second representation (001 §6.1.2).
408    ///
409    /// Trailing operands with no operator (malformed per §7.8.2
410    /// "operands shall not be left over") are simply not yielded —
411    /// the tolerance every real viewer applies; the tokens remain in
412    /// `self.tokens` for lossless re-emission.
413    pub fn operations(&self) -> impl Iterator<Item = Operation<'_>> {
414        let mut run_start = 0usize;
415        self.tokens
416            .iter()
417            .enumerate()
418            .filter_map(move |(i, tok)| match tok.kind {
419                ContentTokenKind::Operand(_) => None,
420                _ => {
421                    let operands = self.tokens.get(run_start..i).unwrap_or(&[]);
422                    run_start = i + 1;
423                    Some(Operation {
424                        operands,
425                        operator: tok,
426                    })
427                }
428            })
429    }
430}
431
432/// Grows a content stream's token vector using **this stream's own measured
433/// token density** instead of `Vec`'s doubling.
434///
435/// # The problem, measured rather than assumed
436///
437/// `Vec` grows by doubling, so a vector's final capacity is the next power of
438/// two at or above its length and the waste is up to 50 %. On the operator's
439/// Toronto street map that is not a rounding detail, it is the whole memory
440/// profile:
441///
442/// ```text
443/// peak after start           4.6 MB
444/// peak after load           32.7 MB
445/// peak after parse          301.7 MB
446///   largest form:  2,291,669 tokens = 139.9 MB used
447///                  4,194,304 reserved = 256.0 MB   (116.1 MB of slack)
448///   sum of ALL forms' tokens         = 241.9 MB
449/// ```
450///
451/// Note which of those two numbers is the peak. The sum is 241.9 MB but
452/// every form is dropped as soon as it is interpreted, so only ONE is ever
453/// live — the 301.7 MB is `32.7 + 256.0 + the decoded buffer`, and it closes
454/// to within a megabyte. The peak was never token VOLUME, which is why the
455/// fix is here and not in `ContentToken`'s layout: shrinking the token is a
456/// breaking change to a published type that would have addressed the smaller
457/// half of the wrong quantity.
458///
459/// # Why a projection and not a constant
460///
461/// The obvious estimate is `buf.len() / 5` — measured density across this
462/// file is 5.05 bytes per token. It is also a trap, because density is a
463/// property of the CONTENT, not of PDF: a vector-heavy stream of `m`/`l`/`c`
464/// with short numeric operands runs about 5 bytes per token, while a stream
465/// that is mostly long strings, or one `BI … EI` inline image, can run
466/// hundreds. A fixed divisor tuned on a street map would over-reserve by
467/// orders of magnitude on a scanned page — winning on the file it was
468/// measured against and quietly costing everywhere else.
469///
470/// So the divisor is not fixed: it is **measured from the stream being
471/// parsed**, continuously, and used to project the final count.
472///
473/// # The algorithm
474///
475/// 1. **Below [`Self::MIN_SAMPLE`] tokens, double.** A density taken from a
476///    handful of tokens is noise. Doubling to 4,096 tokens wastes at most
477///    256 KB, which is the price of not projecting from nothing.
478/// 2. **At or above it, project**: `tokens_so_far × total_bytes ÷
479///    bytes_consumed`, plus a margin, and reserve that exactly.
480/// 3. **The margin GROWS each time a projection turns out low.** The first
481///    projection adds ⅛; every later one adds ¼. That is the adaptive half:
482///    a stream whose density is uniform is projected once and never
483///    reallocated, and a stream that fooled the first projection is assumed
484///    to be able to do it again.
485/// 4. **Never grow by less than 25 %**, whatever the projection says, so the
486///    amortised cost of `push` stays constant even if the projection is
487///    pathological.
488///
489/// WHY THE MARGIN MATTERS MORE THAN IT LOOKS. A reallocation holds the
490/// OLD buffer and the NEW one at the same time. Reallocating a 140 MB vector
491/// therefore costs ~310 MB transiently — worse than the slack being removed.
492/// So the projection is deliberately made EARLY, while the vector is still
493/// 256 KB and a mistake is cheap, and deliberately biased HIGH. An estimator
494/// that is exact on average but occasionally low at the end of a large parse
495/// would be worse than the doubling it replaces.
496#[derive(Debug, Default)]
497struct TokenCapacity {
498    /// How many times a projection has been made. Only the first is trusted
499    /// with the narrow margin; see step 3.
500    projections: u32,
501}
502
503impl TokenCapacity {
504    /// Tokens to accumulate before a density is worth believing.
505    const MIN_SAMPLE: usize = 4096;
506    /// Floor for the first allocation.
507    ///
508    /// It is **4**, matching what `Vec` itself would have done, and the
509    /// first draft's 64 is why this constant has a comment. 64 was chosen to
510    /// "save a series of small allocations" — reasoning with nothing behind
511    /// it — and the corpus leg of the harness priced it: across the 372
512    /// synthetic fixtures, whose content streams are all small, reserved
513    /// memory went **0.7 MB -> 1.6 MB**. The change fixed a 176 MB problem on
514    /// one large file and made every small file worse, which is the exact
515    /// shape of failure this Pass set out to avoid.
516    ///
517    /// At 4, a stream below `MIN_SAMPLE` tokens grows through the same
518    /// sequence `Vec` would have used, so small streams are byte-for-byte
519    /// unaffected by this whole mechanism and only large ones are projected.
520    const MIN_CAPACITY: usize = 4;
521
522    /// Called before each push. Does nothing at all unless the vector is
523    /// exactly full, so the common case is one `len == capacity` comparison.
524    ///
525    /// * `consumed` — bytes of the content buffer already tokenized.
526    /// * `total` — the buffer's full length.
527    fn grow_if_full(&mut self, tokens: &mut Vec<ContentToken>, consumed: usize, total: usize) {
528        if tokens.len() < tokens.capacity() {
529            return;
530        }
531        let cap = tokens.capacity();
532        let floor = cap.saturating_add(cap / 4).max(Self::MIN_CAPACITY);
533        let target = if tokens.len() >= Self::MIN_SAMPLE && consumed > 0 && total > consumed {
534            // `u128` because `tokens.len() * total` overflows `usize` on a
535            // 32-bit target long before either factor is implausible, and a
536            // wrapped projection would reserve a nonsense capacity.
537            let projected = u128::from(tokens.len() as u64)
538                .saturating_mul(u128::from(total as u64))
539                / u128::from(consumed as u64);
540            let divisor = if self.projections == 0 { 8 } else { 4 };
541            let with_margin = projected.saturating_add(projected / divisor);
542            self.projections = self.projections.saturating_add(1);
543            usize::try_from(with_margin)
544                .unwrap_or(usize::MAX)
545                .max(floor)
546        } else {
547            cap.saturating_mul(2).max(Self::MIN_CAPACITY)
548        };
549        // `reserve_exact`, not `reserve`: `reserve` may round the request up
550        // by its own growth policy, which is the behaviour being replaced.
551        tokens.reserve_exact(target.saturating_sub(tokens.len()));
552    }
553}
554
555/// Assemble one complete operand object starting from `first`,
556/// consuming container contents from the lexer. Returns the object and
557/// its full composite span.
558fn assemble_operand(
559    buf: &[u8],
560    first: Token,
561    lexer: &mut Lexer<'_>,
562    depth: usize,
563) -> Result<(Object, ByteSpan), ContentError> {
564    if depth > MAX_OPERAND_DEPTH {
565        return Err(ContentError::TooDeep(first.span.start));
566    }
567    let start = first.span.start;
568    match first.kind {
569        TokenKind::Integer(v) => Ok((Object::Integer(v), first.span)),
570        TokenKind::Real(v) => Ok((Object::Real(v), first.span)),
571        TokenKind::String(s) => Ok((Object::String(s), first.span)),
572        TokenKind::Name(n) => Ok((Object::Name(Name(n)), first.span)),
573        TokenKind::ArrayOpen => {
574            let mut items = Vec::new();
575            loop {
576                let Some(tok) = lexer.next_token()? else {
577                    return Err(ContentError::BadOperand(start));
578                };
579                match tok.kind {
580                    TokenKind::ArrayClose => {
581                        return Ok((
582                            Object::Array(items),
583                            ByteSpan::from_range(start..tok.span.end()),
584                        ));
585                    }
586                    TokenKind::Keyword => match tok.lexeme(buf) {
587                        Some(b"true") => items.push(Object::Boolean(true)),
588                        Some(b"false") => items.push(Object::Boolean(false)),
589                        Some(b"null") => items.push(Object::Null),
590                        // An operator keyword inside an array operand
591                        // is malformed (§7.8.2 grammar).
592                        _ => return Err(ContentError::BadOperand(tok.span.start)),
593                    },
594                    _ => {
595                        let (obj, _) = assemble_operand(buf, tok, lexer, depth + 1)?;
596                        items.push(obj);
597                    }
598                }
599            }
600        }
601        TokenKind::DictOpen => {
602            let mut dict = Dict::new();
603            loop {
604                let Some(tok) = lexer.next_token()? else {
605                    return Err(ContentError::BadOperand(start));
606                };
607                match tok.kind {
608                    TokenKind::DictClose => {
609                        return Ok((
610                            Object::Dict(dict),
611                            ByteSpan::from_range(start..tok.span.end()),
612                        ));
613                    }
614                    TokenKind::Name(key) => {
615                        let Some(value_tok) = lexer.next_token()? else {
616                            return Err(ContentError::BadOperand(start));
617                        };
618                        let value = match value_tok.kind {
619                            TokenKind::Keyword => match value_tok.lexeme(buf) {
620                                Some(b"true") => Object::Boolean(true),
621                                Some(b"false") => Object::Boolean(false),
622                                Some(b"null") => Object::Null,
623                                _ => return Err(ContentError::BadOperand(value_tok.span.start)),
624                            },
625                            _ => assemble_operand(buf, value_tok, lexer, depth + 1)?.0,
626                        };
627                        dict.insert(Name(key), value);
628                    }
629                    _ => return Err(ContentError::BadOperand(tok.span.start)),
630                }
631            }
632        }
633        // Braces (Type 4 function syntax) and stray closers are
634        // malformed at operand position in a content stream.
635        _ => Err(ContentError::BadOperand(start)),
636    }
637}
638
639// ---------------------------------------------------------------------------
640// Inline images (§8.9.7)
641// ---------------------------------------------------------------------------
642
643/// Parse a complete inline image. `bi` is the already-consumed `BI`
644/// operator token. Returns the token and the buffer offset to resume
645/// lexing at (just past `EI`).
646fn parse_inline_image(
647    buf: &[u8],
648    bi: &Token,
649    lexer: &mut Lexer<'_>,
650) -> Result<(ContentToken, usize), ContentError> {
651    // --- key/value pairs until ID (bare pairs, not a dictionary) ---
652    let mut params = Dict::new();
653    let id_end;
654    loop {
655        let Some(tok) = lexer.next_token()? else {
656            return Err(ContentError::BadInlineParams(bi.span.start));
657        };
658        match tok.kind {
659            TokenKind::Keyword if tok.lexeme(buf) == Some(b"ID") => {
660                id_end = tok.span.end();
661                break;
662            }
663            TokenKind::Name(key) => {
664                let Some(value_tok) = lexer.next_token()? else {
665                    return Err(ContentError::BadInlineParams(bi.span.start));
666                };
667                let value = match value_tok.kind {
668                    TokenKind::Keyword => match value_tok.lexeme(buf) {
669                        Some(b"true") => Object::Boolean(true),
670                        Some(b"false") => Object::Boolean(false),
671                        Some(b"null") => Object::Null,
672                        _ => return Err(ContentError::BadInlineParams(value_tok.span.start)),
673                    },
674                    _ => {
675                        assemble_operand(buf, value_tok, lexer, 0)
676                            .map_err(|_| ContentError::BadInlineParams(bi.span.start))?
677                            .0
678                    }
679                };
680                let key = normalize_key(&key);
681                let value = normalize_value(&key, value);
682                params.insert(key, value);
683            }
684            _ => return Err(ContentError::BadInlineParams(tok.span.start)),
685        }
686    }
687
688    // --- data start: ID + ONE whitespace character (§8.9.7's byte
689    // rule; for AHx/A85 the spec relaxes this, but a single skipped
690    // whitespace is still correct there since those filters ignore
691    // whitespace anyway) ---
692    //
693    // "ONE whitespace CHARACTER" is not the same as "one whitespace
694    // BYTE", and the difference is load-bearing. §7.2.2: "CR (0Dh) and
695    // LF (0Ah) are both EOL markers. CR immediately followed by LF =
696    // ONE EOL marker." So a producer that writes `ID\r\n` has written
697    // `ID` plus a single white-space character, exactly as §8.9.7
698    // requires — and it is the common habit, because it is the same
699    // framing §7.3.8.1 mandates after the `stream` keyword.
700    //
701    // Consuming only the CR leaves a stray LF at the head of the image
702    // data, which every non-ASCII filter then chokes on: a JPEG that
703    // does not start with `FF D8`, a zlib stream with a garbage header,
704    // an LZW stream whose first code is shifted. Measured on the
705    // veraPDF corpus (2026-07-30): four inline DCT images failed with
706    // "codestream does not begin with SOI" for exactly this reason.
707    // CR alone and LF alone are still one character each.
708    let data_start = match (buf.get(id_end).copied(), buf.get(id_end + 1).copied()) {
709        (Some(b'\r'), Some(b'\n')) => id_end + 2,
710        (Some(b), _) if crate::lexer::is_whitespace(b) => id_end + 1,
711        _ => id_end,
712    };
713
714    // --- data end: the strategy ladder (module docs) ---
715    let data_end = locate_inline_data_end(buf, data_start, &params)
716        .ok_or(ContentError::UnterminatedInlineImage(bi.span.start))?;
717
718    // --- EI ---
719    let mut tail = Lexer::at(buf, data_end);
720    let Ok(Some(ei)) = tail.next_token() else {
721        return Err(ContentError::UnterminatedInlineImage(bi.span.start));
722    };
723    if !(matches!(ei.kind, TokenKind::Keyword) && ei.lexeme(buf) == Some(b"EI")) {
724        return Err(ContentError::UnterminatedInlineImage(bi.span.start));
725    }
726
727    Ok((
728        ContentToken {
729            kind: ContentTokenKind::InlineImage {
730                params,
731                data: ByteSpan::from_range(data_start..data_end),
732            },
733            span: ByteSpan::from_range(bi.span.start..ei.span.end()),
734        },
735        ei.span.end(),
736    ))
737}
738
739/// Find the end of inline image data per the strategy ladder.
740fn locate_inline_data_end(buf: &[u8], start: usize, params: &Dict) -> Option<usize> {
741    let filters = inline_filters(params);
742
743    if filters.is_empty() {
744        // Case 1: unfiltered — compute, don't scan.
745        if let Some(len) = unfiltered_data_len(params) {
746            let end = start.checked_add(len)?;
747            return (end <= buf.len()).then_some(end);
748        }
749        // Missing W/H/BPC: malformed, but fall through to the scan so
750        // the error becomes "unterminated" only if EI truly absent.
751    } else if let Some(first) = filters.first() {
752        // Case 2: ASCII filters self-terminate.
753        let region = buf.get(start..)?;
754        match first.as_slice() {
755            b"ASCIIHexDecode" => {
756                let eod = region.iter().position(|&b| b == b'>')?;
757                return Some(start + eod + 1);
758            }
759            b"ASCII85Decode" => {
760                let eod = region.windows(2).position(|w| w == b"~>")?;
761                return Some(start + eod + 2);
762            }
763            _ => {}
764        }
765    }
766
767    // Case 3 fallback (NOT spec-sourced — module docs): scan for `EI`
768    // preceded by whitespace and followed by whitespace/delimiter/EOF.
769    let mut i = start;
770    while i + 1 < buf.len() {
771        if buf.get(i) == Some(&b'E')
772            && buf.get(i + 1) == Some(&b'I')
773            && i > start
774            && buf
775                .get(i - 1)
776                .copied()
777                .is_some_and(crate::lexer::is_whitespace)
778        {
779            let after = buf.get(i + 2).copied();
780            let terminated = match after {
781                None => true,
782                Some(b) => crate::lexer::is_whitespace(b) || crate::lexer::is_delimiter(b),
783            };
784            if terminated {
785                // Return the offset of the whitespace before EI so the
786                // caller's lexer re-lexes EI itself.
787                return Some(i - 1);
788            }
789        }
790        i += 1;
791    }
792    None
793}
794
795/// Byte length of unfiltered inline data:
796/// `ceil(W × colors × BPC / 8) × H` (§8.9.7 case 1; row-padded per
797/// §7.4.4.4 rule 2's shared convention for sampled data).
798fn unfiltered_data_len(params: &Dict) -> Option<usize> {
799    let get_u64 = |key: &[u8]| -> Option<u64> {
800        params
801            .get(key)
802            .and_then(Object::as_int)
803            .and_then(|v| u64::try_from(v).ok())
804    };
805    let w = get_u64(b"Width")?;
806    let h = get_u64(b"Height")?;
807    let image_mask = matches!(params.get(b"ImageMask"), Some(Object::Boolean(true)));
808    let bpc = if image_mask {
809        1
810    } else {
811        get_u64(b"BitsPerComponent")?
812    };
813    let colors = if image_mask {
814        1
815    } else {
816        match params.get(b"ColorSpace") {
817            Some(Object::Name(n)) => match n.as_bytes() {
818                b"DeviceRGB" => 3,
819                b"DeviceCMYK" => 4,
820                // DeviceGray, Indexed (1 index component), and named
821                // resource spaces (component count unknown → treat as
822                // 1 and let the scan fallback correct a mismatch).
823                _ => 1,
824            },
825            Some(Object::Array(_)) => 1, // Indexed [ /I base hival lookup ]
826            _ => 1,
827        }
828    };
829    let row_bytes = (w.checked_mul(colors)?.checked_mul(bpc)?).div_ceil(8);
830    usize::try_from(row_bytes.checked_mul(h)?).ok()
831}
832
833/// The inline image's filter chain as full (normalized) names.
834fn inline_filters(params: &Dict) -> Vec<Vec<u8>> {
835    match params.get(b"Filter") {
836        Some(Object::Name(n)) => vec![n.as_bytes().to_vec()],
837        Some(Object::Array(items)) => items
838            .iter()
839            .filter_map(|o| o.as_name().map(|n| n.as_bytes().to_vec()))
840            .collect(),
841        _ => Vec::new(),
842    }
843}
844
845/// Normalize a Table 93 abbreviated KEY to its full name.
846fn normalize_key(key: &[u8]) -> Name {
847    Name(
848        match key {
849            b"BPC" => &b"BitsPerComponent"[..],
850            b"CS" => b"ColorSpace",
851            b"D" => b"Decode",
852            b"DP" => b"DecodeParms",
853            b"F" => b"Filter",
854            b"H" => b"Height",
855            b"IM" => b"ImageMask",
856            b"I" => b"Interpolate", // key position ⇒ Interpolate, not Indexed
857            b"W" => b"Width",
858            other => other,
859        }
860        .to_vec(),
861    )
862}
863
864/// Normalize Table 94 abbreviated VALUES — only where they can occur
865/// (`Filter` and `ColorSpace` values, including inside arrays). `I`
866/// here means `Indexed` (value position), disambiguated from the
867/// `Interpolate` KEY by context exactly as the RAG's gotcha requires.
868fn normalize_value(key: &Name, value: Object) -> Object {
869    fn map_name(bytes: &[u8]) -> Option<&'static [u8]> {
870        Some(match bytes {
871            b"G" => b"DeviceGray",
872            b"RGB" => b"DeviceRGB",
873            b"CMYK" => b"DeviceCMYK",
874            b"I" => b"Indexed",
875            b"AHx" => b"ASCIIHexDecode",
876            b"A85" => b"ASCII85Decode",
877            b"LZW" => b"LZWDecode",
878            b"Fl" => b"FlateDecode",
879            b"RL" => b"RunLengthDecode",
880            b"CCF" => b"CCITTFaxDecode",
881            b"DCT" => b"DCTDecode",
882            _ => return None,
883        })
884    }
885    if !matches!(key.as_bytes(), b"Filter" | b"ColorSpace") {
886        return value;
887    }
888    match value {
889        Object::Name(n) => match map_name(n.as_bytes()) {
890            Some(full) => Object::Name(Name(full.to_vec())),
891            None => Object::Name(n),
892        },
893        Object::Array(items) => Object::Array(
894            items
895                .into_iter()
896                .map(|o| match o {
897                    Object::Name(n) => match map_name(n.as_bytes()) {
898                        Some(full) => Object::Name(Name(full.to_vec())),
899                        None => Object::Name(n),
900                    },
901                    other => other,
902                })
903                .collect(),
904        ),
905        other => other,
906    }
907}
908
909#[cfg(test)]
910#[allow(
911    clippy::unwrap_used,
912    clippy::expect_used,
913    clippy::panic,
914    clippy::indexing_slicing
915)]
916mod tests {
917    use super::*;
918
919    fn parse(input: &[u8]) -> ContentStream {
920        ContentStream::parse(input.to_vec()).unwrap()
921    }
922
923    #[test]
924    fn parse_from_a_token_boundary_equals_a_whole_parse() {
925        let whole: &[u8] = b"q 1 0 0 1 5 5 cm BI /W 1 /H 1 /BPC 8 /CS /G ID x EI Q
9260 0 m 9 9 l S";
927        let cut = 52;
928        let prefix = parse(whole.get(..cut).unwrap()).tokens;
929        let resumed = ContentStream::parse_from(whole.to_vec(), prefix, cut).unwrap();
930        assert_eq!(resumed.tokens, parse(whole).tokens);
931    }
932
933    /// Collect (operator name, operand objects) pairs.
934    fn ops(cs: &ContentStream) -> Vec<(Vec<u8>, Vec<Object>)> {
935        cs.operations()
936            .map(|op| {
937                let name = op.operator_name(&cs.buf).unwrap_or(b"<inline>").to_vec();
938                let operands = op
939                    .operands
940                    .iter()
941                    .filter_map(|t| match &t.kind {
942                        ContentTokenKind::Operand(o) => Some(o.clone()),
943                        _ => None,
944                    })
945                    .collect();
946                (name, operands)
947            })
948            .collect()
949    }
950
951    #[test]
952    fn basic_operations_projection() {
953        let cs = parse(b"q 1 0 0 1 72 712 cm BT /F1 12 Tf (Hello) Tj ET Q");
954        let ops = ops(&cs);
955        let names: Vec<&[u8]> = ops.iter().map(|(n, _)| n.as_slice()).collect();
956        assert_eq!(
957            names,
958            vec![&b"q"[..], b"cm", b"BT", b"Tf", b"Tj", b"ET", b"Q"]
959        );
960        // cm has six numeric operands.
961        assert_eq!(ops[1].1.len(), 6);
962        // Tf: name + number.
963        assert_eq!(ops[3].1[0], Object::Name(Name::from(b"F1")));
964        // Tj: the string.
965        assert_eq!(ops[4].1[0], Object::String(b"Hello".to_vec()));
966    }
967
968    #[test]
969    fn tj_array_is_one_operand_with_full_span() {
970        let buf: &[u8] = b"[(He)-20(llo)] TJ";
971        let cs = parse(buf);
972        let ops = ops(&cs);
973        assert_eq!(ops[0].0, b"TJ");
974        assert_eq!(ops[0].1.len(), 1, "the TJ array is ONE operand");
975        // Lossless span: the operand token covers the whole array.
976        let ContentTokenKind::Operand(_) = &cs.tokens[0].kind else {
977            panic!("expected operand");
978        };
979        assert_eq!(cs.tokens[0].span.slice(buf).unwrap(), b"[(He)-20(llo)]");
980    }
981
982    #[test]
983    fn dict_operand_for_marked_content() {
984        let cs = parse(b"/OC << /Type /OCMD >> BDC EMC");
985        let ops = ops(&cs);
986        assert_eq!(ops[0].0, b"BDC");
987        assert_eq!(ops[0].1.len(), 2);
988        assert!(matches!(ops[0].1[1], Object::Dict(_)));
989    }
990
991    #[test]
992    fn keywords_true_false_null_are_operands_not_operators() {
993        let cs = parse(b"true false null gs");
994        let ops = ops(&cs);
995        assert_eq!(ops.len(), 1);
996        assert_eq!(ops[0].0, b"gs");
997        assert_eq!(ops[0].1.len(), 3);
998    }
999
1000    #[test]
1001    fn trailing_operands_without_operator_are_not_yielded() {
1002        // Malformed per §7.8.2; tolerated per module docs — tokens
1003        // stay recorded, projection just doesn't yield an operation.
1004        let cs = parse(b"q Q 1 2 3");
1005        assert_eq!(ops(&cs).len(), 2);
1006        assert_eq!(cs.tokens.len(), 5, "operand tokens preserved");
1007    }
1008
1009    #[test]
1010    fn unknown_operator_is_a_token_not_an_error() {
1011        // Recognition is the interpreter's job (BX/EX, log-and-skip).
1012        let cs = parse(b"1 2 frobnicate");
1013        assert_eq!(ops(&cs)[0].0, b"frobnicate");
1014    }
1015
1016    #[test]
1017    fn inline_image_unfiltered_computed_length() {
1018        // 2×2 grayscale 8bpc ⇒ exactly 4 data bytes — which happen to
1019        // spell "EI x" garbage-free; the COMPUTED path must not scan.
1020        // Data bytes deliberately contain "EI" to prove no scanning.
1021        let buf: &[u8] = b"BI /W 2 /H 2 /CS /G /BPC 8 ID \x45\x49\x00\xFF EI Q";
1022        let cs = parse(buf);
1023        let ContentTokenKind::InlineImage { params, data } = &cs.tokens[0].kind else {
1024            panic!("expected inline image, got {:?}", cs.tokens[0].kind);
1025        };
1026        assert_eq!(data.slice(buf).unwrap(), b"\x45\x49\x00\xFF");
1027        // Keys and CS value normalized to full names.
1028        assert!(params.contains_key(b"Width"));
1029        assert_eq!(
1030            params
1031                .get(b"ColorSpace")
1032                .unwrap()
1033                .as_name()
1034                .unwrap()
1035                .as_bytes(),
1036            b"DeviceGray"
1037        );
1038        // The Q after EI still lexes.
1039        assert_eq!(ops(&cs).last().unwrap().0, b"Q");
1040        // The token's own span covers BI..EI for verbatim re-emission.
1041        assert!(cs.tokens[0].span.slice(buf).unwrap().starts_with(b"BI"));
1042        assert!(cs.tokens[0].span.slice(buf).unwrap().ends_with(b"EI"));
1043    }
1044
1045    #[test]
1046    fn id_followed_by_crlf_consumes_both_bytes() {
1047        // §8.9.7 requires ONE white-space CHARACTER after `ID`, and
1048        // §7.2.2 makes "CR immediately followed by LF" exactly one EOL
1049        // marker — the same reading §7.3.8.1 gives the `stream`
1050        // keyword, and the framing real producers actually emit.
1051        //
1052        // Consuming only the CR leaves a stray LF at the head of the
1053        // image data. Measured on the veraPDF corpus (2026-07-30): four
1054        // inline DCT images failed with "codestream does not begin with
1055        // SOI" for precisely this reason, so this is a regression test
1056        // for a real corpus finding, not a hypothetical.
1057        let buf: &[u8] = b"BI /W 2 /H 2 /CS /G /BPC 8 ID\r\n\x01\x02\x03\x04 EI Q";
1058        let cs = parse(buf);
1059        let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
1060            panic!("expected inline image, got {:?}", cs.tokens[0].kind);
1061        };
1062        assert_eq!(data.slice(buf).unwrap(), b"\x01\x02\x03\x04");
1063    }
1064
1065    #[test]
1066    fn id_followed_by_a_single_whitespace_consumes_exactly_one_byte() {
1067        // The other half of the rule: only a CR *immediately followed
1068        // by* LF is one marker. Every other single white-space
1069        // character consumes exactly one byte, so a first data byte
1070        // that happens to be 0x0A must not be swallowed.
1071        //
1072        // The lone-CR case is deliberately tested with a non-LF first
1073        // data byte, because `ID\r` + a 0x0A data byte is genuinely
1074        // ambiguous in the format itself — §7.2.2 resolves it in favour
1075        // of CRLF being one marker, which is exactly why §7.3.8.1
1076        // forbids CR alone after the `stream` keyword. There is no
1077        // reading that recovers that data byte, and pretending
1078        // otherwise would be a test asserting a fiction.
1079        for (eol, first) in [
1080            (&b"\r"[..], 0x01u8),
1081            (b"\n", 0x0A),
1082            (b" ", 0x0A),
1083            (b"\t", 0x0A),
1084        ] {
1085            let mut buf = b"BI /W 2 /H 2 /CS /G /BPC 8 ID".to_vec();
1086            buf.extend_from_slice(eol);
1087            buf.extend_from_slice(&[first, 0x02, 0x03, 0x04]);
1088            buf.extend_from_slice(b" EI Q");
1089            let cs = parse(&buf);
1090            let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
1091                panic!("expected inline image");
1092            };
1093            assert_eq!(
1094                data.slice(&buf).unwrap(),
1095                &[first, 0x02, 0x03, 0x04],
1096                "eol {eol:?} must consume exactly one byte"
1097            );
1098        }
1099    }
1100
1101    #[test]
1102    fn inline_image_ascii_hex_self_terminates() {
1103        let buf: &[u8] = b"BI /W 1 /H 1 /CS /G /BPC 8 /F /AHx ID FF> EI";
1104        let cs = parse(buf);
1105        let ContentTokenKind::InlineImage { params, data } = &cs.tokens[0].kind else {
1106            panic!("expected inline image");
1107        };
1108        assert_eq!(data.slice(buf).unwrap(), b"FF>");
1109        assert_eq!(
1110            params.get(b"Filter").unwrap().as_name().unwrap().as_bytes(),
1111            b"ASCIIHexDecode"
1112        );
1113    }
1114
1115    #[test]
1116    fn inline_image_filtered_falls_back_to_ei_scan() {
1117        // Fl-filtered data of unknown length: whitespace-delimited EI
1118        // scan (the documented non-spec heuristic).
1119        let buf: &[u8] = b"BI /W 1 /H 1 /CS /G /BPC 8 /F /Fl ID \x78\x9c\x63\x00\x00 EI";
1120        let cs = parse(buf);
1121        let ContentTokenKind::InlineImage { data, .. } = &cs.tokens[0].kind else {
1122            panic!("expected inline image");
1123        };
1124        assert_eq!(data.slice(buf).unwrap(), b"\x78\x9c\x63\x00\x00");
1125    }
1126
1127    #[test]
1128    fn inline_image_interpolate_vs_indexed_disambiguation() {
1129        // /I in KEY position = Interpolate; /I in ColorSpace VALUE
1130        // position (inside the Indexed array) = Indexed.
1131        let buf: &[u8] = b"BI /W 1 /H 1 /BPC 8 /I true /CS [/I /RGB 0 <000000>] ID \x00 EI";
1132        let cs = parse(buf);
1133        let ContentTokenKind::InlineImage { params, .. } = &cs.tokens[0].kind else {
1134            panic!("expected inline image");
1135        };
1136        assert_eq!(params.get(b"Interpolate").unwrap(), &Object::Boolean(true));
1137        let Object::Array(cs_arr) = params.get(b"ColorSpace").unwrap() else {
1138            panic!("Indexed array expected");
1139        };
1140        assert_eq!(cs_arr[0].as_name().unwrap().as_bytes(), b"Indexed");
1141        assert_eq!(cs_arr[1].as_name().unwrap().as_bytes(), b"DeviceRGB");
1142    }
1143
1144    #[test]
1145    fn unterminated_inline_image_is_error() {
1146        let e =
1147            ContentStream::parse(b"BI /W 9 /H 9 /CS /G /BPC 8 ID \x00\x01".to_vec()).unwrap_err();
1148        assert!(matches!(e, ContentError::UnterminatedInlineImage(_)));
1149    }
1150
1151    #[test]
1152    fn reference_syntax_in_content_is_just_an_unknown_operator() {
1153        // §7.8.2 bans indirect references; `1 0 R` lexes as two
1154        // operands + operator R, which the interpreter will reject.
1155        let cs = parse(b"1 0 R");
1156        let ops = ops(&cs);
1157        assert_eq!(ops[0].0, b"R");
1158        assert_eq!(ops[0].1.len(), 2);
1159    }
1160
1161    #[test]
1162    fn spans_recover_exact_source_for_every_token() {
1163        let buf: &[u8] = b"q 0.5 0 0 0.5 0 0 cm /Im1 Do Q";
1164        let cs = parse(buf);
1165        // Reconstructing the stream from token spans + inter-token
1166        // whitespace is the round-trip foundation; here just verify
1167        // each token's span slices cleanly and in order.
1168        let mut last_end = 0;
1169        for t in &cs.tokens {
1170            assert!(t.span.start >= last_end);
1171            assert!(t.span.slice(buf).is_some());
1172            last_end = t.span.end();
1173        }
1174    }
1175}