Skip to main content

pdfboss_core/
content.rs

1//! Content-stream operator parsing (ISO 32000 §8/§9), including inline
2//! images. Lenient: unknown operators and arity mismatches are skipped
3//! (the operand stack is cleared), never an error.
4
5use crate::elements::Span;
6use crate::error::{Error, Result};
7use crate::geom::Matrix;
8use crate::lexer::{decode_hex, is_whitespace, Lexer, RawToken, Token};
9use crate::object::{Dict, Name, Object};
10
11/// Maximum operand container (array/dictionary) nesting depth. Composing
12/// values recurses per nesting level, so without a bound a content stream
13/// of e.g. 50k `[`s overflows the stack and aborts the process. Genuine
14/// operands (dash arrays, `TJ` arrays, property dicts) nest one or two
15/// levels deep.
16const MAX_NESTING_DEPTH: usize = 128;
17
18/// The syntax error reported when `MAX_NESTING_DEPTH` is exceeded.
19fn too_deep(lexer: &Lexer) -> Error {
20    Error::Syntax {
21        offset: lexer.pos(),
22        msg: "operand nesting too deep".into(),
23    }
24}
25
26/// An inline image (`BI ... ID ... EI`) with its dictionary keys and
27/// colorspace abbreviations expanded to their canonical names
28/// (e.g. `/BPC` -> `/BitsPerComponent`, `/RGB` -> `/DeviceRGB`).
29#[derive(Debug, Clone, PartialEq)]
30pub struct ImageParams {
31    pub dict: Dict,
32    pub data: Vec<u8>,
33}
34
35/// One element of a `TJ` (show text with adjustments) array.
36#[derive(Debug, Clone, PartialEq)]
37pub enum TextItem {
38    /// A string to show.
39    Str(Vec<u8>),
40    /// A position adjustment in thousandths of text-space units.
41    Offset(f32),
42}
43
44/// A parsed content-stream operator with its operands.
45#[derive(Debug, Clone, PartialEq)]
46pub enum Op {
47    // Graphics state.
48    /// `q`
49    Save,
50    /// `Q`
51    Restore,
52    /// `cm`
53    Concat(Matrix),
54    /// `w`
55    SetLineWidth(f32),
56    /// `J`
57    SetLineCap(i32),
58    /// `j`
59    SetLineJoin(i32),
60    /// `M`
61    SetMiterLimit(f32),
62    /// `d` (dash array, phase)
63    SetDash(Vec<f32>, f32),
64    /// `ri`
65    SetRenderingIntent(Name),
66    /// `i`
67    SetFlatness(f32),
68    /// `gs`
69    SetExtGState(Name),
70
71    // Path construction.
72    /// `m`
73    MoveTo(f32, f32),
74    /// `l`
75    LineTo(f32, f32),
76    /// `c`
77    CurveTo(f32, f32, f32, f32, f32, f32),
78    /// `v` (first control point = current point)
79    CurveToV(f32, f32, f32, f32),
80    /// `y` (second control point = end point)
81    CurveToY(f32, f32, f32, f32),
82    /// `h`
83    ClosePath,
84    /// `re` (x, y, width, height)
85    Rect(f32, f32, f32, f32),
86
87    // Path painting.
88    /// `S`
89    Stroke,
90    /// `s`
91    CloseStroke,
92    /// `f` / `F`
93    Fill,
94    /// `f*`
95    FillEvenOdd,
96    /// `B`
97    FillStroke,
98    /// `B*`
99    FillStrokeEvenOdd,
100    /// `b`
101    CloseFillStroke,
102    /// `b*`
103    CloseFillStrokeEvenOdd,
104    /// `n`
105    EndPath,
106    /// `W`
107    ClipNonZero,
108    /// `W*`
109    ClipEvenOdd,
110
111    // Color.
112    /// `CS`
113    SetStrokeColorSpace(Name),
114    /// `cs`
115    SetFillColorSpace(Name),
116    /// `SC`
117    SetStrokeColor(Vec<f32>),
118    /// `SCN` (components, optional pattern name)
119    SetStrokeColorN(Vec<f32>, Option<Name>),
120    /// `sc`
121    SetFillColor(Vec<f32>),
122    /// `scn` (components, optional pattern name)
123    SetFillColorN(Vec<f32>, Option<Name>),
124    /// `G`
125    SetStrokeGray(f32),
126    /// `g`
127    SetFillGray(f32),
128    /// `RG`
129    SetStrokeRGB(f32, f32, f32),
130    /// `rg`
131    SetFillRGB(f32, f32, f32),
132    /// `K`
133    SetStrokeCMYK(f32, f32, f32, f32),
134    /// `k`
135    SetFillCMYK(f32, f32, f32, f32),
136
137    // Text.
138    /// `BT`
139    BeginText,
140    /// `ET`
141    EndText,
142    /// `Tc`
143    SetCharSpacing(f32),
144    /// `Tw`
145    SetWordSpacing(f32),
146    /// `Tz`
147    SetHorizScaling(f32),
148    /// `TL`
149    SetLeading(f32),
150    /// `Tf` (font resource name, size)
151    SetFont(Name, f32),
152    /// `d0` (wx, wy): sets the glyph width for a colored Type3 glyph,
153    /// whose content sets its own color (ISO 32000-1 Table 113).
154    SetGlyphWidth(f32, f32),
155    /// `d1` (wx, wy, llx, lly, urx, ury): sets the glyph width and bounding
156    /// box for an uncolored Type3 glyph description; color comes from the
157    /// text state and color operators in the proc are ignored
158    /// (ISO 32000-1 Table 113).
159    SetGlyphWidthBBox(f32, f32, f32, f32, f32, f32),
160    /// `Tr`
161    SetTextRender(i32),
162    /// `Ts`
163    SetTextRise(f32),
164    /// `Td`
165    TextMove(f32, f32),
166    /// `TD`
167    TextMoveSetLeading(f32, f32),
168    /// `Tm`
169    SetTextMatrix(Matrix),
170    /// `T*`
171    TextNextLine,
172    /// `Tj`
173    ShowText(Vec<u8>),
174    /// `TJ`
175    ShowTextAdjusted(Vec<TextItem>),
176    /// `'`
177    NextLineShowText(Vec<u8>),
178    /// `"` (word spacing, char spacing, string)
179    NextLineShowTextSpaced(f32, f32, Vec<u8>),
180
181    // XObjects, images, shading, marked content.
182    /// `Do`
183    XObject(Name),
184    /// `BI ... ID ... EI`
185    InlineImage(ImageParams),
186    /// `sh`
187    Shading(Name),
188    /// `MP`
189    MarkedContentPoint(Name),
190    /// `DP` (tag, properties: inline dict or resource name)
191    MarkedContentPointProps(Name, Object),
192    /// `BMC`
193    BeginMarkedContent(Name),
194    /// `BDC` (tag, properties: inline dict or resource name)
195    BeginMarkedContentProps(Name, Object),
196    /// `EMC`
197    EndMarkedContent,
198    /// `BX`
199    BeginCompat,
200    /// `EX`
201    EndCompat,
202}
203
204/// Parses a decoded content stream into a sequence of operators. Inline
205/// image data runs from after `ID` plus one whitespace byte to `EI` at a
206/// token boundary (or the declared `/L`ength when present, which is
207/// trusted).
208///
209/// Covers ISO 32000-1 §7.8.2.
210pub fn parse_content(data: &[u8]) -> Result<Vec<Op>> {
211    let mut ops = Vec::with_capacity(ops_estimate(data.len()));
212    parse_content_ops(data, |op, _| ops.push(op))?;
213    Ok(ops)
214}
215
216/// Like [`parse_content`], but also reports each operator's byte range —
217/// from the first token of its operand run through the operator keyword —
218/// within `data`.
219pub fn parse_content_spanned(data: &[u8]) -> Result<Vec<(Op, Span)>> {
220    let mut ops = Vec::with_capacity(ops_estimate(data.len()));
221    parse_content_ops(data, |op, span| ops.push((op, span)))?;
222    Ok(ops)
223}
224
225/// Initial operator-vector capacity for a content stream of `len` bytes.
226/// An operator run (operands, keyword, separators) averages well above 16
227/// bytes, so `len / 16` reserves slightly high instead of growing; the cap
228/// keeps a huge stream — usually mostly inline-image data — from
229/// pre-claiming space for operators it may never produce.
230fn ops_estimate(len: usize) -> usize {
231    (len / 16).min(1 << 17)
232}
233
234/// The parse loop behind both public entry points, as a wrapper over the
235/// pull parser: each finished operator is handed to `emit` — so the
236/// span-less caller never materializes spans it will throw away.
237fn parse_content_ops(data: &[u8], mut emit: impl FnMut(Op, Span)) -> Result<()> {
238    let mut ops = ContentOps::new(data);
239    while let Some((op, span)) = ops.next_op()? {
240        emit(op, span);
241    }
242    Ok(())
243}
244
245/// A pull parser over one content stream: each [`ContentOps::next_op`]
246/// yields the next operator with its byte range, in stream order — an
247/// executor consumes operators one at a time without materializing the
248/// whole vector.
249pub struct ContentOps<'a> {
250    lexer: Lexer<'a>,
251    stack: Vec<Object>,
252    /// Start of the current operand run; cleared whenever the run dies
253    /// (an operator was emitted, an unknown operator dropped it, or a
254    /// stray closer flushed it).
255    run_start: Option<usize>,
256}
257
258impl<'a> ContentOps<'a> {
259    /// Starts a pull parse at the beginning of `data`.
260    pub fn new(data: &'a [u8]) -> ContentOps<'a> {
261        ContentOps::at(data, 0)
262    }
263
264    /// Resumes a pull parse at byte offset `pos`. The operand stack is
265    /// empty at every operator boundary, so the offset [`ContentOps::pos`]
266    /// reported between two `next_op` calls is the parser's whole state —
267    /// an executor that suspends a stream mid-walk (a form invocation)
268    /// rebuilds from it exactly.
269    pub fn at(data: &'a [u8], pos: usize) -> ContentOps<'a> {
270        ContentOps {
271            lexer: Lexer::at(data, pos),
272            stack: Vec::new(),
273            run_start: None,
274        }
275    }
276
277    /// The cursor's byte offset — a resume point between `next_op` calls.
278    pub fn pos(&self) -> usize {
279        self.lexer.pos()
280    }
281
282    /// Parses forward to the next complete operator and returns it with
283    /// its span, or `None` at the end of the stream.
284    ///
285    /// Covers ISO 32000-1 §7.8.2.
286    pub fn next_op(&mut self) -> Result<Option<(Op, Span)>> {
287        loop {
288            let (token_start, raw) = self.lexer.next_raw_token_spanned()?;
289            let kw = match raw {
290                RawToken::Keyword(kw) => {
291                    if self.run_start.is_none() {
292                        self.run_start = Some(token_start);
293                    }
294                    kw
295                }
296                RawToken::Hex(span) => {
297                    if self.run_start.is_none() {
298                        self.run_start = Some(token_start);
299                    }
300                    self.stack.push(Object::String(decode_hex(span)));
301                    continue;
302                }
303                RawToken::Owned(token) => {
304                    if !matches!(token, Token::Eof) && self.run_start.is_none() {
305                        self.run_start = Some(token_start);
306                    }
307                    match token {
308                        Token::Eof => return Ok(None),
309                        Token::Int(i) => self.stack.push(Object::Int(i)),
310                        Token::Real(r) => self.stack.push(Object::Real(r)),
311                        Token::Name(n) => self.stack.push(Object::Name(n)),
312                        Token::LitString(s) | Token::HexString(s) => {
313                            self.stack.push(Object::String(s))
314                        }
315                        Token::ArrayOpen => {
316                            let a = parse_array(&mut self.lexer, 0)?;
317                            self.stack.push(a);
318                        }
319                        Token::DictOpen => {
320                            let d = parse_dict(&mut self.lexer, 0)?;
321                            self.stack.push(Object::Dict(d));
322                        }
323                        // Stray closers: malformed input, drop pending operands.
324                        Token::ArrayClose | Token::DictClose => {
325                            self.stack.clear();
326                            self.run_start = None;
327                        }
328                        Token::Keyword(_) => {}
329                    }
330                    continue;
331                }
332            };
333            match kw {
334                b"true" => self.stack.push(Object::Bool(true)),
335                b"false" => self.stack.push(Object::Bool(false)),
336                b"null" => self.stack.push(Object::Null),
337                b"BI" => {
338                    let start = self.run_start.take().unwrap_or(token_start);
339                    let image = parse_inline_image(&mut self.lexer);
340                    self.stack.clear();
341                    if let Some(op) = image {
342                        let span = Span::new(start as u64, self.lexer.pos() as u64);
343                        return Ok(Some((op, span)));
344                    }
345                }
346                _ => {
347                    let start = self.run_start.take().unwrap_or(token_start);
348                    let op = dispatch(kw, &mut self.stack);
349                    self.stack.clear();
350                    if let Some(op) = op {
351                        let span = Span::new(start as u64, self.lexer.pos() as u64);
352                        return Ok(Some((op, span)));
353                    }
354                }
355            }
356        }
357    }
358}
359
360/// Composes an array value; the opening `[` has already been consumed.
361/// Unexpected tokens inside are skipped leniently; nesting deeper than
362/// `MAX_NESTING_DEPTH` is a syntax error.
363fn parse_array(lexer: &mut Lexer, depth: usize) -> Result<Object> {
364    if depth >= MAX_NESTING_DEPTH {
365        return Err(too_deep(lexer));
366    }
367    let mut items = Vec::new();
368    loop {
369        match lexer.next_raw_token()? {
370            RawToken::Owned(Token::ArrayClose | Token::Eof) => break,
371            raw => {
372                if let Some(v) = compose_raw_value(lexer, raw, depth)? {
373                    items.push(v);
374                }
375            }
376        }
377    }
378    Ok(Object::Array(items))
379}
380
381/// Numeric coercion for operands: `Int` and `Real` both become `f32`.
382fn num(o: &Object) -> Option<f32> {
383    match o {
384        Object::Int(i) => Some(*i as f32),
385        Object::Real(r) => Some(*r as f32),
386        _ => None,
387    }
388}
389
390/// The last `N` operands as numbers, or `None` on arity/type mismatch.
391fn nums<const N: usize>(stack: &[Object]) -> Option<[f32; N]> {
392    if stack.len() < N {
393        return None;
394    }
395    let tail = &stack[stack.len() - N..];
396    let mut out = [0.0f32; N];
397    for (slot, o) in out.iter_mut().zip(tail) {
398        *slot = num(o)?;
399    }
400    Some(out)
401}
402
403/// The last operand as an integer (`Real` truncated leniently).
404fn int1(stack: &[Object]) -> Option<i32> {
405    match stack.last()? {
406        Object::Int(i) => Some(*i as i32),
407        Object::Real(r) => Some(*r as i32),
408        _ => None,
409    }
410}
411
412/// The last operand as a name, taken off the stack: the caller clears the
413/// stack after every dispatch, so operands are moved out, never cloned.
414fn name1(stack: &mut [Object]) -> Option<Name> {
415    match stack.last_mut()? {
416        Object::Name(n) => Some(Name(std::mem::take(&mut n.0))),
417        _ => None,
418    }
419}
420
421/// The last operand as a string's bytes, taken off the stack like [`name1`].
422fn str1(stack: &mut [Object]) -> Option<Vec<u8>> {
423    match stack.last_mut()? {
424        Object::String(s) => Some(std::mem::take(s)),
425        _ => None,
426    }
427}
428
429/// Every operand on the stack as a number (for `SC`/`sc`).
430fn all_nums(stack: &[Object]) -> Option<Vec<f32>> {
431    stack.iter().map(num).collect()
432}
433
434/// A six-number tail as a [`Matrix`] (for `cm`/`Tm`).
435fn matrix(stack: &[Object]) -> Option<Matrix> {
436    let [a, b, c, d, e, f] = nums::<6>(stack)?;
437    Some(Matrix { a, b, c, d, e, f })
438}
439
440/// Composes a dictionary; the opening `<<` has already been consumed.
441/// Nesting deeper than `MAX_NESTING_DEPTH` is a syntax error.
442fn parse_dict(lexer: &mut Lexer, depth: usize) -> Result<Dict> {
443    if depth >= MAX_NESTING_DEPTH {
444        return Err(too_deep(lexer));
445    }
446    let mut dict = Dict::new();
447    loop {
448        match lexer.next_raw_token()? {
449            RawToken::Owned(Token::DictClose | Token::Eof) => break,
450            RawToken::Owned(Token::Name(key)) => {
451                let raw = lexer.next_raw_token()?;
452                if matches!(raw, RawToken::Owned(Token::DictClose | Token::Eof)) {
453                    // Key with no value: drop it.
454                    break;
455                }
456                if let Some(v) = compose_raw_value(lexer, raw, depth)? {
457                    dict.insert(key, v);
458                }
459            }
460            // Non-name key: malformed, skip the token.
461            _ => {}
462        }
463    }
464    Ok(dict)
465}
466
467/// Maps an operator keyword plus its operand stack to a typed [`Op`].
468/// Returns `None` (operator skipped) for unknown keywords or operand
469/// arity/type mismatches.
470///
471/// The stack is dispatch's to consume — the caller clears it after every
472/// keyword — so heap operands (strings, names) are moved into the `Op`
473/// rather than cloned, and a mismatch may leave the stack partially
474/// emptied.
475///
476/// Covers ISO 32000-1 §8.2, §8.4.4, §8.5.2.1, §8.6.5.8 and Annex A.2.
477fn dispatch(kw: &[u8], stack: &mut [Object]) -> Option<Op> {
478    Some(match kw {
479        // Graphics state.
480        b"q" => Op::Save,
481        b"Q" => Op::Restore,
482        b"cm" => Op::Concat(matrix(stack)?),
483        b"w" => Op::SetLineWidth(nums::<1>(stack)?[0]),
484        b"J" => Op::SetLineCap(int1(stack)?),
485        b"j" => Op::SetLineJoin(int1(stack)?),
486        b"M" => Op::SetMiterLimit(nums::<1>(stack)?[0]),
487        b"d" => {
488            if stack.len() < 2 {
489                return None;
490            }
491            let phase = num(&stack[stack.len() - 1])?;
492            let Object::Array(items) = &stack[stack.len() - 2] else {
493                return None;
494            };
495            let dashes: Vec<f32> = items.iter().map(num).collect::<Option<_>>()?;
496            Op::SetDash(dashes, phase)
497        }
498        b"ri" => Op::SetRenderingIntent(name1(stack)?),
499        b"i" => Op::SetFlatness(nums::<1>(stack)?[0]),
500        b"gs" => Op::SetExtGState(name1(stack)?),
501
502        // Path construction.
503        b"m" => {
504            let [x, y] = nums(stack)?;
505            Op::MoveTo(x, y)
506        }
507        b"l" => {
508            let [x, y] = nums(stack)?;
509            Op::LineTo(x, y)
510        }
511        b"c" => {
512            let [x1, y1, x2, y2, x3, y3] = nums(stack)?;
513            Op::CurveTo(x1, y1, x2, y2, x3, y3)
514        }
515        b"v" => {
516            let [x2, y2, x3, y3] = nums(stack)?;
517            Op::CurveToV(x2, y2, x3, y3)
518        }
519        b"y" => {
520            let [x1, y1, x3, y3] = nums(stack)?;
521            Op::CurveToY(x1, y1, x3, y3)
522        }
523        b"h" => Op::ClosePath,
524        b"re" => {
525            let [x, y, w, h] = nums(stack)?;
526            Op::Rect(x, y, w, h)
527        }
528
529        // Path painting and clipping.
530        b"S" => Op::Stroke,
531        b"s" => Op::CloseStroke,
532        b"f" | b"F" => Op::Fill,
533        b"f*" => Op::FillEvenOdd,
534        b"B" => Op::FillStroke,
535        b"B*" => Op::FillStrokeEvenOdd,
536        b"b" => Op::CloseFillStroke,
537        b"b*" => Op::CloseFillStrokeEvenOdd,
538        b"n" => Op::EndPath,
539        b"W" => Op::ClipNonZero,
540        b"W*" => Op::ClipEvenOdd,
541
542        _ => return dispatch_color_text(kw, stack),
543    })
544}
545
546/// Continuation of [`dispatch`]: color and text operators.
547///
548/// Covers ISO 32000-1 §8.6.8, §9.2.2, §9.3.2, §9.4.2, §9.4.3 and Annex A.2.
549fn dispatch_color_text(kw: &[u8], stack: &mut [Object]) -> Option<Op> {
550    Some(match kw {
551        // Color.
552        b"CS" => Op::SetStrokeColorSpace(name1(stack)?),
553        b"cs" => Op::SetFillColorSpace(name1(stack)?),
554        b"SC" => Op::SetStrokeColor(all_nums(stack)?),
555        b"sc" => Op::SetFillColor(all_nums(stack)?),
556        b"SCN" => {
557            let (comps, pattern) = color_n(stack)?;
558            Op::SetStrokeColorN(comps, pattern)
559        }
560        b"scn" => {
561            let (comps, pattern) = color_n(stack)?;
562            Op::SetFillColorN(comps, pattern)
563        }
564        b"G" => Op::SetStrokeGray(nums::<1>(stack)?[0]),
565        b"g" => Op::SetFillGray(nums::<1>(stack)?[0]),
566        b"RG" => {
567            let [r, g, b] = nums(stack)?;
568            Op::SetStrokeRGB(r, g, b)
569        }
570        b"rg" => {
571            let [r, g, b] = nums(stack)?;
572            Op::SetFillRGB(r, g, b)
573        }
574        b"K" => {
575            let [c, m, y, k] = nums(stack)?;
576            Op::SetStrokeCMYK(c, m, y, k)
577        }
578        b"k" => {
579            let [c, m, y, k] = nums(stack)?;
580            Op::SetFillCMYK(c, m, y, k)
581        }
582
583        // Text.
584        b"BT" => Op::BeginText,
585        b"ET" => Op::EndText,
586        b"Tc" => Op::SetCharSpacing(nums::<1>(stack)?[0]),
587        b"Tw" => Op::SetWordSpacing(nums::<1>(stack)?[0]),
588        b"Tz" => Op::SetHorizScaling(nums::<1>(stack)?[0]),
589        b"TL" => Op::SetLeading(nums::<1>(stack)?[0]),
590        b"Tf" => {
591            if stack.len() < 2 {
592                return None;
593            }
594            let size = num(&stack[stack.len() - 1])?;
595            let at = stack.len() - 2;
596            let Object::Name(font) = &mut stack[at] else {
597                return None;
598            };
599            Op::SetFont(Name(std::mem::take(&mut font.0)), size)
600        }
601        b"d0" => {
602            let [wx, wy] = nums::<2>(stack)?;
603            Op::SetGlyphWidth(wx, wy)
604        }
605        b"d1" => {
606            let [wx, wy, llx, lly, urx, ury] = nums::<6>(stack)?;
607            Op::SetGlyphWidthBBox(wx, wy, llx, lly, urx, ury)
608        }
609        b"Tr" => Op::SetTextRender(int1(stack)?),
610        b"Ts" => Op::SetTextRise(nums::<1>(stack)?[0]),
611        b"Td" => {
612            let [tx, ty] = nums(stack)?;
613            Op::TextMove(tx, ty)
614        }
615        b"TD" => {
616            let [tx, ty] = nums(stack)?;
617            Op::TextMoveSetLeading(tx, ty)
618        }
619        b"Tm" => Op::SetTextMatrix(matrix(stack)?),
620        b"T*" => Op::TextNextLine,
621        b"Tj" => Op::ShowText(str1(stack)?),
622        b"TJ" => {
623            let Object::Array(items) = stack.last_mut()? else {
624                return None;
625            };
626            let mut adjusted = Vec::with_capacity(items.len());
627            adjusted.extend(items.iter_mut().filter_map(|o| match o {
628                Object::String(s) => Some(TextItem::Str(std::mem::take(s))),
629                other => num(other).map(TextItem::Offset),
630            }));
631            Op::ShowTextAdjusted(adjusted)
632        }
633        b"'" => Op::NextLineShowText(str1(stack)?),
634        b"\"" => {
635            if stack.len() < 3 {
636                return None;
637            }
638            let s = str1(stack)?;
639            let [aw, ac] = nums_at::<2>(stack, stack.len() - 3)?;
640            Op::NextLineShowTextSpaced(aw, ac, s)
641        }
642
643        _ => return dispatch_misc(kw, stack),
644    })
645}
646
647/// Continuation of [`dispatch`]: XObject, shading, marked-content, and
648/// compatibility operators.
649///
650/// Covers ISO 32000-1 §14.6.1 and §8.8.1.
651fn dispatch_misc(kw: &[u8], stack: &mut [Object]) -> Option<Op> {
652    Some(match kw {
653        b"Do" => Op::XObject(name1(stack)?),
654        b"sh" => Op::Shading(name1(stack)?),
655        b"MP" => Op::MarkedContentPoint(name1(stack)?),
656        b"DP" => {
657            let (tag, props) = tag_props(stack)?;
658            Op::MarkedContentPointProps(tag, props)
659        }
660        b"BMC" => Op::BeginMarkedContent(name1(stack)?),
661        b"BDC" => {
662            let (tag, props) = tag_props(stack)?;
663            Op::BeginMarkedContentProps(tag, props)
664        }
665        b"EMC" => Op::EndMarkedContent,
666        b"BX" => Op::BeginCompat,
667        b"EX" => Op::EndCompat,
668        _ => return None,
669    })
670}
671
672/// `N` numbers starting at `start` (for operators whose numeric operands
673/// are not last on the stack).
674fn nums_at<const N: usize>(stack: &[Object], start: usize) -> Option<[f32; N]> {
675    let slice = stack.get(start..start + N)?;
676    let mut out = [0.0f32; N];
677    for (slot, o) in out.iter_mut().zip(slice) {
678        *slot = num(o)?;
679    }
680    Some(out)
681}
682
683/// Operands of `SCN`/`scn`: numeric components optionally followed by a
684/// pattern name (taken off the stack like [`name1`]).
685fn color_n(stack: &mut [Object]) -> Option<(Vec<f32>, Option<Name>)> {
686    match stack.last_mut() {
687        Some(Object::Name(n)) => {
688            let pattern = Name(std::mem::take(&mut n.0));
689            let comps = all_nums(&stack[..stack.len() - 1])?;
690            Some((comps, Some(pattern)))
691        }
692        _ => Some((all_nums(stack)?, None)),
693    }
694}
695
696/// Operands of `DP`/`BDC`: a tag name and a properties value (an inline
697/// dictionary or a resource name), both taken off the stack like [`name1`].
698fn tag_props(stack: &mut [Object]) -> Option<(Name, Object)> {
699    if stack.len() < 2 {
700        return None;
701    }
702    let last = stack.len() - 1;
703    let props = match &stack[last] {
704        Object::Dict(_) | Object::Name(_) => std::mem::replace(&mut stack[last], Object::Null),
705        _ => return None,
706    };
707    let Object::Name(tag) = &mut stack[last - 1] else {
708        return None;
709    };
710    Some((Name(std::mem::take(&mut tag.0)), props))
711}
712
713/// Parses an inline image; the `BI` keyword has already been consumed.
714/// Returns `None` (image skipped) when the stream ends before `ID` or no
715/// `EI` terminator can be located.
716///
717/// Covers ISO 32000-1 §8.9.7.
718fn parse_inline_image(lexer: &mut Lexer) -> Option<Op> {
719    let mut dict = Dict::new();
720    loop {
721        match lexer.next_token().ok()? {
722            Token::Keyword(kw) if kw == b"ID" => break,
723            Token::Eof => return None,
724            Token::Name(key) => {
725                let tok = lexer.next_token().ok()?;
726                if matches!(tok, Token::Eof) {
727                    return None;
728                }
729                let Some(value) = compose_value(lexer, tok, 0).ok()? else {
730                    continue;
731                };
732                let canon = expand_image_key(&key.0);
733                let value = if canon == "ColorSpace" {
734                    expand_colorspace(value)
735                } else {
736                    value
737                };
738                dict.insert(Name(canon.to_string()), value);
739            }
740            // Malformed entry: skip the stray token.
741            _ => {}
742        }
743    }
744    let bytes = lexer.data();
745    let mut start = lexer.pos();
746    // Exactly one whitespace byte separates `ID` from the image data.
747    if bytes.get(start).is_some_and(|&b| is_whitespace(b)) {
748        start += 1;
749    }
750    let declared = dict.get_int("Length").or_else(|| dict.get_int("L"));
751    let data = if let Some(n) = declared.and_then(|n| usize::try_from(n).ok()) {
752        // A declared length is trusted.
753        let end = (start + n).min(bytes.len());
754        lexer.seek(end);
755        bytes[start..end].to_vec()
756    } else {
757        let Some((end, ei)) = inline_data_end(bytes, start, &dict) else {
758            // No terminator anywhere: drop the image and stop lexing what
759            // can only be binary garbage.
760            lexer.seek(bytes.len());
761            return None;
762        };
763        lexer.seek(ei);
764        bytes[start..end].to_vec()
765    };
766    consume_ei(lexer);
767    Some(Op::InlineImage(ImageParams { dict, data }))
768}
769
770/// Operators that may legitimately follow an inline image.
771const OPERATORS: &[&[u8]] = &[
772    b"q", b"Q", b"cm", b"w", b"J", b"j", b"M", b"d", b"ri", b"i", b"gs", b"m", b"l", b"c", b"v",
773    b"y", b"h", b"re", b"S", b"s", b"f", b"F", b"f*", b"B", b"B*", b"b", b"b*", b"n", b"W", b"W*",
774    b"CS", b"cs", b"SC", b"sc", b"SCN", b"scn", b"G", b"g", b"RG", b"rg", b"K", b"k", b"BT", b"ET",
775    b"Tc", b"Tw", b"Tz", b"TL", b"Tf", b"d0", b"d1", b"Tr", b"Ts", b"Td", b"TD", b"Tm", b"T*",
776    b"Tj", b"TJ", b"'", b"\"", b"Do", b"sh", b"MP", b"DP", b"BMC", b"BDC", b"EMC", b"BX", b"EX",
777];
778
779/// Operators that must follow a candidate `EI` before it is believed.
780const EI_CONFIRMING_OPERATORS: usize = 3;
781
782/// Tokens examined after a candidate `EI`.
783const EI_LOOKAHEAD_TOKENS: usize = 32;
784
785/// Component count of an inline image colour space, when the dictionary
786/// alone determines it.
787fn inline_components(dict: &Dict) -> Option<u64> {
788    let by_name = |n: &str| match n {
789        "DeviceGray" | "CalGray" => Some(1),
790        "DeviceRGB" | "CalRGB" | "Lab" => Some(3),
791        "DeviceCMYK" => Some(4),
792        _ => None,
793    };
794    match dict.get("ColorSpace")? {
795        Object::Name(n) => by_name(&n.0),
796        Object::Array(items) => match items.first()? {
797            Object::Name(n) if n.0 == "Indexed" => Some(1),
798            Object::Name(n) => by_name(&n.0),
799            _ => None,
800        },
801        _ => None,
802    }
803}
804
805/// Byte length of an unfiltered inline image payload, when the
806/// dictionary determines it.
807fn inline_payload_len(dict: &Dict) -> Option<usize> {
808    if dict.get("Filter").is_some() {
809        return None;
810    }
811    let width = u64::try_from(dict.get_int("Width")?).ok()?;
812    let height = u64::try_from(dict.get_int("Height")?).ok()?;
813    let (components, bpc) = if dict.get("ImageMask") == Some(&Object::Bool(true)) {
814        (1, 1)
815    } else {
816        let bpc = u64::try_from(dict.get_int("BitsPerComponent")?).ok()?;
817        (inline_components(dict)?, bpc)
818    };
819    let row = width.checked_mul(components)?.checked_mul(bpc)?.div_ceil(8);
820    usize::try_from(row.checked_mul(height)?).ok()
821}
822
823/// End of the image data and the offset of its `EI`. The length computed
824/// from the dictionary is tried first; otherwise the first `EI` followed
825/// by plausible content wins, then the first bare `EI`.
826fn inline_data_end(bytes: &[u8], start: usize, dict: &Dict) -> Option<(usize, usize)> {
827    if let Some(len) = inline_payload_len(dict) {
828        let end = start.checked_add(len)?;
829        let mut at = end;
830        while bytes.get(at).is_some_and(|&b| is_whitespace(b)) {
831            at += 1;
832        }
833        if end <= bytes.len() && ei_at(bytes, at) && ei_followed_by_content(bytes, at + 2) {
834            return Some((end, at));
835        }
836    }
837    let ei = find_ei(bytes, start)?;
838    let end = if ei > start && is_whitespace(bytes[ei - 1]) {
839        ei - 1
840    } else {
841        ei
842    };
843    Some((end, ei))
844}
845
846fn ei_at(bytes: &[u8], p: usize) -> bool {
847    if bytes.get(p) != Some(&b'E') || bytes.get(p + 1) != Some(&b'I') {
848        return false;
849    }
850    match bytes.get(p + 2) {
851        None => true,
852        Some(&b) => !crate::lexer::is_regular(b),
853    }
854}
855
856/// Whether the bytes at `after` read as content-stream operands and
857/// operators for a short window.
858fn ei_followed_by_content(bytes: &[u8], after: usize) -> bool {
859    let mut lexer = Lexer::at(bytes, after);
860    let mut operators = 0;
861    let mut depth = 0usize;
862    for _ in 0..EI_LOOKAHEAD_TOKENS {
863        let Ok(raw) = lexer.next_raw_token() else {
864            return false;
865        };
866        match raw {
867            RawToken::Hex(_) => {}
868            RawToken::Owned(Token::Eof) => return true,
869            RawToken::Owned(Token::LitString(_)) => {
870                let terminated = lexer.pos() < bytes.len() || bytes[lexer.pos() - 1] == b')';
871                if !terminated {
872                    return false;
873                }
874            }
875            RawToken::Owned(Token::ArrayOpen | Token::DictOpen) => depth += 1,
876            RawToken::Owned(Token::ArrayClose | Token::DictClose) => {
877                if depth == 0 {
878                    return false;
879                }
880                depth -= 1;
881            }
882            RawToken::Owned(_) => {}
883            RawToken::Keyword(b"true" | b"false" | b"null") => {}
884            RawToken::Keyword(b"BI") => return true,
885            RawToken::Keyword(kw) => {
886                if !OPERATORS.contains(&kw) {
887                    return false;
888                }
889                operators += 1;
890                if operators >= EI_CONFIRMING_OPERATORS {
891                    return true;
892                }
893            }
894        }
895    }
896    true
897}
898
899/// Finds the offset of an `EI` terminator at a token boundary: preceded
900/// by whitespace (or the data start) and followed by a non-regular byte
901/// or end of input. The first candidate whose following bytes read as
902/// content wins; when none does, the first candidate.
903fn find_ei(bytes: &[u8], start: usize) -> Option<usize> {
904    let mut from = start;
905    let mut first = None;
906    while let Some(off) = memchr::memchr(b'E', &bytes[from..]) {
907        let p = from + off;
908        from = p + 1;
909        if !ei_at(bytes, p) || !(p == start || is_whitespace(bytes[p - 1])) {
910            continue;
911        }
912        if ei_followed_by_content(bytes, p + 2) {
913            return Some(p);
914        }
915        first = first.or(Some(p));
916    }
917    first
918}
919
920/// Consumes the `EI` keyword after inline image data, scanning forward
921/// leniently if the very next token is something else.
922fn consume_ei(lexer: &mut Lexer) {
923    let save = lexer.pos();
924    if let Ok(Token::Keyword(kw)) = lexer.next_token() {
925        if kw == b"EI" {
926            return;
927        }
928    }
929    match find_ei(lexer.data(), save) {
930        Some(p) => lexer.seek(p + 2),
931        None => lexer.seek(lexer.data().len()),
932    }
933}
934
935/// Canonical spelling of an inline image dictionary key (ISO 32000
936/// §8.9.7, Table 91).
937///
938/// Covers ISO 32000-1 §8.9.7.
939fn expand_image_key(key: &str) -> &str {
940    match key {
941        "BPC" => "BitsPerComponent",
942        "CS" => "ColorSpace",
943        "D" => "Decode",
944        "DP" => "DecodeParms",
945        "F" => "Filter",
946        "H" => "Height",
947        "W" => "Width",
948        "IM" => "ImageMask",
949        "I" => "Interpolate",
950        other => other,
951    }
952}
953
954/// Expands colorspace name abbreviations inside a `/CS` value, including
955/// names nested in an `Indexed` array.
956fn expand_colorspace(value: Object) -> Object {
957    match value {
958        Object::Name(Name(n)) => Object::Name(Name(match n.as_str() {
959            "G" => "DeviceGray".to_string(),
960            "RGB" => "DeviceRGB".to_string(),
961            "CMYK" => "DeviceCMYK".to_string(),
962            "I" => "Indexed".to_string(),
963            _ => n,
964        })),
965        Object::Array(items) => Object::Array(items.into_iter().map(expand_colorspace).collect()),
966        other => other,
967    }
968}
969
970/// [`compose_value`] over a raw token: a borrowed keyword matches the
971/// three value keywords without the copy [`Lexer::next_token`] would
972/// make, and a hex span decodes straight to its string bytes.
973fn compose_raw_value(lexer: &mut Lexer, raw: RawToken, depth: usize) -> Result<Option<Object>> {
974    match raw {
975        RawToken::Owned(tok) => compose_value(lexer, tok, depth),
976        RawToken::Keyword(kw) => Ok(match kw {
977            b"true" => Some(Object::Bool(true)),
978            b"false" => Some(Object::Bool(false)),
979            b"null" => Some(Object::Null),
980            _ => None,
981        }),
982        RawToken::Hex(span) => Ok(Some(Object::String(decode_hex(span)))),
983    }
984}
985
986/// Turns a leading token into an [`Object`], recursing for containers
987/// (bounded by `MAX_NESTING_DEPTH`). Returns `None` for tokens that
988/// carry no value (stray delimiters, unexpected keywords).
989fn compose_value(lexer: &mut Lexer, tok: Token, depth: usize) -> Result<Option<Object>> {
990    Ok(match tok {
991        Token::Int(i) => Some(Object::Int(i)),
992        Token::Real(r) => Some(Object::Real(r)),
993        Token::Name(n) => Some(Object::Name(n)),
994        Token::LitString(s) | Token::HexString(s) => Some(Object::String(s)),
995        Token::ArrayOpen => Some(parse_array(lexer, depth + 1)?),
996        Token::DictOpen => Some(Object::Dict(parse_dict(lexer, depth + 1)?)),
997        Token::Keyword(kw) => match kw.as_slice() {
998            b"true" => Some(Object::Bool(true)),
999            b"false" => Some(Object::Bool(false)),
1000            b"null" => Some(Object::Null),
1001            _ => None,
1002        },
1003        _ => None,
1004    })
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use super::*;
1010
1011    fn ops(src: &[u8]) -> Vec<Op> {
1012        parse_content(src).expect("content parses")
1013    }
1014
1015    fn name(s: &str) -> Name {
1016        Name(s.to_string())
1017    }
1018
1019    // Covers ISO 32000-1 §7.8.2, §8.2 and Annex A.2.
1020    #[test]
1021    fn shapes_fixture_parses_to_expected_ops() {
1022        let path = concat!(
1023            env!("CARGO_MANIFEST_DIR"),
1024            "/../../tests/fixtures/shapes.pdf"
1025        );
1026        let doc = crate::document::Document::open(path).expect("open shapes.pdf");
1027        let page = doc.page(0).expect("page 0");
1028        let content = page.content(&doc).expect("page content");
1029        let got = ops(&content);
1030        let m = |a, b, c, d, e, f| Matrix { a, b, c, d, e, f };
1031        assert_eq!(
1032            got,
1033            vec![
1034                Op::SetFillRGB(1.0, 0.0, 0.0),
1035                Op::Rect(72.0, 600.0, 100.0, 80.0),
1036                Op::Fill,
1037                Op::SetFillRGB(0.0, 0.5, 1.0),
1038                Op::Rect(200.0, 600.0, 120.0, 60.0),
1039                Op::Fill,
1040                Op::SetFillRGB(0.2, 0.8, 0.2),
1041                Op::Rect(340.0, 590.0, 90.0, 90.0),
1042                Op::Fill,
1043                Op::SetStrokeRGB(0.0, 0.0, 0.0),
1044                Op::SetLineWidth(2.0),
1045                Op::MoveTo(100.0, 300.0),
1046                Op::CurveTo(150.0, 400.0, 250.0, 400.0, 300.0, 300.0),
1047                Op::Stroke,
1048                Op::Save,
1049                Op::Concat(m(0.5, 0.0, 0.0, 0.5, 300.0, 100.0)),
1050                Op::SetFillRGB(0.8, 0.0, 0.8),
1051                Op::Rect(0.0, 0.0, 200.0, 200.0),
1052                Op::Fill,
1053                Op::Restore,
1054            ]
1055        );
1056    }
1057
1058    // Covers ISO 32000-1 §8.3.2.3, §8.4.3.3, §8.4.3.4, §8.4.3.5, §8.4.4, §8.6.5.8 and Annex A.2.
1059    #[test]
1060    fn graphics_state_ops_round_trip() {
1061        let got = ops(b"q Q 1 0 0 1 10 20 cm 2 w 1 J 2 j 3.5 M [3 1] 0.5 d \
1062                        /Perceptual ri 1 i /GS1 gs");
1063        assert_eq!(
1064            got,
1065            vec![
1066                Op::Save,
1067                Op::Restore,
1068                Op::Concat(Matrix {
1069                    a: 1.0,
1070                    b: 0.0,
1071                    c: 0.0,
1072                    d: 1.0,
1073                    e: 10.0,
1074                    f: 20.0
1075                }),
1076                Op::SetLineWidth(2.0),
1077                Op::SetLineCap(1),
1078                Op::SetLineJoin(2),
1079                Op::SetMiterLimit(3.5),
1080                Op::SetDash(vec![3.0, 1.0], 0.5),
1081                Op::SetRenderingIntent(name("Perceptual")),
1082                Op::SetFlatness(1.0),
1083                Op::SetExtGState(name("GS1")),
1084            ]
1085        );
1086    }
1087
1088    // Covers ISO 32000-1 §8.4.3.6.
1089    #[test]
1090    fn empty_dash_array_round_trips() {
1091        assert_eq!(ops(b"[] 0 d"), vec![Op::SetDash(vec![], 0.0)]);
1092    }
1093
1094    // Covers ISO 32000-1 §8.5.2.1 and Annex A.2.
1095    #[test]
1096    fn path_ops_round_trip() {
1097        let got = ops(b"10 20 m 30 40 l 1 2 3 4 5 6 c 1 2 3 4 v 5 6 7 8 y h \
1098                        72 600 100 80 re");
1099        assert_eq!(
1100            got,
1101            vec![
1102                Op::MoveTo(10.0, 20.0),
1103                Op::LineTo(30.0, 40.0),
1104                Op::CurveTo(1.0, 2.0, 3.0, 4.0, 5.0, 6.0),
1105                Op::CurveToV(1.0, 2.0, 3.0, 4.0),
1106                Op::CurveToY(5.0, 6.0, 7.0, 8.0),
1107                Op::ClosePath,
1108                Op::Rect(72.0, 600.0, 100.0, 80.0),
1109            ]
1110        );
1111    }
1112
1113    #[test]
1114    fn negative_and_real_coordinates_coerce() {
1115        assert_eq!(
1116            ops(b"-1.5 +2 m .5 -3 l"),
1117            vec![Op::MoveTo(-1.5, 2.0), Op::LineTo(0.5, -3.0)]
1118        );
1119    }
1120
1121    // Covers ISO 32000-1 §14.6.1, §14.6.2, §8.2 and Annex A.2.
1122    #[test]
1123    fn xobject_shading_marked_content_round_trip() {
1124        let got = ops(b"/Im1 Do /Sh1 sh /Tag MP /Tag /P DP /Span BMC \
1125                        /Span << /MCID 3 >> BDC EMC BX EX");
1126        let mut props = Dict::new();
1127        props.insert(name("MCID"), Object::Int(3));
1128        assert_eq!(
1129            got,
1130            vec![
1131                Op::XObject(name("Im1")),
1132                Op::Shading(name("Sh1")),
1133                Op::MarkedContentPoint(name("Tag")),
1134                Op::MarkedContentPointProps(name("Tag"), Object::Name(name("P"))),
1135                Op::BeginMarkedContent(name("Span")),
1136                Op::BeginMarkedContentProps(name("Span"), Object::Dict(props)),
1137                Op::EndMarkedContent,
1138                Op::BeginCompat,
1139                Op::EndCompat,
1140            ]
1141        );
1142    }
1143
1144    // Covers ISO 32000-1 §7.8.2, §8.2, Annex A.2 and Annex I.
1145    #[test]
1146    fn unknown_operator_is_skipped_without_breaking_following_ops() {
1147        assert_eq!(
1148            ops(b"zz 1 2 10 20 m 30 40 l"),
1149            vec![Op::MoveTo(10.0, 20.0), Op::LineTo(30.0, 40.0)]
1150        );
1151        // Unknown operator with operands before it: operands are dropped.
1152        assert_eq!(ops(b"1 2 zz 3 4 l"), vec![Op::LineTo(3.0, 4.0)]);
1153    }
1154
1155    // Covers ISO 32000-1 §7.8.2.
1156    #[test]
1157    fn malformed_operands_are_skipped() {
1158        // Too few operands.
1159        assert_eq!(ops(b"1 m 5 6 l"), vec![Op::LineTo(5.0, 6.0)]);
1160        // Wrong operand types.
1161        assert_eq!(ops(b"(a) (b) m S"), vec![Op::Stroke]);
1162        assert_eq!(ops(b"/N w"), Vec::<Op>::new());
1163        assert_eq!(ops(b"5 Tf"), Vec::<Op>::new());
1164        // `TJ` whose operand is not an array.
1165        assert_eq!(ops(b"(x) TJ q"), vec![Op::Save]);
1166        // Non-string, non-number entries inside a `TJ` array are dropped.
1167        assert_eq!(
1168            ops(b"[(y) /Bad 5] TJ"),
1169            vec![Op::ShowTextAdjusted(vec![
1170                TextItem::Str(b"y".to_vec()),
1171                TextItem::Offset(5.0),
1172            ])]
1173        );
1174        // Dash without an array operand.
1175        assert_eq!(ops(b"3 0 d"), Vec::<Op>::new());
1176        // Extra operands: the trailing ones are used.
1177        assert_eq!(ops(b"9 9 1 2 m"), vec![Op::MoveTo(1.0, 2.0)]);
1178    }
1179
1180    // Covers ISO 32000-1 §7.8.2, §8.9.7 and Annex A.2.
1181    #[test]
1182    fn inline_image_with_hex_data_ending_in_ei() {
1183        let got = ops(b"q BI /W 2 /H 2 /BPC 8 /CS /G /F /AHx ID 00FF80FF> EI Q");
1184        assert_eq!(got.len(), 3);
1185        assert_eq!(got[0], Op::Save);
1186        assert_eq!(got[2], Op::Restore);
1187        let Op::InlineImage(img) = &got[1] else {
1188            panic!("expected inline image, got {:?}", got[1]);
1189        };
1190        assert_eq!(img.data, b"00FF80FF>");
1191        assert_eq!(img.dict.get_int("Width"), Some(2));
1192        assert_eq!(img.dict.get_int("Height"), Some(2));
1193        assert_eq!(img.dict.get_int("BitsPerComponent"), Some(8));
1194        assert_eq!(img.dict.get_name("ColorSpace"), Some(&name("DeviceGray")));
1195        assert_eq!(img.dict.get_name("Filter"), Some(&name("AHx")));
1196    }
1197
1198    // Covers ISO 32000-1 §8.9.7.
1199    #[test]
1200    fn inline_image_trusts_declared_length() {
1201        // Binary payload contains a spurious ` EI ` sequence; /L must win.
1202        let mut src = b"BI /W 3 /H 1 /BPC 8 /CS /RGB /L 9 ID ".to_vec();
1203        src.extend_from_slice(b"ab EI wxy");
1204        src.extend_from_slice(b" EI 1 2 m");
1205        let got = ops(&src);
1206        assert_eq!(got.len(), 2);
1207        let Op::InlineImage(img) = &got[0] else {
1208            panic!("expected inline image, got {:?}", got[0]);
1209        };
1210        assert_eq!(img.data, b"ab EI wxy");
1211        assert_eq!(img.dict.get_name("ColorSpace"), Some(&name("DeviceRGB")));
1212        assert_eq!(got[1], Op::MoveTo(1.0, 2.0));
1213    }
1214
1215    // Covers ISO 32000-1 §8.9.7.
1216    #[test]
1217    fn inline_image_expands_indexed_colorspace_array() {
1218        let got = ops(
1219            b"BI /W 1 /H 1 /BPC 8 /CS [/I /RGB 1 <FF0000>] /IM false /I true \
1220                        ID \xde\xad EI",
1221        );
1222        let Op::InlineImage(img) = &got[0] else {
1223            panic!("expected inline image, got {:?}", got[0]);
1224        };
1225        assert_eq!(img.data, b"\xde\xad");
1226        assert_eq!(img.dict.get("ImageMask"), Some(&Object::Bool(false)));
1227        assert_eq!(img.dict.get("Interpolate"), Some(&Object::Bool(true)));
1228        let cs = img.dict.get_array("ColorSpace").expect("CS array");
1229        assert_eq!(cs[0], Object::Name(name("Indexed")));
1230        assert_eq!(cs[1], Object::Name(name("DeviceRGB")));
1231        assert_eq!(cs[2], Object::Int(1));
1232        assert_eq!(cs[3], Object::String(b"\xff\x00\x00".to_vec()));
1233    }
1234
1235    #[test]
1236    fn inline_image_without_terminator_is_skipped() {
1237        assert_eq!(ops(b"BI /W 1 ID \x01\x02\x03"), Vec::<Op>::new());
1238        assert_eq!(ops(b"BI /W 1"), Vec::<Op>::new());
1239    }
1240
1241    #[test]
1242    fn inline_image_with_empty_data() {
1243        let got = ops(b"BI /W 0 /H 0 ID  EI n");
1244        assert_eq!(got.len(), 2);
1245        let Op::InlineImage(img) = &got[0] else {
1246            panic!("expected inline image, got {:?}", got[0]);
1247        };
1248        assert!(img.data.is_empty());
1249        assert_eq!(got[1], Op::EndPath);
1250    }
1251
1252    // Covers ISO 32000-1 §8.9.7.
1253    #[test]
1254    fn inline_image_without_length_skips_fake_ei_with_open_string() {
1255        let src = b"BI /W 8 /H 1 /CS /G /BPC 8 ID AAAA EI (x\nEI\nBT (AFTER) Tj ET\n";
1256        let got = ops(src);
1257        let Op::InlineImage(img) = &got[0] else {
1258            panic!("expected inline image, got {:?}", got[0]);
1259        };
1260        assert_eq!(img.data, b"AAAA EI (x");
1261        assert_eq!(got.len(), 4);
1262    }
1263
1264    // Covers ISO 32000-1 §8.9.7.
1265    #[test]
1266    fn inline_image_computed_length_beats_plausible_fake_ei() {
1267        let src = b"BI /W 10 /H 1 /CS /G /BPC 8 ID A EI Q Q Q\nEI\nBT (AFTER) Tj ET\n";
1268        let got = ops(src);
1269        let Op::InlineImage(img) = &got[0] else {
1270            panic!("expected inline image, got {:?}", got[0]);
1271        };
1272        assert_eq!(img.data, b"A EI Q Q Q");
1273        assert_eq!(got.len(), 4);
1274    }
1275
1276    // Covers ISO 32000-1 §8.9.7.
1277    #[test]
1278    fn inline_image_computed_length_handles_indexed_mask_and_rows() {
1279        let src = b"BI /W 40 /H 2 /CS [/I /RGB 1 <000000FFFFFF>] /BPC 1 ID A EI Q Q Q\nEI\nQ";
1280        let got = ops(src);
1281        let Op::InlineImage(img) = &got[0] else {
1282            panic!("expected inline image, got {:?}", got[0]);
1283        };
1284        assert_eq!(img.data, b"A EI Q Q Q");
1285        let src = b"BI /W 40 /H 2 /IM true ID A EI Q Q Q\nEI\nQ";
1286        let got = ops(src);
1287        let Op::InlineImage(img) = &got[0] else {
1288            panic!("expected inline image, got {:?}", got[0]);
1289        };
1290        assert_eq!(img.data, b"A EI Q Q Q");
1291    }
1292
1293    // Covers ISO 32000-1 §8.9.7.
1294    #[test]
1295    fn inline_image_scan_skips_fake_ei_followed_by_open_string() {
1296        let src =
1297            b"BI /W 9 /H 1 /CS /G /BPC 8 /F /Fl ID AAAA EI (swallowed\nEI\nBT (AFTER) Tj ET\n";
1298        let got = ops(src);
1299        let Op::InlineImage(img) = &got[0] else {
1300            panic!("expected inline image, got {:?}", got[0]);
1301        };
1302        assert_eq!(img.data, b"AAAA EI (swallowed");
1303        assert_eq!(got.len(), 4);
1304    }
1305
1306    // Covers ISO 32000-1 §8.9.7.
1307    #[test]
1308    fn inline_image_scan_skips_fake_ei_followed_by_binary() {
1309        let src = b"BI /W 1 /H 1 /F /DCT ID \x01 EI \xff\xfe\x00 junk EI\nQ";
1310        let got = ops(src);
1311        let Op::InlineImage(img) = &got[0] else {
1312            panic!("expected inline image, got {:?}", got[0]);
1313        };
1314        assert_eq!(img.data, b"\x01 EI \xff\xfe\x00 junk");
1315        assert_eq!(got[1], Op::Restore);
1316    }
1317
1318    #[test]
1319    fn stray_delimiters_and_comments_are_tolerated() {
1320        assert_eq!(
1321            ops(b"% comment\n1 2 m ] >> 3 4 l"),
1322            vec![Op::MoveTo(1.0, 2.0), Op::LineTo(3.0, 4.0)]
1323        );
1324        assert_eq!(ops(b""), Vec::<Op>::new());
1325        assert_eq!(ops(b"   \n  "), Vec::<Op>::new());
1326    }
1327
1328    // Covers ISO 32000-1 §9.3.1, §9.3.2, §9.3.4 and Annex A.2.
1329    #[test]
1330    fn text_state_ops_round_trip() {
1331        let got = ops(b"BT 0.5 Tc 1 Tw 90 Tz 14 TL /F1 12 Tf 3 Tr 4.5 Ts ET");
1332        assert_eq!(
1333            got,
1334            vec![
1335                Op::BeginText,
1336                Op::SetCharSpacing(0.5),
1337                Op::SetWordSpacing(1.0),
1338                Op::SetHorizScaling(90.0),
1339                Op::SetLeading(14.0),
1340                Op::SetFont(name("F1"), 12.0),
1341                Op::SetTextRender(3),
1342                Op::SetTextRise(4.5),
1343                Op::EndText,
1344            ]
1345        );
1346    }
1347
1348    // Covers ISO 32000-1 §9.3.5, §9.4.2, §9.4.3 and Annex A.2.
1349    #[test]
1350    fn text_positioning_and_showing_round_trip() {
1351        let got = ops(b"BT 72 720 Td 0 -14 TD 1 0 0 1 50 60 Tm T* \
1352                        (Hi) Tj (there) ' 2 3 (spaced) \" ET");
1353        assert_eq!(
1354            got,
1355            vec![
1356                Op::BeginText,
1357                Op::TextMove(72.0, 720.0),
1358                Op::TextMoveSetLeading(0.0, -14.0),
1359                Op::SetTextMatrix(Matrix {
1360                    a: 1.0,
1361                    b: 0.0,
1362                    c: 0.0,
1363                    d: 1.0,
1364                    e: 50.0,
1365                    f: 60.0
1366                }),
1367                Op::TextNextLine,
1368                Op::ShowText(b"Hi".to_vec()),
1369                Op::NextLineShowText(b"there".to_vec()),
1370                Op::NextLineShowTextSpaced(2.0, 3.0, b"spaced".to_vec()),
1371                Op::EndText,
1372            ]
1373        );
1374    }
1375
1376    // Covers ISO 32000-1 Annex A.2.
1377    #[test]
1378    fn parses_d0_glyph_width() {
1379        let ops = parse_content(b"1000 0 d0").expect("parse");
1380        assert_eq!(ops, vec![Op::SetGlyphWidth(1000.0, 0.0)]);
1381    }
1382
1383    // Covers ISO 32000-1 §9.6.5 and Annex A.2.
1384    #[test]
1385    fn parses_d1_glyph_width_bbox() {
1386        let ops = parse_content(b"1000 0 0 0 750 700 d1").expect("parse");
1387        assert_eq!(
1388            ops,
1389            vec![Op::SetGlyphWidthBBox(1000.0, 0.0, 0.0, 0.0, 750.0, 700.0)]
1390        );
1391    }
1392
1393    #[test]
1394    fn d0_with_wrong_arity_is_skipped() {
1395        // Too few operands: leniently skipped (like any arity mismatch), not a panic.
1396        let ops = parse_content(b"1000 d0").expect("parse");
1397        assert!(ops.is_empty());
1398    }
1399
1400    // Covers ISO 32000-1 §9.4.3.
1401    #[test]
1402    fn tj_array_mixes_strings_and_numbers() {
1403        let got = ops(b"[(He) -120 (llo) 33.5 <20>] TJ");
1404        assert_eq!(
1405            got,
1406            vec![Op::ShowTextAdjusted(vec![
1407                TextItem::Str(b"He".to_vec()),
1408                TextItem::Offset(-120.0),
1409                TextItem::Str(b"llo".to_vec()),
1410                TextItem::Offset(33.5),
1411                TextItem::Str(b" ".to_vec()),
1412            ])]
1413        );
1414    }
1415
1416    // Covers ISO 32000-1 §8.6.2, §8.6.8 and Annex A.2.
1417    #[test]
1418    fn color_ops_round_trip() {
1419        let got = ops(b"/DeviceRGB CS /DeviceGray cs 1 0 0 SC 0.5 sc \
1420                        0.3 G 0.7 g 1 0 0 RG 0 1 0 rg 0 0 0 1 K 1 0 0 0 k");
1421        assert_eq!(
1422            got,
1423            vec![
1424                Op::SetStrokeColorSpace(name("DeviceRGB")),
1425                Op::SetFillColorSpace(name("DeviceGray")),
1426                Op::SetStrokeColor(vec![1.0, 0.0, 0.0]),
1427                Op::SetFillColor(vec![0.5]),
1428                Op::SetStrokeGray(0.3),
1429                Op::SetFillGray(0.7),
1430                Op::SetStrokeRGB(1.0, 0.0, 0.0),
1431                Op::SetFillRGB(0.0, 1.0, 0.0),
1432                Op::SetStrokeCMYK(0.0, 0.0, 0.0, 1.0),
1433                Op::SetFillCMYK(1.0, 0.0, 0.0, 0.0),
1434            ]
1435        );
1436    }
1437
1438    // Covers ISO 32000-1 §8.6.6.2, §8.6.8 and Annex A.2.
1439    #[test]
1440    fn scn_with_and_without_pattern_name() {
1441        let got = ops(b"0.2 0.4 0.6 scn /P1 scn 0.1 0.2 /P2 SCN 1 SCN");
1442        assert_eq!(
1443            got,
1444            vec![
1445                Op::SetFillColorN(vec![0.2, 0.4, 0.6], None),
1446                Op::SetFillColorN(vec![], Some(name("P1"))),
1447                Op::SetStrokeColorN(vec![0.1, 0.2], Some(name("P2"))),
1448                Op::SetStrokeColorN(vec![1.0], None),
1449            ]
1450        );
1451    }
1452
1453    // Covers ISO 32000-1 §8.5.3.1, §8.5.3.3.3 and Annex A.2.
1454    #[test]
1455    fn painting_and_clipping_ops_round_trip() {
1456        let got = ops(b"S s f F f* B B* b b* n W W*");
1457        assert_eq!(
1458            got,
1459            vec![
1460                Op::Stroke,
1461                Op::CloseStroke,
1462                Op::Fill,
1463                Op::Fill,
1464                Op::FillEvenOdd,
1465                Op::FillStroke,
1466                Op::FillStrokeEvenOdd,
1467                Op::CloseFillStroke,
1468                Op::CloseFillStrokeEvenOdd,
1469                Op::EndPath,
1470                Op::ClipNonZero,
1471                Op::ClipEvenOdd,
1472            ]
1473        );
1474    }
1475
1476    /// Runs `f` on a deliberately small stack so that unbounded recursion
1477    /// would abort the test binary instead of silently passing on a large
1478    /// main-thread stack.
1479    fn on_small_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
1480        std::thread::Builder::new()
1481            .stack_size(512 * 1024)
1482            .spawn(f)
1483            .expect("spawn test thread")
1484            .join()
1485            .expect("content parser must not overflow the stack")
1486    }
1487
1488    #[test]
1489    fn deeply_nested_array_is_rejected_not_stack_overflow() {
1490        let data = vec![b'['; 50_000];
1491        let result = on_small_stack(move || parse_content(&data));
1492        assert!(matches!(result, Err(Error::Syntax { .. })));
1493    }
1494
1495    #[test]
1496    fn deeply_nested_dict_is_rejected_not_stack_overflow() {
1497        let mut data = Vec::new();
1498        for _ in 0..50_000 {
1499            data.extend_from_slice(b"<</K");
1500        }
1501        let result = on_small_stack(move || parse_content(&data));
1502        assert!(matches!(result, Err(Error::Syntax { .. })));
1503    }
1504
1505    // Covers ISO 32000-1 §14.6.1 and Annex C.2.
1506    #[test]
1507    fn nesting_within_the_limit_still_parses() {
1508        // A BDC property dict holding a modestly nested array operand.
1509        let mut data: Vec<u8> = b"/Tag <</Deep ".to_vec();
1510        data.extend(std::iter::repeat_n(b'[', 50));
1511        data.extend(std::iter::repeat_n(b']', 50));
1512        data.extend_from_slice(b" >> BDC");
1513        let got = ops(&data);
1514        assert_eq!(got.len(), 1);
1515        assert!(matches!(got[0], Op::BeginMarkedContentProps(_, _)));
1516    }
1517
1518    #[test]
1519    fn spanned_ops_cover_their_source_bytes() {
1520        let data = b"q 1 0 0 1 5 5 cm BT /F1 12 Tf (Hi) Tj ET Q";
1521        let spanned = parse_content_spanned(data).unwrap();
1522        let plain = parse_content(data).unwrap();
1523        assert_eq!(
1524            spanned
1525                .iter()
1526                .map(|pair| pair.0.clone())
1527                .collect::<Vec<_>>(),
1528            plain
1529        );
1530        for (op, span) in &spanned {
1531            assert!(span.start < span.end && span.end as usize <= data.len());
1532            // Re-parsing exactly the spanned bytes yields exactly this op.
1533            let slice = &data[span.start as usize..span.end as usize];
1534            let reparsed = parse_content(slice).unwrap();
1535            assert_eq!(reparsed.len(), 1, "span of {op:?} reparses to one op");
1536            assert_eq!(&reparsed[0], op);
1537        }
1538        // Spans are ordered and non-overlapping.
1539        for pair in spanned.windows(2) {
1540            assert!(pair[0].1.end <= pair[1].1.start);
1541        }
1542    }
1543
1544    #[test]
1545    fn unknown_operator_does_not_stretch_the_next_span() {
1546        // `zz` is unknown: its operands are dropped, and the following op's
1547        // span must start at `q`, not at `7`.
1548        let data = b"7 8 zz q";
1549        let spanned = parse_content_spanned(data).unwrap();
1550        assert_eq!(spanned.len(), 1);
1551        assert_eq!(spanned[0].0, Op::Save);
1552        assert_eq!(
1553            &data[spanned[0].1.start as usize..spanned[0].1.end as usize],
1554            b"q"
1555        );
1556    }
1557}