pdfcer_model/writer/content.rs
1//! # Content-stream serializer (ISO 32000-1 §7.8.2, §8.2, §8.4.3, §8.5, §8.6)
2//!
3//! The project's **first content-stream writer**. Where
4//! [`super::serialize`] turns a COS value tree into object bytes, this
5//! module turns *graphics operations* into the postfix operator syntax of
6//! a content stream — the bytes that live between `stream` and
7//! `endstream` in a page's `/Contents` or, for Pass 6.1, inside an
8//! annotation's `/AP` `/N` appearance form XObject.
9//!
10//! Two independent capabilities live here, sharing one set of token
11//! emitters:
12//!
13//! 1. [`ContentBuilder`] — **authoring**. A stateful appender that emits
14//! path-construction, path-painting, graphics-state and colour
15//! operators for a *new* content stream (the appearance generator in
16//! `pdfcer_core::annot_author` is its first and only Pass-6.1 consumer). It
17//! is deliberately a low-level primitive: it emits exactly the tokens
18//! asked for, in the order asked for, and it is the caller's job to
19//! respect the W-E ordering constraint (colour + graphics-state before
20//! the path, never inside it — see below). The one structural guard it
21//! *does* enforce is that operands cannot fuse (a SPACE is emitted
22//! between adjacent numeric operands so `1 0` never becomes `10`).
23//!
24//! 2. [`reemit_canonical`] — the **R46 identity gate's** re-emission.
25//! Parse → re-emit → byte-compare every content stream in the loadable
26//! corpus. This is Pass 3.0's object-level identity move applied one
27//! level down, and it is nearly free because [`crate::content`] already
28//! carries a per-token byte span. See that function's docs for exactly
29//! what it re-emits from value (numbers, the X6 target) versus verbatim
30//! (strings, arrays, operators, whitespace — everything a geometric
31//! serializer must never touch), and why that split is the mechanically
32//! self-enforcing guard against silent normalization (X6).
33//!
34//! ## Spec sources (PDF-spec RAG, ISO 32000-1:2008)
35//!
36//! - `iso32000__s__8.10.md` `## WRITE DIRECTION` (W-D operator emission,
37//! W-E ordering, WF1–WF6) — the authoring audit this module enacts.
38//! - `iso32000__ref__writer_emission.md` (A1–A3 token/number emission).
39//! - `iso32000__s__8.5.md` (path construction/painting operators),
40//! `iso32000__s__8.4.3.md` (`w`/`J`/`j`/`M`/`d`), `iso32000__s__8.6.md`
41//! (device colour operators — `CS`/`cs` unneeded, WF5),
42//! `iso32000__s__8.2.md` (Figure 9 state machine — the W-E ordering
43//! rule, and "no semantic significance to gstate arrangement", WF6).
44//!
45//! ## The W-E ordering constraint (Figure 9), stated once
46//!
47//! Graphics-state operators (`w`/`J`/`j`/`M`/`d`) and colour operators
48//! (`RG`/`rg`/`G`/`g`/`K`/`k`/`CS`/`cs`/`gs`) are **illegal inside a path
49//! object**: once `m`/`re` begins a path, only further construction
50//! operators (and `W`/`W*`) are legal until the paint operator returns to
51//! page-description level. A generator must therefore emit every colour
52//! and line parameter it needs **before** the `m`/`re` that begins the
53//! path. [`ContentBuilder`]'s method set is grouped to make the correct
54//! call order the obvious one, and its doc comments name the constraint at
55//! each path-construction entry point.
56//!
57//! ## Number emission (WF / A1–A3)
58//!
59//! Coordinates and parameters are `f64`. [`emit_number`] emits an integral
60//! value in integer form (`10`, not `10.0`) and a non-integral value
61//! through [`super::serialize::write_real`] — which guarantees no
62//! exponential notation (§7.3.3 has no exponent) and never emits NaN/Inf.
63//! Integer form for integral values keeps authored geometry compact and
64//! matches the spelling the spec's own W-F worked examples use
65//! (`10 10 m`, not `10.0 10.0 m`).
66
67use crate::content::{ContentStream, ContentToken, ContentTokenKind};
68use crate::object::Object;
69
70use super::serialize::{write_name, write_real};
71
72/// A line-cap style (`J` operator, §8.4.3.3, Table 54). The three legal
73/// integer values, named so a caller cannot pass an out-of-range code.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum LineCap {
76 /// 0 — butt cap: the stroke is squared off at the endpoint.
77 Butt = 0,
78 /// 1 — round cap: a semicircular arc caps the endpoint.
79 Round = 1,
80 /// 2 — projecting square cap: the stroke extends half a line width
81 /// past the endpoint and is squared off.
82 ProjectingSquare = 2,
83}
84
85/// A line-join style (`j` operator, §8.4.3.4, Table 55).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum LineJoin {
88 /// 0 — miter join: the outer edges extend to meet at a point (subject
89 /// to the miter limit `M`).
90 Miter = 0,
91 /// 1 — round join: an arc of a circle joins the segments.
92 Round = 1,
93 /// 2 — bevel join: the two segments are finished with butt caps and
94 /// the notch is filled with a triangle.
95 Bevel = 2,
96}
97
98/// The path-painting operator that ends one path object (§8.5.3,
99/// Table 60). Exactly one paint operator ends each path object (§8.2
100/// Figure 9), so this is a closed enum rather than free-form.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Paint {
103 /// `S` — stroke the path (open geometry: Line, Ink, PolyLine).
104 Stroke,
105 /// `s` — close then stroke (≡ `h S`).
106 CloseStroke,
107 /// `f` — fill, nonzero winding. Emitted as `f`, never the
108 /// compatibility-only `F` (§8.5: a writer `should` use `f`).
109 Fill,
110 /// `f*` — fill, even-odd winding.
111 FillEvenOdd,
112 /// `B` — fill then stroke. Consults the non-stroking colour for the
113 /// fill and the stroking colour for the stroke, so **both** must be
114 /// set before the path (§8.5 `B` NOTE).
115 FillStroke,
116 /// `b` — close, fill, then stroke (≡ `h B`).
117 CloseFillStroke,
118 /// `n` — end the path with no painting (used only to establish a clip
119 /// with a preceding `W`/`W*`).
120 NoPaint,
121}
122
123impl Paint {
124 /// The operator keyword bytes.
125 const fn keyword(self) -> &'static [u8] {
126 match self {
127 Self::Stroke => b"S",
128 Self::CloseStroke => b"s",
129 Self::Fill => b"f",
130 Self::FillEvenOdd => b"f*",
131 Self::FillStroke => b"B",
132 Self::CloseFillStroke => b"b",
133 Self::NoPaint => b"n",
134 }
135 }
136}
137
138/// A stateful builder that emits the bytes of a new content stream
139/// (ISO 32000-1 §8.2 postfix operator syntax).
140///
141/// See the module docs for the W-E ordering contract the caller honours
142/// and the one fusion guard the builder enforces. Construct with
143/// [`ContentBuilder::new`], drive it with the operator methods, and take
144/// the finished bytes with [`ContentBuilder::into_bytes`].
145///
146/// The finished bytes are a **raw** (unfiltered) content stream. Per WF2
147/// the spec places no filter requirement on an appearance stream, and for
148/// the small geometric appearances Pass 6.1 authors, raw is simpler and
149/// more minimal-diff-friendly than Flate (nothing to reproduce
150/// byte-identically on re-save) — a recorded convention, not a `shall`.
151///
152/// # Examples
153///
154/// The red 2-unit `Line` appearance from §8.10 W-F (W-E ordering: colour
155/// and width precede `m`):
156///
157/// ```
158/// use pdfcer_model::writer::content::{ContentBuilder, Paint};
159///
160/// let mut b = ContentBuilder::new();
161/// b.set_stroke_rgb(1.0, 0.0, 0.0);
162/// b.set_line_width(2.0);
163/// b.move_to(10.0, 10.0);
164/// b.line_to(90.0, 40.0);
165/// b.paint(Paint::Stroke);
166/// assert_eq!(b.into_bytes(), b"1 0 0 RG\n2 w\n10 10 m\n90 40 l\nS\n");
167/// ```
168#[derive(Debug, Default, Clone)]
169pub struct ContentBuilder {
170 out: Vec<u8>,
171 /// Whether a path object is currently open (an `m`/`re` has been
172 /// emitted and no paint operator has closed it yet). Used only for a
173 /// `debug_assert` that catches a W-E ordering mistake in tests; it is
174 /// never a runtime refusal (a content builder has no untrusted input).
175 in_path: bool,
176}
177
178impl ContentBuilder {
179 /// A fresh, empty builder. An empty content stream is itself a valid
180 /// appearance (§8.10 W-C — the common `/Off` checkbox appearance), so
181 /// a builder that is never driven produces conforming zero-byte output.
182 #[must_use]
183 pub fn new() -> Self {
184 Self {
185 out: Vec::new(),
186 in_path: false,
187 }
188 }
189
190 /// The finished content-stream bytes.
191 #[must_use]
192 pub fn into_bytes(self) -> Vec<u8> {
193 self.out
194 }
195
196 /// The bytes emitted so far (for length checks before finishing).
197 #[must_use]
198 pub fn as_bytes(&self) -> &[u8] {
199 &self.out
200 }
201
202 /// Append already-formed content-stream bytes verbatim.
203 ///
204 /// The composition escape hatch, for splicing in a fragment some other
205 /// generator produced — the case it exists for is baking a
206 /// `pdfcer_core::vartext::build_variable_text` block (a form field's value,
207 /// a redaction's `/OverlayText`) into a larger stream, where
208 /// re-emitting the text through this builder would mean a SECOND text
209 /// layout implementation in the binary.
210 ///
211 /// # Contract
212 ///
213 /// The caller guarantees `bytes` is **self-contained and balanced**:
214 /// every `q` matched by a `Q`, every `BT` by an `ET`, every `BMC`/`BDC`
215 /// by an `EMC`, and no path left open. Nothing is parsed or validated
216 /// here — this is a byte append. Passing an unbalanced fragment
217 /// corrupts every operator that follows it in the stream, which is why
218 /// the intended source is a generator with that guarantee in its own
219 /// contract rather than hand-written bytes.
220 ///
221 /// Wrap the call in [`save_state`](Self::save_state) /
222 /// [`restore_state`](Self::restore_state) if the fragment sets graphics
223 /// state the surrounding content must not inherit.
224 pub fn append_raw(&mut self, bytes: &[u8]) {
225 debug_assert!(
226 !self.in_path,
227 "append_raw with an open path: the fragment would be spliced between a path \
228 construction operator and its paint operator"
229 );
230 self.out.extend_from_slice(bytes);
231 }
232
233 // -- graphics state (§8.4.3) — must precede any path (W-E) ----------
234
235 /// `w` — set the line width in form-space units (§8.4.3.2). A width of
236 /// `0` denotes the thinnest line the device can render. Emit before
237 /// beginning a path.
238 pub fn set_line_width(&mut self, width: f64) {
239 self.debug_assert_not_in_path("w");
240 self.op1(width, b"w");
241 }
242
243 /// `J` — set the line-cap style (§8.4.3.3). Emit before beginning a
244 /// path.
245 pub fn set_line_cap(&mut self, cap: LineCap) {
246 self.debug_assert_not_in_path("J");
247 self.emit_int(cap as i64);
248 self.finish_op(b"J");
249 }
250
251 /// `j` — set the line-join style (§8.4.3.4). Emit before beginning a
252 /// path.
253 pub fn set_line_join(&mut self, join: LineJoin) {
254 self.debug_assert_not_in_path("j");
255 self.emit_int(join as i64);
256 self.finish_op(b"j");
257 }
258
259 /// `M` — set the miter limit (§8.4.3.5). Relevant only when the join
260 /// style is miter.
261 pub fn set_miter_limit(&mut self, limit: f64) {
262 self.debug_assert_not_in_path("M");
263 self.op1(limit, b"M");
264 }
265
266 /// `d` — set the dash pattern (§8.4.3.6): an array of on/off run
267 /// lengths and a phase. `set_dash(&[], 0.0)` emits `[] 0 d`, the solid
268 /// line. Dash elements must be non-negative and not all zero (§8.4.3.6)
269 /// — a caller invariant, not enforced here.
270 pub fn set_dash(&mut self, pattern: &[f64], phase: f64) {
271 self.debug_assert_not_in_path("d");
272 self.out.push(b'[');
273 for (i, v) in pattern.iter().enumerate() {
274 if i > 0 {
275 self.out.push(b' ');
276 }
277 emit_number(&mut self.out, *v);
278 }
279 self.out.push(b']');
280 self.out.push(b' ');
281 self.operand(phase);
282 self.finish_op(b"d");
283 }
284
285 /// `/name gs` — apply the named `ExtGState` resource (§8.4.5). Used by
286 /// the Highlight appearance to select `/BM /Multiply`. The name must be
287 /// present in the appearance stream's own `/Resources` `/ExtGState`
288 /// (X8: an appearance stream is a closed resource world). Emit before
289 /// beginning a path.
290 pub fn set_ext_gstate(&mut self, name: &[u8]) {
291 self.debug_assert_not_in_path("gs");
292 write_name(&mut self.out, &crate::object::Name(name.to_vec()));
293 self.out.push(b' ');
294 self.finish_op(b"gs");
295 }
296
297 // -- colour (§8.6) — must precede any path (W-E) --------------------
298
299 /// `RG` — set the stroking colour to a DeviceRGB triple (0.0–1.0). The
300 /// operator sets both colour space and value; no `CS` and no
301 /// `ColorSpace` resource is needed for a device colour (WF5).
302 pub fn set_stroke_rgb(&mut self, r: f64, g: f64, b: f64) {
303 self.debug_assert_not_in_path("RG");
304 self.op3(r, g, b, b"RG");
305 }
306
307 /// `rg` — set the non-stroking (fill) colour to a DeviceRGB triple.
308 pub fn set_fill_rgb(&mut self, r: f64, g: f64, b: f64) {
309 self.debug_assert_not_in_path("rg");
310 self.op3(r, g, b, b"rg");
311 }
312
313 /// `G` — set the stroking colour to a DeviceGray value (0=black,
314 /// 1=white).
315 pub fn set_stroke_gray(&mut self, gray: f64) {
316 self.debug_assert_not_in_path("G");
317 self.op1(gray, b"G");
318 }
319
320 /// `g` — set the non-stroking (fill) colour to a DeviceGray value.
321 pub fn set_fill_gray(&mut self, gray: f64) {
322 self.debug_assert_not_in_path("g");
323 self.op1(gray, b"g");
324 }
325
326 /// `K` — set the stroking colour to a DeviceCMYK quadruple
327 /// (`0 0 0 0`=white, `0 0 0 1`=black).
328 pub fn set_stroke_cmyk(&mut self, c: f64, m: f64, y: f64, k: f64) {
329 self.debug_assert_not_in_path("K");
330 self.op4(c, m, y, k, b"K");
331 }
332
333 /// `k` — set the non-stroking (fill) colour to a DeviceCMYK quadruple.
334 pub fn set_fill_cmyk(&mut self, c: f64, m: f64, y: f64, k: f64) {
335 self.debug_assert_not_in_path("k");
336 self.op4(c, m, y, k, b"k");
337 }
338
339 // -- path construction (§8.5.2) — the W-E boundary ------------------
340
341 /// `m` — begin a new subpath at `(x, y)` (§8.5.2.1). This is the
342 /// operator that enters path-object state: **every** colour and
343 /// graphics-state parameter the path needs must already have been
344 /// emitted (W-E). Consecutive `m` collapse (last wins).
345 pub fn move_to(&mut self, x: f64, y: f64) {
346 self.in_path = true;
347 self.op2(x, y, b"m");
348 }
349
350 /// `l` — add a line segment from the current point to `(x, y)`.
351 pub fn line_to(&mut self, x: f64, y: f64) {
352 self.op2(x, y, b"l");
353 }
354
355 /// `c` — add a cubic Bézier with control points `(x1,y1)`, `(x2,y2)`
356 /// and endpoint `(x3,y3)` (§8.5.2.2). A generator emits full `c`
357 /// rather than the abbreviated `v`/`y` to avoid their operand-ordering
358 /// confusion.
359 #[allow(clippy::too_many_arguments)]
360 pub fn curve_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) {
361 self.operand(x1);
362 self.operand(y1);
363 self.operand(x2);
364 self.operand(y2);
365 self.operand(x3);
366 self.operand(y3);
367 self.finish_op(b"c");
368 }
369
370 /// `re` — append a complete rectangular subpath with lower-left corner
371 /// `(x, y)` and the given width and height (§8.5.2.1). Like `m`, this
372 /// enters path-object state, so all state must precede it (W-E). It is
373 /// its own complete subpath (ends with an implicit `h`).
374 pub fn rect(&mut self, x: f64, y: f64, width: f64, height: f64) {
375 self.in_path = true;
376 self.operand(x);
377 self.operand(y);
378 self.operand(width);
379 self.operand(height);
380 self.finish_op(b"re");
381 }
382
383 /// `h` — close the current subpath (§8.5.2.1) with a straight segment
384 /// back to its start. Use to close a Polygon.
385 pub fn close_subpath(&mut self) {
386 self.finish_op(b"h");
387 }
388
389 /// `W` — intersect the current clipping path with the current path,
390 /// nonzero winding (§8.5.4). Legal only inside a path object, and it
391 /// does **not** end the path: a paint operator (usually
392 /// [`Paint::NoPaint`], `n`) must follow. Used by the variable-text
393 /// generator to clip the shown text to the appearance `/BBox`
394 /// (§12.7.3.3 `/Tx BMC` body).
395 pub fn clip_nonzero(&mut self) {
396 self.finish_op(b"W");
397 }
398
399 // -- path painting (§8.5.3) — returns to page-description level ------
400
401 /// Emit the single paint operator that ends the current path object
402 /// (§8.2 Figure 9). Returns the builder to page-description level, so
403 /// the next colour/graphics-state operator is legal again.
404 pub fn paint(&mut self, op: Paint) {
405 self.finish_op(op.keyword());
406 self.in_path = false;
407 }
408
409 // -- graphics-state stack (§8.4.2) ----------------------------------
410
411 /// `q` — save the current graphics state onto the stack (§8.4.2). The
412 /// variable-text `/Tx BMC` body wraps its clip + text in `q … Q` so
413 /// the clip does not leak past the appearance (§12.7.3.3 template).
414 pub fn save_state(&mut self) {
415 self.finish_op(b"q");
416 }
417
418 /// `Q` — restore the graphics state from the stack (§8.4.2).
419 pub fn restore_state(&mut self) {
420 self.finish_op(b"Q");
421 }
422
423 /// `a b c d e f cm` — concatenate a matrix onto the current
424 /// transformation matrix (§8.3.4). Emitted at page-description level
425 /// (outside a path object); used to translate a composed sub-appearance
426 /// (e.g. centring a stamp's label band within its frame).
427 #[allow(clippy::too_many_arguments)]
428 pub fn concat_matrix(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
429 self.debug_assert_not_in_path("cm");
430 self.operand(a);
431 self.operand(b);
432 self.operand(c);
433 self.operand(d);
434 self.operand(e);
435 self.operand(f);
436 self.finish_op(b"cm");
437 }
438
439 /// `/name Do` — paint the named external object (§8.10.1). For Pass 7.1
440 /// flatten, `name` is a form-XObject resource (an existing widget `/AP`
441 /// `/N` appearance) present in the page's `/Resources` `/XObject`
442 /// sub-dictionary; the `Do` procedure itself concatenates that form's
443 /// `/Matrix` and clips to its `/BBox`, so the caller emits only the
444 /// §12.5.5 placement `cm` beforehand (never the `/Matrix` again — the
445 /// double-apply trap). Emitted at page-description level.
446 pub fn invoke_xobject(&mut self, name: &[u8]) {
447 self.debug_assert_not_in_path("Do");
448 write_name(&mut self.out, &crate::object::Name(name.to_vec()));
449 self.out.push(b' ');
450 self.finish_op(b"Do");
451 }
452
453 // -- marked content (§14.6) -----------------------------------------
454
455 /// `/tag BMC` — begin a marked-content sequence (§14.6.1). The
456 /// variable-text generator tags its body `/Tx` so a future
457 /// value-update can find and replace it (§12.7.3.3 update algorithm
458 /// keys on the `/Tx BMC … EMC` span).
459 pub fn begin_marked_content(&mut self, tag: &[u8]) {
460 write_name(&mut self.out, &crate::object::Name(tag.to_vec()));
461 self.out.push(b' ');
462 self.finish_op(b"BMC");
463 }
464
465 /// `EMC` — end the innermost marked-content sequence (§14.6.1).
466 pub fn end_marked_content(&mut self) {
467 self.finish_op(b"EMC");
468 }
469
470 // -- text objects (§9.4) --------------------------------------------
471
472 /// `BT` — begin a text object (§9.4.1). Resets the text matrix and
473 /// text line matrix to identity. Text-showing and text-state
474 /// operators are legal only between `BT` and `ET`.
475 pub fn begin_text(&mut self) {
476 self.finish_op(b"BT");
477 }
478
479 /// `ET` — end the current text object (§9.4.1).
480 pub fn end_text(&mut self) {
481 self.finish_op(b"ET");
482 }
483
484 /// `/name size Tf` — set the text font and size (§9.3.1). `name` is a
485 /// resource name present in the stream's `/Resources` `/Font`
486 /// sub-dictionary (X8: an appearance is a closed resource world).
487 /// This is the one operator §12.7.3.3 mandates a `/DA` string carry.
488 pub fn set_font(&mut self, name: &[u8], size: f64) {
489 write_name(&mut self.out, &crate::object::Name(name.to_vec()));
490 self.out.push(b' ');
491 self.op1(size, b"Tf");
492 }
493
494 /// `mode Tr` — set the text rendering mode (§9.3.6, Table 106).
495 ///
496 /// The value pdfcer cares about most is **3, "neither fill nor stroke text
497 /// (invisible)"** — the mechanism an OCR text layer uses to sit over a
498 /// scanned image without painting anything. The page keeps the appearance
499 /// of the original scan while the text becomes selectable, searchable and
500 /// extractable.
501 ///
502 /// Two Table 106 rules a caller has to respect, neither of which this
503 /// method can enforce:
504 ///
505 /// - Modes 4–7 accumulate a CLIPPING path, and §9.3.6 requires that the
506 /// mode "shall not be changed back to a nonclipping mode" before the
507 /// `ET` that ends the text object.
508 /// - Text state is NOT reset by `BT` (§9.4.1 — only `Tm`/`Tlm` are), so a
509 /// mode set in one text object persists into the next one in the same
510 /// content stream. A caller that sets 3 and does not set it back has
511 /// made everything after it invisible too.
512 ///
513 /// Takes `u8` rather than an enum deliberately: Table 106 defines exactly
514 /// eight values, but the operand is an integer and a malformed document
515 /// may carry anything. This is the WRITER, so callers pass a literal from
516 /// the table; the reader is where an out-of-range value gets a policy.
517 pub fn set_render_mode(&mut self, mode: u8) {
518 self.op1(f64::from(mode), b"Tr");
519 }
520
521 /// `l TL` — set the text leading (line spacing) in unscaled text
522 /// units (§9.3.5). Consumed by `T*` and `'`; the variable-text
523 /// generator uses explicit `Td` moves instead, but sets `TL` for
524 /// readers that reflow.
525 pub fn set_text_leading(&mut self, leading: f64) {
526 self.op1(leading, b"TL");
527 }
528
529 /// `tx ty Td` — move to the start of the next line, offset `(tx, ty)`
530 /// from the start of the current line, in unscaled text space
531 /// (§9.4.2). Used for per-line positioning after the single `Tm`.
532 pub fn text_move(&mut self, tx: f64, ty: f64) {
533 self.op2(tx, ty, b"Td");
534 }
535
536 /// `tx ty TD` — like [`ContentBuilder::text_move`] but also sets the
537 /// leading to `-ty` (§9.4.2).
538 pub fn text_move_set_leading(&mut self, tx: f64, ty: f64) {
539 self.op2(tx, ty, b"TD");
540 }
541
542 /// `a b c d e f Tm` — set the text matrix and text line matrix
543 /// (§9.4.2). §12.7.3.3 allows **at most one** `Tm` in a `/DA` string;
544 /// pdfcer authors zero in the `/DA` and emits exactly one here to set
545 /// the first line's origin, then positions subsequent lines with
546 /// `Td` (which is not a `Tm`).
547 #[allow(clippy::too_many_arguments)]
548 pub fn set_text_matrix(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
549 self.operand(a);
550 self.operand(b);
551 self.operand(c);
552 self.operand(d);
553 self.operand(e);
554 self.operand(f);
555 self.finish_op(b"Tm");
556 }
557
558 /// `tc Tc` — set the character spacing (§9.3.2), added to each glyph's
559 /// advance.
560 pub fn set_char_spacing(&mut self, tc: f64) {
561 self.op1(tc, b"Tc");
562 }
563
564 /// `tw Tw` — set the word spacing (§9.3.3), added to the advance of
565 /// each single-byte code 32 (space).
566 pub fn set_word_spacing(&mut self, tw: f64) {
567 self.op1(tw, b"Tw");
568 }
569
570 /// `scale Tz` — set the horizontal scaling as a percentage (§9.3.4;
571 /// `100` = normal).
572 pub fn set_horizontal_scaling(&mut self, percent: f64) {
573 self.op1(percent, b"Tz");
574 }
575
576 /// `(string) Tj` — show a text string (§9.4.3). `bytes` are the raw
577 /// character codes (for the variable-text generator, `WinAnsi` bytes);
578 /// they are emitted as a §7.3.4.2 literal string with `(`, `)` and `\`
579 /// escaped and every non-printable or high byte written as a
580 /// three-digit octal escape, so the content stream stays ASCII and
581 /// paren-balanced regardless of the text.
582 pub fn show_text(&mut self, bytes: &[u8]) {
583 emit_literal_string(&mut self.out, bytes);
584 self.out.push(b' ');
585 self.finish_op(b"Tj");
586 }
587
588 // -- internal token emitters ---------------------------------------
589
590 /// Emit one integer operand followed by the SPACE that separates it
591 /// from what comes next (§7.3.3: no sign, no padding). The SPACE is
592 /// mandatory before an operator or a following operand so tokens never
593 /// fuse (`1 0` must not become `10`).
594 fn emit_int(&mut self, v: i64) {
595 self.out.extend_from_slice(v.to_string().as_bytes());
596 self.out.push(b' ');
597 }
598
599 /// Emit one numeric operand followed by its separating SPACE.
600 fn operand(&mut self, v: f64) {
601 emit_number(&mut self.out, v);
602 self.out.push(b' ');
603 }
604
605 /// Terminate an operation with the operator keyword and a LF. Any
606 /// operands were each emitted with a trailing SPACE, so the keyword is
607 /// already separated; a zero-operand operator (`S`, `h`, `n`) sits on
608 /// its own line. One operation per line keeps authored streams
609 /// `diff`-friendly and is the form the §8.10 W-F worked examples use.
610 fn finish_op(&mut self, keyword: &[u8]) {
611 self.out.extend_from_slice(keyword);
612 self.out.push(b'\n');
613 }
614
615 /// One numeric operand + operator (`v op`).
616 fn op1(&mut self, v: f64, keyword: &[u8]) {
617 self.operand(v);
618 self.finish_op(keyword);
619 }
620
621 /// Two numeric operands + operator (`a b op`).
622 fn op2(&mut self, a: f64, b: f64, keyword: &[u8]) {
623 self.operand(a);
624 self.operand(b);
625 self.finish_op(keyword);
626 }
627
628 /// Three numeric operands + operator (`a b c op`).
629 fn op3(&mut self, a: f64, b: f64, c: f64, keyword: &[u8]) {
630 self.operand(a);
631 self.operand(b);
632 self.operand(c);
633 self.finish_op(keyword);
634 }
635
636 /// Four numeric operands + operator (`a b c d op`).
637 fn op4(&mut self, a: f64, b: f64, c: f64, d: f64, keyword: &[u8]) {
638 self.operand(a);
639 self.operand(b);
640 self.operand(c);
641 self.operand(d);
642 self.finish_op(keyword);
643 }
644
645 /// Debug-only W-E ordering guard: colour/graphics-state operators are
646 /// illegal inside a path object (§8.2 Figure 9). A content builder has
647 /// no untrusted input, so this is an implementation-bug tripwire in
648 /// tests, never a runtime refusal.
649 fn debug_assert_not_in_path(&self, op: &str) {
650 debug_assert!(
651 !self.in_path,
652 "W-E ordering: {op} is illegal inside a path object; emit it before move_to/rect"
653 );
654 }
655}
656
657/// Emit a number operand in canonical content-stream form (§7.3.3,
658/// A1–A3): integer form for an integral value, real form otherwise.
659///
660/// Integral values within the `i64` range emit without a decimal point
661/// (`10`, not `10.0`) — compact, and the spelling the §8.10 W-F examples
662/// use. Everything else routes through [`write_real`], which guarantees
663/// fixed-point (never exponential) output and degrades a non-finite value
664/// to `0.0` rather than emitting a token no reader can parse.
665#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
666pub fn emit_number(out: &mut Vec<u8>, v: f64) {
667 if v.is_finite() && v.fract() == 0.0 && v.abs() < 9.007_199_254_740_992e15 {
668 // Exactly representable as an integer; emit integer form.
669 out.extend_from_slice((v as i64).to_string().as_bytes());
670 } else {
671 write_real(out, v);
672 }
673}
674
675/// Emit `bytes` as a §7.3.4.2 literal string operand `(…)` for a `Tj`
676/// showing operator. `(`, `)` and `\` are backslash-escaped; every byte
677/// outside the printable ASCII range `0x20..=0x7E` is written as a
678/// three-digit octal escape (`\ooo`). This keeps an authored content
679/// stream ASCII and paren-balanced for arbitrary (e.g. `WinAnsi`
680/// high-byte) text, at the cost of never using the raw-byte form a
681/// hand-written stream might — a deterministic, reader-safe choice for a
682/// generator (the raw high bytes and the octal escape denote the same
683/// string per §7.3.4.2).
684#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
685pub fn emit_literal_string(out: &mut Vec<u8>, bytes: &[u8]) {
686 out.push(b'(');
687 for &b in bytes {
688 match b {
689 b'(' | b')' | b'\\' => {
690 out.push(b'\\');
691 out.push(b);
692 }
693 0x20..=0x7E => out.push(b),
694 other => {
695 // Three-digit octal escape, always three digits so a
696 // following digit cannot extend it (§7.3.4.2).
697 out.push(b'\\');
698 out.push(b'0' + (other >> 6));
699 out.push(b'0' + ((other >> 3) & 0o7));
700 out.push(b'0' + (other & 0o7));
701 }
702 }
703 }
704 out.push(b')');
705}
706
707/// The R46 identity gate's re-emission: reconstruct a parsed content
708/// stream's bytes, re-emitting **numeric operands from their parsed value**
709/// and copying **everything else verbatim** from the source span.
710///
711/// ## Why this exact split is the mechanically self-enforcing X6 guard
712///
713/// X6 is silent content-stream normalization: a serializer that emits
714/// `1.0` as `1`, drops a leading `+`, collapses whitespace, or reorders
715/// operands produces a plausible, working, **wrong** stream that passes
716/// every structural check. The geometric serializer this Pass ships emits
717/// exactly one class of thing that carries a normalization hazard —
718/// **numbers** (coordinates, colours, widths). So the gate re-emits every
719/// numeric operand in the corpus through the same [`emit_number`] /
720/// [`write_real`] path the authoring builder uses, and copies strings,
721/// names, arrays, dictionaries, inline images, operators, whitespace and
722/// comments **verbatim** (a geometric serializer must never touch those,
723/// and re-emitting a `TJ` array's internal spacing from value would drown
724/// the signal in legal-whitespace noise).
725///
726/// The result: a stream whose numbers are already in canonical form
727/// re-emits **byte-identically**, and one that is not is enumerated by the
728/// caller with the first divergence as its reason (`1.` → `1.0`, `+5` →
729/// `5`, `.5` → `0.5`). If a future edit to [`write_real`] or
730/// [`emit_number`] ever normalizes a value it should not, the byte-compare
731/// flips red across hundreds of corpus files at once — the same mechanism
732/// that made the object-writer's R33 self-enforcing, one level down (R46).
733///
734/// The returned bytes are compared by the caller against `stream.buf` (the
735/// decoded content buffer every token span indexes).
736#[must_use]
737pub fn reemit_canonical(stream: &ContentStream) -> Vec<u8> {
738 let buf = &stream.buf;
739 let mut out = Vec::with_capacity(buf.len());
740 let mut cursor = 0usize;
741 for token in &stream.tokens {
742 // Inter-token bytes (whitespace, comments) are not part of any
743 // token span; copy them verbatim so the gate is never confounded
744 // by legal formatting a serializer must preserve.
745 if let Some(gap) = buf.get(cursor..token.span.start) {
746 out.extend_from_slice(gap);
747 }
748 emit_token_canonical(&mut out, buf, token);
749 cursor = token.span.end();
750 }
751 // Trailing bytes after the last token (final whitespace/comment).
752 if let Some(tail) = buf.get(cursor..) {
753 out.extend_from_slice(tail);
754 }
755 out
756}
757
758/// Re-emit one token: a numeric operand from its parsed value (the X6
759/// target), everything else verbatim from its source span.
760fn emit_token_canonical(out: &mut Vec<u8>, buf: &[u8], token: &ContentToken) {
761 let verbatim = |out: &mut Vec<u8>| {
762 if let Some(bytes) = token.span.slice(buf) {
763 out.extend_from_slice(bytes);
764 }
765 };
766 match &token.kind {
767 ContentTokenKind::Operand(Object::Integer(v)) => {
768 out.extend_from_slice(v.to_string().as_bytes());
769 }
770 ContentTokenKind::Operand(Object::Real(v)) => {
771 write_real(out, *v);
772 }
773 // Strings, names, booleans, null, arrays and dictionaries re-emit
774 // verbatim: a geometric serializer authors none of them, and
775 // re-emitting a string's escaping or an array's internal spacing
776 // from value would be normalization the gate must not itself
777 // introduce. Names in particular are non-canonical on read
778 // (`/A#42` ≡ `/AB`, §7.3.5 NOTE 1) and must survive byte-exact.
779 ContentTokenKind::Operand(_) | ContentTokenKind::Operator => verbatim(out),
780 // An inline image is one indivisible token including its raw data
781 // bytes; always verbatim.
782 ContentTokenKind::InlineImage { .. } => verbatim(out),
783 }
784}
785
786/// Classify why a re-emitted token diverged from its source bytes, for the
787/// R46 gate's by-file/by-reason enumeration (R20). Returns `None` when the
788/// token re-emits identically. Only numeric operands can diverge (the only
789/// tokens [`reemit_canonical`] re-emits from value), so the reason is
790/// always a number-spelling normalization.
791#[must_use]
792pub fn number_divergence_reason(buf: &[u8], token: &ContentToken) -> Option<String> {
793 let source = token.span.slice(buf)?;
794 let mut canonical = Vec::new();
795 match &token.kind {
796 ContentTokenKind::Operand(Object::Integer(v)) => {
797 canonical.extend_from_slice(v.to_string().as_bytes());
798 }
799 ContentTokenKind::Operand(Object::Real(v)) => write_real(&mut canonical, *v),
800 _ => return None,
801 }
802 if canonical == source {
803 return None;
804 }
805 Some(format!(
806 "{} -> {}",
807 String::from_utf8_lossy(source),
808 String::from_utf8_lossy(&canonical)
809 ))
810}
811
812#[cfg(test)]
813#[allow(
814 clippy::unwrap_used,
815 clippy::expect_used,
816 clippy::panic,
817 clippy::indexing_slicing,
818 clippy::float_cmp
819)]
820mod tests {
821 use super::*;
822
823 fn s(bytes: &[u8]) -> String {
824 String::from_utf8(bytes.to_vec()).unwrap()
825 }
826
827 #[test]
828 fn empty_builder_is_a_valid_empty_appearance() {
829 // §8.10 W-C: the empty content stream is a conforming appearance.
830 assert!(ContentBuilder::new().into_bytes().is_empty());
831 }
832
833 #[test]
834 fn line_worked_example_matches_the_spec() {
835 // §8.10 W-F red 2-unit Line: W-E ordering, colour + width before m.
836 let mut b = ContentBuilder::new();
837 b.set_stroke_rgb(1.0, 0.0, 0.0);
838 b.set_line_width(2.0);
839 b.move_to(10.0, 10.0);
840 b.line_to(90.0, 40.0);
841 b.paint(Paint::Stroke);
842 assert_eq!(s(&b.into_bytes()), "1 0 0 RG\n2 w\n10 10 m\n90 40 l\nS\n");
843 }
844
845 #[test]
846 fn filled_stroked_square_sets_both_colours_before_the_path() {
847 // §8.10 W-F: B fills (non-stroking colour) then strokes (stroking).
848 let mut b = ContentBuilder::new();
849 b.set_fill_rgb(1.0, 1.0, 0.0);
850 b.set_stroke_rgb(0.0, 0.0, 1.0);
851 b.set_line_width(2.0);
852 b.rect(1.0, 1.0, 98.0, 58.0);
853 b.paint(Paint::FillStroke);
854 assert_eq!(
855 s(&b.into_bytes()),
856 "1 1 0 rg\n0 0 1 RG\n2 w\n1 1 98 58 re\nB\n"
857 );
858 }
859
860 #[test]
861 fn integral_values_emit_integer_form_reals_keep_the_point() {
862 let mut out = Vec::new();
863 emit_number(&mut out, 10.0);
864 emit_number(&mut out, 0.5);
865 emit_number(&mut out, -3.0);
866 assert_eq!(s(&out), "100.5-3");
867 }
868
869 #[test]
870 fn number_emission_never_uses_exponential_notation() {
871 // §7.3.3 has no exponent; the write_real path must expand it.
872 let mut out = Vec::new();
873 emit_number(&mut out, 0.000_002);
874 assert!(!s(&out).contains('e') && !s(&out).contains('E'));
875 }
876
877 #[test]
878 fn dash_solid_and_patterned() {
879 let mut b = ContentBuilder::new();
880 b.set_dash(&[], 0.0);
881 b.set_dash(&[3.0, 2.0], 1.0);
882 assert_eq!(s(&b.into_bytes()), "[] 0 d\n[3 2] 1 d\n");
883 }
884
885 #[test]
886 fn caps_joins_and_gs_emit_their_codes_and_names() {
887 let mut b = ContentBuilder::new();
888 b.set_line_cap(LineCap::Round);
889 b.set_line_join(LineJoin::Bevel);
890 b.set_ext_gstate(b"GS0");
891 assert_eq!(s(&b.into_bytes()), "1 J\n2 j\n/GS0 gs\n");
892 }
893
894 #[test]
895 fn curve_emits_six_operands() {
896 let mut b = ContentBuilder::new();
897 b.move_to(0.0, 0.0);
898 b.curve_to(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
899 b.paint(Paint::Fill);
900 assert_eq!(s(&b.into_bytes()), "0 0 m\n1 2 3 4 5 6 c\nf\n");
901 }
902
903 #[cfg(debug_assertions)]
904 #[test]
905 #[should_panic(expected = "W-E ordering")]
906 fn colour_inside_a_path_object_trips_the_debug_guard() {
907 // The non-conforming counter-example from §8.10 W-E:
908 // `10 10 m ... RG` — colour after m is illegal.
909 let mut b = ContentBuilder::new();
910 b.move_to(10.0, 10.0);
911 b.set_stroke_rgb(1.0, 0.0, 0.0);
912 }
913
914 // -- R46 identity-gate re-emission ---------------------------------
915
916 fn reemit(input: &[u8]) -> Vec<u8> {
917 let cs = ContentStream::parse(input.to_vec()).unwrap();
918 reemit_canonical(&cs)
919 }
920
921 #[test]
922 fn canonical_stream_reemits_byte_identically() {
923 // Integers, canonical reals, names, strings, arrays, operators and
924 // varied whitespace all survive verbatim.
925 for input in [
926 &b"q 1 0 0 1 72 712 cm BT /F1 12 Tf (Hello) Tj ET Q"[..],
927 b"0.5 0 0 0.5 0 0 cm /Im1 Do",
928 b"[(He)-20(llo)] TJ",
929 b"1 0 0 RG\n2 w\n10 10 m\n90 40 l\nS\n",
930 b"% a comment\n1 1 1 rg\n0 0 10 10 re f\n",
931 ] {
932 assert_eq!(reemit(input), input, "{}", s(input));
933 }
934 }
935
936 #[test]
937 fn non_canonical_numbers_are_normalized_and_flagged() {
938 // `1.` -> `1.0`, `+5` -> `5`, `.5` -> `0.5`: the X6 targets. Each
939 // is a byte change, and number_divergence_reason names it.
940 let cs = ContentStream::parse(b"1. +5 .5 re".to_vec()).unwrap();
941 assert_ne!(reemit_canonical(&cs), cs.buf);
942 let reasons: Vec<String> = cs
943 .tokens
944 .iter()
945 .filter_map(|t| number_divergence_reason(&cs.buf, t))
946 .collect();
947 assert_eq!(reasons, vec!["1. -> 1.0", "+5 -> 5", ".5 -> 0.5"]);
948 }
949
950 #[test]
951 fn inline_image_reemits_verbatim_including_its_data() {
952 // The image data bytes must not be re-interpreted as tokens.
953 let input: &[u8] = b"BI /W 2 /H 2 /CS /G /BPC 8 ID \x45\x49\x00\xFF EI Q";
954 assert_eq!(reemit(input), input);
955 }
956
957 #[test]
958 fn a_string_with_non_canonical_number_neighbours_survives() {
959 // Names are non-canonical on read (§7.3.5) — must be verbatim.
960 let input: &[u8] = b"/A#42 12 Tf";
961 assert_eq!(reemit(input), input);
962 }
963}