Skip to main content

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