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