pdfcer_function/function.rs
1//! # `function` — PDF function objects (ISO 32000-1 §7.10)
2//!
3//! A PDF *function* is a static, self-contained numerical transformation:
4//! *m* input numbers in, *n* output numbers out, no side effects, no state.
5//! §7.10's opening paragraph is emphatic that this is **not** a programming
6//! facility — *"PDF is not a programming language, and a PDF file is not a
7//! program"* — and that framing is load-bearing for this module. Everything
8//! here is a pure function of its inputs; nothing reads the document, the
9//! graphics state, or the clock.
10//!
11//! ## Why this module exists at all
12//!
13//! Nothing in pdfcer could evaluate a function before this module, and that
14//! single gap blocked four unrelated features at once. A function is the
15//! representation the standard reaches for whenever a value has to be
16//! *computed* rather than looked up:
17//!
18//! | Consumer | Clause | What the function does there |
19//! |---|---|---|
20//! | `Separation` colour space | §8.6.6.4 | tint → alternate-space components |
21//! | `DeviceN` colour space | §8.6.6.5 | *k* tints → alternate-space components |
22//! | Shading dictionaries | §8.7.4 | parametric coordinate → colour |
23//! | Soft-mask transfer function (`/TR`) | §11.6.5.2 | mask value → mask value |
24//! | ExtGState `/TR`, `/TR2`, `/BG`, `/UCR` | §8.4.5 | tone/black-generation curves |
25//! | Halftone spot functions, `/DotGain` | §10.5.3, §8.6.6.5 | screening |
26//!
27//! One evaluator serves all of them, which is the reason this lives in
28//! `pdfcer-core` rather than beside any one consumer. A second, specialised
29//! copy would drift, and a tint transform that disagrees with a shading's
30//! transform over the same function object is a defect nobody would think to
31//! look for.
32//!
33//! ## The four types, and the missing one
34//!
35//! | `/FunctionType` | Name | PDF | Carried as | `/Range` |
36//! |---|---|---|---|---|
37//! | **0** | Sampled | 1.2 | **stream** | **Required** |
38//! | **2** | Exponential interpolation | 1.3 | dictionary | Optional |
39//! | **3** | Stitching | 1.3 | dictionary | Optional |
40//! | **4** | PostScript calculator | 1.3 | **stream** | **Required** |
41//!
42//! There is **no type 1**. The gap is real, not a transcription slip, and
43//! [`FunctionError::UnknownFunctionType`] reports `1` exactly like it reports
44//! `7` — this module never invents a meaning for it.
45//!
46//! `/Range` is required for types 0 and 4 because *n* cannot be recovered any
47//! other way (§7.10.1: *"The number of output values can usually be inferred
48//! from other attributes of the function; if not (as is always the case for
49//! type 0 and type 4 functions), the `Range` entry is required"*). For types 2
50//! and 3 it is optional, and **its absence means no output clipping at all** —
51//! see the clamping section below, because getting that backwards is the
52//! single most damaging mistake available in this file.
53//!
54//! ## Clamping is specified, not optional
55//!
56//! Table 38, on `/Domain`: *"Input values outside the declared domain **shall**
57//! be clipped to the nearest boundary value."*
58//!
59//! Table 38, on `/Range`: *"Output values outside the declared range **shall**
60//! be clipped to the nearest boundary value. **If this entry is absent, no
61//! clipping shall be done.**"*
62//!
63//! Both are `shall`s, and both are implemented once, centrally, in
64//! [`PdfFunction::eval_into`] — not per type — so no type can be written that
65//! forgets one. The asymmetry in the second rule is why [`PdfFunction::range`]
66//! returns `Option` rather than a defaulted `[0, 1]` per output: a shading
67//! function whose outputs were silently squeezed into the unit interval
68//! produces colour that is wrong in a way that still *looks* like colour.
69//!
70//! A tint of `1.4` is therefore evaluated as `1.0`, and a CMYK component of
71//! `-0.2` coming out of a transform with a `/Range` of `[0 1 0 1 0 1 0 1]` is
72//! clamped to `0.0`. Neither is a tolerance; both are the standard.
73//!
74//! ## Refusal posture: a wrong colour is worse than no colour
75//!
76//! §7.10.5.2 is the only place in §7.10 that addresses failure, it covers
77//! **type 4 only**, and it explicitly declines to say what a reader should do:
78//! *"This specification does not define a representation for the errors; those
79//! details shall be provided by the conforming reader."* For types 0, 2 and 3
80//! the standard says nothing at all about a truncated sample stream, a
81//! `/Bounds` array out of order, or a negative `/N` with `x = 0`.
82//!
83//! So the failure behaviour here is **pdfcer policy, chosen deliberately**, and
84//! recorded as such (the spec RAG files this as negative result `F-N1` in
85//! `iso32000__s__7.10.md`): every malformed function is **refused by name**.
86//! [`FunctionError`] never degrades to a plausible substitute — no all-zero
87//! output vector, no identity transform, no black. The reason is specific to
88//! colour: an empty output vector read as "all components zero" is *white* in
89//! `DeviceCMYK` and *black* in `DeviceGray`, so any silent substitution is
90//! guaranteed to be catastrophically wrong for half of its callers while
91//! looking entirely reasonable. A named error lets the caller disclose the
92//! failure (project rule 4, fuzzy-never-sneaky); a fabricated colour cannot be
93//! distinguished from a real one downstream.
94//!
95//! ## Resource bounds
96//!
97//! Functions are attacker-controlled input (`ARCHITECTURE.md` §10). Every loop
98//! in this module is bounded:
99//!
100//! | Bound | Value | Source |
101//! |---|---|---|
102//! | [`PS_STACK_LIMIT`] | 100 | **spec** — §7.10.5.1 `shall`-minimum |
103//! | [`MAX_PS_STEPS`] | 1,000,000 | **pdfcer policy** — no spec equivalent |
104//! | [`MAX_PS_NESTING`] | 32 | **pdfcer policy** — no spec equivalent |
105//! | [`MAX_SAMPLED_INPUTS`] | 8 | **pdfcer policy**, spec-sanctioned (§7.10.2) |
106//! | [`MAX_FUNCTION_DEPTH`] | 8 | **pdfcer policy** — no spec equivalent |
107//!
108//! The distinction between the first row and the rest is not pedantry. The
109//! 100-entry stack is a conformance fact: §7.10.5.1 says an implementation
110//! *"shall provide a stack with room for at least 100 entries"*, that *"no
111//! implementation shall be required to provide a larger stack"*, and that it
112//! *"shall be an error to overflow the stack"*. A fixed 100-entry stack that
113//! errors on overflow is therefore **exactly conformant**, and growing it
114//! dynamically would not be robustness — it would be inventing a dialect that
115//! only pdfcer can run.
116//!
117//! The step and nesting caps have no such backing. ISO 32000-1 imposes no
118//! limit on how many operators a type 4 program may execute, so a program that
119//! never terminates is *legal* and a conforming reader must still not hang.
120//! [`MAX_PS_STEPS`] is pdfcer's answer to that, and it is a policy number that
121//! may be tuned; it is not a claim about the standard.
122//!
123//! [`MAX_SAMPLED_INPUTS`] sits between the two. §7.10.2 says there is *"no
124//! dimensionality limit of a sampled function **except for possible
125//! implementation limits**"* — an explicit licence to impose one. Eight is
126//! chosen because multilinear interpolation visits 2^m corners per evaluation
127//! (256 at m = 8) and a `DeviceN` image runs the transform once per pixel; the
128//! spec's own worked example of a hard case is a six-component hexachrome.
129//!
130//! ## Spec sources
131//!
132//! - `iso32000__s__7.10.md` — §7.10 in full: Tables 38–42, the type 0
133//! evaluation algorithm, the type 3 partition rule, §7.10.5.2's error list,
134//! and the recorded ambiguities `F-A1` (cubic spline unspecified), `F-A2`
135//! (multilinear named only in an informative NOTE) and `F-N1`/`F-N2` (no
136//! fallback for an unevaluatable function or an arity mismatch).
137//! - `iso32000__annex__b.md` — **ISO 32000-1 Annex B, `(normative)`,
138//! "Operators in Type 4 Functions"**: the stack effect, arity and
139//! operand/result typing of all 42 Table 42 entries. §7.10.5 never
140//! cross-references it, so it is easy to conclude from the clause alone that
141//! the operator semantics are unsourceable inside ISO 32000-1. They are not.
142//! - PLRM3 §8.2 (`_sources/Adobe_PLRM3_1999.pdf`) — what Annex B leaves out:
143//! rounding directions, sign conventions, integer preservation, `atan`'s
144//! `[0, 360)` normalisation, the zero-fill of a right shift. §7.10.5.1 points
145//! at PLRM3's *"Appendix B"* for this, which is a **misdirected
146//! cross-reference** (erratum `F-E3`) — that appendix is *Implementation
147//! Limits*; the operators are Chapter 8. PLRM3 is a Bibliography reference
148//! and therefore *informative*, so it is cited alongside Annex B, never
149//! instead of it.
150//! - `iso32000__s__7.3.8.md` — stream extent, for the type 0 "long enough"
151//! rule.
152//! - `iso32000__annex__c.md` — implementation limits, which type 4
153//! *intermediates* are explicitly exempt from.
154
155use pdfcer_model::filters::{self, FilterError};
156use pdfcer_model::graph::ObjectGraph as _;
157use pdfcer_model::lexer::{LexError, Lexer, TokenKind};
158use pdfcer_model::object::{Dict, Object, Stream};
159use pdfcer_model::view::DocumentView;
160
161mod breaks;
162
163// ---------------------------------------------------------------------------
164// Resource bounds
165// ---------------------------------------------------------------------------
166
167/// Operand-stack capacity for a type 4 program — **a spec value, not policy**.
168///
169/// §7.10.5.1: *"Implementations of type 4 functions shall provide a stack with
170/// room for at least 100 entries. No implementation shall be required to
171/// provide a larger stack, and it shall be an error to overflow the stack."*
172///
173/// Both halves matter. 100 is a floor pdfcer must meet, and it is simultaneously
174/// a ceiling pdfcer is entitled to stop at — so overflowing at exactly 100 with
175/// [`FunctionError::StackOverflow`] is conformant behaviour, not a limitation.
176/// A program that needs 101 entries is malformed by the standard's own
177/// definition; accommodating it would mean silently accepting files that no
178/// other conforming reader accepts.
179pub const PS_STACK_LIMIT: usize = 100;
180
181/// Maximum operators a single type 4 evaluation may execute — **pdfcer policy**.
182///
183/// **ISO 32000-1 imposes no execution-step limit of any kind.** Annex C's
184/// implementation limits cover object sizes and nesting in the file grammar,
185/// and §7.10.5.1 explicitly grants type 4 *intermediate results* an exemption
186/// from even those: *"the intermediate results in type 4 function computations
187/// shall not [fall under those limits]. An implementation may use a
188/// representation that exceeds those limits."* There is no clause to cite for
189/// a step cap, which is exactly why this one is labelled policy.
190///
191/// **What it actually defends against, stated honestly.** Table 42 has no jump,
192/// loop or repeat operator, and a `{ … }` block runs at most once per
193/// `if`/`ifelse` it is attached to — so an evaluation's step count is bounded
194/// above by the number of nodes in the parsed program. A type 4 function
195/// therefore cannot hang. The hazard is *size*, not looping: a function stream
196/// may decode to as much as [`pdfcer_model::filters::MAX_DECODED_LEN`] (256 MiB), which
197/// is room for tens of millions of operators, and a `DeviceN` image runs the
198/// transform **once per pixel**. This cap keeps that product bounded.
199///
200/// One million steps is several orders of magnitude beyond any legitimate tint
201/// transform (real ones run in tens of operators — the spec's own DoubleDot
202/// example is nine) while keeping a hostile function's per-evaluation cost to
203/// milliseconds. Tunable; not a conformance claim.
204pub const MAX_PS_STEPS: usize = 1_000_000;
205
206/// Maximum `{ }` nesting depth inside a type 4 program — **pdfcer policy**.
207///
208/// §7.10.5.1 describes the brace syntax for `if`/`ifelse` and states no depth
209/// limit; Annex C's nesting limits are about the *file* grammar (arrays and
210/// dictionaries), not this sub-language. The cap exists because the parser
211/// recurses one frame per `{`, and `pdfcer-core`'s panic-free policy treats a
212/// stack overflow from untrusted input exactly as seriously as an `unwrap` —
213/// an abort is not a graceful refusal.
214///
215/// 32 is far past any hand-written or machine-generated transform; the deepest
216/// realistic construct is a handful of nested `ifelse` branches.
217pub const MAX_PS_NESTING: usize = 32;
218
219/// Maximum input dimensionality of a type 0 sampled function — **pdfcer policy,
220/// explicitly permitted by the spec**.
221///
222/// §7.10.2: *"There shall be no dimensionality limit of a sampled function
223/// except for possible implementation limits."* That clause grants the limit;
224/// it does not set it.
225///
226/// Eight is chosen from the cost of the evaluation itself. Multilinear
227/// interpolation reads 2^m table corners per evaluation — 256 at m = 8, 65,536
228/// at m = 16 — and a `DeviceN` image runs the transform once per pixel, so the
229/// exponent is multiplied by megapixels. The spec's own illustration of an
230/// expensive case is a six-component hexachrome `DeviceN`, which fits.
231pub const MAX_SAMPLED_INPUTS: usize = 8;
232
233/// Maximum nesting depth of type 3 stitching sub-functions — **pdfcer policy**.
234///
235/// A type 3 function's `/Functions` array may itself contain type 3 functions,
236/// and nothing in §7.10.4 forbids a cycle through indirect references
237/// (`5 0 obj << /FunctionType 3 /Functions [5 0 R] … >>` is syntactically
238/// legal). Without a depth guard, loading that recurses forever.
239///
240/// This is the same class of guard `ARCHITECTURE.md` §10 requires on every
241/// recursive structure walker. Eight levels is far beyond the one or two
242/// levels real stitching functions use.
243pub const MAX_FUNCTION_DEPTH: usize = 8;
244
245/// Sample widths `/BitsPerSample` may take (§7.10.2 Table 39).
246///
247/// *"Valid values shall be 1, 2, 4, 8, 12, 16, 24, and 32."* Note what is
248/// **not** in the list: 3, 5, 6, 10, 64. The set is closed, so
249/// [`FunctionError::BadBitsPerSample`] is a refusal with spec backing rather
250/// than an implementation gap.
251pub const VALID_BITS_PER_SAMPLE: [u32; 8] = [1, 2, 4, 8, 12, 16, 24, 32];
252
253// ---------------------------------------------------------------------------
254// Errors
255// ---------------------------------------------------------------------------
256
257/// Everything that can stop a function from loading or evaluating.
258///
259/// Follows the Rust API Guidelines' `C-GOOD-ERR`: implements
260/// [`std::error::Error`] through `thiserror` and is `Send + Sync + 'static`.
261/// `#[non_exhaustive]` so later work (a cubic-spline evaluator, a type 5) can
262/// add variants without a breaking change.
263///
264/// Every variant names *what* was wrong specifically enough that a caller can
265/// put it in front of the operator. That is the whole point — see the module
266/// docs' refusal-posture section for why there is no `Unknown` catch-all and no
267/// silent degradation.
268#[derive(Debug, Clone, PartialEq, thiserror::Error)]
269#[non_exhaustive]
270pub enum FunctionError {
271 /// The object is not a dictionary or a stream, so it cannot be a function
272 /// (§7.10.1: every type is one or the other).
273 #[error("function object is neither a dictionary nor a stream")]
274 NotAFunction,
275
276 /// `/FunctionType` is absent or is not an integer.
277 #[error("/FunctionType is missing or not an integer")]
278 MissingFunctionType,
279
280 /// `/FunctionType` held a value §7.10 does not define. **`1` reaches here
281 /// too** — there is no type 1 (module docs).
282 #[error("unknown /FunctionType {0} (ISO 32000-1 §7.10 defines 0, 2, 3 and 4 only)")]
283 UnknownFunctionType(i64),
284
285 /// The type requires a stream (types 0 and 4 carry their payload as stream
286 /// data) but the object was a bare dictionary.
287 #[error("/FunctionType {function_type} must be a stream, not a dictionary")]
288 NotAStream {
289 /// The declared `/FunctionType`.
290 function_type: i64,
291 },
292
293 /// The stream's byte span could not be served by the view — a truncated
294 /// file or a span from a different document (see
295 /// [`pdfcer_model::view::StreamSource::slice`]).
296 #[error("the function stream's data span could not be read from this document")]
297 StreamUnreadable,
298
299 /// The stream's `/Filter` chain failed to decode.
300 #[error("function stream decode failed: {0}")]
301 Filter(#[from] FilterError),
302
303 /// A required entry is absent.
304 #[error("/{key} is required for /FunctionType {function_type} and is missing")]
305 MissingEntry {
306 /// The absent key, without its leading solidus.
307 key: &'static str,
308 /// The declared `/FunctionType`.
309 function_type: i64,
310 },
311
312 /// An entry is present but structurally wrong (not an array, holds a
313 /// non-number, an odd element count where pairs are required, …).
314 #[error("/{key} is malformed: {detail}")]
315 BadEntry {
316 /// The offending key, without its leading solidus.
317 key: &'static str,
318 /// What specifically was wrong.
319 detail: String,
320 },
321
322 /// An array's length disagrees with the dimensionality every other entry
323 /// implies. Table 38: the dimensionality *"shall be consistent"*.
324 #[error("/{key} has {got} elements; {expected} required for this function's dimensionality")]
325 BadArrayLength {
326 /// The offending key, without its leading solidus.
327 key: &'static str,
328 /// The length the rest of the function implies.
329 expected: usize,
330 /// The length actually found.
331 got: usize,
332 },
333
334 /// A `/Domain` or `/Range` pair had its bounds inverted. Table 38 requires
335 /// `Domain_2i <= Domain_2i+1`.
336 #[error("/{key} pair {index} is inverted: [{low}, {high}]")]
337 InvertedInterval {
338 /// `Domain` or `Range`.
339 key: &'static str,
340 /// Which pair (0-based).
341 index: usize,
342 /// The declared lower bound.
343 low: f64,
344 /// The declared upper bound.
345 high: f64,
346 },
347
348 /// Input dimensionality exceeded [`MAX_SAMPLED_INPUTS`].
349 #[error(
350 "sampled function has {got} inputs; pdfcer's limit is {limit} (§7.10.2 permits an implementation limit)"
351 )]
352 TooManyInputs {
353 /// The declared *m*.
354 got: usize,
355 /// [`MAX_SAMPLED_INPUTS`].
356 limit: usize,
357 },
358
359 /// `/BitsPerSample` was not one of [`VALID_BITS_PER_SAMPLE`].
360 #[error("/BitsPerSample {0} is not one of 1, 2, 4, 8, 12, 16, 24, 32 (§7.10.2 Table 39)")]
361 BadBitsPerSample(i64),
362
363 /// The sample table implied by `/Size`, `/Range` and `/BitsPerSample`
364 /// needs more bytes than the decoded stream holds (§7.10.2: *"The stream
365 /// data shall be long enough to contain the entire sample array"*).
366 #[error(
367 "sample stream holds {have} bytes; {need} required by /Size, /Range and /BitsPerSample"
368 )]
369 SampleDataTooShort {
370 /// Bytes the table requires.
371 need: usize,
372 /// Bytes actually decoded.
373 have: usize,
374 },
375
376 /// `/Size`'s product overflowed `usize`, or the resulting bit count did.
377 /// The table cannot exist, so the arithmetic is refused rather than
378 /// wrapped.
379 #[error("the sample table implied by /Size and /BitsPerSample overflows address arithmetic")]
380 SampleTableTooLarge,
381
382 /// A sample index fell outside the validated table. Structurally
383 /// unreachable — the load-time length check makes every index computable
384 /// from a clamped input in range — and reported rather than papered over
385 /// so that a future refactor which breaks the invariant is visible instead
386 /// of silently reading zeros.
387 #[error("internal: sample index {index} is outside the validated sample table")]
388 SampleIndexOutOfRange {
389 /// The offending flat sample index.
390 index: usize,
391 },
392
393 /// Type 2's `/N` is non-integral while `/Domain` admits a negative `x`, or
394 /// `/N` is negative while `/Domain` admits `x = 0`. §7.10.3: *"Values of
395 /// `Domain` shall constrain x in such a way that if N is not an integer,
396 /// all values of x shall be non-negative, and if N is negative, no value
397 /// of x shall be zero."* Both cases would evaluate to `NaN` or infinity.
398 #[error("/Domain [{low}, {high}] does not constrain x for /N {n} (§7.10.3)")]
399 DomainIncompatibleWithExponent {
400 /// The exponent.
401 n: f64,
402 /// `Domain_0`.
403 low: f64,
404 /// `Domain_1`.
405 high: f64,
406 },
407
408 /// A type 2 or type 3 function declared more than one input. §7.10.3 and
409 /// §7.10.4 both restrict these to *m* = 1.
410 #[error("/FunctionType {function_type} takes exactly one input; /Domain declares {got}")]
411 NotOneInput {
412 /// The declared `/FunctionType`.
413 function_type: i64,
414 /// The *m* implied by `/Domain`.
415 got: usize,
416 },
417
418 /// A type 3's `/Functions` array was empty. §7.10.4 allows *k* = 1 but not
419 /// *k* = 0 — with no sub-function there is nothing to evaluate and *n* is
420 /// undefined.
421 #[error("/Functions is empty; a stitching function needs at least one sub-function")]
422 NoSubFunctions,
423
424 /// Two sub-functions of a type 3 disagree on output dimensionality.
425 /// §7.10.4: *"The output dimensionality of all functions shall be the
426 /// same."*
427 #[error(
428 "/Functions sub-function {index} produces {got} outputs; sub-function 0 produces {expected}"
429 )]
430 SubFunctionArity {
431 /// Which sub-function disagreed.
432 index: usize,
433 /// The count set by sub-function 0.
434 expected: usize,
435 /// The count this one declared.
436 got: usize,
437 },
438
439 /// `/Bounds` was not in non-decreasing order, or a bound fell outside
440 /// `/Domain`. §7.10.4: *"`Bounds` elements shall be in order of increasing
441 /// value, and each value shall be within the domain defined by `Domain`."*
442 #[error("/Bounds is not a valid partition of /Domain: {detail}")]
443 BadBounds {
444 /// What specifically was wrong.
445 detail: String,
446 },
447
448 /// Function nesting (type 3 sub-functions) exceeded [`MAX_FUNCTION_DEPTH`],
449 /// which also catches a reference cycle through `/Functions`.
450 #[error(
451 "function nesting exceeded pdfcer's depth limit of {limit} (cycle, or pathologically nested /Functions)"
452 )]
453 NestingTooDeep {
454 /// [`MAX_FUNCTION_DEPTH`].
455 limit: usize,
456 },
457
458 /// The type 4 program stream did not lex.
459 #[error("type 4 program lex error: {0}")]
460 PostScriptLex(#[from] LexError),
461
462 /// The type 4 program lexed but did not parse (missing outer braces, a
463 /// brace block not consumed by `if`/`ifelse`, an unterminated block, …).
464 /// §7.10.5.2 makes reader-side syntax detection a `shall`.
465 #[error("type 4 program syntax error: {detail}")]
466 PostScriptSyntax {
467 /// What specifically was wrong.
468 detail: String,
469 },
470
471 /// A token in the type 4 program is not one of Table 42's 42 operators.
472 ///
473 /// The set is closed: §7.10.5.1 introduces it as *"Table 42 lists the
474 /// operators that can be used in this type of function"*, and the same
475 /// paragraph bans everything a name could otherwise refer to — *"no
476 /// composite data structures such as strings or arrays, no procedures, and
477 /// no variables or names"*. So an unrecognised token is a defect in the
478 /// file, not a gap in pdfcer.
479 #[error("unknown type 4 operator {0:?}; §7.10.5.1 Table 42 is the complete operator set")]
480 UnknownOperator(String),
481
482 /// `{ }` nesting exceeded [`MAX_PS_NESTING`].
483 #[error("type 4 program brace nesting exceeded pdfcer's limit of {limit}")]
484 PostScriptNestingTooDeep {
485 /// [`MAX_PS_NESTING`].
486 limit: usize,
487 },
488
489 /// The operand stack grew past [`PS_STACK_LIMIT`]. §7.10.5.2 lists stack
490 /// overflow first among the errors a reader *"shall detect and report"*.
491 #[error("type 4 operand stack overflowed the {limit}-entry limit (§7.10.5.1)")]
492 StackOverflow {
493 /// [`PS_STACK_LIMIT`].
494 limit: usize,
495 },
496
497 /// An operator needed more operands than the stack held (§7.10.5.2, stack
498 /// underflow).
499 #[error("type 4 stack underflow: {op} needs {needed} operand(s), {had} available")]
500 StackUnderflow {
501 /// The operator that underflowed.
502 op: &'static str,
503 /// Operands required.
504 needed: usize,
505 /// Operands present.
506 had: usize,
507 },
508
509 /// An operand had the wrong type (§7.10.5.2's *"type error (for example,
510 /// applying `not` to a real number)"*).
511 #[error("type 4 type error at {op}: {detail}")]
512 PostScriptType {
513 /// The operator that rejected its operand.
514 op: &'static str,
515 /// What was expected and what arrived.
516 detail: &'static str,
517 },
518
519 /// An operand was outside an operator's mathematical domain
520 /// (§7.10.5.2's *"range error (for example, applying `sqrt` to a negative
521 /// number)"*).
522 #[error("type 4 range error at {op}: {detail}")]
523 PostScriptRange {
524 /// The operator that rejected its operand.
525 op: &'static str,
526 /// What was out of range.
527 detail: &'static str,
528 },
529
530 /// The computation had no defined result (§7.10.5.2's *"undefined result
531 /// (for example, dividing by 0)"*).
532 #[error("type 4 undefined result at {op}: {detail}")]
533 UndefinedResult {
534 /// The operator with no defined result.
535 op: &'static str,
536 /// Why it is undefined.
537 detail: &'static str,
538 },
539
540 /// Execution passed [`MAX_PS_STEPS`] (pdfcer policy — see that constant).
541 #[error("type 4 program exceeded pdfcer's {limit}-step execution cap")]
542 StepLimit {
543 /// [`MAX_PS_STEPS`].
544 limit: usize,
545 },
546
547 /// The program finished with an operand count that does not match
548 /// `/Range`. §7.10.5.1: *"It shall be an error for the number of remaining
549 /// operands to differ from the number of output variables specified by
550 /// `Range`."*
551 #[error("type 4 program left {got} value(s) on the stack; /Range requires {expected}")]
552 OutputArity {
553 /// *n*, from `/Range`.
554 expected: usize,
555 /// What the program actually left.
556 got: usize,
557 },
558
559 /// The program left a boolean where `/Range` requires a number.
560 /// §7.10.5.1 makes this an error in the same sentence as the count
561 /// mismatch: *"…or for any of them to be objects other than numbers."*
562 #[error("type 4 program left a boolean in output position {index}; outputs must be numbers")]
563 NonNumericOutput {
564 /// Which output position held the boolean.
565 index: usize,
566 },
567
568 /// [`PdfFunction::eval`] was handed the wrong number of inputs. Not a file
569 /// defect — a caller defect — but reported the same way rather than padded
570 /// or truncated, because a `DeviceN` transform fed the wrong tint count
571 /// would otherwise return a confidently wrong colour.
572 #[error("this function takes {expected} input(s); {got} supplied")]
573 InputArity {
574 /// *m*.
575 expected: usize,
576 /// What the caller passed.
577 got: usize,
578 },
579
580 /// An input was `NaN` or infinite.
581 ///
582 /// Clamping cannot rescue these: Rust's `f64::max` returns the *non*-`NaN`
583 /// operand, so a `NaN` tint clamped to `/Domain` would silently become the
584 /// domain's lower bound — a fabricated value wearing the shape of a real
585 /// one. Refused instead.
586 #[error("input {index} is not finite ({value})")]
587 NonFiniteInput {
588 /// Which input.
589 index: usize,
590 /// The offending value.
591 value: f64,
592 },
593
594 /// An output was `NaN` or infinite *after* `/Range` clamping (so it can
595 /// only happen when `/Range` is absent, since clamping maps infinities
596 /// onto finite bounds).
597 #[error("output {index} is not finite ({value}) and /Range is absent, so it cannot be clamped")]
598 NonFiniteOutput {
599 /// Which output.
600 index: usize,
601 /// The offending value.
602 value: f64,
603 },
604}
605
606// ---------------------------------------------------------------------------
607// Public type
608// ---------------------------------------------------------------------------
609
610/// Which of §7.10's four types a [`PdfFunction`] is.
611///
612/// Exposed so a caller can report or branch on the type without matching on
613/// private internals — the renderer wants to say "type 4 tint transform failed"
614/// in a diagnostic, and a `DeviceN` optimiser may want to pre-bake a type 4 into
615/// a lookup table while leaving a type 0 alone (which already *is* one).
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
617#[non_exhaustive]
618pub enum FunctionType {
619 /// Type 0 — sampled (§7.10.2).
620 Sampled,
621 /// Type 2 — exponential interpolation (§7.10.3).
622 Exponential,
623 /// Type 3 — stitching (§7.10.4).
624 Stitching,
625 /// Type 4 — PostScript calculator (§7.10.5).
626 PostScript,
627}
628
629impl FunctionType {
630 /// The `/FunctionType` integer this variant is written as.
631 ///
632 /// # Examples
633 ///
634 /// ```
635 /// use pdfcer_function::function::FunctionType;
636 /// assert_eq!(FunctionType::Stitching.as_i64(), 3);
637 /// ```
638 #[must_use]
639 pub const fn as_i64(self) -> i64 {
640 match self {
641 Self::Sampled => 0,
642 Self::Exponential => 2,
643 Self::Stitching => 3,
644 Self::PostScript => 4,
645 }
646 }
647}
648
649/// A loaded, evaluatable PDF function (§7.10).
650///
651/// Construct with [`PdfFunction::load`], evaluate with [`PdfFunction::eval`] or
652/// [`PdfFunction::eval_into`]. The value is self-contained once loaded: it holds
653/// its own sample bytes or program, borrows nothing from the document, and is
654/// therefore cheap to keep alongside a colour space and reuse per pixel.
655///
656/// # Examples
657///
658/// The commonest tint transform in the wild — a type 2 with `/N 1`, which is a
659/// straight interpolation from `C0` (paper) to `C1` (the colorant at full
660/// strength):
661///
662/// ```
663/// use pdfcer_model::PdfVersion;
664/// use pdfcer_function::function::PdfFunction;
665/// use pdfcer_model::graph::ObjectGraph;
666/// use pdfcer_model::object::{Dict, Name, ObjId, Object};
667/// use pdfcer_model::view::DocumentView;
668///
669/// // A function whose entries are all direct needs no real document behind it.
670/// struct NoObjects;
671/// impl ObjectGraph for NoObjects {
672/// fn value(&self, _: ObjId) -> Option<&Object> { None }
673/// fn trailer_entry(&self, _: &[u8]) -> Option<&Object> { None }
674/// }
675///
676/// fn num(v: f64) -> Object { Object::Real(v) }
677///
678/// let mut d = Dict::new();
679/// d.insert(Name::from(&b"FunctionType"[..]), Object::Integer(2));
680/// d.insert(Name::from(&b"Domain"[..]), Object::Array(vec![num(0.0), num(1.0)]));
681/// d.insert(Name::from(&b"N"[..]), Object::Integer(1));
682/// // Full-strength ink is 100% magenta.
683/// d.insert(Name::from(&b"C0"[..]), Object::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)]));
684/// d.insert(Name::from(&b"C1"[..]), Object::Array(vec![num(0.0), num(1.0), num(0.0), num(0.0)]));
685///
686/// let graph = NoObjects;
687/// let view = DocumentView::new(&graph, b"", PdfVersion { major: 1, minor: 7 });
688/// let f = PdfFunction::load(&view, &Object::Dict(d)).unwrap();
689///
690/// assert_eq!(f.inputs(), 1);
691/// assert_eq!(f.outputs(), 4);
692/// assert_eq!(f.eval(&[0.5]).unwrap(), vec![0.0, 0.5, 0.0, 0.0]);
693///
694/// // Table 38: an input outside /Domain is clipped, not extrapolated.
695/// assert_eq!(f.eval(&[1.4]).unwrap(), vec![0.0, 1.0, 0.0, 0.0]);
696/// ```
697#[derive(Debug, Clone, PartialEq)]
698pub struct PdfFunction {
699 /// `/Domain`, reshaped from its flat 2 × m form into one `[min, max]` pair
700 /// per input. Validated non-empty with `min <= max` at load.
701 domain: Vec<[f64; 2]>,
702 /// `/Range`, reshaped the same way. `None` means the entry was absent,
703 /// which Table 38 defines as *no output clipping* — see the module docs.
704 range: Option<Vec<[f64; 2]>>,
705 /// The type-specific payload.
706 kind: Kind,
707}
708
709/// Type-specific payload. Private: the four shapes have nothing useful in
710/// common for a caller, and exposing them would freeze internal
711/// representations (the sample table's `Vec<u8>`, the program tree) as public
712/// API for no benefit.
713#[derive(Debug, Clone, PartialEq)]
714enum Kind {
715 Sampled(Sampled),
716 Exponential(Exponential),
717 Stitching(Stitching),
718 PostScript(PostScript),
719}
720
721// ---------------------------------------------------------------------------
722// Loading
723// ---------------------------------------------------------------------------
724
725impl PdfFunction {
726 /// Load a function from an object in `view`'s graph.
727 ///
728 /// `obj` may be the function dictionary/stream itself or an indirect
729 /// reference to it; references are followed with §7.3.10's rules, and so
730 /// are the individual entries (a `/Domain` written as `12 0 R` is legal and
731 /// is resolved here).
732 ///
733 /// Loading is where **all structural validation happens**. By the time this
734 /// returns `Ok`, the function's dimensionality is internally consistent, its
735 /// intervals are ordered, a type 0's sample stream is known to be long
736 /// enough, a type 2's `/Domain` is known to be compatible with its `/N`, a
737 /// type 3's `/Bounds` is known to partition its `/Domain`, and a type 4's
738 /// program is known to parse. [`PdfFunction::eval`] can then fail only for
739 /// reasons that genuinely depend on the input values (a type 4 dividing by
740 /// zero, an arity mismatch from the caller).
741 ///
742 /// That split is deliberate: a tint transform is loaded once and evaluated
743 /// once per pixel, so per-evaluation validation would be both slow and, far
744 /// worse, would surface a file defect one pixel at a time.
745 ///
746 /// # Errors
747 ///
748 /// [`FunctionError`] — every variant except the evaluation-time ones
749 /// ([`FunctionError::InputArity`], [`FunctionError::NonFiniteInput`], the
750 /// `PostScript*` runtime errors, [`FunctionError::StepLimit`],
751 /// [`FunctionError::OutputArity`]). See the module docs on refusal posture:
752 /// a malformed function is never repaired into a plausible one.
753 pub fn load(view: &DocumentView<'_>, obj: &Object) -> Result<Self, FunctionError> {
754 Self::load_at_depth(view, obj, 0)
755 }
756
757 /// [`PdfFunction::load`] with the type 3 recursion counter threaded
758 /// through, so `/Functions` cycles terminate ([`MAX_FUNCTION_DEPTH`]).
759 fn load_at_depth(
760 view: &DocumentView<'_>,
761 obj: &Object,
762 depth: usize,
763 ) -> Result<Self, FunctionError> {
764 if depth > MAX_FUNCTION_DEPTH {
765 return Err(FunctionError::NestingTooDeep {
766 limit: MAX_FUNCTION_DEPTH,
767 });
768 }
769
770 let resolved = view.resolve(obj);
771 // `Object::as_dict` deliberately answers for a stream too — a stream is
772 // usable wherever its dictionary's content is what matters, which is
773 // exactly the case for the Table 38 entries common to all four types.
774 let dict = resolved.as_dict().ok_or(FunctionError::NotAFunction)?;
775
776 let function_type = entry(view, dict, b"FunctionType")
777 .and_then(Object::as_int)
778 .ok_or(FunctionError::MissingFunctionType)?;
779
780 let domain = pairs(view, dict, b"Domain")?.ok_or(FunctionError::MissingEntry {
781 key: "Domain",
782 function_type,
783 })?;
784 if domain.is_empty() {
785 return Err(FunctionError::BadEntry {
786 key: "Domain",
787 detail: "empty; a function needs at least one input".to_owned(),
788 });
789 }
790 check_ordered(&domain, "Domain")?;
791
792 let range = pairs(view, dict, b"Range")?;
793 if let Some(r) = range.as_deref() {
794 if r.is_empty() {
795 return Err(FunctionError::BadEntry {
796 key: "Range",
797 detail: "empty; /Range must declare at least one output".to_owned(),
798 });
799 }
800 check_ordered(r, "Range")?;
801 }
802
803 let kind = match function_type {
804 0 => Kind::Sampled(load_sampled(
805 view,
806 resolved,
807 dict,
808 &domain,
809 range.as_deref(),
810 )?),
811 2 => Kind::Exponential(load_exponential(view, dict, &domain)?),
812 3 => Kind::Stitching(load_stitching(
813 view,
814 dict,
815 &domain,
816 range.as_deref(),
817 depth,
818 )?),
819 4 => Kind::PostScript(load_postscript(view, resolved, &domain, range.as_deref())?),
820 other => return Err(FunctionError::UnknownFunctionType(other)),
821 };
822
823 // Table 38: "The dimensionality of the function implied by the Domain
824 // and Range entries shall be consistent with that implied by other
825 // attributes of the function." For types 0 and 4, /Range IS the only
826 // source of n, so there is nothing to cross-check; for 2 and 3, n comes
827 // from /C0//C1 or from the sub-functions and /Range must agree with it.
828 if let Some(r) = range.as_deref() {
829 let implied = kind.outputs();
830 if r.len() != implied {
831 return Err(FunctionError::BadArrayLength {
832 key: "Range",
833 expected: implied * 2,
834 got: r.len() * 2,
835 });
836 }
837 }
838
839 Ok(Self {
840 domain,
841 range,
842 kind,
843 })
844 }
845}
846
847// ---------------------------------------------------------------------------
848// Accessors
849// ---------------------------------------------------------------------------
850
851impl PdfFunction {
852 /// Which of the four types this is.
853 #[must_use]
854 pub const fn function_type(&self) -> FunctionType {
855 match self.kind {
856 Kind::Sampled(_) => FunctionType::Sampled,
857 Kind::Exponential(_) => FunctionType::Exponential,
858 Kind::Stitching(_) => FunctionType::Stitching,
859 Kind::PostScript(_) => FunctionType::PostScript,
860 }
861 }
862
863 /// *m* — the number of input values this function takes.
864 #[must_use]
865 pub fn inputs(&self) -> usize {
866 self.domain.len()
867 }
868
869 /// *n* — the number of output values this function produces.
870 #[must_use]
871 pub fn outputs(&self) -> usize {
872 self.kind.outputs()
873 }
874
875 /// `/Domain` as one `[min, max]` pair per input.
876 ///
877 /// Reshaped from the flat 2 × m array the file carries, because every use
878 /// of it is pairwise and a flat slice invites an off-by-one that produces a
879 /// plausible-looking wrong answer.
880 #[must_use]
881 pub fn domain(&self) -> &[[f64; 2]] {
882 &self.domain
883 }
884
885 /// `/Range` as one `[min, max]` pair per output, or `None` when the entry
886 /// was absent.
887 ///
888 /// **`None` is meaningful and must not be defaulted.** Table 38: *"If this
889 /// entry is absent, no clipping shall be done."* Types 0 and 4 always
890 /// return `Some` (the entry is required for them).
891 #[must_use]
892 pub fn range(&self) -> Option<&[[f64; 2]]> {
893 self.range.as_deref()
894 }
895
896 /// Whether evaluating this function silently uses linear interpolation
897 /// where the file asked for cubic — i.e. a type 0 with `/Order 3` that the
898 /// spec does *not* let pdfcer ignore.
899 ///
900 /// This is disclosure plumbing for project rule 4 (fuzzy, never sneaky).
901 /// pdfcer evaluates every sampled function multilinearly. §7.10.2 permits
902 /// exactly one case of ignoring `/Order 3` — *"If `Size` is less than 4,
903 /// cubic spline interpolation is not possible and `Order` 3 shall be
904 /// ignored if specified"* — and in that case this returns `false`, because
905 /// nothing was downgraded. It returns `true` only when a cubic
906 /// interpolation was genuinely requested, genuinely possible, and not
907 /// performed, so a caller can say so rather than let the operator assume
908 /// fidelity that isn't there.
909 ///
910 /// The reason pdfcer does not simply implement it: §7.10.2 names *"cubic
911 /// spline interpolation"* and then specifies **no spline** — no basis, no
912 /// end conditions, no continuity requirement. Two conforming readers
913 /// legitimately produce different pixels (recorded as ambiguity `F-A1` in
914 /// the spec RAG). Guessing a spline would be inventing the standard's
915 /// missing half and calling the result fidelity.
916 ///
917 /// Recurses into a type 3's sub-functions, since that is where a sampled
918 /// function usually hides.
919 #[must_use]
920 pub fn cubic_downgraded(&self) -> bool {
921 match &self.kind {
922 Kind::Sampled(s) => s.order3_downgraded,
923 Kind::Stitching(s) => s.functions.iter().any(Self::cubic_downgraded),
924 Kind::Exponential(_) | Kind::PostScript(_) => false,
925 }
926 }
927}
928
929impl Kind {
930 /// *n* for this payload.
931 fn outputs(&self) -> usize {
932 match self {
933 Self::Sampled(s) => s.decode.len(),
934 Self::Exponential(e) => e.c0.len(),
935 Self::Stitching(s) => s.outputs,
936 Self::PostScript(p) => p.outputs,
937 }
938 }
939}
940
941// ---------------------------------------------------------------------------
942// Evaluation — the shared clamping frame
943// ---------------------------------------------------------------------------
944
945impl PdfFunction {
946 /// Evaluate the function, allocating a fresh output vector.
947 ///
948 /// Convenience over [`PdfFunction::eval_into`]; prefer that one in a
949 /// per-pixel loop, where this allocation dominates the arithmetic.
950 ///
951 /// # Errors
952 ///
953 /// [`FunctionError::InputArity`] if `inputs.len()` is not
954 /// [`PdfFunction::inputs`]; [`FunctionError::NonFiniteInput`] for a `NaN` or
955 /// infinite input; plus any type 4 runtime error. See
956 /// [`PdfFunction::eval_into`].
957 ///
958 /// # Examples
959 ///
960 /// ```
961 /// # use pdfcer_model::PdfVersion;
962 /// # use pdfcer_function::function::PdfFunction;
963 /// # use pdfcer_model::graph::ObjectGraph;
964 /// # use pdfcer_model::object::{Dict, Name, ObjId, Object};
965 /// # use pdfcer_model::view::DocumentView;
966 /// # struct G;
967 /// # impl ObjectGraph for G {
968 /// # fn value(&self, _: ObjId) -> Option<&Object> { None }
969 /// # fn trailer_entry(&self, _: &[u8]) -> Option<&Object> { None }
970 /// # }
971 /// # let mut d = Dict::new();
972 /// # d.insert(Name::from(&b"FunctionType"[..]), Object::Integer(2));
973 /// # d.insert(Name::from(&b"Domain"[..]), Object::Array(vec![Object::Real(0.0), Object::Real(1.0)]));
974 /// # d.insert(Name::from(&b"N"[..]), Object::Integer(2));
975 /// # let g = G;
976 /// # let view = DocumentView::new(&g, b"", PdfVersion { major: 1, minor: 7 });
977 /// // /C0 and /C1 default to [0.0] and [1.0], so this is y = x^2.
978 /// let f = PdfFunction::load(&view, &Object::Dict(d)).unwrap();
979 /// assert_eq!(f.eval(&[0.5]).unwrap(), vec![0.25]);
980 /// ```
981 pub fn eval(&self, inputs: &[f64]) -> Result<Vec<f64>, FunctionError> {
982 let mut out = Vec::with_capacity(self.outputs());
983 self.eval_into(inputs, &mut out)?;
984 Ok(out)
985 }
986
987 /// Evaluate the function into `out`, which is cleared first.
988 ///
989 /// This is the real entry point; [`PdfFunction::eval`] wraps it. Reusing one
990 /// buffer across a scanline is the difference between one allocation and one
991 /// per pixel for a `DeviceN` image.
992 ///
993 /// ## What this method owns, and why it is not per-type
994 ///
995 /// The two Table 38 clipping `shall`s are applied **here**, around whatever
996 /// the type-specific evaluator does:
997 ///
998 /// 1. every input is clipped to its `/Domain` pair before dispatch;
999 /// 2. every output is clipped to its `/Range` pair afterwards — and, when
1000 /// `/Range` is absent, deliberately **not** clipped.
1001 ///
1002 /// Putting them in one place means no type can be added later that forgets
1003 /// one. Type 0's own algorithm (§7.10.2) restates both clips internally;
1004 /// applying them again here is idempotent, so the duplication costs
1005 /// nothing and the guarantee holds even if that evaluator changes.
1006 ///
1007 /// ## Non-finite values are refused, not clamped
1008 ///
1009 /// A `NaN` input cannot be clipped meaningfully — Rust's `f64::max` returns
1010 /// the non-`NaN` operand, so clamping would quietly turn `NaN` into
1011 /// `Domain_0`. That is a fabricated value that looks exactly like a real
1012 /// one downstream, so [`FunctionError::NonFiniteInput`] is returned instead.
1013 /// Symmetrically, an output that is still non-finite after clipping (only
1014 /// possible when `/Range` is absent) yields
1015 /// [`FunctionError::NonFiniteOutput`].
1016 ///
1017 /// # Errors
1018 ///
1019 /// - [`FunctionError::InputArity`] — wrong number of inputs.
1020 /// - [`FunctionError::NonFiniteInput`] / [`FunctionError::NonFiniteOutput`].
1021 /// - [`FunctionError::SampleIndexOutOfRange`] — type 0 internal invariant.
1022 /// - Type 4 runtime errors: [`FunctionError::StackOverflow`],
1023 /// [`FunctionError::StackUnderflow`], [`FunctionError::PostScriptType`],
1024 /// [`FunctionError::PostScriptRange`], [`FunctionError::UndefinedResult`],
1025 /// [`FunctionError::StepLimit`], [`FunctionError::OutputArity`],
1026 /// [`FunctionError::NonNumericOutput`].
1027 pub fn eval_into(&self, inputs: &[f64], out: &mut Vec<f64>) -> Result<(), FunctionError> {
1028 if inputs.len() != self.domain.len() {
1029 return Err(FunctionError::InputArity {
1030 expected: self.domain.len(),
1031 got: inputs.len(),
1032 });
1033 }
1034
1035 // Clip inputs to /Domain (Table 38, `shall`). Collected into a small
1036 // stack-friendly vector rather than mutated in place because `inputs`
1037 // is the caller's slice.
1038 let mut clipped: Vec<f64> = Vec::with_capacity(inputs.len());
1039 for (index, (&x, pair)) in inputs.iter().zip(self.domain.iter()).enumerate() {
1040 if !x.is_finite() {
1041 return Err(FunctionError::NonFiniteInput { index, value: x });
1042 }
1043 clipped.push(clip(x, pair[0], pair[1]));
1044 }
1045
1046 out.clear();
1047 match &self.kind {
1048 Kind::Sampled(s) => s.eval(&self.domain, &clipped, out)?,
1049 Kind::Exponential(e) => e.eval(&clipped, out),
1050 Kind::Stitching(s) => s.eval(&self.domain, &clipped, out)?,
1051 Kind::PostScript(p) => p.eval(&clipped, out)?,
1052 }
1053
1054 // Clip outputs to /Range (Table 38, `shall`) — or, when /Range is
1055 // absent, do not (Table 38, equally a `shall`).
1056 match self.range.as_deref() {
1057 Some(range) => {
1058 for (value, pair) in out.iter_mut().zip(range.iter()) {
1059 *value = clip(*value, pair[0], pair[1]);
1060 }
1061 }
1062 None => {
1063 for (index, &value) in out.iter().enumerate() {
1064 if !value.is_finite() {
1065 return Err(FunctionError::NonFiniteOutput { index, value });
1066 }
1067 }
1068 }
1069 }
1070 Ok(())
1071 }
1072}
1073
1074// ---------------------------------------------------------------------------
1075// Shared numeric helpers
1076// ---------------------------------------------------------------------------
1077
1078/// §7.10.1's `Interpolate(x, xmin, xmax, ymin, ymax)`:
1079/// `ymin + ((x − xmin) × (ymax − ymin) / (xmax − xmin))`.
1080///
1081/// The whole of §7.10 is built from this one primitive — type 0 uses it twice
1082/// (encode and decode), type 3 uses it to map a subdomain onto a sub-function's
1083/// domain.
1084///
1085/// ## The degenerate case, and a place where the spec meets us halfway
1086///
1087/// `xmax == xmin` makes the formula a division by zero, and §7.10.1 does not
1088/// address it even though Table 38 permits it (`Domain_2i <= Domain_2i+1`,
1089/// with equality allowed — a `/Domain [0.5 0.5]` is legal). pdfcer returns
1090/// `ymin`, which is the limit of the expression as the interval collapses from
1091/// the left and the only value the interval can produce.
1092///
1093/// That choice is not free-floating: §7.10.4 states the same answer for the one
1094/// instance of this it *does* consider — *"If the last bound, `Bounds_k−2`, is
1095/// equal to `Domain_1`, then x′ shall be defined to be `Encode_2i`"* — which is
1096/// exactly `ymin` for that collapsed interval. Generalising it is pdfcer policy,
1097/// but policy converging on the standard's own answer rather than away from it.
1098fn interpolate(x: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> f64 {
1099 let span = xmax - xmin;
1100 if span == 0.0 {
1101 return ymin;
1102 }
1103 ymin + (x - xmin) * (ymax - ymin) / span
1104}
1105
1106/// Clip `v` into `[lo, hi]` — Table 38's *"clipped to the nearest boundary
1107/// value"*, for both the `/Domain` and `/Range` cases.
1108///
1109/// Written as explicit comparisons rather than `f64::clamp` because `clamp`
1110/// panics when `lo > hi`, and `pdfcer-core`'s panic-free policy does not accept
1111/// "the loader validated it" as a reason to leave a reachable panic in place.
1112/// (The loader *does* validate it — [`check_ordered`] — so the comparisons
1113/// below never see an inverted pair; this is belt and braces on untrusted
1114/// input.) `NaN` propagates unchanged, and callers check for it explicitly.
1115fn clip(v: f64, lo: f64, hi: f64) -> f64 {
1116 if v < lo {
1117 lo
1118 } else if v > hi {
1119 hi
1120 } else {
1121 v
1122 }
1123}
1124
1125/// Resolve a dictionary entry through the graph (an entry may be an indirect
1126/// reference — §7.3.10's substitutability applies to function entries like any
1127/// other).
1128fn entry<'v>(view: &'v DocumentView<'_>, dict: &'v Dict, key: &[u8]) -> Option<&'v Object> {
1129 dict.get(key).map(|obj| view.resolve(obj))
1130}
1131
1132/// Read an array-valued entry as a flat `Vec<f64>`, resolving both the array
1133/// itself and each element.
1134///
1135/// `Ok(None)` means the entry was absent — which is meaningfully different from
1136/// "present but empty" and from "present but wrong", both of which are errors.
1137///
1138/// # Errors
1139///
1140/// [`FunctionError::BadEntry`] if the entry is not an array, or holds an element
1141/// that is not a number (§7.3.3's integer-where-real rule is honoured via
1142/// [`Object::as_number`]).
1143fn numbers(
1144 view: &DocumentView<'_>,
1145 dict: &Dict,
1146 key: &'static str,
1147) -> Result<Option<Vec<f64>>, FunctionError> {
1148 let Some(obj) = entry(view, dict, key.as_bytes()) else {
1149 return Ok(None);
1150 };
1151 let Some(items) = obj.as_array() else {
1152 return Err(FunctionError::BadEntry {
1153 key,
1154 detail: "not an array".to_owned(),
1155 });
1156 };
1157 let mut out = Vec::with_capacity(items.len());
1158 for (i, item) in items.iter().enumerate() {
1159 let Some(v) = view.resolve(item).as_number() else {
1160 return Err(FunctionError::BadEntry {
1161 key,
1162 detail: format!("element {i} is not a number"),
1163 });
1164 };
1165 if !v.is_finite() {
1166 return Err(FunctionError::BadEntry {
1167 key,
1168 detail: format!("element {i} is not finite"),
1169 });
1170 }
1171 out.push(v);
1172 }
1173 Ok(Some(out))
1174}
1175
1176/// [`numbers`], reshaped into `[min, max]` pairs — the form every 2 × k entry in
1177/// §7.10 actually has (`/Domain`, `/Range`, `/Encode`, `/Decode`).
1178///
1179/// # Errors
1180///
1181/// [`FunctionError::BadEntry`] for a non-array, a non-numeric element, or an odd
1182/// element count (which would leave a pair half-specified — refused rather than
1183/// truncated, since silently dropping the last value would shift every
1184/// subsequent pair).
1185fn pairs(
1186 view: &DocumentView<'_>,
1187 dict: &Dict,
1188 key: &'static [u8],
1189) -> Result<Option<Vec<[f64; 2]>>, FunctionError> {
1190 // The key is ASCII by construction (all §7.10 keys are), so the lossy
1191 // conversion below cannot lose anything; it exists only to satisfy the
1192 // `&'static str` in the error payload.
1193 let key_str: &'static str = match key {
1194 b"Domain" => "Domain",
1195 b"Range" => "Range",
1196 b"Encode" => "Encode",
1197 b"Decode" => "Decode",
1198 _ => "unknown",
1199 };
1200 let Some(flat) = numbers(view, dict, key_str)? else {
1201 return Ok(None);
1202 };
1203 if flat.len() % 2 != 0 {
1204 return Err(FunctionError::BadEntry {
1205 key: key_str,
1206 detail: format!("has {} elements; a 2 × n array is required", flat.len()),
1207 });
1208 }
1209 Ok(Some(
1210 flat.as_chunks::<2>()
1211 .0
1212 .iter()
1213 .map(|c| {
1214 [
1215 c.first().copied().unwrap_or(0.0),
1216 c.get(1).copied().unwrap_or(0.0),
1217 ]
1218 })
1219 .collect(),
1220 ))
1221}
1222
1223/// Enforce Table 38's *"`Domain_2i` shall be less than or equal to
1224/// `Domain_2i+1`"* (and the identical rule for `/Range`).
1225///
1226/// Equality is allowed by the spec and accepted here — a collapsed interval is
1227/// a legal, if odd, way to pin an input to one value, and [`interpolate`]
1228/// handles it. Only an *inverted* pair is refused, because there is no reading
1229/// of `[1.0, 0.0]` that the standard sanctions and clipping into it would
1230/// produce whichever bound the comparison happened to hit first.
1231///
1232/// # Errors
1233///
1234/// [`FunctionError::InvertedInterval`].
1235fn check_ordered(intervals: &[[f64; 2]], key: &'static str) -> Result<(), FunctionError> {
1236 for (index, pair) in intervals.iter().enumerate() {
1237 if pair[0] > pair[1] {
1238 return Err(FunctionError::InvertedInterval {
1239 key,
1240 index,
1241 low: pair[0],
1242 high: pair[1],
1243 });
1244 }
1245 }
1246 Ok(())
1247}
1248
1249/// Decode a function stream's data through its `/Filter` chain.
1250///
1251/// # Errors
1252///
1253/// [`FunctionError::StreamUnreadable`] if the view cannot serve the span,
1254/// [`FunctionError::Filter`] if the chain fails.
1255fn stream_bytes(view: &DocumentView<'_>, stream: &Stream) -> Result<Vec<u8>, FunctionError> {
1256 let raw = view
1257 .slice(stream.data_span)
1258 .ok_or(FunctionError::StreamUnreadable)?;
1259 Ok(filters::decode_stream(&stream.dict, raw)?)
1260}
1261
1262// ---------------------------------------------------------------------------
1263// Type 0 — sampled (§7.10.2)
1264// ---------------------------------------------------------------------------
1265
1266/// A type 0 sampled function: a lookup table plus the two linear maps that get
1267/// values into and out of it.
1268///
1269/// ## The shape of the data
1270///
1271/// The table has `Size_0 × Size_1 × … × Size_(m−1)` entries, each entry holding
1272/// *n* samples of `bits_per_sample` bits. §7.10.2 fixes the layout exactly:
1273///
1274/// > *"Sample data shall be represented as a stream of bytes. The bytes shall
1275/// > constitute a continuous bit stream, with the high-order bit of each byte
1276/// > first. Each sample value shall be represented as a sequence of
1277/// > `BitsPerSample` bits. Successive values shall be adjacent in the bit
1278/// > stream; there shall be no padding at byte boundaries."*
1279///
1280/// Two consequences that are easy to get wrong and produce garbage rather than
1281/// an error:
1282///
1283/// - **No byte alignment.** At `/BitsPerSample 4` two samples share a byte, high
1284/// nibble first; at 12, sample 0 occupies bits 0–11 and sample 1 bits 12–23,
1285/// so sample 1 straddles bytes 1 and 2. This is why [`read_bits`] works in
1286/// bits rather than bytes, with a byte-wise fast path only for the widths
1287/// where alignment is guaranteed.
1288/// - **First dimension varies fastest.** §7.10.2: *"the sample values in the
1289/// first dimension vary fastest, and the values in the last dimension vary
1290/// slowest"* — `f(0,0)`, `f(1,0)`, … `f(Size_0−1, 0)`, `f(0,1)`, …. That is
1291/// column-major, the *opposite* of C row-major order, and getting it backwards
1292/// transposes a 2-input transform without any symptom the code can detect.
1293/// [`Sampled::strides`] encodes it.
1294///
1295/// ## Interpolation
1296///
1297/// pdfcer interpolates multilinearly (2^m corners, weights the product of each
1298/// axis's fraction). The normative text says only *"Interpolation shall be used
1299/// to determine output values from the nearest surrounding values in the sample
1300/// table"*; the word "multilinear" appears only in an **informative NOTE**
1301/// (recorded as ambiguity `F-A2` in the spec RAG), so multilinear is the
1302/// universal reading rather than a quoted requirement. `/Order 3` is discussed
1303/// on [`PdfFunction::cubic_downgraded`].
1304#[derive(Debug, Clone, PartialEq)]
1305struct Sampled {
1306 /// `/Size` — samples per input dimension, each ≥ 1. Length *m*.
1307 size: Vec<usize>,
1308 /// Flat-index multipliers, `strides[0] = 1`,
1309 /// `strides[i] = strides[i−1] × size[i−1]`. Precomputed because it encodes
1310 /// the first-dimension-fastest rule in exactly one place.
1311 strides: Vec<usize>,
1312 /// `/BitsPerSample`, one of [`VALID_BITS_PER_SAMPLE`].
1313 bits_per_sample: u32,
1314 /// `2^bits_per_sample − 1`, the `xmax` of the decode interpolation.
1315 /// Precomputed as `f64` because it is otherwise recomputed per output per
1316 /// evaluation, and at 32 bits it does not fit a `u32`.
1317 max_sample: f64,
1318 /// `/Encode` — one pair per input. Defaults to `[0, Size_i − 1]`.
1319 encode: Vec<[f64; 2]>,
1320 /// `/Decode` — one pair per output. Defaults to `/Range`. Its length is *n*.
1321 decode: Vec<[f64; 2]>,
1322 /// The decoded sample stream.
1323 samples: Vec<u8>,
1324 /// `/Order 3` was requested, cubic was possible, and pdfcer did it linearly
1325 /// anyway. See [`PdfFunction::cubic_downgraded`].
1326 order3_downgraded: bool,
1327}
1328
1329/// Build a [`Sampled`] from its stream and dictionary, validating everything
1330/// Table 39 constrains.
1331///
1332/// # Errors
1333///
1334/// [`FunctionError`] — see [`PdfFunction::load`].
1335fn load_sampled(
1336 view: &DocumentView<'_>,
1337 resolved: &Object,
1338 dict: &Dict,
1339 domain: &[[f64; 2]],
1340 range: Option<&[[f64; 2]]>,
1341) -> Result<Sampled, FunctionError> {
1342 let Object::Stream(stream) = resolved else {
1343 return Err(FunctionError::NotAStream { function_type: 0 });
1344 };
1345
1346 let m = domain.len();
1347 if m > MAX_SAMPLED_INPUTS {
1348 return Err(FunctionError::TooManyInputs {
1349 got: m,
1350 limit: MAX_SAMPLED_INPUTS,
1351 });
1352 }
1353
1354 // /Range is required for type 0 — it is the only source of n (§7.10.1).
1355 let range = range.ok_or(FunctionError::MissingEntry {
1356 key: "Range",
1357 function_type: 0,
1358 })?;
1359 let n = range.len();
1360
1361 // --- /Size ---------------------------------------------------------
1362 let size_raw = numbers(view, dict, "Size")?.ok_or(FunctionError::MissingEntry {
1363 key: "Size",
1364 function_type: 0,
1365 })?;
1366 if size_raw.len() != m {
1367 return Err(FunctionError::BadArrayLength {
1368 key: "Size",
1369 expected: m,
1370 got: size_raw.len(),
1371 });
1372 }
1373 let mut size = Vec::with_capacity(m);
1374 for (i, &s) in size_raw.iter().enumerate() {
1375 // Table 39: "m positive integers". A zero or fractional Size makes the
1376 // table's extent undefined, so it is refused rather than rounded.
1377 if s < 1.0 || s.fract() != 0.0 {
1378 return Err(FunctionError::BadEntry {
1379 key: "Size",
1380 detail: format!("element {i} is {s}; each must be a positive integer"),
1381 });
1382 }
1383 // `s` is finite (checked in `numbers`), ≥ 1 and integral; the cast is
1384 // exact for any value the length check below will accept, and a value
1385 // beyond `usize` range saturates into `SampleTableTooLarge` there.
1386 size.push(s as usize);
1387 }
1388
1389 // Strides: first dimension fastest (see `Sampled`'s docs).
1390 let mut strides = Vec::with_capacity(m);
1391 let mut acc: usize = 1;
1392 for &s in &size {
1393 strides.push(acc);
1394 acc = acc
1395 .checked_mul(s)
1396 .ok_or(FunctionError::SampleTableTooLarge)?;
1397 }
1398 let total_entries = acc;
1399
1400 // --- /BitsPerSample ------------------------------------------------
1401 let bits_raw = entry(view, dict, b"BitsPerSample")
1402 .and_then(Object::as_int)
1403 .ok_or(FunctionError::MissingEntry {
1404 key: "BitsPerSample",
1405 function_type: 0,
1406 })?;
1407 let bits_per_sample = u32::try_from(bits_raw)
1408 .ok()
1409 .filter(|b| VALID_BITS_PER_SAMPLE.contains(b))
1410 .ok_or(FunctionError::BadBitsPerSample(bits_raw))?;
1411
1412 // --- the "long enough" check (§7.10.2, §7.3.8.2) --------------------
1413 //
1414 // Every multiplication is checked: `Size` is attacker-controlled, and a
1415 // wrapped product would compute a *small* required length, pass this check,
1416 // and then read arbitrary in-bounds bytes as colour.
1417 let total_samples = total_entries
1418 .checked_mul(n)
1419 .ok_or(FunctionError::SampleTableTooLarge)?;
1420 let total_bits = total_samples
1421 .checked_mul(bits_per_sample as usize)
1422 .ok_or(FunctionError::SampleTableTooLarge)?;
1423 let need = total_bits
1424 .checked_add(7)
1425 .ok_or(FunctionError::SampleTableTooLarge)?
1426 / 8;
1427
1428 let samples = stream_bytes(view, stream)?;
1429 if samples.len() < need {
1430 return Err(FunctionError::SampleDataTooShort {
1431 need,
1432 have: samples.len(),
1433 });
1434 }
1435
1436 // --- /Encode (default [0, Size_i − 1]) ------------------------------
1437 let encode = match pairs(view, dict, b"Encode")? {
1438 Some(e) if e.len() != m => {
1439 return Err(FunctionError::BadArrayLength {
1440 key: "Encode",
1441 expected: m * 2,
1442 got: e.len() * 2,
1443 });
1444 }
1445 Some(e) => e,
1446 None => size
1447 .iter()
1448 .map(|&s| [0.0, (s.saturating_sub(1)) as f64])
1449 .collect(),
1450 };
1451
1452 // --- /Decode (default: same as /Range) ------------------------------
1453 let decode = match pairs(view, dict, b"Decode")? {
1454 Some(d) if d.len() != n => {
1455 return Err(FunctionError::BadArrayLength {
1456 key: "Decode",
1457 expected: n * 2,
1458 got: d.len() * 2,
1459 });
1460 }
1461 Some(d) => d,
1462 None => range.to_vec(),
1463 };
1464
1465 // --- /Order ----------------------------------------------------------
1466 let order = entry(view, dict, b"Order")
1467 .and_then(Object::as_int)
1468 .unwrap_or(1);
1469 if order != 1 && order != 3 {
1470 return Err(FunctionError::BadEntry {
1471 key: "Order",
1472 detail: format!("{order} is not 1 (linear) or 3 (cubic spline)"),
1473 });
1474 }
1475 // §7.10.2: "If Size is less than 4, cubic spline interpolation is not
1476 // possible and Order 3 shall be ignored if specified." So an /Order 3 on a
1477 // table with no axis of 4+ samples is not a downgrade at all — ignoring it
1478 // is what the spec requires. Only the other case is a disclosure.
1479 let order3_downgraded = order == 3 && size.iter().any(|&s| s >= 4);
1480
1481 Ok(Sampled {
1482 size,
1483 strides,
1484 bits_per_sample,
1485 max_sample: (2f64).powi(bits_per_sample as i32) - 1.0,
1486 encode,
1487 decode,
1488 samples,
1489 order3_downgraded,
1490 })
1491}
1492
1493/// Per-axis interpolation state for one evaluation: which two table indices
1494/// bracket the encoded input, how far between them it fell, and the flat-index
1495/// multiplier for the axis.
1496///
1497/// Materialised as a small struct rather than three parallel vectors so the
1498/// corner loop can iterate without indexing (crate policy denies
1499/// `clippy::indexing_slicing`) and so `upper` is computed once per axis rather
1500/// than once per corner.
1501struct Axis {
1502 /// Lower bracketing table index.
1503 lower: usize,
1504 /// Upper bracketing index — `min(lower + 1, size − 1)`, so the top edge of
1505 /// the table brackets against itself with weight zero.
1506 upper: usize,
1507 /// Fractional position between `lower` and `upper`, in `[0, 1)`.
1508 frac: f64,
1509 /// Flat-index multiplier for this axis.
1510 stride: usize,
1511}
1512
1513impl Sampled {
1514 /// Evaluate at `inputs` (already clipped to `/Domain` by
1515 /// [`PdfFunction::eval_into`]).
1516 ///
1517 /// Implements §7.10.2's algorithm verbatim:
1518 ///
1519 /// ```text
1520 /// e_i = Interpolate(x_i, Domain_2i, Domain_2i+1, Encode_2i, Encode_2i+1)
1521 /// e'_i = min(max(e_i, 0), Size_i − 1)
1522 /// r_j = <multilinear blend of the surrounding table samples>
1523 /// r'_j = Interpolate(r_j, 0, 2^BitsPerSample − 1, Decode_2j, Decode_2j+1)
1524 /// y_j = min(max(r'_j, Range_2j), Range_2j+1) <- applied by the caller
1525 /// ```
1526 ///
1527 /// The blend is done on **raw** sample values and decoded afterwards, which
1528 /// is what the algorithm above says and is also equivalent to decoding
1529 /// first: both `Interpolate` steps are affine, and an affine map commutes
1530 /// with a convex combination. Doing it in the spec's order keeps one decode
1531 /// per output instead of one per corner per output.
1532 ///
1533 /// # Errors
1534 ///
1535 /// [`FunctionError::SampleIndexOutOfRange`] — structurally unreachable given
1536 /// the load-time length check; see that variant.
1537 fn eval(
1538 &self,
1539 domain: &[[f64; 2]],
1540 inputs: &[f64],
1541 out: &mut Vec<f64>,
1542 ) -> Result<(), FunctionError> {
1543 let n = self.decode.len();
1544
1545 // --- encode each input into table coordinates --------------------
1546 let mut axes: Vec<Axis> = Vec::with_capacity(self.size.len());
1547 for (((&x, dom), enc), (&size, &stride)) in inputs
1548 .iter()
1549 .zip(domain.iter())
1550 .zip(self.encode.iter())
1551 .zip(self.size.iter().zip(self.strides.iter()))
1552 {
1553 let top = size.saturating_sub(1);
1554 // `top` is a table index, always small enough to be exact in f64.
1555 let top_f = top as f64;
1556 let e = clip(interpolate(x, dom[0], dom[1], enc[0], enc[1]), 0.0, top_f);
1557 // `e` is finite and in [0, top], so `floor` is in range and the cast
1558 // is exact. `min(top)` guards the `e == top` case where floor lands
1559 // exactly on the last index.
1560 let floor = e.floor();
1561 let lower = (floor as usize).min(top);
1562 axes.push(Axis {
1563 lower,
1564 upper: (lower + 1).min(top),
1565 frac: e - floor,
1566 stride,
1567 });
1568 }
1569
1570 // --- multilinear blend over 2^m corners --------------------------
1571 //
1572 // Bounded by MAX_SAMPLED_INPUTS (load-time), so `1 << m` cannot
1573 // overflow and the loop cannot run away.
1574 let mut acc = vec![0.0f64; n];
1575 let corners = 1usize << axes.len();
1576 for corner in 0..corners {
1577 let mut weight = 1.0f64;
1578 let mut flat = 0usize;
1579 for (i, axis) in axes.iter().enumerate() {
1580 let take_upper = (corner >> i) & 1 == 1;
1581 let (index, w) = if take_upper {
1582 (axis.upper, axis.frac)
1583 } else {
1584 (axis.lower, 1.0 - axis.frac)
1585 };
1586 weight *= w;
1587 flat = flat.saturating_add(index.saturating_mul(axis.stride));
1588 }
1589 // A zero-weight corner contributes nothing; skipping it also avoids
1590 // reading the duplicate top-edge index for a collapsed axis.
1591 if weight == 0.0 {
1592 continue;
1593 }
1594 for (j, slot) in acc.iter_mut().enumerate() {
1595 *slot += weight * self.sample(flat, j, n)?;
1596 }
1597 }
1598
1599 // --- decode ------------------------------------------------------
1600 for (raw, dec) in acc.into_iter().zip(self.decode.iter()) {
1601 out.push(interpolate(raw, 0.0, self.max_sample, dec[0], dec[1]));
1602 }
1603 Ok(())
1604 }
1605
1606 /// Read output `j` of table entry `flat` as a raw sample value.
1607 ///
1608 /// The flat sample number is `flat × n + j` (§7.10.2: multidimensional
1609 /// output values *"shall be stored in the same order as `Range`"*, i.e. the
1610 /// *n* outputs of one table entry are adjacent), and its bit offset is that
1611 /// number times `/BitsPerSample`.
1612 ///
1613 /// # Errors
1614 ///
1615 /// [`FunctionError::SampleIndexOutOfRange`] if the computed bits fall
1616 /// outside the loaded stream — unreachable after the load-time length
1617 /// check, and reported rather than defaulted so a broken invariant is
1618 /// visible instead of rendering as a colour.
1619 fn sample(&self, flat: usize, j: usize, n: usize) -> Result<f64, FunctionError> {
1620 let index = flat
1621 .checked_mul(n)
1622 .and_then(|base| base.checked_add(j))
1623 .ok_or(FunctionError::SampleIndexOutOfRange { index: flat })?;
1624 let bit_offset = index
1625 .checked_mul(self.bits_per_sample as usize)
1626 .ok_or(FunctionError::SampleIndexOutOfRange { index })?;
1627 let raw = read_bits(&self.samples, bit_offset, self.bits_per_sample)
1628 .ok_or(FunctionError::SampleIndexOutOfRange { index })?;
1629 // u64 -> f64 is exact for every value 32 bits can hold.
1630 Ok(raw as f64)
1631 }
1632}
1633
1634/// Read `bits` bits starting at bit `offset`, MSB-first within each byte.
1635///
1636/// §7.10.2's bit stream is big-endian at the bit level: *"the high-order bit of
1637/// each byte first"*, values *"adjacent in the bit stream"* with *"no padding at
1638/// byte boundaries"*. So at `/BitsPerSample 4`, byte `0xAB` holds sample `0xA`
1639/// then sample `0xB`; at 12, bytes `0xAB 0xCD` hold `0xABC` and the first nibble
1640/// of the next sample is `0xD`.
1641///
1642/// Returns `None` when the requested bits are not wholly inside `data`, which
1643/// callers turn into a named refusal rather than a zero sample.
1644///
1645/// ## Why two paths
1646///
1647/// For widths 8, 16, 24 and 32 the offset is necessarily a whole number of
1648/// bytes (every preceding sample was too), so those read byte-wise — the common
1649/// case, and the one that runs per pixel. Widths 1, 2, 4 and 12 take the bit
1650/// loop, which runs at most 12 iterations. The alternative, a single generic
1651/// shift-and-mask over a `u64` window, needs careful handling when a 32-bit
1652/// sample starts mid-byte (it cannot, but the code would have to prove it) and
1653/// is not obviously correct on inspection; this version is.
1654fn read_bits(data: &[u8], offset: usize, bits: u32) -> Option<u64> {
1655 let bits_usize = bits as usize;
1656 let end = offset.checked_add(bits_usize)?;
1657 if end > data.len().checked_mul(8)? {
1658 return None;
1659 }
1660
1661 if bits.is_multiple_of(8) && offset.is_multiple_of(8) {
1662 let start = offset / 8;
1663 let stop = end / 8;
1664 let mut acc: u64 = 0;
1665 for &byte in data.get(start..stop)? {
1666 acc = (acc << 8) | u64::from(byte);
1667 }
1668 return Some(acc);
1669 }
1670
1671 let mut acc: u64 = 0;
1672 for i in 0..bits_usize {
1673 let bit_index = offset.checked_add(i)?;
1674 let byte = *data.get(bit_index / 8)?;
1675 // 7 − (bit_index % 8): bit 0 of the stream is the *high* bit of byte 0.
1676 let shift = 7 - (bit_index % 8);
1677 acc = (acc << 1) | u64::from((byte >> shift) & 1);
1678 }
1679 Some(acc)
1680}
1681
1682// ---------------------------------------------------------------------------
1683// Type 2 — exponential interpolation (§7.10.3)
1684// ---------------------------------------------------------------------------
1685
1686/// A type 2 function: `y_j = C0_j + x^N × (C1_j − C0_j)`.
1687///
1688/// One input, *n* outputs, three numbers of configuration. §7.10.3 notes that
1689/// *"when N is 1, the function performs a linear interpolation between C0 and
1690/// C1"* — and that case, a straight ramp from paper to full-strength ink, is
1691/// what the overwhelming majority of `Separation` tint transforms actually are.
1692///
1693/// ## The default trap
1694///
1695/// `/C0` defaults to `[0.0]` and `/C1` to `[1.0]` — **scalars, not vectors**. A
1696/// type 2 with neither entry present is therefore a 1-output function, and a
1697/// 4-output tint transform *must* carry explicit four-element arrays. A loader
1698/// that defaulted them to "n zeros" using an *n* from somewhere else would
1699/// silently accept a malformed function; here *n* is *defined* by `/C0`/`/C1`
1700/// and any `/Range` present is checked against it
1701/// ([`FunctionError::BadArrayLength`]).
1702#[derive(Debug, Clone, PartialEq)]
1703struct Exponential {
1704 /// `/C0` — the result at `x = 0`. Length *n*.
1705 c0: Vec<f64>,
1706 /// `/C1` — the result at `x = 1`. Length *n*, equal to `c0`'s.
1707 c1: Vec<f64>,
1708 /// `/N` — the interpolation exponent.
1709 n: f64,
1710}
1711
1712/// Build an [`Exponential`], validating Table 40 and §7.10.3's domain
1713/// constraint.
1714///
1715/// # Errors
1716///
1717/// [`FunctionError`] — see [`PdfFunction::load`].
1718fn load_exponential(
1719 view: &DocumentView<'_>,
1720 dict: &Dict,
1721 domain: &[[f64; 2]],
1722) -> Result<Exponential, FunctionError> {
1723 // §7.10.3: "exponential interpolation of one input value".
1724 if domain.len() != 1 {
1725 return Err(FunctionError::NotOneInput {
1726 function_type: 2,
1727 got: domain.len(),
1728 });
1729 }
1730 let bounds = domain.first().copied().unwrap_or([0.0, 1.0]);
1731
1732 let exponent =
1733 entry(view, dict, b"N")
1734 .and_then(Object::as_number)
1735 .ok_or(FunctionError::MissingEntry {
1736 key: "N",
1737 function_type: 2,
1738 })?;
1739 if !exponent.is_finite() {
1740 return Err(FunctionError::BadEntry {
1741 key: "N",
1742 detail: "not finite".to_owned(),
1743 });
1744 }
1745
1746 let c0 = numbers(view, dict, "C0")?.unwrap_or_else(|| vec![0.0]);
1747 let c1 = numbers(view, dict, "C1")?.unwrap_or_else(|| vec![1.0]);
1748 if c0.is_empty() {
1749 return Err(FunctionError::BadEntry {
1750 key: "C0",
1751 detail: "empty".to_owned(),
1752 });
1753 }
1754 if c0.len() != c1.len() {
1755 return Err(FunctionError::BadArrayLength {
1756 key: "C1",
1757 expected: c0.len(),
1758 got: c1.len(),
1759 });
1760 }
1761
1762 // §7.10.3: "Values of Domain shall constrain x in such a way that if N is
1763 // not an integer, all values of x shall be non-negative, and if N is
1764 // negative, no value of x shall be zero."
1765 //
1766 // Both are checked at LOAD, from /Domain, rather than at evaluation from
1767 // x — which is what the sentence actually requires, and which is also the
1768 // only way to catch it once instead of once per pixel. The failure modes
1769 // they prevent are `NaN` (a negative base under a fractional exponent) and
1770 // an infinity (a zero base under a negative exponent); either would sail
1771 // through a /Range clamp as a boundary colour.
1772 if exponent.fract() != 0.0 && bounds[0] < 0.0 {
1773 return Err(FunctionError::DomainIncompatibleWithExponent {
1774 n: exponent,
1775 low: bounds[0],
1776 high: bounds[1],
1777 });
1778 }
1779 if exponent < 0.0 && bounds[0] <= 0.0 && bounds[1] >= 0.0 {
1780 return Err(FunctionError::DomainIncompatibleWithExponent {
1781 n: exponent,
1782 low: bounds[0],
1783 high: bounds[1],
1784 });
1785 }
1786
1787 Ok(Exponential {
1788 c0,
1789 c1,
1790 n: exponent,
1791 })
1792}
1793
1794impl Exponential {
1795 /// `y_j = C0_j + x^N × (C1_j − C0_j)` for each output.
1796 ///
1797 /// `x` arrives already clipped to `/Domain`, and the load-time checks above
1798 /// guarantee `x^N` is finite for every `x` the domain admits, so this
1799 /// cannot produce `NaN`.
1800 fn eval(&self, inputs: &[f64], out: &mut Vec<f64>) {
1801 let x = inputs.first().copied().unwrap_or(0.0);
1802 // `powi` for integral exponents: exact for the common N = 1 and N = 2,
1803 // and avoids `powf`'s log/exp round trip. `powf` otherwise.
1804 let xn = if self.n.fract() == 0.0 && self.n.abs() <= f64::from(i32::MAX) {
1805 x.powi(self.n as i32)
1806 } else {
1807 x.powf(self.n)
1808 };
1809 for (a, b) in self.c0.iter().zip(self.c1.iter()) {
1810 out.push(a + xn * (b - a));
1811 }
1812 }
1813}
1814
1815// ---------------------------------------------------------------------------
1816// Type 3 — stitching (§7.10.4)
1817// ---------------------------------------------------------------------------
1818
1819/// A type 3 function: *k* 1-input sub-functions laid end to end across
1820/// `/Domain`, each fed a rescaled slice of it.
1821///
1822/// ## The partition, and the half-open convention
1823///
1824/// §7.10.4 fixes the ordering
1825///
1826/// ```text
1827/// Domain_0 < Bounds_0 < Bounds_1 < … < Bounds_(k−2) < Domain_1
1828/// ```
1829///
1830/// and the intervals are *"half-open intervals, closed on the left and open on
1831/// the right (except the last, which is closed on the right as well)"*:
1832///
1833/// | Sub-function | Interval |
1834/// |---|---|
1835/// | 0 | `Domain_0 ≤ x < Bounds_0` |
1836/// | *i* | `Bounds_(i−1) ≤ x < Bounds_i` |
1837/// | *k−1* | `Bounds_(k−2) ≤ x ≤ Domain_1` |
1838///
1839/// **Exactly on a bound, the later sub-function wins.** [`Stitching::select`]
1840/// implements that by counting how many bounds `x` is greater than or equal to,
1841/// which gets the boundary case right by construction rather than by an
1842/// `if`-chain that has to remember which comparison is strict.
1843///
1844/// ## `k = 1` is the domain-reversal idiom
1845///
1846/// §7.10.4 explicitly allows a single sub-function with an empty `/Bounds`, and
1847/// notes that *"type 3 functions provide a general mechanism for inverting the
1848/// domains of 1-input functions"*: with `/Domain [0 1]` and `/Encode [1 0]`, a
1849/// one-element stitching function computes `g(x) = f(1 − x)`. It is not a
1850/// degenerate case to be special-cased away — it is a deliberate construction
1851/// that appears in real shadings.
1852#[derive(Debug, Clone, PartialEq)]
1853struct Stitching {
1854 /// `/Functions` — *k* sub-functions, each with one input.
1855 functions: Vec<PdfFunction>,
1856 /// `/Bounds` — *k* − 1 interior partition points.
1857 bounds: Vec<f64>,
1858 /// `/Encode` — one `[lo, hi]` pair per sub-function.
1859 encode: Vec<[f64; 2]>,
1860 /// *n*, taken from sub-function 0 and verified equal for all the others.
1861 outputs: usize,
1862}
1863
1864/// Build a [`Stitching`], validating Table 41 and the partition rule.
1865///
1866/// # Errors
1867///
1868/// [`FunctionError`] — see [`PdfFunction::load`].
1869fn load_stitching(
1870 view: &DocumentView<'_>,
1871 dict: &Dict,
1872 domain: &[[f64; 2]],
1873 range: Option<&[[f64; 2]]>,
1874 depth: usize,
1875) -> Result<Stitching, FunctionError> {
1876 // §7.10.4: "Domain shall be of size 2 (that is, m = 1)".
1877 if domain.len() != 1 {
1878 return Err(FunctionError::NotOneInput {
1879 function_type: 3,
1880 got: domain.len(),
1881 });
1882 }
1883 let bounds_of_domain = domain.first().copied().unwrap_or([0.0, 1.0]);
1884
1885 // --- /Functions ------------------------------------------------------
1886 let entries: Vec<Object> = entry(view, dict, b"Functions")
1887 .and_then(Object::as_array)
1888 .ok_or(FunctionError::MissingEntry {
1889 key: "Functions",
1890 function_type: 3,
1891 })?
1892 // Cloned because each sub-function load re-borrows the view, and a
1893 // borrow of the array would alias that. The array holds at most a
1894 // handful of references; this is not a hot path (load, not eval).
1895 .to_vec();
1896 if entries.is_empty() {
1897 return Err(FunctionError::NoSubFunctions);
1898 }
1899
1900 let mut functions = Vec::with_capacity(entries.len());
1901 let mut outputs = 0usize;
1902 for (index, sub) in entries.iter().enumerate() {
1903 let f = PdfFunction::load_at_depth(view, sub, depth + 1)?;
1904 // §7.10.4: "an array of k 1-input functions".
1905 if f.inputs() != 1 {
1906 return Err(FunctionError::BadEntry {
1907 key: "Functions",
1908 detail: format!(
1909 "sub-function {index} takes {} inputs; stitching sub-functions take one",
1910 f.inputs()
1911 ),
1912 });
1913 }
1914 // §7.10.4: "The output dimensionality of all functions shall be the
1915 // same". Sub-function 0 sets it.
1916 if index == 0 {
1917 outputs = f.outputs();
1918 } else if f.outputs() != outputs {
1919 return Err(FunctionError::SubFunctionArity {
1920 index,
1921 expected: outputs,
1922 got: f.outputs(),
1923 });
1924 }
1925 functions.push(f);
1926 }
1927 let k = functions.len();
1928
1929 // Table 38's consistency rule, applied to the one place a type 3 can
1930 // contradict itself: /Range says n, the sub-functions say something else.
1931 if let Some(r) = range
1932 && r.len() != outputs
1933 {
1934 return Err(FunctionError::BadArrayLength {
1935 key: "Range",
1936 expected: outputs * 2,
1937 got: r.len() * 2,
1938 });
1939 }
1940
1941 // --- /Bounds ---------------------------------------------------------
1942 let bounds = numbers(view, dict, "Bounds")?.ok_or(FunctionError::MissingEntry {
1943 key: "Bounds",
1944 function_type: 3,
1945 })?;
1946 // §7.10.4: "an array of k − 1 numbers"; "The value of k may be 1, in which
1947 // case the Bounds array shall be empty".
1948 if bounds.len() + 1 != k {
1949 return Err(FunctionError::BadArrayLength {
1950 key: "Bounds",
1951 expected: k - 1,
1952 got: bounds.len(),
1953 });
1954 }
1955 // "Bounds elements shall be in order of increasing value, and each value
1956 // shall be within the domain defined by Domain."
1957 //
1958 // Two deliberate readings, both narrower than a maximally strict one:
1959 //
1960 // * EQUAL adjacent bounds are ACCEPTED. The partition rule is written with
1961 // strict `<`, but `[b, b)` is an unambiguously empty interval whose
1962 // sub-function is simply never selected — there is nothing to guess.
1963 // Refusing it would reject files over a defect with no observable
1964 // consequence. Only a strictly DECREASING pair is refused, because that
1965 // has no reading at all.
1966 // * A bound EQUAL to Domain_0 or Domain_1 is accepted, for the same
1967 // reason and because §7.10.4 explicitly contemplates the second case
1968 // ("If the last bound … is equal to Domain_1 …").
1969 let mut previous = f64::NEG_INFINITY;
1970 for (i, &b) in bounds.iter().enumerate() {
1971 if b < previous {
1972 return Err(FunctionError::BadBounds {
1973 detail: format!(
1974 "element {i} ({b}) is less than element {} ({previous})",
1975 i - 1
1976 ),
1977 });
1978 }
1979 if b < bounds_of_domain[0] || b > bounds_of_domain[1] {
1980 return Err(FunctionError::BadBounds {
1981 detail: format!(
1982 "element {i} ({b}) is outside /Domain [{}, {}]",
1983 bounds_of_domain[0], bounds_of_domain[1]
1984 ),
1985 });
1986 }
1987 previous = b;
1988 }
1989
1990 // --- /Encode ---------------------------------------------------------
1991 let encode = pairs(view, dict, b"Encode")?.ok_or(FunctionError::MissingEntry {
1992 key: "Encode",
1993 function_type: 3,
1994 })?;
1995 if encode.len() != k {
1996 return Err(FunctionError::BadArrayLength {
1997 key: "Encode",
1998 expected: k * 2,
1999 got: encode.len() * 2,
2000 });
2001 }
2002 // /Encode pairs are NOT checked with `check_ordered`: unlike /Domain and
2003 // /Range they are a mapping, not an interval, and `[1 0]` is the documented
2004 // domain-reversal idiom (see this type's docs).
2005
2006 Ok(Stitching {
2007 functions,
2008 bounds,
2009 encode,
2010 outputs,
2011 })
2012}
2013
2014impl Stitching {
2015 /// Which sub-function owns `x`.
2016 ///
2017 /// Counts the bounds `x` has reached or passed. With the half-open
2018 /// convention (closed left, open right) that count *is* the index: `x`
2019 /// below every bound gives 0; `x` exactly on `Bounds_0` gives 1, which is
2020 /// the "closed on the left" rule; `x` at `Domain_1` gives `k − 1`, the last
2021 /// sub-function, whose interval is closed on the right too.
2022 ///
2023 /// The `min` is belt and braces — `x` is pre-clipped to `/Domain` and every
2024 /// bound is inside it, so the count cannot exceed `k − 1` — but it keeps the
2025 /// function total for any input.
2026 fn select(&self, x: f64) -> usize {
2027 self.bounds
2028 .iter()
2029 .filter(|&&b| x >= b)
2030 .count()
2031 .min(self.functions.len().saturating_sub(1))
2032 }
2033
2034 /// Evaluate: pick the sub-function, rescale `x` onto its domain, delegate.
2035 ///
2036 /// # Errors
2037 ///
2038 /// Whatever the selected sub-function returns.
2039 fn eval(
2040 &self,
2041 domain: &[[f64; 2]],
2042 inputs: &[f64],
2043 out: &mut Vec<f64>,
2044 ) -> Result<(), FunctionError> {
2045 let bounds_of_domain = domain.first().copied().unwrap_or([0.0, 1.0]);
2046 let x = inputs.first().copied().unwrap_or(0.0);
2047 let i = self.select(x);
2048
2049 // §7.10.4's Bounds_(−1) = Domain_0 and Bounds_(k−1) = Domain_1
2050 // convention, made explicit.
2051 let low = if i == 0 {
2052 bounds_of_domain[0]
2053 } else {
2054 self.bounds
2055 .get(i - 1)
2056 .copied()
2057 .unwrap_or(bounds_of_domain[0])
2058 };
2059 let high = self.bounds.get(i).copied().unwrap_or(bounds_of_domain[1]);
2060
2061 let enc = self.encode.get(i).copied().unwrap_or([0.0, 1.0]);
2062 // When low == high (a collapsed subinterval, including §7.10.4's
2063 // "last bound equal to Domain_1" case), `interpolate` returns
2064 // `enc[0]` — which is precisely what that clause specifies.
2065 let encoded = interpolate(x, low, high, enc[0], enc[1]);
2066
2067 let Some(f) = self.functions.get(i) else {
2068 // Unreachable: `select` clamps to the function count, and
2069 // `load_stitching` refuses an empty array.
2070 return Err(FunctionError::NoSubFunctions);
2071 };
2072 // The sub-function clips `encoded` to its OWN /Domain and its result to
2073 // its own /Range; the outer /Range clip then applies on top, in
2074 // `PdfFunction::eval_into`. Both are required — they are different
2075 // functions' declarations.
2076 f.eval_into(&[encoded], out)
2077 }
2078}
2079
2080// ---------------------------------------------------------------------------
2081// Type 4 — PostScript calculator (§7.10.5)
2082// ---------------------------------------------------------------------------
2083
2084/// A parsed type 4 program plus its declared output count.
2085///
2086/// §7.10.5.1: the code is *"a small subset of the PostScript language"* with
2087/// *"integers, real numbers, and boolean values only"* and *"no composite data
2088/// structures such as strings or arrays, no procedures, and no variables or
2089/// names"*. So there is no environment to model — the whole machine is an
2090/// operand stack.
2091#[derive(Debug, Clone, PartialEq)]
2092struct PostScript {
2093 /// The top-level block, already stripped of its enclosing braces.
2094 program: Vec<PsOp>,
2095 /// *n*, from `/Range` (required for type 4).
2096 outputs: usize,
2097}
2098
2099/// One instruction.
2100///
2101/// `if`/`ifelse` carry their branches inline rather than as jump targets. The
2102/// spec's own framing supports it: *"This construct is purely syntactic; unlike
2103/// in PostScript, no 'procedure objects' shall be involved"* — a brace block is
2104/// not a value that can be pushed, duplicated or stored, so it can only ever be
2105/// the immediate operand of the operator that follows it. A tree therefore
2106/// loses nothing and makes the "a block must be consumed by `if`/`ifelse`"
2107/// rule a parse-time property rather than a runtime one.
2108#[derive(Debug, Clone, PartialEq)]
2109enum PsOp {
2110 /// A numeric literal. Integers and reals are kept apart because Table 42
2111 /// distinguishes them (`idiv` and `bitshift` are integer-only).
2112 Push(PsValue),
2113 /// A Table 42 operator.
2114 Op(PsOperator),
2115 /// `bool { … } if`
2116 If(Vec<PsOp>),
2117 /// `bool { … } { … } ifelse`
2118 IfElse(Vec<PsOp>, Vec<PsOp>),
2119}
2120
2121/// A value on the operand stack.
2122///
2123/// Three types, exactly as §7.10.5.1 allows. Integers are `i32`: PostScript
2124/// integers are 32-bit, Annex C's implementation limits describe the same
2125/// width for the file grammar, and `bitshift` is only well defined against a
2126/// fixed width.
2127#[derive(Debug, Clone, Copy, PartialEq)]
2128enum PsValue {
2129 /// An integer.
2130 Int(i32),
2131 /// A real.
2132 Real(f64),
2133 /// A boolean.
2134 Bool(bool),
2135}
2136
2137impl PsValue {
2138 /// The numeric value, or `None` for a boolean.
2139 fn as_number(self) -> Option<f64> {
2140 match self {
2141 Self::Int(i) => Some(f64::from(i)),
2142 Self::Real(r) => Some(r),
2143 Self::Bool(_) => None,
2144 }
2145 }
2146
2147 /// The boolean value, or `None` for a number.
2148 fn as_bool(self) -> Option<bool> {
2149 match self {
2150 Self::Bool(b) => Some(b),
2151 Self::Int(_) | Self::Real(_) => None,
2152 }
2153 }
2154
2155 /// The integer value, or `None` for a real or boolean.
2156 fn as_int(self) -> Option<i32> {
2157 match self {
2158 Self::Int(i) => Some(i),
2159 Self::Real(_) | Self::Bool(_) => None,
2160 }
2161 }
2162}
2163
2164/// Table 42's operator set — **42 entries**, of which the 38 below are
2165/// dispatched at run time and the other four are handled structurally by the
2166/// parser (`true`/`false` become [`PsOp::Push`], `if`/`ifelse` become
2167/// [`PsOp::If`]/[`PsOp::IfElse`]).
2168///
2169/// The 42/38 split is worth stating because the table's own grouping invites a
2170/// miscount: its "Relational, boolean, and bitwise" row contains 13 names, two
2171/// of which (`true`, `false`) are literals rather than operators.
2172///
2173/// **The set is closed.** §7.10.5.1 presents Table 42 as the operators
2174/// available, and §7.10.5.2 makes syntax detection a reader `shall`, so a token
2175/// that is not in this list is a defect in the file
2176/// ([`FunctionError::UnknownOperator`]) rather than a pdfcer gap to be silently
2177/// skipped. Skipping an unknown token would leave the stack the wrong depth and
2178/// surface as a bewildering output-arity error at the end of an otherwise valid
2179/// program.
2180#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2181enum PsOperator {
2182 // Arithmetic (21).
2183 Abs,
2184 Add,
2185 Atan,
2186 Ceiling,
2187 Cos,
2188 Cvi,
2189 Cvr,
2190 Div,
2191 Exp,
2192 Floor,
2193 Idiv,
2194 Ln,
2195 Log,
2196 Mod,
2197 Mul,
2198 Neg,
2199 Round,
2200 Sin,
2201 Sqrt,
2202 Sub,
2203 Truncate,
2204 // Relational, boolean, bitwise (11 — `true` and `false` are literals).
2205 And,
2206 Bitshift,
2207 Eq,
2208 Ge,
2209 Gt,
2210 Le,
2211 Lt,
2212 Ne,
2213 Not,
2214 Or,
2215 Xor,
2216 // Stack (6).
2217 Copy,
2218 Dup,
2219 Exch,
2220 Index,
2221 Pop,
2222 Roll,
2223}
2224
2225impl PsOperator {
2226 /// Map a source token to an operator.
2227 ///
2228 /// Returns `None` for `true`, `false`, `if` and `ifelse`, which the parser
2229 /// handles structurally, and for anything not in Table 42.
2230 fn from_token(name: &[u8]) -> Option<Self> {
2231 Some(match name {
2232 b"abs" => Self::Abs,
2233 b"add" => Self::Add,
2234 b"atan" => Self::Atan,
2235 b"ceiling" => Self::Ceiling,
2236 b"cos" => Self::Cos,
2237 b"cvi" => Self::Cvi,
2238 b"cvr" => Self::Cvr,
2239 b"div" => Self::Div,
2240 b"exp" => Self::Exp,
2241 b"floor" => Self::Floor,
2242 b"idiv" => Self::Idiv,
2243 b"ln" => Self::Ln,
2244 b"log" => Self::Log,
2245 b"mod" => Self::Mod,
2246 b"mul" => Self::Mul,
2247 b"neg" => Self::Neg,
2248 b"round" => Self::Round,
2249 b"sin" => Self::Sin,
2250 b"sqrt" => Self::Sqrt,
2251 b"sub" => Self::Sub,
2252 b"truncate" => Self::Truncate,
2253 b"and" => Self::And,
2254 b"bitshift" => Self::Bitshift,
2255 b"eq" => Self::Eq,
2256 b"ge" => Self::Ge,
2257 b"gt" => Self::Gt,
2258 b"le" => Self::Le,
2259 b"lt" => Self::Lt,
2260 b"ne" => Self::Ne,
2261 b"not" => Self::Not,
2262 b"or" => Self::Or,
2263 b"xor" => Self::Xor,
2264 b"copy" => Self::Copy,
2265 b"dup" => Self::Dup,
2266 b"exch" => Self::Exch,
2267 b"index" => Self::Index,
2268 b"pop" => Self::Pop,
2269 b"roll" => Self::Roll,
2270 _ => return None,
2271 })
2272 }
2273
2274 /// The operator's source spelling, for error messages.
2275 const fn name(self) -> &'static str {
2276 match self {
2277 Self::Abs => "abs",
2278 Self::Add => "add",
2279 Self::Atan => "atan",
2280 Self::Ceiling => "ceiling",
2281 Self::Cos => "cos",
2282 Self::Cvi => "cvi",
2283 Self::Cvr => "cvr",
2284 Self::Div => "div",
2285 Self::Exp => "exp",
2286 Self::Floor => "floor",
2287 Self::Idiv => "idiv",
2288 Self::Ln => "ln",
2289 Self::Log => "log",
2290 Self::Mod => "mod",
2291 Self::Mul => "mul",
2292 Self::Neg => "neg",
2293 Self::Round => "round",
2294 Self::Sin => "sin",
2295 Self::Sqrt => "sqrt",
2296 Self::Sub => "sub",
2297 Self::Truncate => "truncate",
2298 Self::And => "and",
2299 Self::Bitshift => "bitshift",
2300 Self::Eq => "eq",
2301 Self::Ge => "ge",
2302 Self::Gt => "gt",
2303 Self::Le => "le",
2304 Self::Lt => "lt",
2305 Self::Ne => "ne",
2306 Self::Not => "not",
2307 Self::Or => "or",
2308 Self::Xor => "xor",
2309 Self::Copy => "copy",
2310 Self::Dup => "dup",
2311 Self::Exch => "exch",
2312 Self::Index => "index",
2313 Self::Pop => "pop",
2314 Self::Roll => "roll",
2315 }
2316 }
2317}
2318
2319/// Build a [`PostScript`] from its stream: decode, lex, parse.
2320///
2321/// # Errors
2322///
2323/// [`FunctionError`] — see [`PdfFunction::load`].
2324fn load_postscript(
2325 view: &DocumentView<'_>,
2326 resolved: &Object,
2327 domain: &[[f64; 2]],
2328 range: Option<&[[f64; 2]]>,
2329) -> Result<PostScript, FunctionError> {
2330 let Object::Stream(stream) = resolved else {
2331 return Err(FunctionError::NotAStream { function_type: 4 });
2332 };
2333 // §7.10.5.1: "The Domain and Range entries shall both be required."
2334 // /Domain's presence is enforced by the common loader (which also rejects an
2335 // empty one); /Range is checked here because it is type-4-specific and is
2336 // the only source of n.
2337 let _ = domain;
2338 let range = range.ok_or(FunctionError::MissingEntry {
2339 key: "Range",
2340 function_type: 4,
2341 })?;
2342
2343 let source = stream_bytes(view, stream)?;
2344 let program = parse_program(&source)?;
2345 Ok(PostScript {
2346 program,
2347 outputs: range.len(),
2348 })
2349}
2350
2351/// Parse a whole type 4 stream into its top-level block.
2352///
2353/// §7.10.5.1: *"The entire code stream defining the function shall be enclosed
2354/// in braces `{ }`."* pdfcer enforces that literally — a stream whose first
2355/// token is not `{` is refused rather than treated as an implicit block.
2356///
2357/// That strictness is a choice, and it is the one this project's posture calls
2358/// for: the alternative is guessing that a producer meant an implicit outer
2359/// block, and a guess that turns out wrong yields a program that runs and
2360/// produces a colour. A refusal naming the missing brace can be acted on.
2361///
2362/// The lexer already classifies `{` and `}` as [`TokenKind::BraceOpen`] and
2363/// [`TokenKind::BraceClose`] (they are Table 2 delimiters) and skips comments
2364/// and white-space per §7.2 — so this parser needs no tokenizer of its own.
2365/// That reuse is deliberate: a second tokenizer would eventually disagree with
2366/// the first about something like `4.` or a `%` comment inside a program.
2367///
2368/// # Errors
2369///
2370/// [`FunctionError::PostScriptLex`], [`FunctionError::PostScriptSyntax`],
2371/// [`FunctionError::UnknownOperator`],
2372/// [`FunctionError::PostScriptNestingTooDeep`].
2373fn parse_program(source: &[u8]) -> Result<Vec<PsOp>, FunctionError> {
2374 let mut lexer = Lexer::new(source);
2375 let Some(first) = lexer.next_token()? else {
2376 return Err(FunctionError::PostScriptSyntax {
2377 detail: "the program stream is empty".to_owned(),
2378 });
2379 };
2380 if first.kind != TokenKind::BraceOpen {
2381 return Err(FunctionError::PostScriptSyntax {
2382 detail: "the program is not enclosed in braces (§7.10.5.1 requires `{ … }`)".to_owned(),
2383 });
2384 }
2385 let block = parse_block(&mut lexer, source, 1)?;
2386 if let Some(extra) = lexer.next_token()? {
2387 return Err(FunctionError::PostScriptSyntax {
2388 detail: format!(
2389 "trailing content after the closing brace, starting at byte {}",
2390 extra.span.start
2391 ),
2392 });
2393 }
2394 Ok(block)
2395}
2396
2397/// Parse tokens up to the matching `}`.
2398///
2399/// The one non-obvious rule is how brace blocks attach to their operator. In
2400/// this sub-language a block is **not a value** — §7.10.5.1: *"This construct is
2401/// purely syntactic; unlike in PostScript, no 'procedure objects' shall be
2402/// involved"* — so it can only be the operand of the `if` or `ifelse` that
2403/// immediately follows. A parsed block is therefore held in `pending` until one
2404/// of those two claims it, and anything else appearing while `pending` is
2405/// non-empty is a syntax error. That check rejects `{ 1 } 2 add` and
2406/// `{ 1 } { 2 } { 3 } ifelse` at parse time instead of letting them become a
2407/// confusing runtime failure.
2408///
2409/// # Errors
2410///
2411/// As [`parse_program`].
2412fn parse_block(
2413 lexer: &mut Lexer<'_>,
2414 source: &[u8],
2415 depth: usize,
2416) -> Result<Vec<PsOp>, FunctionError> {
2417 if depth > MAX_PS_NESTING {
2418 return Err(FunctionError::PostScriptNestingTooDeep {
2419 limit: MAX_PS_NESTING,
2420 });
2421 }
2422
2423 let mut ops: Vec<PsOp> = Vec::new();
2424 // At most two blocks can be pending (the `ifelse` case).
2425 let mut pending: Vec<Vec<PsOp>> = Vec::new();
2426
2427 loop {
2428 let Some(token) = lexer.next_token()? else {
2429 return Err(FunctionError::PostScriptSyntax {
2430 detail: "end of stream inside a `{ … }` block".to_owned(),
2431 });
2432 };
2433
2434 match token.kind {
2435 TokenKind::BraceClose => {
2436 reject_pending(&pending)?;
2437 return Ok(ops);
2438 }
2439 TokenKind::BraceOpen => {
2440 if pending.len() >= 2 {
2441 return Err(FunctionError::PostScriptSyntax {
2442 detail: "more than two consecutive `{ … }` blocks; `ifelse` takes two"
2443 .to_owned(),
2444 });
2445 }
2446 let nested = parse_block(lexer, source, depth + 1)?;
2447 pending.push(nested);
2448 }
2449 TokenKind::Integer(v) => {
2450 reject_pending(&pending)?;
2451 // Annex C's integer range is ±2^31; a literal outside i32 is
2452 // refused rather than saturated, because a saturated constant is
2453 // a wrong number that then computes silently.
2454 let Ok(i) = i32::try_from(v) else {
2455 return Err(FunctionError::PostScriptSyntax {
2456 detail: format!("integer literal {v} does not fit a 32-bit integer"),
2457 });
2458 };
2459 ops.push(PsOp::Push(PsValue::Int(i)));
2460 }
2461 TokenKind::Real(v) => {
2462 reject_pending(&pending)?;
2463 if !v.is_finite() {
2464 return Err(FunctionError::PostScriptSyntax {
2465 detail: format!("real literal {v} is not finite"),
2466 });
2467 }
2468 ops.push(PsOp::Push(PsValue::Real(v)));
2469 }
2470 TokenKind::Keyword => {
2471 let name = token.lexeme(source).unwrap_or(b"");
2472 match name {
2473 b"true" | b"false" => {
2474 reject_pending(&pending)?;
2475 ops.push(PsOp::Push(PsValue::Bool(name == b"true")));
2476 }
2477 b"if" => {
2478 if pending.len() != 1 {
2479 return Err(FunctionError::PostScriptSyntax {
2480 detail: format!(
2481 "`if` needs exactly one preceding `{{ … }}` block; found {}",
2482 pending.len()
2483 ),
2484 });
2485 }
2486 let then_block = pending.pop().unwrap_or_default();
2487 ops.push(PsOp::If(then_block));
2488 }
2489 b"ifelse" => {
2490 if pending.len() != 2 {
2491 return Err(FunctionError::PostScriptSyntax {
2492 detail: format!(
2493 "`ifelse` needs exactly two preceding `{{ … }}` blocks; found {}",
2494 pending.len()
2495 ),
2496 });
2497 }
2498 // `pending` is [then, else] in source order, so `pop`
2499 // yields the else branch first.
2500 let else_block = pending.pop().unwrap_or_default();
2501 let then_block = pending.pop().unwrap_or_default();
2502 ops.push(PsOp::IfElse(then_block, else_block));
2503 }
2504 other => {
2505 reject_pending(&pending)?;
2506 let op = PsOperator::from_token(other).ok_or_else(|| {
2507 FunctionError::UnknownOperator(
2508 String::from_utf8_lossy(other).into_owned(),
2509 )
2510 })?;
2511 ops.push(PsOp::Op(op));
2512 }
2513 }
2514 }
2515 other => {
2516 return Err(FunctionError::PostScriptSyntax {
2517 detail: format!(
2518 "{other:?} at byte {} has no meaning in a type 4 program \
2519 (§7.10.5.1 allows numbers, booleans, operators and braces only)",
2520 token.span.start
2521 ),
2522 });
2523 }
2524 }
2525 }
2526}
2527
2528/// Refuse a token that appears while a `{ … }` block is still waiting for its
2529/// `if`/`ifelse`.
2530///
2531/// # Errors
2532///
2533/// [`FunctionError::PostScriptSyntax`].
2534fn reject_pending(pending: &[Vec<PsOp>]) -> Result<(), FunctionError> {
2535 if pending.is_empty() {
2536 Ok(())
2537 } else {
2538 Err(FunctionError::PostScriptSyntax {
2539 detail: "a `{ … }` block must be followed immediately by `if` or `ifelse`".to_owned(),
2540 })
2541 }
2542}
2543
2544/// The operand stack, with §7.10.5.1's capacity rule enforced on every push.
2545///
2546/// A newtype rather than a bare `Vec<PsValue>` for one reason: the overflow
2547/// check has to be on *every* growth path, and there are several (`push`, `dup`,
2548/// `copy`, the initial input load). Centralising it here makes
2549/// [`FunctionError::StackOverflow`] impossible to forget, which matters because
2550/// the spec makes overflow *an error* rather than a resize.
2551#[derive(Debug)]
2552struct PsStack {
2553 values: Vec<PsValue>,
2554}
2555
2556impl PsStack {
2557 /// A stack pre-sized to the spec's 100-entry capacity, so no evaluation
2558 /// reallocates.
2559 fn new() -> Self {
2560 Self {
2561 values: Vec::with_capacity(PS_STACK_LIMIT),
2562 }
2563 }
2564
2565 /// Push, refusing to exceed [`PS_STACK_LIMIT`].
2566 ///
2567 /// # Errors
2568 ///
2569 /// [`FunctionError::StackOverflow`].
2570 fn push(&mut self, value: PsValue) -> Result<(), FunctionError> {
2571 if self.values.len() >= PS_STACK_LIMIT {
2572 return Err(FunctionError::StackOverflow {
2573 limit: PS_STACK_LIMIT,
2574 });
2575 }
2576 self.values.push(value);
2577 Ok(())
2578 }
2579
2580 /// Pop one value.
2581 ///
2582 /// # Errors
2583 ///
2584 /// [`FunctionError::StackUnderflow`].
2585 fn pop(&mut self, op: &'static str) -> Result<PsValue, FunctionError> {
2586 self.values.pop().ok_or(FunctionError::StackUnderflow {
2587 op,
2588 needed: 1,
2589 had: 0,
2590 })
2591 }
2592
2593 /// Pop two values and return them in **source order** — `(first, second)`
2594 /// for a program that wrote `first second op`.
2595 ///
2596 /// Returning them pre-swapped is not a nicety. `sub`, `div`, `idiv`, `mod`,
2597 /// `exp`, `bitshift` and every relational operator are non-commutative, and
2598 /// the classic defect in a hand-written PostScript machine is
2599 /// `a b sub` computing `b − a`. Doing the swap in exactly one place removes
2600 /// the chance to get it wrong per operator.
2601 ///
2602 /// # Errors
2603 ///
2604 /// [`FunctionError::StackUnderflow`].
2605 fn pop2(&mut self, op: &'static str) -> Result<(PsValue, PsValue), FunctionError> {
2606 if self.values.len() < 2 {
2607 return Err(FunctionError::StackUnderflow {
2608 op,
2609 needed: 2,
2610 had: self.values.len(),
2611 });
2612 }
2613 let second = self.values.pop().ok_or(FunctionError::StackUnderflow {
2614 op,
2615 needed: 2,
2616 had: 0,
2617 })?;
2618 let first = self.values.pop().ok_or(FunctionError::StackUnderflow {
2619 op,
2620 needed: 2,
2621 had: 1,
2622 })?;
2623 Ok((first, second))
2624 }
2625
2626 /// Pop one value as a number.
2627 ///
2628 /// # Errors
2629 ///
2630 /// [`FunctionError::StackUnderflow`], or [`FunctionError::PostScriptType`]
2631 /// if the operand is a boolean.
2632 fn pop_number(&mut self, op: &'static str) -> Result<f64, FunctionError> {
2633 self.pop(op)?
2634 .as_number()
2635 .ok_or(FunctionError::PostScriptType {
2636 op,
2637 detail: "expected a number, found a boolean",
2638 })
2639 }
2640
2641 /// Pop two values as numbers, in source order.
2642 ///
2643 /// # Errors
2644 ///
2645 /// As [`PsStack::pop2`] and [`PsStack::pop_number`].
2646 fn pop2_numbers(&mut self, op: &'static str) -> Result<(f64, f64), FunctionError> {
2647 let (a, b) = self.pop2(op)?;
2648 let ty = FunctionError::PostScriptType {
2649 op,
2650 detail: "expected two numbers, found a boolean",
2651 };
2652 Ok((
2653 a.as_number().ok_or_else(|| ty.clone())?,
2654 b.as_number().ok_or(ty)?,
2655 ))
2656 }
2657
2658 /// Pop one value as a 32-bit integer.
2659 ///
2660 /// # Errors
2661 ///
2662 /// [`FunctionError::StackUnderflow`], or [`FunctionError::PostScriptType`]
2663 /// for a real or a boolean. A real is rejected rather than truncated: `idiv`
2664 /// and `bitshift` are integer operators, and quietly truncating `2.7` to `2`
2665 /// would turn a file defect into a wrong number.
2666 fn pop_int(&mut self, op: &'static str) -> Result<i32, FunctionError> {
2667 self.pop(op)?.as_int().ok_or(FunctionError::PostScriptType {
2668 op,
2669 detail: "expected an integer; reals and booleans are not accepted here",
2670 })
2671 }
2672
2673 /// Pop one value as a count operand for `copy`, `index` or `roll`.
2674 ///
2675 /// # Errors
2676 ///
2677 /// [`FunctionError::StackUnderflow`], [`FunctionError::PostScriptType`] for a
2678 /// non-integer, or [`FunctionError::PostScriptRange`] for a negative count.
2679 fn pop_count(&mut self, op: &'static str) -> Result<usize, FunctionError> {
2680 let n = self.pop_int(op)?;
2681 usize::try_from(n).map_err(|_| FunctionError::PostScriptRange {
2682 op,
2683 detail: "the count operand is negative",
2684 })
2685 }
2686
2687 /// Current depth.
2688 fn len(&self) -> usize {
2689 self.values.len()
2690 }
2691}
2692
2693impl PostScript {
2694 /// Run the program with `inputs` as the initial operand stack.
2695 ///
2696 /// §7.10.5.1: *"The input variables shall constitute the initial operand
2697 /// stack; the items remaining on the operand stack after execution … shall
2698 /// be the output variables. It shall be an error for the number of
2699 /// remaining operands to differ from the number of output variables
2700 /// specified by `Range` or for any of them to be objects other than
2701 /// numbers."*
2702 ///
2703 /// Both halves of that final sentence are enforced
2704 /// ([`FunctionError::OutputArity`], [`FunctionError::NonNumericOutput`]).
2705 /// Neither is negotiable: a program that leaves three values for a
2706 /// four-component alternate space has no defined meaning, and §7.10's
2707 /// negative result `F-N2` records that the standard offers no recovery for
2708 /// it either.
2709 ///
2710 /// Inputs are pushed **in order**, so input 0 is deepest — the natural
2711 /// reading of "the input variables constitute the initial stack", and what
2712 /// makes a 2-in program's `exch` behave as its author intended.
2713 ///
2714 /// # Errors
2715 ///
2716 /// Every `PostScript*` variant of [`FunctionError`], plus
2717 /// [`FunctionError::StepLimit`], [`FunctionError::OutputArity`] and
2718 /// [`FunctionError::NonNumericOutput`].
2719 fn eval(&self, inputs: &[f64], out: &mut Vec<f64>) -> Result<(), FunctionError> {
2720 let mut stack = PsStack::new();
2721 for &x in inputs {
2722 stack.push(PsValue::Real(x))?;
2723 }
2724
2725 let mut steps = 0usize;
2726 exec_block(&self.program, &mut stack, &mut steps)?;
2727
2728 if stack.len() != self.outputs {
2729 return Err(FunctionError::OutputArity {
2730 expected: self.outputs,
2731 got: stack.len(),
2732 });
2733 }
2734 for (index, value) in stack.values.iter().enumerate() {
2735 let Some(v) = value.as_number() else {
2736 return Err(FunctionError::NonNumericOutput { index });
2737 };
2738 out.push(v);
2739 }
2740 Ok(())
2741 }
2742}
2743
2744/// Execute a block of operations against `stack`.
2745///
2746/// `steps` is threaded through rather than held per-block so the
2747/// [`MAX_PS_STEPS`] cap covers the whole evaluation, not each branch
2748/// separately. Recursion depth is bounded by [`MAX_PS_NESTING`] at parse time,
2749/// so this cannot overflow the native stack.
2750///
2751/// # Errors
2752///
2753/// As [`PostScript::eval`].
2754fn exec_block(ops: &[PsOp], stack: &mut PsStack, steps: &mut usize) -> Result<(), FunctionError> {
2755 for op in ops {
2756 *steps += 1;
2757 if *steps > MAX_PS_STEPS {
2758 return Err(FunctionError::StepLimit {
2759 limit: MAX_PS_STEPS,
2760 });
2761 }
2762 match op {
2763 PsOp::Push(v) => stack.push(*v)?,
2764 PsOp::Op(o) => apply(*o, stack)?,
2765 PsOp::If(then_block) => {
2766 let cond = stack.pop("if")?;
2767 let Some(b) = cond.as_bool() else {
2768 return Err(FunctionError::PostScriptType {
2769 op: "if",
2770 detail: "the condition operand is not a boolean",
2771 });
2772 };
2773 if b {
2774 exec_block(then_block, stack, steps)?;
2775 }
2776 }
2777 PsOp::IfElse(then_block, else_block) => {
2778 let cond = stack.pop("ifelse")?;
2779 let Some(b) = cond.as_bool() else {
2780 return Err(FunctionError::PostScriptType {
2781 op: "ifelse",
2782 detail: "the condition operand is not a boolean",
2783 });
2784 };
2785 if b {
2786 exec_block(then_block, stack, steps)?;
2787 } else {
2788 exec_block(else_block, stack, steps)?;
2789 }
2790 }
2791 }
2792 }
2793 Ok(())
2794}
2795
2796/// Integer width for type 4 arithmetic — **a resolved spec ambiguity, not a
2797/// sourced value** (recorded as `F-A3` in `iso32000__s__7.10.md`).
2798///
2799/// `bitshift`'s *direction* and zero-fill are sourced (Annex B and PLRM3 §8.2),
2800/// but the *width* it shifts within is disclaimed by both documents.
2801/// §7.10.5.1 exempts type 4 intermediates from Annex C's limits — *"an
2802/// implementation may use a representation that exceeds those limits"* — and
2803/// PLRM3 says the representation of integers *"may depend on the CPU
2804/// architecture"*. So there is no width to look up.
2805///
2806/// pdfcer fixes it at **32**, because Annex C Table C.1's `integer` row is the
2807/// only integer range ISO 32000-1 states anywhere, and because it is what every
2808/// PostScript interpreter of the era used. The choice is observable in three
2809/// places: the result of a right shift on a negative operand, the point at
2810/// which `add`/`sub`/`mul` spill from integer to real, and `cvi`'s
2811/// `rangecheck`.
2812///
2813/// This is exactly the shape of thing that belongs in
2814/// `pdfcer_core::settings::Settings` alongside the other resolved ambiguities
2815/// rather than being frozen in a constant; it is a constant here only because
2816/// this module was added without touching the settings surface. Wiring it up is
2817/// a small, mechanical follow-up.
2818pub const PS_INTEGER_BITS: u32 = 32;
2819
2820/// A `typecheck` refusal (§7.10.5.2's *"type error"* class).
2821const fn type_err(op: &'static str, detail: &'static str) -> FunctionError {
2822 FunctionError::PostScriptType { op, detail }
2823}
2824
2825/// A `rangecheck` refusal (§7.10.5.2's *"range error"* class).
2826const fn range_err(op: &'static str, detail: &'static str) -> FunctionError {
2827 FunctionError::PostScriptRange { op, detail }
2828}
2829
2830/// An `undefinedresult` refusal (§7.10.5.2's *"undefined result"* class).
2831const fn undefined(op: &'static str, detail: &'static str) -> FunctionError {
2832 FunctionError::UndefinedResult { op, detail }
2833}
2834
2835/// Binary arithmetic with Annex B's integer-preservation rule.
2836///
2837/// Annex B types `add`, `sub` and `mul` as `num1 num2 → sum`, and PLRM3 §8.2
2838/// fixes what "num" means on the way out: the result is an **integer if both
2839/// operands were integers and the true result is representable as one**, and a
2840/// **real otherwise**. The overflow half of that is not a rounding detail — it
2841/// is why `2000000000 2000000000 add` yields `4.0e9` rather than wrapping to a
2842/// negative number, and a wrapped value here would come out of a tint transform
2843/// as a wildly wrong colour component.
2844///
2845/// `int_op` is the checked integer form (returning `None` on overflow) and
2846/// `real_op` the `f64` fallback, so the two paths cannot drift apart.
2847///
2848/// # Errors
2849///
2850/// [`FunctionError::PostScriptType`] if either operand is a boolean.
2851fn arith(
2852 op: &'static str,
2853 a: PsValue,
2854 b: PsValue,
2855 int_op: fn(i32, i32) -> Option<i32>,
2856 real_op: fn(f64, f64) -> f64,
2857) -> Result<PsValue, FunctionError> {
2858 if let (PsValue::Int(x), PsValue::Int(y)) = (a, b) {
2859 return Ok(match int_op(x, y) {
2860 Some(v) => PsValue::Int(v),
2861 None => PsValue::Real(real_op(f64::from(x), f64::from(y))),
2862 });
2863 }
2864 let detail = "expected two numbers, found a boolean";
2865 let x = a.as_number().ok_or(type_err(op, detail))?;
2866 let y = b.as_number().ok_or(type_err(op, detail))?;
2867 Ok(PsValue::Real(real_op(x, y)))
2868}
2869
2870/// The four rounding operators, which are **type-preserving, not
2871/// integer-producing**.
2872///
2873/// This is the single most surprising rule in Table 42 and the one most likely
2874/// to be got wrong from intuition. PLRM3 §8.2: `3.2 floor` yields the **real**
2875/// `3.0`, not the integer `3`; `99 floor` yields the integer `99` unchanged.
2876/// Only `cvi` converts a real to an integer.
2877///
2878/// It matters because it is *observable*: a program that writes
2879/// `2 div floor 2 idiv` is malformed, because `floor` handed `idiv` a real and
2880/// `idiv` is integer-only. An implementation that helpfully returned an integer
2881/// from `floor` would accept that program and compute a value no conforming
2882/// reader computes.
2883///
2884/// # Errors
2885///
2886/// [`FunctionError::PostScriptType`] for a boolean operand.
2887fn round_like(
2888 op: &'static str,
2889 v: PsValue,
2890 real_op: fn(f64) -> f64,
2891) -> Result<PsValue, FunctionError> {
2892 match v {
2893 // Already integral, and its type is preserved.
2894 PsValue::Int(i) => Ok(PsValue::Int(i)),
2895 PsValue::Real(r) => Ok(PsValue::Real(real_op(r))),
2896 PsValue::Bool(_) => Err(type_err(op, "expected a number, found a boolean")),
2897 }
2898}
2899
2900/// PostScript's `round`: to the nearest integral value, **ties toward the
2901/// greater** value.
2902///
2903/// PLRM3 §8.2 gives `6.5 round → 7.0` and `-6.5 round → -6.0`. Rust's
2904/// `f64::round` breaks ties *away from zero*, so it returns `-7.0` for the
2905/// second — the one case where the obvious call is wrong. `(x + 0.5).floor()`
2906/// reproduces the specified behaviour for both signs.
2907fn round_half_up(x: f64) -> f64 {
2908 (x + 0.5).floor()
2909}
2910
2911/// Apply one Table 42 operator to the operand stack.
2912///
2913/// ## Where these semantics come from
2914///
2915/// Table 42 itself (§7.10.5.1) lists **only operator names** — it has no
2916/// semantics column. The clause delegates: *"the semantics are those of the
2917/// corresponding PostScript operators"*, pointing at the *PostScript Language
2918/// Reference*, 3rd edition. Two things follow, and both are recorded in
2919/// `iso32000__s__7.10.md`:
2920///
2921/// 1. **ISO 32000-1 Annex B, `(normative)`, "Operators in Type 4 Functions"**
2922/// supplies the stack effect, arity and operand/result typing for all 42
2923/// entries. §7.10.5 never cross-references it, which is why it is easy to
2924/// miss from the clause — but it is normative, first-party, and it settles
2925/// degrees-versus-radians, `atan`'s two-operand form, `exp` as `pow`, `log`
2926/// as base 10, `bitshift`'s direction, and the `bool|int` polymorphism of
2927/// `and`/`or`/`xor`/`not`.
2928/// 2. **PLRM3 §8.2** supplies what Annex B does not: rounding directions, sign
2929/// conventions, integer preservation, `atan`'s `[0, 360)` normalisation, the
2930/// zero-fill of a right shift, and the error classes. Note that §7.10.5.1's
2931/// own pointer to *"Appendix B"* of PLRM3 is **misdirected** — PLRM3's
2932/// Appendix B is *Implementation Limits*; the operator definitions are in
2933/// Chapter 8. (Erratum `F-E3`.) PLRM3 is a Bibliography reference, i.e.
2934/// *informative*, which is why it is cited here alongside Annex B rather
2935/// than instead of it.
2936///
2937/// ## Errors, and only these errors
2938///
2939/// §7.10.5.2 lists five classes and they map one-to-one onto PostScript's:
2940/// `stackoverflow`, `stackunderflow`, `typecheck`, `rangecheck`,
2941/// `undefinedresult`. PostScript's `invalidaccess`, `syntaxerror` and
2942/// `limitcheck` are **unreachable** in this subset — they belong to the
2943/// string/array/dictionary/file forms of `copy`, `cvi`, `cvr`, `eq` and the
2944/// relationals, and the subset has no composite types at all. They are
2945/// deliberately not implemented.
2946///
2947/// # Errors
2948///
2949/// [`FunctionError::StackUnderflow`], [`FunctionError::StackOverflow`],
2950/// [`FunctionError::PostScriptType`], [`FunctionError::PostScriptRange`],
2951/// [`FunctionError::UndefinedResult`].
2952fn apply(op: PsOperator, stack: &mut PsStack) -> Result<(), FunctionError> {
2953 use PsOperator as O;
2954 let name = op.name();
2955
2956 match op {
2957 // --- Arithmetic (Annex B; PLRM3 §8.2) ------------------------------
2958 O::Add => {
2959 let (a, b) = stack.pop2(name)?;
2960 let v = arith(name, a, b, i32::checked_add, |x, y| x + y)?;
2961 stack.push(v)?;
2962 }
2963 O::Sub => {
2964 let (a, b) = stack.pop2(name)?;
2965 let v = arith(name, a, b, i32::checked_sub, |x, y| x - y)?;
2966 stack.push(v)?;
2967 }
2968 O::Mul => {
2969 let (a, b) = stack.pop2(name)?;
2970 let v = arith(name, a, b, i32::checked_mul, |x, y| x * y)?;
2971 stack.push(v)?;
2972 }
2973 // Annex B types `div` as `num1 num2 div → quotient`, and PLRM3 makes
2974 // the result ALWAYS a real, even for `4 2 div` (which yields 2.0, not
2975 // the integer 2). Integer division is a separate operator.
2976 O::Div => {
2977 let (a, b) = stack.pop2_numbers(name)?;
2978 if b == 0.0 {
2979 return Err(undefined(name, "division by zero"));
2980 }
2981 stack.push(PsValue::Real(a / b))?;
2982 }
2983 // `idiv` and `mod` are integer-only, and their sign conventions ARE
2984 // stated (PLRM3 §8.2): `idiv` truncates toward zero (`-5 2 idiv → -2`)
2985 // and `mod` takes the sign of the DIVIDEND (`-5 3 mod → -2`, described
2986 // as "a remainder operation rather than a true modulo"). Rust's `/` and
2987 // `%` on `i32` have exactly those semantics, so no adjustment is needed
2988 // — but the checked forms are used because `i32::MIN / -1` overflows.
2989 O::Idiv => {
2990 let (a, b) = stack.pop2(name)?;
2991 let (x, y) = (int_operand(name, a)?, int_operand(name, b)?);
2992 let q = x
2993 .checked_div(y)
2994 .ok_or(undefined(name, "division by zero, or i32::MIN / -1"))?;
2995 stack.push(PsValue::Int(q))?;
2996 }
2997 O::Mod => {
2998 let (a, b) = stack.pop2(name)?;
2999 let (x, y) = (int_operand(name, a)?, int_operand(name, b)?);
3000 let r = x
3001 .checked_rem(y)
3002 .ok_or(undefined(name, "division by zero, or i32::MIN % -1"))?;
3003 stack.push(PsValue::Int(r))?;
3004 }
3005 // `neg` and `abs` preserve their operand's type, with one documented
3006 // escape: the most negative integer has no positive counterpart, so it
3007 // becomes a real rather than wrapping back to itself.
3008 O::Neg => {
3009 let v = stack.pop(name)?;
3010 let r = match v {
3011 PsValue::Int(i) => i
3012 .checked_neg()
3013 .map_or_else(|| PsValue::Real(-f64::from(i)), PsValue::Int),
3014 PsValue::Real(r) => PsValue::Real(-r),
3015 PsValue::Bool(_) => {
3016 return Err(type_err(name, "expected a number, found a boolean"));
3017 }
3018 };
3019 stack.push(r)?;
3020 }
3021 O::Abs => {
3022 let v = stack.pop(name)?;
3023 let r = match v {
3024 PsValue::Int(i) => i
3025 .checked_abs()
3026 .map_or_else(|| PsValue::Real(f64::from(i).abs()), PsValue::Int),
3027 PsValue::Real(r) => PsValue::Real(r.abs()),
3028 PsValue::Bool(_) => {
3029 return Err(type_err(name, "expected a number, found a boolean"));
3030 }
3031 };
3032 stack.push(r)?;
3033 }
3034 O::Ceiling => {
3035 let v = stack.pop(name)?;
3036 let r = round_like(name, v, f64::ceil)?;
3037 stack.push(r)?;
3038 }
3039 O::Floor => {
3040 let v = stack.pop(name)?;
3041 let r = round_like(name, v, f64::floor)?;
3042 stack.push(r)?;
3043 }
3044 O::Round => {
3045 let v = stack.pop(name)?;
3046 let r = round_like(name, v, round_half_up)?;
3047 stack.push(r)?;
3048 }
3049 O::Truncate => {
3050 let v = stack.pop(name)?;
3051 let r = round_like(name, v, f64::trunc)?;
3052 stack.push(r)?;
3053 }
3054 O::Sqrt => {
3055 let x = stack.pop_number(name)?;
3056 if x < 0.0 {
3057 return Err(range_err(name, "sqrt of a negative number"));
3058 }
3059 stack.push(PsValue::Real(x.sqrt()))?;
3060 }
3061 // Annex B types these `angle sin → real` with the operand "in degrees".
3062 // The clause's own EXAMPLE corroborates it: the DoubleDot spot function
3063 // is `{ 360 mul sin 2 div exch 360 mul sin 2 div add }` over a
3064 // /Domain of [-1 1 -1 1] — the `360 mul` before each `sin` only makes
3065 // sense if `sin` wants degrees.
3066 O::Sin => {
3067 let x = stack.pop_number(name)?;
3068 stack.push(PsValue::Real(x.to_radians().sin()))?;
3069 }
3070 O::Cos => {
3071 let x = stack.pop_number(name)?;
3072 stack.push(PsValue::Real(x.to_radians().cos()))?;
3073 }
3074 // `num den atan → angle`: a two-operand arctangent, in DEGREES,
3075 // normalised to [0, 360) and therefore never negative.
3076 //
3077 // It is `atan2` with three divergences, and each one is a defect if
3078 // missed: Rust's `f64::atan2` returns radians, returns (−180°, 180°]
3079 // once converted, and answers 0 for `atan2(0.0, 0.0)`. PLRM3 requires
3080 // 270.0 where `atan2` gives −90.0, and makes `0 0 atan` an error.
3081 O::Atan => {
3082 let (num, den) = stack.pop2_numbers(name)?;
3083 if num == 0.0 && den == 0.0 {
3084 return Err(undefined(name, "atan of 0 over 0"));
3085 }
3086 let degrees = num.atan2(den).to_degrees();
3087 // `+ 0.0` normalises a negative zero to positive zero, so the
3088 // result is genuinely in [0, 360) rather than [-0.0, 360).
3089 let normalised = if degrees < 0.0 {
3090 degrees + 360.0
3091 } else {
3092 degrees + 0.0
3093 };
3094 stack.push(PsValue::Real(normalised))?;
3095 }
3096 // Annex B: `base exponent exp → real`. This is POW, not e^x — `9 0.5
3097 // exp` is 3.0. (`e^x` would be written `2.718… exch exp`.) Reading it
3098 // as e^x is the single easiest way to make a shading look plausible and
3099 // be wrong.
3100 O::Exp => {
3101 let (base, exponent) = stack.pop2_numbers(name)?;
3102 let r = base.powf(exponent);
3103 if !r.is_finite() {
3104 // 0 raised to a negative power, or a negative base under a
3105 // fractional exponent. §7.10.5.2's "undefined result".
3106 return Err(undefined(name, "exp has no finite result"));
3107 }
3108 stack.push(PsValue::Real(r))?;
3109 }
3110 // `ln` is natural, `log` is base 10 (Annex B states both). Both require
3111 // a positive operand.
3112 O::Ln => {
3113 let x = stack.pop_number(name)?;
3114 if x <= 0.0 {
3115 return Err(range_err(name, "ln of a non-positive number"));
3116 }
3117 stack.push(PsValue::Real(x.ln()))?;
3118 }
3119 O::Log => {
3120 let x = stack.pop_number(name)?;
3121 if x <= 0.0 {
3122 return Err(range_err(name, "log of a non-positive number"));
3123 }
3124 stack.push(PsValue::Real(x.log10()))?;
3125 }
3126 // `cvi` is the ONLY real-to-integer conversion in the language, and it
3127 // truncates toward zero (`-47.8 cvi → -47`), not toward negative
3128 // infinity. A value outside the integer range is a `rangecheck`.
3129 O::Cvi => {
3130 let x = stack.pop_number(name)?;
3131 let truncated = x.trunc();
3132 if !truncated.is_finite()
3133 || truncated < f64::from(i32::MIN)
3134 || truncated > f64::from(i32::MAX)
3135 {
3136 return Err(range_err(name, "value is outside the integer range"));
3137 }
3138 // In range and integral by construction, so the cast is exact.
3139 stack.push(PsValue::Int(truncated as i32))?;
3140 }
3141 O::Cvr => {
3142 let x = stack.pop_number(name)?;
3143 stack.push(PsValue::Real(x))?;
3144 }
3145
3146 // --- Relational, boolean, bitwise ----------------------------------
3147 //
3148 // Annex B's typing here is deliberately three-way, and the contrast is
3149 // the evidence that it is deliberate:
3150 // `eq`/`ne` -> any, any
3151 // `gt`/`ge`/`lt`/`le` -> num, num (a boolean is a typecheck)
3152 // `and`/`or`/`xor`/`not` -> bool|int (POLYMORPHIC)
3153 O::Eq => {
3154 let (a, b) = stack.pop2(name)?;
3155 stack.push(PsValue::Bool(ps_equal(a, b)))?;
3156 }
3157 O::Ne => {
3158 let (a, b) = stack.pop2(name)?;
3159 stack.push(PsValue::Bool(!ps_equal(a, b)))?;
3160 }
3161 O::Gt => {
3162 let (a, b) = stack.pop2_numbers(name)?;
3163 stack.push(PsValue::Bool(a > b))?;
3164 }
3165 O::Ge => {
3166 let (a, b) = stack.pop2_numbers(name)?;
3167 stack.push(PsValue::Bool(a >= b))?;
3168 }
3169 O::Lt => {
3170 let (a, b) = stack.pop2_numbers(name)?;
3171 stack.push(PsValue::Bool(a < b))?;
3172 }
3173 O::Le => {
3174 let (a, b) = stack.pop2_numbers(name)?;
3175 stack.push(PsValue::Bool(a <= b))?;
3176 }
3177 O::And => {
3178 let (a, b) = stack.pop2(name)?;
3179 let r = logical(name, a, b, |x, y| x && y, |x, y| x & y)?;
3180 stack.push(r)?;
3181 }
3182 O::Or => {
3183 let (a, b) = stack.pop2(name)?;
3184 let r = logical(name, a, b, |x, y| x || y, |x, y| x | y)?;
3185 stack.push(r)?;
3186 }
3187 O::Xor => {
3188 let (a, b) = stack.pop2(name)?;
3189 let r = logical(name, a, b, |x, y| x != y, |x, y| x ^ y)?;
3190 stack.push(r)?;
3191 }
3192 // On an integer, `not` is the ONES COMPLEMENT, not a zero test:
3193 // PLRM3's own example is `52 not → -53`. A boolean-only `not` that
3194 // coerced an integer would silently produce `false` there.
3195 O::Not => {
3196 let v = stack.pop(name)?;
3197 let r = match v {
3198 PsValue::Bool(b) => PsValue::Bool(!b),
3199 PsValue::Int(i) => PsValue::Int(!i),
3200 PsValue::Real(_) => {
3201 return Err(type_err(
3202 name,
3203 "expected a boolean or an integer, found a real",
3204 ));
3205 }
3206 };
3207 stack.push(r)?;
3208 }
3209 // `int1 shift bitshift → int2`. Positive shifts left, negative shifts
3210 // right, and PLRM3 is explicit that "bits shifted out are lost; bits
3211 // shifted in are 0" — so the right shift is LOGICAL, and `-8 -1
3212 // bitshift` is a large positive number rather than `-4`. The width it
3213 // shifts within is [`PS_INTEGER_BITS`], which is a resolved ambiguity
3214 // rather than a sourced value; see that constant.
3215 O::Bitshift => {
3216 let (a, s) = stack.pop2(name)?;
3217 let value = int_operand(name, a)?.cast_unsigned();
3218 let shift = int_operand(name, s)?;
3219 let width = PS_INTEGER_BITS;
3220 let shifted = if shift >= 0 {
3221 // `shift` is non-negative, so the conversion cannot fail.
3222 let by = u32::try_from(shift).unwrap_or(width);
3223 if by >= width { 0 } else { value << by }
3224 } else {
3225 // `checked_neg` guards `i32::MIN`, whose magnitude is far past
3226 // the width anyway — either way the answer is 0.
3227 let by = shift
3228 .checked_neg()
3229 .and_then(|m| u32::try_from(m).ok())
3230 .unwrap_or(width);
3231 if by >= width { 0 } else { value >> by }
3232 };
3233 stack.push(PsValue::Int(shifted.cast_signed()))?;
3234 }
3235
3236 // --- Stack ----------------------------------------------------------
3237 O::Pop => {
3238 stack.pop(name)?;
3239 }
3240 O::Exch => {
3241 let (a, b) = stack.pop2(name)?;
3242 stack.push(b)?;
3243 stack.push(a)?;
3244 }
3245 // Read rather than pop-and-push-twice, so a `dup` at exactly the stack
3246 // limit reports the overflow the spec calls for instead of succeeding
3247 // by transiently freeing a slot.
3248 O::Dup => {
3249 let top = *stack.values.last().ok_or(FunctionError::StackUnderflow {
3250 op: name,
3251 needed: 1,
3252 had: 0,
3253 })?;
3254 stack.push(top)?;
3255 }
3256 // `any1 … anyn n copy → any1 … anyn any1 … anyn`. The count is popped
3257 // first and is NOT part of the copied region. `0 copy` is explicitly a
3258 // legal no-op in PLRM3, so it must not be special-cased into an error.
3259 O::Copy => {
3260 let n = stack.pop_count(name)?;
3261 if n > 0 {
3262 let start = stack
3263 .len()
3264 .checked_sub(n)
3265 .ok_or(range_err(name, "count exceeds the stack depth"))?;
3266 let duplicated: Vec<PsValue> = stack
3267 .values
3268 .get(start..)
3269 .ok_or(range_err(name, "count exceeds the stack depth"))?
3270 .to_vec();
3271 for v in duplicated {
3272 stack.push(v)?;
3273 }
3274 }
3275 }
3276 // `anyn … any0 n index → anyn … any0 anyn`. Zero-based **from the top**,
3277 // so `0 index` is exactly `dup` — an implementation that counted from
3278 // the bottom, or from 1, would return a plausible wrong value rather
3279 // than fail.
3280 O::Index => {
3281 let n = stack.pop_count(name)?;
3282 let position = stack
3283 .len()
3284 .checked_sub(1)
3285 .and_then(|top| top.checked_sub(n))
3286 .ok_or(range_err(
3287 name,
3288 "index reaches past the bottom of the stack",
3289 ))?;
3290 let v = *stack.values.get(position).ok_or(range_err(
3291 name,
3292 "index reaches past the bottom of the stack",
3293 ))?;
3294 stack.push(v)?;
3295 }
3296 // `anyn−1 … any0 n j roll`: rotate the top `n` elements by `j`, with a
3297 // **positive `j` rotating upward** (toward the top).
3298 //
3299 // Reading `(a)(b)(c)` bottom-to-top with `(c)` on top, PLRM3 gives
3300 // `3 1 roll → (c)(a)(b)` and `3 -1 roll → (b)(c)(a)`. In a `Vec` whose
3301 // last element is the top, "upward by j" is precisely `rotate_right(j)`.
3302 // An implementation that rotated the other way agrees at `j = 0` and
3303 // disagrees at every other `j`, which is why the tests pin `j = ±1`.
3304 //
3305 // `n = 0` leaves `j mod n` undefined (ambiguity `F-A4`); treated as the
3306 // identity, consistent with `0 copy` being a legal no-op.
3307 O::Roll => {
3308 let j = stack.pop_int(name)?;
3309 let n = stack.pop_count(name)?;
3310 if n > 0 {
3311 let start = stack
3312 .len()
3313 .checked_sub(n)
3314 .ok_or(range_err(name, "count exceeds the stack depth"))?;
3315 let window = i64::try_from(n).unwrap_or(i64::MAX);
3316 // Euclidean remainder, so a negative `j` lands in [0, n).
3317 let by = i64::from(j).rem_euclid(window);
3318 let by = usize::try_from(by).unwrap_or(0);
3319 stack
3320 .values
3321 .get_mut(start..)
3322 .ok_or(range_err(name, "count exceeds the stack depth"))?
3323 .rotate_right(by);
3324 }
3325 }
3326 }
3327 Ok(())
3328}
3329
3330/// Pop-side type check for the integer-only operators (`idiv`, `mod`,
3331/// `bitshift`).
3332///
3333/// A real is **refused, not truncated**. Annex B types these operands `int`,
3334/// and `3.0 2 idiv` is a malformed program: truncating it to `3 2 idiv` would
3335/// make pdfcer compute a value where a conforming reader raises `typecheck`.
3336///
3337/// # Errors
3338///
3339/// [`FunctionError::PostScriptType`].
3340fn int_operand(op: &'static str, v: PsValue) -> Result<i32, FunctionError> {
3341 v.as_int().ok_or(type_err(
3342 op,
3343 "expected an integer; reals and booleans are not accepted here",
3344 ))
3345}
3346
3347/// `eq`/`ne` equality over Annex B's `any` operands.
3348///
3349/// Numbers compare across the integer/real divide — PLRM3's `4.0 4 eq → true`
3350/// — while a boolean is equal only to a boolean. A boolean compared with a
3351/// number is **`false`, not an error**: Annex B types these two operators
3352/// `any any`, unlike `gt`/`ge`/`lt`/`le` which it types `num num`. That
3353/// asymmetry is deliberate and is the reason these two do not share the
3354/// relational path.
3355fn ps_equal(a: PsValue, b: PsValue) -> bool {
3356 match (a, b) {
3357 (PsValue::Bool(x), PsValue::Bool(y)) => x == y,
3358 (PsValue::Bool(_), _) | (_, PsValue::Bool(_)) => false,
3359 _ => a.as_number() == b.as_number(),
3360 }
3361}
3362
3363/// `and`/`or`/`xor`: polymorphic over two booleans **or** two integers.
3364///
3365/// Annex B writes the operands and the result as `bool|int` for all three, so
3366/// the polymorphism is normative rather than inferred: `true false and` is
3367/// `false`, and `52 7 and` is `4`. A **mixed** pair is a `typecheck` — there is
3368/// no coercion in either direction.
3369///
3370/// # Errors
3371///
3372/// [`FunctionError::PostScriptType`] for a real operand or a mixed pair.
3373fn logical(
3374 op: &'static str,
3375 a: PsValue,
3376 b: PsValue,
3377 bool_op: fn(bool, bool) -> bool,
3378 int_op: fn(i32, i32) -> i32,
3379) -> Result<PsValue, FunctionError> {
3380 match (a, b) {
3381 (PsValue::Bool(x), PsValue::Bool(y)) => Ok(PsValue::Bool(bool_op(x, y))),
3382 (PsValue::Int(x), PsValue::Int(y)) => Ok(PsValue::Int(int_op(x, y))),
3383 _ => Err(type_err(
3384 op,
3385 "expected two booleans or two integers; mixed and real operands are not accepted",
3386 )),
3387 }
3388}
3389
3390// ---------------------------------------------------------------------------
3391// Tests
3392// ---------------------------------------------------------------------------
3393
3394#[cfg(test)]
3395// Tests are exempt from the crate's panic-free policy: a panicking assertion IS
3396// the test-failure mechanism (see lib.rs's crate-level lint rationale).
3397#[allow(
3398 clippy::unwrap_used,
3399 clippy::expect_used,
3400 clippy::panic,
3401 clippy::indexing_slicing
3402)]
3403mod tests {
3404 use super::*;
3405 use pdfcer_model::PdfVersion;
3406 use pdfcer_model::graph::ObjectGraph;
3407 use pdfcer_model::object::{Name, ObjId};
3408 use pdfcer_model::span::ByteSpan;
3409 use std::collections::BTreeMap;
3410
3411 const V17: PdfVersion = PdfVersion { major: 1, minor: 7 };
3412
3413 /// A hand-built object graph, so a function can be exercised without
3414 /// dragging a parsed file in. Only type 3's `/Functions` and the
3415 /// indirect-entry tests need the object map at all.
3416 #[derive(Default)]
3417 struct TestGraph {
3418 objects: BTreeMap<ObjId, Object>,
3419 trailer: Dict,
3420 }
3421
3422 impl ObjectGraph for TestGraph {
3423 fn value(&self, id: ObjId) -> Option<&Object> {
3424 self.objects.get(&id)
3425 }
3426 fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
3427 self.trailer.get(key)
3428 }
3429 }
3430
3431 fn dict(entries: &[(&[u8], Object)]) -> Dict {
3432 let mut d = Dict::new();
3433 for (k, v) in entries {
3434 d.insert(Name::from(*k), v.clone());
3435 }
3436 d
3437 }
3438
3439 /// `[a, b, c]` as a PDF array of reals.
3440 fn arr(values: &[f64]) -> Object {
3441 Object::Array(values.iter().map(|&v| Object::Real(v)).collect())
3442 }
3443
3444 /// Load a dictionary-shaped function (types 2 and 3).
3445 fn load_dict(entries: &[(&[u8], Object)]) -> Result<PdfFunction, FunctionError> {
3446 let graph = TestGraph::default();
3447 let view = DocumentView::new(&graph, b"", V17);
3448 PdfFunction::load(&view, &Object::Dict(dict(entries)))
3449 }
3450
3451 /// Load a stream-shaped function (types 0 and 4). `data` becomes both the
3452 /// view's byte source and the stream's span, unfiltered.
3453 fn load_stream(entries: &[(&[u8], Object)], data: &[u8]) -> Result<PdfFunction, FunctionError> {
3454 let graph = TestGraph::default();
3455 let view = DocumentView::new(&graph, data, V17);
3456 let stream = Stream {
3457 dict: dict(entries),
3458 data_span: ByteSpan::new(0, data.len()),
3459 };
3460 PdfFunction::load(&view, &Object::Stream(stream))
3461 }
3462
3463 /// A one-input, one-output identity ramp as a type 2 — the building block
3464 /// for the stitching tests.
3465 fn ramp(domain: &[f64], c0: &[f64], c1: &[f64]) -> Object {
3466 Object::Dict(dict(&[
3467 (b"FunctionType", Object::Integer(2)),
3468 (b"Domain", arr(domain)),
3469 (b"N", Object::Integer(1)),
3470 (b"C0", arr(c0)),
3471 (b"C1", arr(c1)),
3472 ]))
3473 }
3474
3475 #[track_caller]
3476 fn close(actual: &[f64], expected: &[f64]) {
3477 assert_eq!(
3478 actual.len(),
3479 expected.len(),
3480 "output arity: {actual:?} vs {expected:?}"
3481 );
3482 for (a, e) in actual.iter().zip(expected.iter()) {
3483 assert!(
3484 (a - e).abs() < 1e-9,
3485 "expected {expected:?}, got {actual:?}"
3486 );
3487 }
3488 }
3489
3490 // -- Table 38: the entries common to every type -------------------------
3491
3492 /// Catches a loader that accepts a non-function object (an array, a name)
3493 /// and then fails somewhere less legible — or, worse, treats a stream's
3494 /// absence of `/FunctionType` as type 0.
3495 #[test]
3496 fn non_dictionary_object_is_refused() {
3497 let graph = TestGraph::default();
3498 let view = DocumentView::new(&graph, b"", V17);
3499 let err = PdfFunction::load(&view, &Object::Integer(4)).unwrap_err();
3500 assert_eq!(err, FunctionError::NotAFunction);
3501 }
3502
3503 /// Catches a loader that defaults a missing `/FunctionType`. There is no
3504 /// default; Table 38 marks it Required.
3505 #[test]
3506 fn missing_function_type_is_refused() {
3507 let err = load_dict(&[(b"Domain", arr(&[0.0, 1.0]))]).unwrap_err();
3508 assert_eq!(err, FunctionError::MissingFunctionType);
3509 }
3510
3511 /// Catches an implementation that invents a type 1. §7.10 defines 0, 2, 3
3512 /// and 4 only, and the gap at 1 is real — see the module docs.
3513 #[test]
3514 fn function_type_one_is_unknown_like_any_other() {
3515 for t in [1i64, 5, -3] {
3516 let err = load_dict(&[
3517 (b"FunctionType", Object::Integer(t)),
3518 (b"Domain", arr(&[0.0, 1.0])),
3519 ])
3520 .unwrap_err();
3521 assert_eq!(err, FunctionError::UnknownFunctionType(t));
3522 }
3523 }
3524
3525 /// Catches a loader that treats `/Domain` as optional. Every type requires
3526 /// it; without it *m* is unknown.
3527 #[test]
3528 fn missing_domain_is_refused() {
3529 let err = load_dict(&[(b"FunctionType", Object::Integer(2))]).unwrap_err();
3530 assert_eq!(
3531 err,
3532 FunctionError::MissingEntry {
3533 key: "Domain",
3534 function_type: 2
3535 }
3536 );
3537 }
3538
3539 /// Catches a loader that silently drops a trailing odd element from a
3540 /// 2 × n array — which would shift every subsequent pair by one and produce
3541 /// a function that evaluates without complaint and is entirely wrong.
3542 #[test]
3543 fn odd_length_domain_is_refused() {
3544 let err = load_dict(&[
3545 (b"FunctionType", Object::Integer(2)),
3546 (b"Domain", arr(&[0.0, 1.0, 2.0])),
3547 ])
3548 .unwrap_err();
3549 assert!(matches!(err, FunctionError::BadEntry { key: "Domain", .. }));
3550 }
3551
3552 /// Catches clipping into an inverted interval, where the result depends on
3553 /// which comparison runs first rather than on the file.
3554 #[test]
3555 fn inverted_domain_pair_is_refused() {
3556 let err = load_dict(&[
3557 (b"FunctionType", Object::Integer(2)),
3558 (b"Domain", arr(&[1.0, 0.0])),
3559 (b"N", Object::Integer(1)),
3560 ])
3561 .unwrap_err();
3562 assert!(matches!(
3563 err,
3564 FunctionError::InvertedInterval {
3565 key: "Domain",
3566 index: 0,
3567 ..
3568 }
3569 ));
3570 }
3571
3572 /// Catches a `/Range` whose output count contradicts what `/C0` implies —
3573 /// Table 38's "shall be consistent" rule. A reader that let this through
3574 /// would hand a 3-vector to a 4-component alternate space.
3575 #[test]
3576 fn range_inconsistent_with_c0_is_refused() {
3577 let err = load_dict(&[
3578 (b"FunctionType", Object::Integer(2)),
3579 (b"Domain", arr(&[0.0, 1.0])),
3580 (b"N", Object::Integer(1)),
3581 (b"C0", arr(&[0.0, 0.0])),
3582 (b"C1", arr(&[1.0, 1.0])),
3583 (b"Range", arr(&[0.0, 1.0])),
3584 ])
3585 .unwrap_err();
3586 assert!(matches!(
3587 err,
3588 FunctionError::BadArrayLength { key: "Range", .. }
3589 ));
3590 }
3591
3592 // -- Table 38: the two clipping `shall`s --------------------------------
3593
3594 /// Catches a missing `/Domain` clip at BOTH ends in one test: a tint of
3595 /// −5 must evaluate as 0 and a tint of +5 as 1, not extrapolate.
3596 #[test]
3597 fn inputs_are_clipped_to_domain_at_both_ends() {
3598 let f = load_dict(&[
3599 (b"FunctionType", Object::Integer(2)),
3600 (b"Domain", arr(&[0.0, 1.0])),
3601 (b"N", Object::Integer(1)),
3602 (b"C0", arr(&[10.0])),
3603 (b"C1", arr(&[20.0])),
3604 ])
3605 .unwrap();
3606 close(&f.eval(&[-5.0]).unwrap(), &[10.0]);
3607 close(&f.eval(&[5.0]).unwrap(), &[20.0]);
3608 // And the interior is untouched.
3609 close(&f.eval(&[0.5]).unwrap(), &[15.0]);
3610 }
3611
3612 /// Catches a missing `/Range` clip at both ends. With `/Range [0.25 0.75]`
3613 /// the unclipped results would be 0.0 and 1.0.
3614 #[test]
3615 fn outputs_are_clipped_to_range_at_both_ends() {
3616 let f = load_dict(&[
3617 (b"FunctionType", Object::Integer(2)),
3618 (b"Domain", arr(&[0.0, 1.0])),
3619 (b"N", Object::Integer(1)),
3620 (b"C0", arr(&[0.0])),
3621 (b"C1", arr(&[1.0])),
3622 (b"Range", arr(&[0.25, 0.75])),
3623 ])
3624 .unwrap();
3625 close(&f.eval(&[0.0]).unwrap(), &[0.25]);
3626 close(&f.eval(&[1.0]).unwrap(), &[0.75]);
3627 close(&f.eval(&[0.5]).unwrap(), &[0.5]);
3628 }
3629
3630 /// Catches the inverse and more damaging error: clipping to a default
3631 /// `[0, 1]` when `/Range` is ABSENT. Table 38 — "If this entry is absent,
3632 /// no clipping shall be done." A shading function whose outputs were
3633 /// squeezed into the unit interval renders as plausible, wrong colour.
3634 #[test]
3635 fn absent_range_means_no_output_clipping() {
3636 let f = load_dict(&[
3637 (b"FunctionType", Object::Integer(2)),
3638 (b"Domain", arr(&[0.0, 1.0])),
3639 (b"N", Object::Integer(1)),
3640 (b"C0", arr(&[-3.0])),
3641 (b"C1", arr(&[7.0])),
3642 ])
3643 .unwrap();
3644 assert!(f.range().is_none());
3645 close(&f.eval(&[0.0]).unwrap(), &[-3.0]);
3646 close(&f.eval(&[1.0]).unwrap(), &[7.0]);
3647 }
3648
3649 /// Catches a `NaN` input being silently clamped to `Domain_0`.
3650 /// `f64::max` returns the non-`NaN` operand, so a naive clamp fabricates a
3651 /// boundary value that is indistinguishable from a real one downstream.
3652 #[test]
3653 fn non_finite_input_is_refused_not_clamped() {
3654 let f = load_dict(&[
3655 (b"FunctionType", Object::Integer(2)),
3656 (b"Domain", arr(&[0.0, 1.0])),
3657 (b"N", Object::Integer(1)),
3658 ])
3659 .unwrap();
3660 for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
3661 let err = f.eval(&[bad]).unwrap_err();
3662 assert!(matches!(
3663 err,
3664 FunctionError::NonFiniteInput { index: 0, .. }
3665 ));
3666 }
3667 }
3668
3669 /// Catches a caller passing the wrong tint count being papered over by
3670 /// padding or truncation instead of refused.
3671 #[test]
3672 fn input_arity_mismatch_is_refused() {
3673 let f = load_dict(&[
3674 (b"FunctionType", Object::Integer(2)),
3675 (b"Domain", arr(&[0.0, 1.0])),
3676 (b"N", Object::Integer(1)),
3677 ])
3678 .unwrap();
3679 assert_eq!(
3680 f.eval(&[]).unwrap_err(),
3681 FunctionError::InputArity {
3682 expected: 1,
3683 got: 0
3684 }
3685 );
3686 assert_eq!(
3687 f.eval(&[0.1, 0.2]).unwrap_err(),
3688 FunctionError::InputArity {
3689 expected: 1,
3690 got: 2
3691 }
3692 );
3693 }
3694
3695 // -- Type 0 (sampled), §7.10.2 ------------------------------------------
3696
3697 /// The 8-bit base case: linear interpolation between two table entries.
3698 /// Catches an evaluator that snaps to the nearest sample instead of
3699 /// interpolating ("Interpolation shall be used", §7.10.2).
3700 #[test]
3701 fn type0_interpolates_between_eight_bit_samples() {
3702 // Size 2, samples 0 and 255, Decode defaults to Range [0 1].
3703 let f = load_stream(
3704 &[
3705 (b"FunctionType", Object::Integer(0)),
3706 (b"Domain", arr(&[0.0, 1.0])),
3707 (b"Range", arr(&[0.0, 1.0])),
3708 (b"Size", Object::Array(vec![Object::Integer(2)])),
3709 (b"BitsPerSample", Object::Integer(8)),
3710 ],
3711 &[0x00, 0xFF],
3712 )
3713 .unwrap();
3714 assert_eq!(f.function_type(), FunctionType::Sampled);
3715 assert_eq!(f.inputs(), 1);
3716 assert_eq!(f.outputs(), 1);
3717 close(&f.eval(&[0.0]).unwrap(), &[0.0]);
3718 close(&f.eval(&[0.25]).unwrap(), &[0.25]);
3719 close(&f.eval(&[1.0]).unwrap(), &[1.0]);
3720 }
3721
3722 /// **4-bit samples.** Catches the commonest bit-unpacking defect: reading a
3723 /// whole byte per sample, or taking the LOW nibble first. §7.10.2 packs two
3724 /// 4-bit samples per byte, high-order bits first, so `0x05` is samples 0 and
3725 /// 5 — not 5 and 0, and not the single value 5.
3726 #[test]
3727 fn type0_four_bit_samples_pack_two_per_byte_high_nibble_first() {
3728 // Four samples 0, 5, 10, 15 -> bytes 0x05, 0xAF.
3729 let f = load_stream(
3730 &[
3731 (b"FunctionType", Object::Integer(0)),
3732 (b"Domain", arr(&[0.0, 1.0])),
3733 (b"Range", arr(&[0.0, 15.0])),
3734 (b"Size", Object::Array(vec![Object::Integer(4)])),
3735 (b"BitsPerSample", Object::Integer(4)),
3736 // Decode maps the raw 0..15 straight through, so the assertions
3737 // below are on the RAW sample values and a mis-unpack is
3738 // unmistakable.
3739 (b"Decode", arr(&[0.0, 15.0])),
3740 ],
3741 &[0x05, 0xAF],
3742 )
3743 .unwrap();
3744 close(&f.eval(&[0.0]).unwrap(), &[0.0]); // sample 0, high nibble of 0x05
3745 close(&f.eval(&[1.0 / 3.0]).unwrap(), &[5.0]); // sample 1, low nibble
3746 close(&f.eval(&[2.0 / 3.0]).unwrap(), &[10.0]); // sample 2, high of 0xAF
3747 close(&f.eval(&[1.0]).unwrap(), &[15.0]); // sample 3, low of 0xAF
3748 // And halfway between samples 1 and 2 is 7.5, proving interpolation
3749 // happens on unpacked values rather than on bytes.
3750 close(&f.eval(&[0.5]).unwrap(), &[7.5]);
3751 }
3752
3753 /// **12-bit samples.** The width where a byte-oriented reader breaks
3754 /// outright: sample 1 straddles bytes 1 and 2. Catches an unpacker that
3755 /// assumes byte alignment, and one that pads each sample to 16 bits.
3756 #[test]
3757 fn type0_twelve_bit_samples_straddle_byte_boundaries() {
3758 // Samples 0x000, 0x800, 0xFFF as a continuous bit stream:
3759 // 0000 0000 0000 | 1000 0000 0000 | 1111 1111 1111 | (4 pad bits)
3760 // = 0x00 0x08 0x00 0xFF 0xF0
3761 let f = load_stream(
3762 &[
3763 (b"FunctionType", Object::Integer(0)),
3764 (b"Domain", arr(&[0.0, 1.0])),
3765 (b"Range", arr(&[0.0, 4095.0])),
3766 (b"Size", Object::Array(vec![Object::Integer(3)])),
3767 (b"BitsPerSample", Object::Integer(12)),
3768 (b"Decode", arr(&[0.0, 4095.0])),
3769 ],
3770 &[0x00, 0x08, 0x00, 0xFF, 0xF0],
3771 )
3772 .unwrap();
3773 close(&f.eval(&[0.0]).unwrap(), &[0.0]);
3774 close(&f.eval(&[0.5]).unwrap(), &[2048.0]);
3775 close(&f.eval(&[1.0]).unwrap(), &[4095.0]);
3776 }
3777
3778 /// 16-bit samples, where the fast byte-aligned path runs. Catches a
3779 /// little-endian read (§7.10.2 is high-order-bit-first, so `0x12 0x34` is
3780 /// 0x1234, not 0x3412).
3781 #[test]
3782 fn type0_sixteen_bit_samples_are_big_endian() {
3783 let f = load_stream(
3784 &[
3785 (b"FunctionType", Object::Integer(0)),
3786 (b"Domain", arr(&[0.0, 1.0])),
3787 (b"Range", arr(&[0.0, 65535.0])),
3788 (b"Size", Object::Array(vec![Object::Integer(2)])),
3789 (b"BitsPerSample", Object::Integer(16)),
3790 (b"Decode", arr(&[0.0, 65535.0])),
3791 ],
3792 &[0x12, 0x34, 0xFF, 0xFF],
3793 )
3794 .unwrap();
3795 close(&f.eval(&[0.0]).unwrap(), &[f64::from(0x1234u32)]);
3796 }
3797
3798 /// **Multi-input interpolation.** Catches two distinct defects at once:
3799 /// nearest-neighbour instead of bilinear blending, and — via the asymmetric
3800 /// corner values — a transposed sample order. §7.10.2 stores the FIRST
3801 /// dimension fastest, which is column-major and the opposite of C's default.
3802 #[test]
3803 fn type0_two_input_bilinear_with_first_dimension_fastest() {
3804 // f(0,0)=0 f(1,0)=51 f(0,1)=102 f(1,1)=204, stored in the spec's
3805 // order: f(0,0), f(1,0), f(0,1), f(1,1).
3806 let f = load_stream(
3807 &[
3808 (b"FunctionType", Object::Integer(0)),
3809 (b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
3810 (b"Range", arr(&[0.0, 1.0])),
3811 (
3812 b"Size",
3813 Object::Array(vec![Object::Integer(2), Object::Integer(2)]),
3814 ),
3815 (b"BitsPerSample", Object::Integer(8)),
3816 ],
3817 &[0, 51, 102, 204],
3818 )
3819 .unwrap();
3820 assert_eq!(f.inputs(), 2);
3821 // The two off-diagonal corners are what a transposition swaps.
3822 close(&f.eval(&[1.0, 0.0]).unwrap(), &[51.0 / 255.0]);
3823 close(&f.eval(&[0.0, 1.0]).unwrap(), &[102.0 / 255.0]);
3824 close(&f.eval(&[1.0, 1.0]).unwrap(), &[204.0 / 255.0]);
3825 // The centre is the mean of all four corners only if all four are
3826 // blended — a nearest-neighbour evaluator returns one of them.
3827 close(
3828 &f.eval(&[0.5, 0.5]).unwrap(),
3829 &[(0.0 + 51.0 + 102.0 + 204.0) / 4.0 / 255.0],
3830 );
3831 }
3832
3833 /// Multi-OUTPUT layout: §7.10.2 stores one table entry's *n* samples
3834 /// adjacently, "in the same order as Range". Catches an evaluator that
3835 /// strides by table entry per output plane instead.
3836 #[test]
3837 fn type0_multi_output_samples_are_adjacent_per_entry() {
3838 // Two entries, three outputs each: (10,20,30) then (40,50,60).
3839 let f = load_stream(
3840 &[
3841 (b"FunctionType", Object::Integer(0)),
3842 (b"Domain", arr(&[0.0, 1.0])),
3843 (b"Range", arr(&[0.0, 255.0, 0.0, 255.0, 0.0, 255.0])),
3844 (b"Size", Object::Array(vec![Object::Integer(2)])),
3845 (b"BitsPerSample", Object::Integer(8)),
3846 (b"Decode", arr(&[0.0, 255.0, 0.0, 255.0, 0.0, 255.0])),
3847 ],
3848 &[10, 20, 30, 40, 50, 60],
3849 )
3850 .unwrap();
3851 assert_eq!(f.outputs(), 3);
3852 close(&f.eval(&[0.0]).unwrap(), &[10.0, 20.0, 30.0]);
3853 close(&f.eval(&[1.0]).unwrap(), &[40.0, 50.0, 60.0]);
3854 }
3855
3856 /// Catches an `/Encode` default of `[0, 1]` instead of `[0, Size − 1]`,
3857 /// which would confine every lookup to the first two samples of the table.
3858 #[test]
3859 fn type0_encode_defaults_to_zero_through_size_minus_one() {
3860 let f = load_stream(
3861 &[
3862 (b"FunctionType", Object::Integer(0)),
3863 (b"Domain", arr(&[0.0, 1.0])),
3864 (b"Range", arr(&[0.0, 3.0])),
3865 (b"Size", Object::Array(vec![Object::Integer(4)])),
3866 (b"BitsPerSample", Object::Integer(8)),
3867 (b"Decode", arr(&[0.0, 255.0])),
3868 ],
3869 &[0, 1, 2, 3],
3870 )
3871 .unwrap();
3872 // x = 1.0 must reach the LAST sample, not the second.
3873 close(&f.eval(&[1.0]).unwrap(), &[3.0]);
3874 }
3875
3876 /// An explicit `/Encode` that reverses the table. Catches an evaluator that
3877 /// ignores `/Encode` entirely (which the default case above cannot detect,
3878 /// because the default is what an ignoring evaluator accidentally does for
3879 /// a `[0, 1]` domain).
3880 #[test]
3881 fn type0_explicit_encode_can_reverse_the_table() {
3882 let f = load_stream(
3883 &[
3884 (b"FunctionType", Object::Integer(0)),
3885 (b"Domain", arr(&[0.0, 1.0])),
3886 (b"Range", arr(&[0.0, 255.0])),
3887 (b"Size", Object::Array(vec![Object::Integer(4)])),
3888 (b"BitsPerSample", Object::Integer(8)),
3889 (b"Encode", arr(&[3.0, 0.0])),
3890 (b"Decode", arr(&[0.0, 255.0])),
3891 ],
3892 &[0, 1, 2, 3],
3893 )
3894 .unwrap();
3895 close(&f.eval(&[0.0]).unwrap(), &[3.0]);
3896 close(&f.eval(&[1.0]).unwrap(), &[0.0]);
3897 }
3898
3899 /// Catches a `/Decode` default of `[0, 1]` rather than "same as `/Range`"
3900 /// (Table 39). With `/Range [0 100]` and no `/Decode`, a full-scale sample
3901 /// must decode to 100.
3902 #[test]
3903 fn type0_decode_defaults_to_range() {
3904 let f = load_stream(
3905 &[
3906 (b"FunctionType", Object::Integer(0)),
3907 (b"Domain", arr(&[0.0, 1.0])),
3908 (b"Range", arr(&[0.0, 100.0])),
3909 (b"Size", Object::Array(vec![Object::Integer(2)])),
3910 (b"BitsPerSample", Object::Integer(8)),
3911 ],
3912 &[0x00, 0xFF],
3913 )
3914 .unwrap();
3915 close(&f.eval(&[1.0]).unwrap(), &[100.0]);
3916 }
3917
3918 /// §7.10.2: "The `Size` value for an input dimension can be 1, in which case
3919 /// all input values in that dimension shall be mapped to the single allowed
3920 /// value." Catches a division by `Size − 1 = 0` in the encode step, which
3921 /// yields `NaN` or an out-of-range index.
3922 #[test]
3923 fn type0_size_one_axis_maps_every_input_to_the_single_sample() {
3924 let f = load_stream(
3925 &[
3926 (b"FunctionType", Object::Integer(0)),
3927 (b"Domain", arr(&[0.0, 1.0])),
3928 (b"Range", arr(&[0.0, 255.0])),
3929 (b"Size", Object::Array(vec![Object::Integer(1)])),
3930 (b"BitsPerSample", Object::Integer(8)),
3931 (b"Decode", arr(&[0.0, 255.0])),
3932 ],
3933 &[77],
3934 )
3935 .unwrap();
3936 for x in [0.0, 0.5, 1.0] {
3937 close(&f.eval(&[x]).unwrap(), &[77.0]);
3938 }
3939 }
3940
3941 /// §7.10.2 / §7.3.8.2: "The stream data shall be long enough to contain the
3942 /// entire sample array." Catches an evaluator that reads past the end and
3943 /// treats missing bytes as zero — which paints black where the file is
3944 /// truncated.
3945 #[test]
3946 fn type0_short_sample_stream_is_refused() {
3947 let err = load_stream(
3948 &[
3949 (b"FunctionType", Object::Integer(0)),
3950 (b"Domain", arr(&[0.0, 1.0])),
3951 (b"Range", arr(&[0.0, 1.0])),
3952 (b"Size", Object::Array(vec![Object::Integer(4)])),
3953 (b"BitsPerSample", Object::Integer(8)),
3954 ],
3955 &[0x00, 0xFF], // 2 bytes where 4 are required
3956 )
3957 .unwrap_err();
3958 assert_eq!(err, FunctionError::SampleDataTooShort { need: 4, have: 2 });
3959 }
3960
3961 /// Table 39's `/BitsPerSample` set is closed. Catches an implementation that
3962 /// accepts any width its bit reader happens to handle.
3963 #[test]
3964 fn type0_invalid_bits_per_sample_is_refused() {
3965 for bad in [0i64, 3, 5, 6, 10, 64] {
3966 let err = load_stream(
3967 &[
3968 (b"FunctionType", Object::Integer(0)),
3969 (b"Domain", arr(&[0.0, 1.0])),
3970 (b"Range", arr(&[0.0, 1.0])),
3971 (b"Size", Object::Array(vec![Object::Integer(2)])),
3972 (b"BitsPerSample", Object::Integer(bad)),
3973 ],
3974 &[0; 64],
3975 )
3976 .unwrap_err();
3977 assert_eq!(err, FunctionError::BadBitsPerSample(bad));
3978 }
3979 // And every legal width loads.
3980 for good in VALID_BITS_PER_SAMPLE {
3981 load_stream(
3982 &[
3983 (b"FunctionType", Object::Integer(0)),
3984 (b"Domain", arr(&[0.0, 1.0])),
3985 (b"Range", arr(&[0.0, 1.0])),
3986 (b"Size", Object::Array(vec![Object::Integer(2)])),
3987 (b"BitsPerSample", Object::Integer(i64::from(good))),
3988 ],
3989 &[0; 64],
3990 )
3991 .unwrap();
3992 }
3993 }
3994
3995 /// `/Range` is Required for type 0 — it is the only source of *n*. Catches a
3996 /// loader that infers *n* as 1 when it is absent.
3997 #[test]
3998 fn type0_missing_range_is_refused() {
3999 let err = load_stream(
4000 &[
4001 (b"FunctionType", Object::Integer(0)),
4002 (b"Domain", arr(&[0.0, 1.0])),
4003 (b"Size", Object::Array(vec![Object::Integer(2)])),
4004 (b"BitsPerSample", Object::Integer(8)),
4005 ],
4006 &[0x00, 0xFF],
4007 )
4008 .unwrap_err();
4009 assert_eq!(
4010 err,
4011 FunctionError::MissingEntry {
4012 key: "Range",
4013 function_type: 0
4014 }
4015 );
4016 }
4017
4018 /// A type 0 written as a bare dictionary has nowhere to keep its samples.
4019 /// Catches a loader that accepts it and then evaluates against an empty
4020 /// table.
4021 #[test]
4022 fn type0_as_a_bare_dictionary_is_refused() {
4023 let err = load_dict(&[
4024 (b"FunctionType", Object::Integer(0)),
4025 (b"Domain", arr(&[0.0, 1.0])),
4026 (b"Range", arr(&[0.0, 1.0])),
4027 (b"Size", Object::Array(vec![Object::Integer(2)])),
4028 (b"BitsPerSample", Object::Integer(8)),
4029 ])
4030 .unwrap_err();
4031 assert_eq!(err, FunctionError::NotAStream { function_type: 0 });
4032 }
4033
4034 /// Table 39: "m positive integers". Catches a zero or fractional `/Size`
4035 /// being rounded into something workable.
4036 #[test]
4037 fn type0_non_positive_size_is_refused() {
4038 for bad in [0.0, -2.0, 2.5] {
4039 let err = load_stream(
4040 &[
4041 (b"FunctionType", Object::Integer(0)),
4042 (b"Domain", arr(&[0.0, 1.0])),
4043 (b"Range", arr(&[0.0, 1.0])),
4044 (b"Size", arr(&[bad])),
4045 (b"BitsPerSample", Object::Integer(8)),
4046 ],
4047 &[0; 16],
4048 )
4049 .unwrap_err();
4050 assert!(matches!(err, FunctionError::BadEntry { key: "Size", .. }));
4051 }
4052 }
4053
4054 /// Catches a `/Size` whose element count disagrees with `/Domain`'s *m* —
4055 /// Table 38's consistency rule, in the place it bites hardest (the stride
4056 /// computation would silently use the wrong dimensionality).
4057 #[test]
4058 fn type0_size_length_must_match_domain() {
4059 let err = load_stream(
4060 &[
4061 (b"FunctionType", Object::Integer(0)),
4062 (b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
4063 (b"Range", arr(&[0.0, 1.0])),
4064 (b"Size", Object::Array(vec![Object::Integer(2)])),
4065 (b"BitsPerSample", Object::Integer(8)),
4066 ],
4067 &[0; 16],
4068 )
4069 .unwrap_err();
4070 assert_eq!(
4071 err,
4072 FunctionError::BadArrayLength {
4073 key: "Size",
4074 expected: 2,
4075 got: 1
4076 }
4077 );
4078 }
4079
4080 /// §7.10.2 permits an implementation limit on dimensionality; this pins
4081 /// pdfcer's. Catches the limit silently not being enforced, which would let a
4082 /// crafted `/Size` of 30 dimensions ask for 2^30 corner reads per
4083 /// evaluation.
4084 #[test]
4085 fn type0_excess_input_dimensions_are_refused() {
4086 let m = MAX_SAMPLED_INPUTS + 1;
4087 let domain: Vec<f64> = (0..m).flat_map(|_| [0.0, 1.0]).collect();
4088 let size = Object::Array((0..m).map(|_| Object::Integer(2)).collect());
4089 let err = load_stream(
4090 &[
4091 (b"FunctionType", Object::Integer(0)),
4092 (b"Domain", arr(&domain)),
4093 (b"Range", arr(&[0.0, 1.0])),
4094 (b"Size", size),
4095 (b"BitsPerSample", Object::Integer(8)),
4096 ],
4097 &[0; 4096],
4098 )
4099 .unwrap_err();
4100 assert_eq!(
4101 err,
4102 FunctionError::TooManyInputs {
4103 got: m,
4104 limit: MAX_SAMPLED_INPUTS
4105 }
4106 );
4107 }
4108
4109 /// `/Order 3` on a table big enough for a cubic spline is a real fidelity
4110 /// downgrade and must be disclosed (project rule 4). Catches the disclosure
4111 /// being dropped, which would let the operator assume a fidelity pdfcer does
4112 /// not provide.
4113 #[test]
4114 fn type0_order_three_on_a_large_table_is_disclosed_as_downgraded() {
4115 let f = load_stream(
4116 &[
4117 (b"FunctionType", Object::Integer(0)),
4118 (b"Domain", arr(&[0.0, 1.0])),
4119 (b"Range", arr(&[0.0, 1.0])),
4120 (b"Size", Object::Array(vec![Object::Integer(4)])),
4121 (b"BitsPerSample", Object::Integer(8)),
4122 (b"Order", Object::Integer(3)),
4123 ],
4124 &[0, 1, 2, 3],
4125 )
4126 .unwrap();
4127 assert!(f.cubic_downgraded());
4128 }
4129
4130 /// The converse: §7.10.2 says `/Order 3` "shall be ignored" when `Size` is
4131 /// below 4, so ignoring it there is conformance, not a downgrade. Catches a
4132 /// disclosure that cries wolf on every small table.
4133 #[test]
4134 fn type0_order_three_below_size_four_is_not_a_downgrade() {
4135 let f = load_stream(
4136 &[
4137 (b"FunctionType", Object::Integer(0)),
4138 (b"Domain", arr(&[0.0, 1.0])),
4139 (b"Range", arr(&[0.0, 1.0])),
4140 (b"Size", Object::Array(vec![Object::Integer(3)])),
4141 (b"BitsPerSample", Object::Integer(8)),
4142 (b"Order", Object::Integer(3)),
4143 ],
4144 &[0, 1, 2],
4145 )
4146 .unwrap();
4147 assert!(!f.cubic_downgraded());
4148 }
4149
4150 /// Table 39 allows `/Order` 1 and 3 only. Catches a loader that accepts an
4151 /// arbitrary integer and quietly treats it as linear.
4152 #[test]
4153 fn type0_unknown_order_is_refused() {
4154 let err = load_stream(
4155 &[
4156 (b"FunctionType", Object::Integer(0)),
4157 (b"Domain", arr(&[0.0, 1.0])),
4158 (b"Range", arr(&[0.0, 1.0])),
4159 (b"Size", Object::Array(vec![Object::Integer(4)])),
4160 (b"BitsPerSample", Object::Integer(8)),
4161 (b"Order", Object::Integer(2)),
4162 ],
4163 &[0, 1, 2, 3],
4164 )
4165 .unwrap_err();
4166 assert!(matches!(err, FunctionError::BadEntry { key: "Order", .. }));
4167 }
4168
4169 /// Direct coverage of the bit reader at every legal width, independent of
4170 /// the surrounding function machinery. Catches an off-by-one in the shift
4171 /// arithmetic that a whole-function test could mask through interpolation.
4172 #[test]
4173 fn read_bits_is_msb_first_at_every_width() {
4174 let data = [0b1010_0110u8, 0b1100_0011, 0xFF, 0x01];
4175 assert_eq!(read_bits(&data, 0, 1), Some(1));
4176 assert_eq!(read_bits(&data, 1, 1), Some(0));
4177 assert_eq!(read_bits(&data, 0, 2), Some(0b10));
4178 assert_eq!(read_bits(&data, 2, 2), Some(0b10));
4179 assert_eq!(read_bits(&data, 0, 4), Some(0b1010));
4180 assert_eq!(read_bits(&data, 4, 4), Some(0b0110));
4181 assert_eq!(read_bits(&data, 0, 8), Some(0b1010_0110));
4182 // A 12-bit read spanning bytes 0 and 1.
4183 assert_eq!(read_bits(&data, 0, 12), Some(0b1010_0110_1100));
4184 assert_eq!(read_bits(&data, 12, 12), Some(0b0011_1111_1111));
4185 assert_eq!(read_bits(&data, 0, 16), Some(0b1010_0110_1100_0011));
4186 assert_eq!(read_bits(&data, 0, 24), Some(0x00A6_C3FF));
4187 assert_eq!(read_bits(&data, 0, 32), Some(0xA6C3_FF01));
4188 // Past the end is None, never a zero-filled value.
4189 assert_eq!(read_bits(&data, 32, 1), None);
4190 assert_eq!(read_bits(&data, 24, 16), None);
4191 }
4192
4193 // -- Type 2 (exponential interpolation), §7.10.3 ------------------------
4194
4195 /// The dominant real-world tint transform: `/N 1`, a straight ramp from
4196 /// paper to full-strength ink. Catches an evaluator that applies the
4197 /// exponent to the whole expression rather than to `x`.
4198 #[test]
4199 fn type2_with_n_one_is_a_linear_ramp() {
4200 let f = load_dict(&[
4201 (b"FunctionType", Object::Integer(2)),
4202 (b"Domain", arr(&[0.0, 1.0])),
4203 (b"N", Object::Integer(1)),
4204 (b"C0", arr(&[0.0, 0.0, 0.0, 0.0])),
4205 (b"C1", arr(&[0.0, 1.0, 0.6, 0.1])),
4206 ])
4207 .unwrap();
4208 assert_eq!(f.function_type(), FunctionType::Exponential);
4209 assert_eq!(f.outputs(), 4);
4210 close(&f.eval(&[0.0]).unwrap(), &[0.0, 0.0, 0.0, 0.0]);
4211 close(&f.eval(&[0.5]).unwrap(), &[0.0, 0.5, 0.3, 0.05]);
4212 close(&f.eval(&[1.0]).unwrap(), &[0.0, 1.0, 0.6, 0.1]);
4213 }
4214
4215 /// A non-unit exponent. Catches `y = (C0 + x(C1 − C0))^N` — the plausible
4216 /// misreading of the formula, which agrees with the correct one at N = 1 and
4217 /// so slips past a linear-only test.
4218 #[test]
4219 fn type2_applies_the_exponent_to_x_not_to_the_result() {
4220 let f = load_dict(&[
4221 (b"FunctionType", Object::Integer(2)),
4222 (b"Domain", arr(&[0.0, 1.0])),
4223 (b"N", Object::Integer(2)),
4224 (b"C0", arr(&[1.0])),
4225 (b"C1", arr(&[5.0])),
4226 ])
4227 .unwrap();
4228 // 1 + 0.5^2 * (5 − 1) = 2.0. The misreading gives (1 + 0.5*4)^2 = 9.
4229 close(&f.eval(&[0.5]).unwrap(), &[2.0]);
4230 }
4231
4232 /// Table 40's defaults are the SCALARS `[0.0]` and `[1.0]`, so a type 2 with
4233 /// neither entry is a 1-output identity-ish function. Catches a loader that
4234 /// invents an *n*-wide default from `/Range` or from a caller's expectation.
4235 #[test]
4236 fn type2_c0_and_c1_default_to_one_element_arrays() {
4237 let f = load_dict(&[
4238 (b"FunctionType", Object::Integer(2)),
4239 (b"Domain", arr(&[0.0, 1.0])),
4240 (b"N", Object::Integer(1)),
4241 ])
4242 .unwrap();
4243 assert_eq!(f.outputs(), 1);
4244 close(&f.eval(&[0.3]).unwrap(), &[0.3]);
4245 }
4246
4247 /// §7.10.3 restricts type 2 to one input. Catches a loader that accepts a
4248 /// 2-input `/Domain` and then reads only the first value.
4249 #[test]
4250 fn type2_multi_input_domain_is_refused() {
4251 let err = load_dict(&[
4252 (b"FunctionType", Object::Integer(2)),
4253 (b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
4254 (b"N", Object::Integer(1)),
4255 ])
4256 .unwrap_err();
4257 assert_eq!(
4258 err,
4259 FunctionError::NotOneInput {
4260 function_type: 2,
4261 got: 2
4262 }
4263 );
4264 }
4265
4266 /// §7.10.3: "if N is negative, no value of x shall be zero". Catches the
4267 /// resulting infinity being produced and then clamped into a `/Range`
4268 /// boundary, which looks like a legitimate saturated colour.
4269 #[test]
4270 fn type2_negative_exponent_with_zero_in_domain_is_refused() {
4271 let err = load_dict(&[
4272 (b"FunctionType", Object::Integer(2)),
4273 (b"Domain", arr(&[0.0, 1.0])),
4274 (b"N", Object::Real(-1.0)),
4275 ])
4276 .unwrap_err();
4277 assert!(matches!(
4278 err,
4279 FunctionError::DomainIncompatibleWithExponent { .. }
4280 ));
4281 // The same exponent over a domain that excludes zero is fine.
4282 let f = load_dict(&[
4283 (b"FunctionType", Object::Integer(2)),
4284 (b"Domain", arr(&[1.0, 2.0])),
4285 (b"N", Object::Real(-1.0)),
4286 (b"C0", arr(&[0.0])),
4287 (b"C1", arr(&[1.0])),
4288 ])
4289 .unwrap();
4290 close(&f.eval(&[2.0]).unwrap(), &[0.5]);
4291 }
4292
4293 /// §7.10.3: "if N is not an integer, all values of x shall be
4294 /// non-negative". Catches a `NaN` from a negative base under a fractional
4295 /// exponent.
4296 #[test]
4297 fn type2_fractional_exponent_with_negative_domain_is_refused() {
4298 let err = load_dict(&[
4299 (b"FunctionType", Object::Integer(2)),
4300 (b"Domain", arr(&[-1.0, 1.0])),
4301 (b"N", Object::Real(0.5)),
4302 ])
4303 .unwrap_err();
4304 assert!(matches!(
4305 err,
4306 FunctionError::DomainIncompatibleWithExponent { .. }
4307 ));
4308 }
4309
4310 /// Catches `/C0` and `/C1` of different lengths being zipped to the shorter
4311 /// one, which silently drops output components.
4312 #[test]
4313 fn type2_mismatched_c0_c1_lengths_are_refused() {
4314 let err = load_dict(&[
4315 (b"FunctionType", Object::Integer(2)),
4316 (b"Domain", arr(&[0.0, 1.0])),
4317 (b"N", Object::Integer(1)),
4318 (b"C0", arr(&[0.0, 0.0, 0.0])),
4319 (b"C1", arr(&[1.0, 1.0])),
4320 ])
4321 .unwrap_err();
4322 assert_eq!(
4323 err,
4324 FunctionError::BadArrayLength {
4325 key: "C1",
4326 expected: 3,
4327 got: 2
4328 }
4329 );
4330 }
4331
4332 /// `/N` is Required (Table 40). Catches a default of 1 being invented.
4333 #[test]
4334 fn type2_missing_exponent_is_refused() {
4335 let err = load_dict(&[
4336 (b"FunctionType", Object::Integer(2)),
4337 (b"Domain", arr(&[0.0, 1.0])),
4338 ])
4339 .unwrap_err();
4340 assert_eq!(
4341 err,
4342 FunctionError::MissingEntry {
4343 key: "N",
4344 function_type: 2
4345 }
4346 );
4347 }
4348
4349 // -- Type 3 (stitching), §7.10.4 ----------------------------------------
4350
4351 /// Catches a subdomain-selection off-by-one and a missing `/Encode`
4352 /// rescale in one pass: two ramps stitched at 0.5, each encoded onto
4353 /// `[0, 1]`, so the composite runs 0→10 then 100→200.
4354 #[test]
4355 fn type3_selects_and_rescales_each_subdomain() {
4356 let f = load_dict(&[
4357 (b"FunctionType", Object::Integer(3)),
4358 (b"Domain", arr(&[0.0, 1.0])),
4359 (
4360 b"Functions",
4361 Object::Array(vec![
4362 ramp(&[0.0, 1.0], &[0.0], &[10.0]),
4363 ramp(&[0.0, 1.0], &[100.0], &[200.0]),
4364 ]),
4365 ),
4366 (b"Bounds", arr(&[0.5])),
4367 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
4368 ])
4369 .unwrap();
4370 assert_eq!(f.function_type(), FunctionType::Stitching);
4371 assert_eq!(f.outputs(), 1);
4372 close(&f.eval(&[0.0]).unwrap(), &[0.0]);
4373 close(&f.eval(&[0.25]).unwrap(), &[5.0]); // halfway through [0, 0.5)
4374 close(&f.eval(&[0.75]).unwrap(), &[150.0]); // halfway through [0.5, 1]
4375 close(&f.eval(&[1.0]).unwrap(), &[200.0]);
4376 }
4377
4378 /// **Exactly on a bound.** §7.10.4's intervals are closed on the left and
4379 /// open on the right, so `x == Bounds_0` belongs to the LATER
4380 /// sub-function. Catches the off-by-one that puts it in the earlier one —
4381 /// invisible everywhere except at the seam, which is exactly where a
4382 /// gradient shows a visible step.
4383 #[test]
4384 fn type3_exactly_on_a_bound_selects_the_later_subfunction() {
4385 let f = load_dict(&[
4386 (b"FunctionType", Object::Integer(3)),
4387 (b"Domain", arr(&[0.0, 1.0])),
4388 (
4389 b"Functions",
4390 Object::Array(vec![
4391 // Two constants, so only the SELECTION is under test.
4392 ramp(&[0.0, 1.0], &[10.0], &[10.0]),
4393 ramp(&[0.0, 1.0], &[20.0], &[20.0]),
4394 ]),
4395 ),
4396 (b"Bounds", arr(&[0.5])),
4397 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
4398 ])
4399 .unwrap();
4400 close(&f.eval(&[0.499_999]).unwrap(), &[10.0]);
4401 close(&f.eval(&[0.5]).unwrap(), &[20.0]); // the bound itself
4402 close(&f.eval(&[0.500_001]).unwrap(), &[20.0]);
4403 // And the last interval is closed on the RIGHT as well.
4404 close(&f.eval(&[1.0]).unwrap(), &[20.0]);
4405 }
4406
4407 /// The three-interval case, so the middle sub-function's
4408 /// `Bounds_(i−1) ≤ x < Bounds_i` lookup is exercised rather than only the
4409 /// first-and-last special cases.
4410 #[test]
4411 fn type3_middle_interval_uses_both_neighbouring_bounds() {
4412 let f = load_dict(&[
4413 (b"FunctionType", Object::Integer(3)),
4414 (b"Domain", arr(&[0.0, 3.0])),
4415 (
4416 b"Functions",
4417 Object::Array(vec![
4418 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4419 ramp(&[0.0, 1.0], &[10.0], &[11.0]),
4420 ramp(&[0.0, 1.0], &[20.0], &[21.0]),
4421 ]),
4422 ),
4423 (b"Bounds", arr(&[1.0, 2.0])),
4424 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0, 0.0, 1.0])),
4425 ])
4426 .unwrap();
4427 close(&f.eval(&[0.5]).unwrap(), &[0.5]);
4428 close(&f.eval(&[1.5]).unwrap(), &[10.5]);
4429 close(&f.eval(&[2.5]).unwrap(), &[20.5]);
4430 }
4431
4432 /// §7.10.4's `k = 1` domain-reversal idiom: one sub-function, an empty
4433 /// `/Bounds`, and `/Encode [1 0]` gives `g(x) = f(1 − x)`. Catches a loader
4434 /// that rejects an empty `/Bounds`, and an evaluator that ignores `/Encode`
4435 /// when there is only one interval.
4436 #[test]
4437 fn type3_single_subfunction_with_reversed_encode_inverts_the_domain() {
4438 let f = load_dict(&[
4439 (b"FunctionType", Object::Integer(3)),
4440 (b"Domain", arr(&[0.0, 1.0])),
4441 (
4442 b"Functions",
4443 Object::Array(vec![ramp(&[0.0, 1.0], &[0.0], &[1.0])]),
4444 ),
4445 (b"Bounds", Object::Array(vec![])),
4446 (b"Encode", arr(&[1.0, 0.0])),
4447 ])
4448 .unwrap();
4449 close(&f.eval(&[0.25]).unwrap(), &[0.75]);
4450 close(&f.eval(&[0.0]).unwrap(), &[1.0]);
4451 close(&f.eval(&[1.0]).unwrap(), &[0.0]);
4452 }
4453
4454 /// §7.10.4: "If the last bound, `Bounds_k−2`, is equal to `Domain_1`, then
4455 /// x′ shall be defined to be `Encode_2i`." That collapses the last
4456 /// interval, and a naive `Interpolate` divides by zero there. Catches the
4457 /// resulting `NaN`.
4458 #[test]
4459 fn type3_last_bound_equal_to_domain_high_uses_encode_low() {
4460 let f = load_dict(&[
4461 (b"FunctionType", Object::Integer(3)),
4462 (b"Domain", arr(&[0.0, 1.0])),
4463 (
4464 b"Functions",
4465 Object::Array(vec![
4466 ramp(&[0.0, 10.0], &[0.0], &[1.0]),
4467 // y = C0 + x·(C1 − C0) = x over [0, 10], i.e. the identity,
4468 // so the value asserted below IS the x' the spec's rule
4469 // produces rather than something derived from it.
4470 ramp(&[0.0, 10.0], &[0.0], &[1.0]),
4471 ]),
4472 ),
4473 (b"Bounds", arr(&[1.0])), // == Domain_1
4474 (b"Encode", arr(&[0.0, 1.0, 5.0, 9.0])),
4475 ])
4476 .unwrap();
4477 // x = 1.0 selects sub-function 1, whose interval is [1.0, 1.0]; the
4478 // spec pins x' at Encode_2 = 5.
4479 close(&f.eval(&[1.0]).unwrap(), &[5.0]);
4480 }
4481
4482 /// §7.10.4: "`Bounds` elements shall be in order of increasing value."
4483 /// Catches a decreasing pair producing an interval that can never be
4484 /// selected, silently disabling a sub-function.
4485 #[test]
4486 fn type3_decreasing_bounds_are_refused() {
4487 let err = load_dict(&[
4488 (b"FunctionType", Object::Integer(3)),
4489 (b"Domain", arr(&[0.0, 1.0])),
4490 (
4491 b"Functions",
4492 Object::Array(vec![
4493 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4494 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4495 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4496 ]),
4497 ),
4498 (b"Bounds", arr(&[0.7, 0.3])),
4499 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0, 0.0, 1.0])),
4500 ])
4501 .unwrap_err();
4502 assert!(matches!(err, FunctionError::BadBounds { .. }));
4503 }
4504
4505 /// §7.10.4: "each value shall be within the domain defined by `Domain`".
4506 /// Catches a bound outside the domain, which makes one sub-function
4507 /// unreachable for every legal input.
4508 #[test]
4509 fn type3_bound_outside_domain_is_refused() {
4510 let err = load_dict(&[
4511 (b"FunctionType", Object::Integer(3)),
4512 (b"Domain", arr(&[0.0, 1.0])),
4513 (
4514 b"Functions",
4515 Object::Array(vec![
4516 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4517 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4518 ]),
4519 ),
4520 (b"Bounds", arr(&[1.5])),
4521 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
4522 ])
4523 .unwrap_err();
4524 assert!(matches!(err, FunctionError::BadBounds { .. }));
4525 }
4526
4527 /// §7.10.4: `/Bounds` holds exactly *k* − 1 numbers. Catches a length
4528 /// mismatch being absorbed by a `zip`, which would leave the last
4529 /// sub-function permanently selected or permanently dead.
4530 #[test]
4531 fn type3_bounds_length_must_be_k_minus_one() {
4532 let err = load_dict(&[
4533 (b"FunctionType", Object::Integer(3)),
4534 (b"Domain", arr(&[0.0, 1.0])),
4535 (
4536 b"Functions",
4537 Object::Array(vec![
4538 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4539 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4540 ]),
4541 ),
4542 (b"Bounds", arr(&[0.3, 0.6])), // 2 bounds for 2 functions
4543 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
4544 ])
4545 .unwrap_err();
4546 assert_eq!(
4547 err,
4548 FunctionError::BadArrayLength {
4549 key: "Bounds",
4550 expected: 1,
4551 got: 2
4552 }
4553 );
4554 }
4555
4556 /// §7.10.4: "The output dimensionality of all functions shall be the same."
4557 /// Catches a mismatch reaching evaluation, where the output vector's length
4558 /// would then depend on which subdomain the input fell in.
4559 #[test]
4560 fn type3_subfunctions_with_different_output_counts_are_refused() {
4561 let err = load_dict(&[
4562 (b"FunctionType", Object::Integer(3)),
4563 (b"Domain", arr(&[0.0, 1.0])),
4564 (
4565 b"Functions",
4566 Object::Array(vec![
4567 ramp(&[0.0, 1.0], &[0.0, 0.0], &[1.0, 1.0]),
4568 ramp(&[0.0, 1.0], &[0.0], &[1.0]),
4569 ]),
4570 ),
4571 (b"Bounds", arr(&[0.5])),
4572 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
4573 ])
4574 .unwrap_err();
4575 assert_eq!(
4576 err,
4577 FunctionError::SubFunctionArity {
4578 index: 1,
4579 expected: 2,
4580 got: 1
4581 }
4582 );
4583 }
4584
4585 /// Catches an empty `/Functions` loading successfully and then panicking or
4586 /// returning an empty output vector at evaluation.
4587 #[test]
4588 fn type3_empty_functions_array_is_refused() {
4589 let err = load_dict(&[
4590 (b"FunctionType", Object::Integer(3)),
4591 (b"Domain", arr(&[0.0, 1.0])),
4592 (b"Functions", Object::Array(vec![])),
4593 (b"Bounds", Object::Array(vec![])),
4594 (b"Encode", Object::Array(vec![])),
4595 ])
4596 .unwrap_err();
4597 assert_eq!(err, FunctionError::NoSubFunctions);
4598 }
4599
4600 /// §7.10.4: the sub-functions are "k 1-input functions". Catches a 2-input
4601 /// sub-function being fed a 1-element slice at evaluation time.
4602 #[test]
4603 fn type3_multi_input_subfunction_is_refused() {
4604 let two_in = Object::Dict(dict(&[
4605 (b"FunctionType", Object::Integer(4)),
4606 (b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
4607 (b"Range", arr(&[0.0, 1.0])),
4608 ]));
4609 let err = load_dict(&[
4610 (b"FunctionType", Object::Integer(3)),
4611 (b"Domain", arr(&[0.0, 1.0])),
4612 (b"Functions", Object::Array(vec![two_in])),
4613 (b"Bounds", Object::Array(vec![])),
4614 (b"Encode", arr(&[0.0, 1.0])),
4615 ])
4616 .unwrap_err();
4617 // A type 4 written as a dictionary is refused before its arity is
4618 // reached, which is itself the right answer here.
4619 assert_eq!(err, FunctionError::NotAStream { function_type: 4 });
4620 }
4621
4622 /// A `/Functions` array referring back to its own object is legal syntax and
4623 /// would recurse forever. Catches a missing depth guard —
4624 /// `ARCHITECTURE.md` §10's rule for every recursive structure walker.
4625 #[test]
4626 fn type3_reference_cycle_through_functions_is_depth_limited() {
4627 let self_ref = ObjId::new(1, 0);
4628 let mut objects = BTreeMap::new();
4629 objects.insert(
4630 self_ref,
4631 Object::Dict(dict(&[
4632 (b"FunctionType", Object::Integer(3)),
4633 (b"Domain", arr(&[0.0, 1.0])),
4634 (
4635 b"Functions",
4636 Object::Array(vec![Object::Reference(self_ref)]),
4637 ),
4638 (b"Bounds", Object::Array(vec![])),
4639 (b"Encode", arr(&[0.0, 1.0])),
4640 ])),
4641 );
4642 let graph = TestGraph {
4643 objects,
4644 trailer: Dict::new(),
4645 };
4646 let view = DocumentView::new(&graph, b"", V17);
4647 let err = PdfFunction::load(&view, &Object::Reference(self_ref)).unwrap_err();
4648 assert_eq!(
4649 err,
4650 FunctionError::NestingTooDeep {
4651 limit: MAX_FUNCTION_DEPTH
4652 }
4653 );
4654 }
4655
4656 /// A nested type 0 with `/Order 3` must surface through the enclosing type 3
4657 /// — the disclosure is about the document, not about one dictionary.
4658 /// Catches `cubic_downgraded` that only looks at the top level.
4659 #[test]
4660 fn type3_reports_a_nested_cubic_downgrade() {
4661 // The sampled sub-function needs a stream, so this one is assembled
4662 // through the object graph rather than with the dict helper.
4663 let sampled_id = ObjId::new(2, 0);
4664 let data: &[u8] = &[0, 1, 2, 3];
4665 let mut objects = BTreeMap::new();
4666 objects.insert(
4667 sampled_id,
4668 Object::Stream(Stream {
4669 dict: dict(&[
4670 (b"FunctionType", Object::Integer(0)),
4671 (b"Domain", arr(&[0.0, 1.0])),
4672 (b"Range", arr(&[0.0, 1.0])),
4673 (b"Size", Object::Array(vec![Object::Integer(4)])),
4674 (b"BitsPerSample", Object::Integer(8)),
4675 (b"Order", Object::Integer(3)),
4676 ]),
4677 data_span: ByteSpan::new(0, data.len()),
4678 }),
4679 );
4680 let graph = TestGraph {
4681 objects,
4682 trailer: Dict::new(),
4683 };
4684 let view = DocumentView::new(&graph, data, V17);
4685 let stitch = Object::Dict(dict(&[
4686 (b"FunctionType", Object::Integer(3)),
4687 (b"Domain", arr(&[0.0, 1.0])),
4688 (
4689 b"Functions",
4690 Object::Array(vec![Object::Reference(sampled_id)]),
4691 ),
4692 (b"Bounds", Object::Array(vec![])),
4693 (b"Encode", arr(&[0.0, 1.0])),
4694 ]));
4695 let f = PdfFunction::load(&view, &stitch).unwrap();
4696 assert!(f.cubic_downgraded());
4697 }
4698
4699 /// Every §7.10 entry may be an indirect reference (§7.3.10). Catches a
4700 /// loader that reads `dict.get(...)` without resolving, which would report
4701 /// a perfectly valid function as malformed.
4702 #[test]
4703 fn indirect_entries_are_resolved() {
4704 let domain_id = ObjId::new(3, 0);
4705 let n_id = ObjId::new(4, 0);
4706 let mut objects = BTreeMap::new();
4707 objects.insert(domain_id, arr(&[0.0, 1.0]));
4708 objects.insert(n_id, Object::Integer(1));
4709 let graph = TestGraph {
4710 objects,
4711 trailer: Dict::new(),
4712 };
4713 let view = DocumentView::new(&graph, b"", V17);
4714 let f = PdfFunction::load(
4715 &view,
4716 &Object::Dict(dict(&[
4717 (b"FunctionType", Object::Integer(2)),
4718 (b"Domain", Object::Reference(domain_id)),
4719 (b"N", Object::Reference(n_id)),
4720 ])),
4721 )
4722 .unwrap();
4723 close(&f.eval(&[0.5]).unwrap(), &[0.5]);
4724 }
4725
4726 /// `eval_into` must CLEAR its buffer. Catches the reuse path appending to a
4727 /// previous result, which in a per-pixel loop grows without bound and
4728 /// returns the first pixel's colour forever.
4729 #[test]
4730 fn eval_into_clears_the_output_buffer() {
4731 let f = load_dict(&[
4732 (b"FunctionType", Object::Integer(2)),
4733 (b"Domain", arr(&[0.0, 1.0])),
4734 (b"N", Object::Integer(1)),
4735 ])
4736 .unwrap();
4737 let mut buf = vec![9.0, 9.0, 9.0];
4738 f.eval_into(&[0.25], &mut buf).unwrap();
4739 close(&buf, &[0.25]);
4740 f.eval_into(&[0.75], &mut buf).unwrap();
4741 close(&buf, &[0.75]);
4742 }
4743
4744 // -- Type 4 (PostScript calculator), §7.10.5 — structure ----------------
4745
4746 /// Load a type 4 whose program text is `src`, with `m` inputs and `n`
4747 /// outputs both declared over `[0, 1]`.
4748 fn load_ps(src: &str, m: usize, n: usize) -> Result<PdfFunction, FunctionError> {
4749 let domain: Vec<f64> = (0..m).flat_map(|_| [0.0, 1.0]).collect();
4750 let range: Vec<f64> = (0..n).flat_map(|_| [-1e300, 1e300]).collect();
4751 load_stream(
4752 &[
4753 (b"FunctionType", Object::Integer(4)),
4754 (b"Domain", arr(&domain)),
4755 (b"Range", arr(&range)),
4756 ],
4757 src.as_bytes(),
4758 )
4759 }
4760
4761 /// Run `src` (1 input, `n` outputs) at `x`.
4762 fn run_ps(src: &str, x: f64, n: usize) -> Result<Vec<f64>, FunctionError> {
4763 load_ps(src, 1, n)?.eval(&[x])
4764 }
4765
4766 /// The two halves of §7.10.5.1's stack contract, tested with **zero
4767 /// operators** so nothing else can be responsible: the inputs *are* the
4768 /// initial stack, and what remains *is* the output. Catches an evaluator
4769 /// that starts from an empty stack and expects the program to fetch its
4770 /// arguments some other way.
4771 #[test]
4772 fn type4_empty_program_passes_inputs_through_as_outputs() {
4773 let f = load_ps("{ }", 2, 2).unwrap();
4774 close(&f.eval(&[0.25, 0.75]).unwrap(), &[0.25, 0.75]);
4775 }
4776
4777 /// §7.10.5.1: "It shall be an error for the number of remaining operands to
4778 /// differ from the number of output variables specified by `Range`."
4779 /// Catches a reader that pads or truncates the result to fit, which for a
4780 /// tint transform means silently inventing or dropping an ink.
4781 #[test]
4782 fn type4_output_arity_mismatch_is_refused() {
4783 let err = run_ps("{ }", 0.5, 2).unwrap_err();
4784 assert_eq!(
4785 err,
4786 FunctionError::OutputArity {
4787 expected: 2,
4788 got: 1
4789 }
4790 );
4791 }
4792
4793 /// The second half of the same sentence: "…or for any of them to be objects
4794 /// other than numbers." Catches a boolean being coerced to 0/1 on the way
4795 /// out.
4796 #[test]
4797 fn type4_boolean_left_in_output_position_is_refused() {
4798 let err = run_ps("{ true }", 0.5, 2).unwrap_err();
4799 assert_eq!(err, FunctionError::NonNumericOutput { index: 1 });
4800 }
4801
4802 /// §7.10.5.1: "The entire code stream defining the function shall be
4803 /// enclosed in braces." Catches an implicit-block tolerance, which would
4804 /// make a truncated stream run as a valid program.
4805 #[test]
4806 fn type4_program_without_enclosing_braces_is_refused() {
4807 let err = load_ps("1 2 add", 1, 1).unwrap_err();
4808 assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
4809 }
4810
4811 /// Catches an unterminated program being accepted as if the closing brace
4812 /// were implied at end of stream.
4813 #[test]
4814 fn type4_unterminated_program_is_refused() {
4815 let err = load_ps("{ 1 2", 1, 1).unwrap_err();
4816 assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
4817 }
4818
4819 /// Catches content after the closing brace being ignored — which would hide
4820 /// a concatenated or partially-overwritten stream.
4821 #[test]
4822 fn type4_trailing_content_after_the_program_is_refused() {
4823 let err = load_ps("{ } 5", 1, 1).unwrap_err();
4824 assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
4825 }
4826
4827 /// Table 42 is the complete operator set. Catches an unknown token being
4828 /// skipped, which leaves the stack at the wrong depth and surfaces as a
4829 /// baffling arity error rather than as the real defect.
4830 #[test]
4831 fn type4_unknown_operator_is_refused_by_name() {
4832 let err = load_ps("{ 2 wibble }", 1, 1).unwrap_err();
4833 assert_eq!(err, FunctionError::UnknownOperator("wibble".to_owned()));
4834 }
4835
4836 /// §7.10.5.1's brace construct is "purely syntactic": a block can only be
4837 /// the operand of `if` or `ifelse`. Catches a parser that treats a block as
4838 /// a pushable value.
4839 #[test]
4840 fn type4_block_not_followed_by_if_or_ifelse_is_refused() {
4841 for src in ["{ { 1 } 2 }", "{ { 1 } }", "{ { 1 } add }"] {
4842 let err = load_ps(src, 1, 1).unwrap_err();
4843 assert!(
4844 matches!(err, FunctionError::PostScriptSyntax { .. }),
4845 "{src} should be a syntax error, got {err:?}"
4846 );
4847 }
4848 }
4849
4850 /// Catches `ifelse` being fed one block, or three blocks being accepted.
4851 #[test]
4852 fn type4_wrong_block_count_for_conditionals_is_refused() {
4853 for src in ["{ true { 1 } ifelse }", "{ true { 1 } { 2 } { 3 } ifelse }"] {
4854 let err = load_ps(src, 1, 1).unwrap_err();
4855 assert!(
4856 matches!(err, FunctionError::PostScriptSyntax { .. }),
4857 "{src} should be a syntax error, got {err:?}"
4858 );
4859 }
4860 let err = load_ps("{ true if }", 1, 1).unwrap_err();
4861 assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
4862 }
4863
4864 /// The parser recurses one frame per `{`. Catches a missing depth guard,
4865 /// which on adversarial input is a native stack overflow — an abort, which
4866 /// `pdfcer-core`'s panic-free policy treats as seriously as an `unwrap`.
4867 #[test]
4868 fn type4_excessive_brace_nesting_is_refused() {
4869 let depth = MAX_PS_NESTING + 2;
4870 let src = format!("{}{}", "{ ".repeat(depth), " }".repeat(depth));
4871 let err = load_ps(&src, 1, 1).unwrap_err();
4872 assert_eq!(
4873 err,
4874 FunctionError::PostScriptNestingTooDeep {
4875 limit: MAX_PS_NESTING
4876 }
4877 );
4878 }
4879
4880 /// §7.10.5.1: "it shall be an error to overflow the stack", with a
4881 /// `shall`-minimum capacity of 100. Catches a `Vec` that simply grows,
4882 /// which accepts programs no conforming reader accepts.
4883 #[test]
4884 fn type4_stack_overflow_at_one_hundred_entries_is_refused() {
4885 // One input already occupies an entry, so 100 more literals overflow.
4886 let src = format!("{{ {} }}", "0 ".repeat(PS_STACK_LIMIT));
4887 let err = run_ps(&src, 0.5, 1).unwrap_err();
4888 assert_eq!(
4889 err,
4890 FunctionError::StackOverflow {
4891 limit: PS_STACK_LIMIT
4892 }
4893 );
4894 // Exactly at the limit is fine — the boundary is inclusive.
4895 let ok = format!("{{ {} }}", "0 ".repeat(PS_STACK_LIMIT - 1));
4896 load_ps(&ok, 1, PS_STACK_LIMIT)
4897 .unwrap()
4898 .eval(&[0.5])
4899 .unwrap();
4900 }
4901
4902 /// §7.10.5.2 lists stack underflow as a reader-detected error. Catches an
4903 /// operator reading a missing operand as zero.
4904 #[test]
4905 fn type4_stack_underflow_is_refused() {
4906 let err = run_ps("{ add add }", 0.5, 1).unwrap_err();
4907 assert!(matches!(err, FunctionError::StackUnderflow { .. }));
4908 }
4909
4910 /// `/Range` is Required for type 4 — it is the only source of *n*, and
4911 /// without it the output-arity check has nothing to check against.
4912 #[test]
4913 fn type4_missing_range_is_refused() {
4914 let err = load_stream(
4915 &[
4916 (b"FunctionType", Object::Integer(4)),
4917 (b"Domain", arr(&[0.0, 1.0])),
4918 ],
4919 b"{ }",
4920 )
4921 .unwrap_err();
4922 assert_eq!(
4923 err,
4924 FunctionError::MissingEntry {
4925 key: "Range",
4926 function_type: 4
4927 }
4928 );
4929 }
4930
4931 /// A type 4 written as a bare dictionary has no program.
4932 #[test]
4933 fn type4_as_a_bare_dictionary_is_refused() {
4934 let err = load_dict(&[
4935 (b"FunctionType", Object::Integer(4)),
4936 (b"Domain", arr(&[0.0, 1.0])),
4937 (b"Range", arr(&[0.0, 1.0])),
4938 ])
4939 .unwrap_err();
4940 assert_eq!(err, FunctionError::NotAStream { function_type: 4 });
4941 }
4942
4943 /// §7.10.5.2's "type error" class, at the conditional. Catches a number
4944 /// being treated as truthy, which C-family instincts make the natural
4945 /// mistake — PostScript has no truthiness.
4946 #[test]
4947 fn type4_non_boolean_condition_is_refused() {
4948 let err = run_ps("{ 1 { 2 } if }", 0.5, 1).unwrap_err();
4949 assert_eq!(
4950 err,
4951 FunctionError::PostScriptType {
4952 op: "if",
4953 detail: "the condition operand is not a boolean"
4954 }
4955 );
4956 let err = run_ps("{ 1.5 { 2 } { 3 } ifelse }", 0.5, 1).unwrap_err();
4957 assert!(matches!(
4958 err,
4959 FunctionError::PostScriptType { op: "ifelse", .. }
4960 ));
4961 }
4962
4963 /// The `%` comment and the white-space rules come from the shared lexer
4964 /// (§7.2), not from a second tokenizer written for this sub-language.
4965 /// Catches a hand-rolled tokenizer being introduced later that disagrees
4966 /// with the object lexer.
4967 #[test]
4968 fn type4_comments_and_irregular_whitespace_are_skipped() {
4969 let f = load_ps("{% leading comment\n\t 1\r\n%another\n}", 1, 2).unwrap();
4970 close(&f.eval(&[0.5]).unwrap(), &[0.5, 1.0]);
4971 }
4972
4973 /// pdfcer's step cap (policy, not spec — see [`MAX_PS_STEPS`]). Catches the
4974 /// counter never being consulted, which would leave a multi-megabyte
4975 /// program running its full length once per pixel.
4976 ///
4977 /// The program is deliberately neutral (`1 pop` leaves the stack alone), so
4978 /// the ONLY thing that can stop it is the cap.
4979 #[test]
4980 fn type4_step_cap_stops_a_pathologically_long_program() {
4981 let pairs = MAX_PS_STEPS / 2 + 8;
4982 let src = format!("{{ {} }}", "1 pop ".repeat(pairs));
4983 let err = run_ps(&src, 0.5, 1).unwrap_err();
4984 assert_eq!(
4985 err,
4986 FunctionError::StepLimit {
4987 limit: MAX_PS_STEPS
4988 }
4989 );
4990 }
4991
4992 /// An integer literal outside the 32-bit range has no representation in
4993 /// this sub-language. Catches it being saturated into a wrong constant that
4994 /// then computes silently.
4995 #[test]
4996 fn type4_out_of_range_integer_literal_is_refused() {
4997 let err = load_ps("{ 99999999999 }", 1, 2).unwrap_err();
4998 assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
4999 }
5000
5001 // -- Type 4 — operator semantics (ISO 32000-1 Annex B; PLRM3 §8.2) ------
5002
5003 /// Evaluate `body` with the one dummy input already discarded, so the
5004 /// assertions are about the operators and nothing else.
5005 fn ps(body: &str, n: usize) -> Result<Vec<f64>, FunctionError> {
5006 run_ps(&format!("{{ pop {body} }}"), 0.0, n)
5007 }
5008
5009 /// `body` must fail; return the error.
5010 #[track_caller]
5011 fn ps_err(body: &str, n: usize) -> FunctionError {
5012 ps(body, n).expect_err("expected a refusal")
5013 }
5014
5015 /// **`ifelse`**, the required conditional test, driven by a real comparison
5016 /// rather than a literal. Catches inverted branch selection — which a
5017 /// `true`-only test cannot see, because both branches of a wrongly-wired
5018 /// `ifelse` still run *something*.
5019 #[test]
5020 fn type4_ifelse_selects_the_branch_the_condition_names() {
5021 close(&ps("0.6 0.5 gt { 11 } { 22 } ifelse", 1).unwrap(), &[11.0]);
5022 close(&ps("0.4 0.5 gt { 11 } { 22 } ifelse", 1).unwrap(), &[22.0]);
5023 // `if` with no else: the block runs or it does not, and nothing else
5024 // changes.
5025 close(&ps("7 true { 1 add } if", 1).unwrap(), &[8.0]);
5026 close(&ps("7 false { 1 add } if", 1).unwrap(), &[7.0]);
5027 // Nested, so the recursive descent through blocks is exercised.
5028 close(
5029 &ps(
5030 "3 dup 2 gt { dup 5 gt { 100 } { 200 } ifelse } { 300 } ifelse exch pop",
5031 1,
5032 )
5033 .unwrap(),
5034 &[200.0],
5035 );
5036 }
5037
5038 /// §7.10.5.1's own worked EXAMPLE — the DoubleDot halftone spot function,
5039 /// a genuine 2-in/1-out program straight out of the standard. Catches any
5040 /// defect that only shows up when several operators compose, and pins
5041 /// `sin`'s units: the `360 mul` before each `sin` is only meaningful in
5042 /// degrees.
5043 #[test]
5044 fn type4_evaluates_the_specs_doubledot_example() {
5045 let f = load_stream(
5046 &[
5047 (b"FunctionType", Object::Integer(4)),
5048 (b"Domain", arr(&[-1.0, 1.0, -1.0, 1.0])),
5049 (b"Range", arr(&[-1.0, 1.0])),
5050 ],
5051 b"{ 360 mul sin 2 div exch 360 mul sin 2 div add }",
5052 )
5053 .unwrap();
5054 assert_eq!(f.inputs(), 2);
5055 assert_eq!(f.outputs(), 1);
5056 // sin(360y)/2 + sin(360x)/2.
5057 close(&f.eval(&[0.0, 0.0]).unwrap(), &[0.0]);
5058 close(&f.eval(&[0.25, 0.0]).unwrap(), &[0.5]);
5059 close(&f.eval(&[0.25, 0.25]).unwrap(), &[1.0]);
5060 close(&f.eval(&[0.75, 0.0]).unwrap(), &[-0.5]);
5061 }
5062
5063 /// `sin`/`cos` take **degrees** (Annex B). Catches a radian implementation,
5064 /// which for a halftone spot function produces a smoothly wrong screen
5065 /// rather than an obvious failure.
5066 #[test]
5067 fn type4_sin_and_cos_take_degrees_not_radians() {
5068 close(&ps("90 sin", 1).unwrap(), &[1.0]);
5069 close(&ps("0 cos", 1).unwrap(), &[1.0]);
5070 close(&ps("180 cos", 1).unwrap(), &[-1.0]);
5071 // sin(180°) is 0; sin(180 rad) is −0.801.
5072 close(&ps("180 sin", 1).unwrap(), &[0.0]);
5073 }
5074
5075 /// `num den atan → angle` in degrees, normalised to `[0, 360)` and never
5076 /// negative. Catches a bare `atan2().to_degrees()`, which answers −90.0
5077 /// where the spec requires 270.0, and catches a one-operand reading.
5078 #[test]
5079 fn type4_atan_is_two_operand_degrees_and_never_negative() {
5080 close(&ps("0 1 atan", 1).unwrap(), &[0.0]);
5081 close(&ps("1 0 atan", 1).unwrap(), &[90.0]);
5082 close(&ps("-100 0 atan", 1).unwrap(), &[270.0]);
5083 close(&ps("4 4 atan", 1).unwrap(), &[45.0]);
5084 // Zero over zero has no defined angle.
5085 assert!(matches!(
5086 ps_err("0 0 atan", 1),
5087 FunctionError::UndefinedResult { op: "atan", .. }
5088 ));
5089 }
5090
5091 /// `base exponent exp` is **pow**, not `e^x` (Annex B). Catches the `e^x`
5092 /// reading, which produces 8103.08 where the answer is 3.
5093 #[test]
5094 fn type4_exp_is_pow_not_e_to_the_x() {
5095 close(&ps("9 0.5 exp", 1).unwrap(), &[3.0]);
5096 close(&ps("2 10 exp", 1).unwrap(), &[1024.0]);
5097 }
5098
5099 /// `log` is base 10 and `ln` is natural (Annex B states both). Catches the
5100 /// two being swapped, which is a 2.3× error that still looks like a curve.
5101 #[test]
5102 fn type4_log_is_base_ten_and_ln_is_natural() {
5103 close(&ps("100 log", 1).unwrap(), &[2.0]);
5104 close(&ps("1 ln", 1).unwrap(), &[0.0]);
5105 close(&ps("2.718281828459045 ln", 1).unwrap(), &[1.0]);
5106 // Both need a positive operand.
5107 assert!(matches!(
5108 ps_err("0 ln", 1),
5109 FunctionError::PostScriptRange { op: "ln", .. }
5110 ));
5111 assert!(matches!(
5112 ps_err("-1 log", 1),
5113 FunctionError::PostScriptRange { op: "log", .. }
5114 ));
5115 }
5116
5117 /// `add`/`sub`/`mul` keep an integer result integral; `div` never does.
5118 /// The type is observed by feeding the result to `idiv`, which is
5119 /// integer-only — the only way an external caller can see the distinction
5120 /// at all, and the reason it must be modelled.
5121 #[test]
5122 fn type4_arithmetic_preserves_integers_but_div_always_produces_a_real() {
5123 // 2 + 3 = the INTEGER 5, so `idiv` accepts it.
5124 close(&ps("2 3 add 2 idiv", 1).unwrap(), &[2.0]);
5125 close(&ps("10 4 sub 3 idiv", 1).unwrap(), &[2.0]);
5126 close(&ps("3 4 mul 5 idiv", 1).unwrap(), &[2.0]);
5127 // 4 div 2 is the REAL 2.0 even though it is exact, so `idiv` refuses.
5128 close(&ps("4 2 div", 1).unwrap(), &[2.0]);
5129 assert!(matches!(
5130 ps_err("4 2 div 2 idiv", 1),
5131 FunctionError::PostScriptType { op: "idiv", .. }
5132 ));
5133 }
5134
5135 /// The overflow half of the same rule: an integer sum that does not fit
5136 /// becomes a **real**, not a wrapped negative. Catches `wrapping_add`,
5137 /// which would turn 4×10⁹ into −294,967,296 and hand that to a colour
5138 /// component.
5139 #[test]
5140 fn type4_integer_overflow_spills_to_real_rather_than_wrapping() {
5141 close(&ps("2000000000 2000000000 add", 1).unwrap(), &[4.0e9]);
5142 // And the result really is a real now, so `idiv` refuses it.
5143 assert!(matches!(
5144 ps_err("2000000000 2000000000 add 2 idiv", 1),
5145 FunctionError::PostScriptType { op: "idiv", .. }
5146 ));
5147 }
5148
5149 /// **The rounding operators are type-preserving, not integer-producing.**
5150 /// `3.7 floor` is the real `3.0`; only `cvi` converts. Catches the
5151 /// intuitive-but-wrong "floor returns an integer", which would make pdfcer
5152 /// accept `3.7 floor 2 idiv` — a program every conforming reader rejects.
5153 #[test]
5154 fn type4_rounding_operators_preserve_their_operands_type() {
5155 close(&ps("3.7 floor", 1).unwrap(), &[3.0]);
5156 close(&ps("3.2 ceiling", 1).unwrap(), &[4.0]);
5157 close(&ps("-4.8 truncate", 1).unwrap(), &[-4.0]);
5158 close(&ps("-4.8 floor", 1).unwrap(), &[-5.0]);
5159 close(&ps("-4.8 ceiling", 1).unwrap(), &[-4.0]);
5160 // A real in, a real out — `idiv` refuses it.
5161 assert!(matches!(
5162 ps_err("3.7 floor 2 idiv", 1),
5163 FunctionError::PostScriptType { op: "idiv", .. }
5164 ));
5165 // An integer in, an integer out — `idiv` accepts it.
5166 close(&ps("99 floor 2 idiv", 1).unwrap(), &[49.0]);
5167 }
5168
5169 /// `round` breaks ties toward the **greater** value, so `-6.5` rounds to
5170 /// `-6.0`. Catches `f64::round`, which breaks ties away from zero and
5171 /// answers `-7.0` — the one rounding call where the obvious choice is
5172 /// wrong.
5173 #[test]
5174 fn type4_round_breaks_ties_toward_the_greater_value() {
5175 close(&ps("6.5 round", 1).unwrap(), &[7.0]);
5176 close(&ps("-6.5 round", 1).unwrap(), &[-6.0]);
5177 close(&ps("3.2 round", 1).unwrap(), &[3.0]);
5178 close(&ps("-3.2 round", 1).unwrap(), &[-3.0]);
5179 }
5180
5181 /// `idiv` truncates toward zero and `mod` takes the sign of the
5182 /// **dividend** — PLRM3 calls it "a remainder operation rather than a true
5183 /// modulo". Catches a floored-division implementation, which answers −3 and
5184 /// +1 where the spec requires −2 and −2.
5185 #[test]
5186 fn type4_idiv_truncates_toward_zero_and_mod_follows_the_dividend() {
5187 close(&ps("-5 2 idiv", 1).unwrap(), &[-2.0]);
5188 close(&ps("5 2 idiv", 1).unwrap(), &[2.0]);
5189 close(&ps("-5 3 mod", 1).unwrap(), &[-2.0]);
5190 close(&ps("5 -3 mod", 1).unwrap(), &[2.0]);
5191 close(&ps("5 3 mod", 1).unwrap(), &[2.0]);
5192 }
5193
5194 /// `cvi` is the only real→integer conversion, and it truncates toward zero.
5195 /// Catches a `floor`-based conversion, which answers −48 for −47.8.
5196 #[test]
5197 fn type4_cvi_truncates_toward_zero_and_yields_an_integer() {
5198 close(&ps("-47.8 cvi", 1).unwrap(), &[-47.0]);
5199 close(&ps("47.8 cvi", 1).unwrap(), &[47.0]);
5200 // The result really is an integer, so `idiv` accepts it.
5201 close(&ps("-47.8 cvi 2 idiv", 1).unwrap(), &[-23.0]);
5202 // Out of the integer range is a range error, not a saturation to
5203 // i32::MAX (which would be a plausible-looking wrong number).
5204 assert!(matches!(
5205 ps_err("3000000000.0 cvi", 1),
5206 FunctionError::PostScriptRange { op: "cvi", .. }
5207 ));
5208 }
5209
5210 /// `not` on an **integer** is the ones complement, not a zero test: PLRM3's
5211 /// own example is `52 not → -53`. Catches a boolean-only `not` that coerces,
5212 /// which would silently answer `false` there.
5213 #[test]
5214 fn type4_not_on_an_integer_is_the_ones_complement() {
5215 close(&ps("52 not", 1).unwrap(), &[-53.0]);
5216 close(&ps("0 not", 1).unwrap(), &[-1.0]);
5217 close(&ps("true not { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
5218 // A real has no complement.
5219 assert!(matches!(
5220 ps_err("1.5 not", 1),
5221 FunctionError::PostScriptType { op: "not", .. }
5222 ));
5223 }
5224
5225 /// `and`/`or`/`xor` are polymorphic over `bool|int` — Annex B's own
5226 /// notation. Catches a boolean-only implementation (which cannot compute
5227 /// `52 7 and → 4`) and an integer-only one (which cannot compute
5228 /// `true false and`).
5229 #[test]
5230 fn type4_bitwise_operators_are_polymorphic_over_booleans_and_integers() {
5231 close(&ps("52 7 and", 1).unwrap(), &[4.0]);
5232 close(&ps("17 5 or", 1).unwrap(), &[21.0]);
5233 close(&ps("7 3 xor", 1).unwrap(), &[4.0]);
5234 close(&ps("true false and { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
5235 close(&ps("true false or { 1 } { 2 } ifelse", 1).unwrap(), &[1.0]);
5236 close(&ps("true true xor { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
5237 }
5238
5239 /// A mixed boolean/integer pair is a `typecheck`, with no coercion in
5240 /// either direction. Catches an implementation that maps `true` to 1.
5241 #[test]
5242 fn type4_mixed_boolean_and_integer_bitwise_operands_are_refused() {
5243 assert!(matches!(
5244 ps_err("true 1 and", 1),
5245 FunctionError::PostScriptType { op: "and", .. }
5246 ));
5247 assert!(matches!(
5248 ps_err("1.0 2.0 or", 1),
5249 FunctionError::PostScriptType { op: "or", .. }
5250 ));
5251 }
5252
5253 /// Annex B types `eq`/`ne` as `any any` but `gt`/`ge`/`lt`/`le` as
5254 /// `num num`. Catches the four relationals accepting booleans, and catches
5255 /// `eq` erroring on a boolean-versus-number comparison that should simply
5256 /// be `false`.
5257 #[test]
5258 fn type4_equality_accepts_any_operands_but_ordering_requires_numbers() {
5259 // An integer and a real compare equal when their values match.
5260 close(&ps("4.0 4 eq { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
5261 close(&ps("4 5 ne { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
5262 // Boolean against boolean.
5263 close(&ps("true true eq { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
5264 // Boolean against a number: false, NOT an error.
5265 close(&ps("true 1 eq { 1 } { 0 } ifelse", 1).unwrap(), &[0.0]);
5266 // Ordering rejects booleans.
5267 for src in [
5268 "true false gt",
5269 "true false lt",
5270 "true false ge",
5271 "true false le",
5272 ] {
5273 assert!(
5274 matches!(ps_err(src, 1), FunctionError::PostScriptType { .. }),
5275 "{src} should be a type error"
5276 );
5277 }
5278 close(&ps("1 2 lt { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
5279 close(&ps("2 2 ge { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
5280 }
5281
5282 /// `bitshift`: positive shifts left, negative shifts right, and the right
5283 /// shift is **logical** — PLRM3, "bits shifted in are 0". Catches an
5284 /// arithmetic right shift, which answers −4 for `-8 -1 bitshift` where the
5285 /// spec's zero-fill gives a large positive number.
5286 #[test]
5287 fn type4_bitshift_is_left_on_positive_and_logically_right_on_negative() {
5288 close(&ps("7 3 bitshift", 1).unwrap(), &[56.0]);
5289 close(&ps("142 -3 bitshift", 1).unwrap(), &[17.0]);
5290 // Zero-fill, not sign-extension: 0xFFFFFFF8 >> 1 = 0x7FFFFFFC.
5291 close(&ps("-8 -1 bitshift", 1).unwrap(), &[2_147_483_644.0]);
5292 // A shift at or past the word width empties the register.
5293 close(&ps("1 32 bitshift", 1).unwrap(), &[0.0]);
5294 close(&ps("1 -32 bitshift", 1).unwrap(), &[0.0]);
5295 }
5296
5297 /// The integer-only operators refuse a real rather than truncating it —
5298 /// §7.10.5.2's "type error" class. Catches a helpful coercion that makes
5299 /// pdfcer compute where a conforming reader raises.
5300 #[test]
5301 fn type4_integer_only_operators_refuse_reals() {
5302 for src in [
5303 "3.0 2 idiv",
5304 "3.0 2 mod",
5305 "3.0 2 bitshift",
5306 "3 2.0 bitshift",
5307 ] {
5308 assert!(
5309 matches!(ps_err(src, 1), FunctionError::PostScriptType { .. }),
5310 "{src} should be a type error"
5311 );
5312 }
5313 }
5314
5315 /// `dup`, `exch` and `pop`, the three unambiguous stack operators.
5316 #[test]
5317 fn type4_dup_exch_and_pop() {
5318 close(&ps("10 dup", 2).unwrap(), &[10.0, 10.0]);
5319 close(&ps("10 20 exch", 2).unwrap(), &[20.0, 10.0]);
5320 close(&ps("10 20 pop", 1).unwrap(), &[10.0]);
5321 }
5322
5323 /// `index` is **zero-based from the top**, so `0 index` is exactly `dup`.
5324 /// Catches one-based counting and counting from the bottom — both of which
5325 /// return a real value from the stack and so fail silently.
5326 #[test]
5327 fn type4_index_counts_from_the_top_starting_at_zero() {
5328 close(
5329 &ps("10 20 30 0 index", 4).unwrap(),
5330 &[10.0, 20.0, 30.0, 30.0],
5331 );
5332 close(
5333 &ps("10 20 30 1 index", 4).unwrap(),
5334 &[10.0, 20.0, 30.0, 20.0],
5335 );
5336 close(
5337 &ps("10 20 30 2 index", 4).unwrap(),
5338 &[10.0, 20.0, 30.0, 10.0],
5339 );
5340 // Reaching past the bottom is a range error, not a wrap.
5341 assert!(matches!(
5342 ps_err("10 5 index", 1),
5343 FunctionError::PostScriptRange { op: "index", .. }
5344 ));
5345 }
5346
5347 /// `copy` duplicates the top *n*, and `0 copy` is an explicitly legal
5348 /// no-op. Catches the count being included in the copied region, and
5349 /// catches `0 copy` being special-cased into an error.
5350 #[test]
5351 fn type4_copy_duplicates_the_top_n_and_zero_is_a_legal_no_op() {
5352 close(&ps("10 20 2 copy", 4).unwrap(), &[10.0, 20.0, 10.0, 20.0]);
5353 close(
5354 &ps("10 20 30 1 copy", 4).unwrap(),
5355 &[10.0, 20.0, 30.0, 30.0],
5356 );
5357 close(&ps("10 20 0 copy", 2).unwrap(), &[10.0, 20.0]);
5358 assert!(matches!(
5359 ps_err("10 20 5 copy", 1),
5360 FunctionError::PostScriptRange { op: "copy", .. }
5361 ));
5362 }
5363
5364 /// `roll` rotates the top *n* by *j*, with a **positive `j` moving elements
5365 /// upward**. Catches a rotation in the wrong direction — which agrees at
5366 /// `j = 0` and disagrees at every other `j`, so `j = ±1` is the whole test.
5367 #[test]
5368 fn type4_roll_rotates_upward_for_a_positive_count() {
5369 close(&ps("10 20 30 3 1 roll", 3).unwrap(), &[30.0, 10.0, 20.0]);
5370 close(&ps("10 20 30 3 -1 roll", 3).unwrap(), &[20.0, 30.0, 10.0]);
5371 close(&ps("10 20 30 3 0 roll", 3).unwrap(), &[10.0, 20.0, 30.0]);
5372 // A rotation of a full turn is the identity, so `j` wraps modulo `n`.
5373 close(&ps("10 20 30 3 3 roll", 3).unwrap(), &[10.0, 20.0, 30.0]);
5374 close(&ps("10 20 30 3 4 roll", 3).unwrap(), &[30.0, 10.0, 20.0]);
5375 // Only the top n move.
5376 close(
5377 &ps("10 20 30 40 2 1 roll", 4).unwrap(),
5378 &[10.0, 20.0, 40.0, 30.0],
5379 );
5380 }
5381
5382 /// `n = 0` leaves `j mod n` undefined (ambiguity `F-A4`); pdfcer treats it as
5383 /// the identity, consistent with `0 copy`. Catches a division by zero in
5384 /// the modulo.
5385 #[test]
5386 fn type4_roll_with_a_zero_window_is_the_identity() {
5387 close(&ps("10 20 0 1 roll", 2).unwrap(), &[10.0, 20.0]);
5388 }
5389
5390 /// A negative count operand is a `rangecheck` for all three counted stack
5391 /// operators. Catches a negative being cast to a huge `usize`.
5392 #[test]
5393 fn type4_negative_count_operands_are_range_errors() {
5394 for src in ["10 20 -1 copy", "10 -1 index", "10 20 -1 1 roll"] {
5395 assert!(
5396 matches!(ps_err(src, 1), FunctionError::PostScriptRange { .. }),
5397 "{src} should be a range error"
5398 );
5399 }
5400 }
5401
5402 /// §7.10.5.2's remaining two error classes, at their canonical examples:
5403 /// "a range error (for example, applying `sqrt` to a negative number)" and
5404 /// "an undefined result (for example, dividing by 0)".
5405 #[test]
5406 fn type4_sqrt_of_a_negative_and_division_by_zero_are_refused() {
5407 assert!(matches!(
5408 ps_err("-1 sqrt", 1),
5409 FunctionError::PostScriptRange { op: "sqrt", .. }
5410 ));
5411 assert!(matches!(
5412 ps_err("1 0 div", 1),
5413 FunctionError::UndefinedResult { op: "div", .. }
5414 ));
5415 assert!(matches!(
5416 ps_err("1 0 idiv", 1),
5417 FunctionError::UndefinedResult { op: "idiv", .. }
5418 ));
5419 assert!(matches!(
5420 ps_err("1 0 mod", 1),
5421 FunctionError::UndefinedResult { op: "mod", .. }
5422 ));
5423 // 0 to a negative power has no finite value.
5424 assert!(matches!(
5425 ps_err("0 -1 exp", 1),
5426 FunctionError::UndefinedResult { op: "exp", .. }
5427 ));
5428 close(&ps("4 sqrt", 1).unwrap(), &[2.0]);
5429 }
5430
5431 /// `neg` and `abs` preserve their operand's type, which the `idiv` probe
5432 /// makes visible. Catches them being routed through `f64` unconditionally.
5433 #[test]
5434 fn type4_neg_and_abs_preserve_the_operand_type() {
5435 close(&ps("5 neg", 1).unwrap(), &[-5.0]);
5436 close(&ps("-5.5 abs", 1).unwrap(), &[5.5]);
5437 close(&ps("-5 abs 2 idiv", 1).unwrap(), &[2.0]);
5438 close(&ps("5 neg 2 idiv", 1).unwrap(), &[-2.0]);
5439 }
5440
5441 /// `cvr` turns an integer into a real, which the `idiv` probe then refuses.
5442 /// Catches `cvr` being implemented as a no-op — harmless-looking, but it
5443 /// means a program that deliberately leaves the integer domain does not.
5444 #[test]
5445 fn type4_cvr_converts_an_integer_to_a_real() {
5446 close(&ps("7 cvr", 1).unwrap(), &[7.0]);
5447 assert!(matches!(
5448 ps_err("7 cvr 2 idiv", 1),
5449 FunctionError::PostScriptType { op: "idiv", .. }
5450 ));
5451 }
5452
5453 /// Every one of Table 42's 42 entries is recognised. Catches an operator
5454 /// being left out of the token map — which would surface as
5455 /// `UnknownOperator` on a perfectly valid file, months later.
5456 #[test]
5457 fn type4_every_table_42_operator_is_recognised() {
5458 const TABLE_42: [&str; 42] = [
5459 "abs", "add", "atan", "ceiling", "cos", "cvi", "cvr", "div", "exp", "floor", "idiv",
5460 "ln", "log", "mod", "mul", "neg", "round", "sin", "sqrt", "sub", "truncate", "and",
5461 "bitshift", "eq", "false", "ge", "gt", "le", "lt", "ne", "not", "or", "true", "xor",
5462 "if", "ifelse", "copy", "dup", "exch", "index", "pop", "roll",
5463 ];
5464 for token in TABLE_42 {
5465 let structural = matches!(token, "true" | "false" | "if" | "ifelse");
5466 assert_eq!(
5467 PsOperator::from_token(token.as_bytes()).is_some(),
5468 !structural,
5469 "{token} classified wrongly"
5470 );
5471 }
5472 // And the round trip through `name` is exact for the 38 dispatched
5473 // operators, so an error message can never blame the wrong operator.
5474 for token in TABLE_42 {
5475 if let Some(op) = PsOperator::from_token(token.as_bytes()) {
5476 assert_eq!(op.name(), token);
5477 }
5478 }
5479 }
5480
5481 /// `affine_breaks`: sample positions, stitch bounds mapped through
5482 /// `/Encode`, `/Range` clip points, and `None` where no list exists.
5483 #[test]
5484 fn affine_breaks_list_where_each_type_bends() {
5485 let sampled = load_stream(
5486 &[
5487 (b"FunctionType", Object::Integer(0)),
5488 (b"Domain", arr(&[0.0, 1.0])),
5489 (b"Range", arr(&[0.0, 1.0])),
5490 (b"Size", Object::Array(vec![Object::Integer(3)])),
5491 (b"BitsPerSample", Object::Integer(8)),
5492 ],
5493 &[0x00, 0xFF, 0x00],
5494 )
5495 .unwrap();
5496 assert_eq!(sampled.affine_breaks(16), Some(vec![0.0, 0.5, 1.0]));
5497 assert_eq!(sampled.affine_breaks(2), None);
5498 let band = load_dict(&[
5499 (b"FunctionType", Object::Integer(3)),
5500 (b"Domain", arr(&[0.0, 1.0])),
5501 (
5502 b"Functions",
5503 Object::Array(vec![
5504 ramp(&[0.0, 1.0], &[0.0], &[0.0]),
5505 ramp(&[0.0, 1.0], &[1.0], &[1.0]),
5506 ramp(&[0.0, 1.0], &[0.0], &[0.0]),
5507 ]),
5508 ),
5509 (b"Bounds", arr(&[0.126, 0.127])),
5510 (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0, 0.0, 1.0])),
5511 ])
5512 .unwrap();
5513 assert_eq!(band.affine_breaks(16), Some(vec![0.0, 0.126, 0.127, 1.0]));
5514 let clipped = load_dict(&[
5515 (b"FunctionType", Object::Integer(2)),
5516 (b"Domain", arr(&[0.0, 1.0])),
5517 (b"Range", arr(&[0.0, 1.0])),
5518 (b"N", Object::Integer(1)),
5519 (b"C0", arr(&[-1.0])),
5520 (b"C1", arr(&[3.0])),
5521 ])
5522 .unwrap();
5523 let b = clipped.affine_breaks(16).unwrap();
5524 assert_eq!(b.len(), 4, "{b:?}");
5525 close(&b, &[0.0, 0.25, 0.5, 1.0]);
5526 let squared = load_dict(&[
5527 (b"FunctionType", Object::Integer(2)),
5528 (b"Domain", arr(&[0.0, 1.0])),
5529 (b"N", Object::Integer(2)),
5530 ])
5531 .unwrap();
5532 assert_eq!(squared.affine_breaks(16), None);
5533 let clip_obj = Object::Dict(dict(&[
5534 (b"FunctionType", Object::Integer(2)),
5535 (b"Domain", arr(&[0.0, 1.0])),
5536 (b"Range", arr(&[0.0, 1.0])),
5537 (b"N", Object::Integer(1)),
5538 (b"C0", arr(&[-1.0])),
5539 (b"C1", arr(&[3.0])),
5540 ]));
5541 let stitched = |second: Object| {
5542 load_dict(&[
5543 (b"FunctionType", Object::Integer(3)),
5544 (b"Domain", arr(&[0.0, 2.0])),
5545 (b"Functions", Object::Array(vec![clip_obj.clone(), second])),
5546 (b"Bounds", arr(&[1.0])),
5547 (b"Encode", arr(&[1.0, 0.0, 0.0, 1.0])),
5548 ])
5549 .unwrap()
5550 };
5551 let b = stitched(clip_obj.clone()).affine_breaks(16).unwrap();
5552 close(&b, &[0.0, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0]);
5553 let curve = Object::Dict(dict(&[
5554 (b"FunctionType", Object::Integer(2)),
5555 (b"Domain", arr(&[0.0, 1.0])),
5556 (b"Range", arr(&[0.0, 1.0])),
5557 (b"N", Object::Integer(2)),
5558 ]));
5559 assert_eq!(stitched(curve).affine_breaks(16), None);
5560 let overshoot = load_dict(&[
5561 (b"FunctionType", Object::Integer(2)),
5562 (b"Domain", arr(&[0.0, 1.0])),
5563 (b"N", Object::Integer(1)),
5564 (b"C0", arr(&[-0.5])),
5565 (b"C1", arr(&[1.5])),
5566 ])
5567 .unwrap();
5568 assert_eq!(overshoot.affine_breaks(16), Some(vec![0.0, 1.0]));
5569 let b = overshoot.affine_breaks_clamped(16, &[[0.0, 1.0]]).unwrap();
5570 close(&b, &[0.0, 0.25, 0.75, 1.0]);
5571 assert_eq!(overshoot.affine_breaks_clamped(3, &[[0.0, 1.0]]), None);
5572 let inside = load_dict(&[
5573 (b"FunctionType", Object::Integer(2)),
5574 (b"Domain", arr(&[0.0, 1.0])),
5575 (b"N", Object::Integer(1)),
5576 ]);
5577 assert_eq!(
5578 inside.unwrap().affine_breaks_clamped(16, &[[0.0, 1.0]]),
5579 Some(vec![0.0, 1.0])
5580 );
5581 }
5582}