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