pub struct PdfFunction { /* private fields */ }Expand description
A loaded, evaluatable PDF function (§7.10).
Construct with PdfFunction::load, evaluate with PdfFunction::eval or
PdfFunction::eval_into. The value is self-contained once loaded: it holds
its own sample bytes or program, borrows nothing from the document, and is
therefore cheap to keep alongside a colour space and reuse per pixel.
§Examples
The commonest tint transform in the wild — a type 2 with /N 1, which is a
straight interpolation from C0 (paper) to C1 (the colorant at full
strength):
use pdfcer_model::PdfVersion;
use pdfcer_function::function::PdfFunction;
use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::{Dict, Name, ObjId, Object};
use pdfcer_model::view::DocumentView;
// A function whose entries are all direct needs no real document behind it.
struct NoObjects;
impl ObjectGraph for NoObjects {
fn value(&self, _: ObjId) -> Option<&Object> { None }
fn trailer_entry(&self, _: &[u8]) -> Option<&Object> { None }
}
fn num(v: f64) -> Object { Object::Real(v) }
let mut d = Dict::new();
d.insert(Name::from(&b"FunctionType"[..]), Object::Integer(2));
d.insert(Name::from(&b"Domain"[..]), Object::Array(vec![num(0.0), num(1.0)]));
d.insert(Name::from(&b"N"[..]), Object::Integer(1));
// Full-strength ink is 100% magenta.
d.insert(Name::from(&b"C0"[..]), Object::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)]));
d.insert(Name::from(&b"C1"[..]), Object::Array(vec![num(0.0), num(1.0), num(0.0), num(0.0)]));
let graph = NoObjects;
let view = DocumentView::new(&graph, b"", PdfVersion { major: 1, minor: 7 });
let f = PdfFunction::load(&view, &Object::Dict(d)).unwrap();
assert_eq!(f.inputs(), 1);
assert_eq!(f.outputs(), 4);
assert_eq!(f.eval(&[0.5]).unwrap(), vec![0.0, 0.5, 0.0, 0.0]);
// Table 38: an input outside /Domain is clipped, not extrapolated.
assert_eq!(f.eval(&[1.4]).unwrap(), vec![0.0, 1.0, 0.0, 0.0]);Implementations§
Source§impl PdfFunction
impl PdfFunction
Sourcepub fn load(
view: &DocumentView<'_>,
obj: &Object,
) -> Result<Self, FunctionError>
pub fn load( view: &DocumentView<'_>, obj: &Object, ) -> Result<Self, FunctionError>
Load a function from an object in view’s graph.
obj may be the function dictionary/stream itself or an indirect
reference to it; references are followed with §7.3.10’s rules, and so
are the individual entries (a /Domain written as 12 0 R is legal and
is resolved here).
Loading is where all structural validation happens. By the time this
returns Ok, the function’s dimensionality is internally consistent, its
intervals are ordered, a type 0’s sample stream is known to be long
enough, a type 2’s /Domain is known to be compatible with its /N, a
type 3’s /Bounds is known to partition its /Domain, and a type 4’s
program is known to parse. PdfFunction::eval can then fail only for
reasons that genuinely depend on the input values (a type 4 dividing by
zero, an arity mismatch from the caller).
That split is deliberate: a tint transform is loaded once and evaluated once per pixel, so per-evaluation validation would be both slow and, far worse, would surface a file defect one pixel at a time.
§Errors
FunctionError — every variant except the evaluation-time ones
(FunctionError::InputArity, FunctionError::NonFiniteInput, the
PostScript* runtime errors, FunctionError::StepLimit,
FunctionError::OutputArity). See the module docs on refusal posture:
a malformed function is never repaired into a plausible one.
Source§impl PdfFunction
impl PdfFunction
Sourcepub const fn function_type(&self) -> FunctionType
pub const fn function_type(&self) -> FunctionType
Which of the four types this is.
Sourcepub fn domain(&self) -> &[[f64; 2]]
pub fn domain(&self) -> &[[f64; 2]]
/Domain as one [min, max] pair per input.
Reshaped from the flat 2 × m array the file carries, because every use of it is pairwise and a flat slice invites an off-by-one that produces a plausible-looking wrong answer.
Sourcepub fn range(&self) -> Option<&[[f64; 2]]>
pub fn range(&self) -> Option<&[[f64; 2]]>
/Range as one [min, max] pair per output, or None when the entry
was absent.
None is meaningful and must not be defaulted. Table 38: “If this
entry is absent, no clipping shall be done.” Types 0 and 4 always
return Some (the entry is required for them).
Sourcepub fn cubic_downgraded(&self) -> bool
pub fn cubic_downgraded(&self) -> bool
Whether evaluating this function silently uses linear interpolation
where the file asked for cubic — i.e. a type 0 with /Order 3 that the
spec does not let pdfcer ignore.
This is disclosure plumbing for project rule 4 (fuzzy, never sneaky).
pdfcer evaluates every sampled function multilinearly. §7.10.2 permits
exactly one case of ignoring /Order 3 — “If Size is less than 4,
cubic spline interpolation is not possible and Order 3 shall be
ignored if specified” — and in that case this returns false, because
nothing was downgraded. It returns true only when a cubic
interpolation was genuinely requested, genuinely possible, and not
performed, so a caller can say so rather than let the operator assume
fidelity that isn’t there.
The reason pdfcer does not simply implement it: §7.10.2 names “cubic
spline interpolation” and then specifies no spline — no basis, no
end conditions, no continuity requirement. Two conforming readers
legitimately produce different pixels (recorded as ambiguity F-A1 in
the spec RAG). Guessing a spline would be inventing the standard’s
missing half and calling the result fidelity.
Recurses into a type 3’s sub-functions, since that is where a sampled function usually hides.
Source§impl PdfFunction
impl PdfFunction
Sourcepub fn eval(&self, inputs: &[f64]) -> Result<Vec<f64>, FunctionError>
pub fn eval(&self, inputs: &[f64]) -> Result<Vec<f64>, FunctionError>
Evaluate the function, allocating a fresh output vector.
Convenience over PdfFunction::eval_into; prefer that one in a
per-pixel loop, where this allocation dominates the arithmetic.
§Errors
FunctionError::InputArity if inputs.len() is not
PdfFunction::inputs; FunctionError::NonFiniteInput for a NaN or
infinite input; plus any type 4 runtime error. See
PdfFunction::eval_into.
§Examples
// /C0 and /C1 default to [0.0] and [1.0], so this is y = x^2.
let f = PdfFunction::load(&view, &Object::Dict(d)).unwrap();
assert_eq!(f.eval(&[0.5]).unwrap(), vec![0.25]);Sourcepub fn eval_into(
&self,
inputs: &[f64],
out: &mut Vec<f64>,
) -> Result<(), FunctionError>
pub fn eval_into( &self, inputs: &[f64], out: &mut Vec<f64>, ) -> Result<(), FunctionError>
Evaluate the function into out, which is cleared first.
This is the real entry point; PdfFunction::eval wraps it. Reusing one
buffer across a scanline is the difference between one allocation and one
per pixel for a DeviceN image.
§What this method owns, and why it is not per-type
The two Table 38 clipping shalls are applied here, around whatever
the type-specific evaluator does:
- every input is clipped to its
/Domainpair before dispatch; - every output is clipped to its
/Rangepair afterwards — and, when/Rangeis absent, deliberately not clipped.
Putting them in one place means no type can be added later that forgets one. Type 0’s own algorithm (§7.10.2) restates both clips internally; applying them again here is idempotent, so the duplication costs nothing and the guarantee holds even if that evaluator changes.
§Non-finite values are refused, not clamped
A NaN input cannot be clipped meaningfully — Rust’s f64::max returns
the non-NaN operand, so clamping would quietly turn NaN into
Domain_0. That is a fabricated value that looks exactly like a real
one downstream, so FunctionError::NonFiniteInput is returned instead.
Symmetrically, an output that is still non-finite after clipping (only
possible when /Range is absent) yields
FunctionError::NonFiniteOutput.
§Errors
FunctionError::InputArity— wrong number of inputs.FunctionError::NonFiniteInput/FunctionError::NonFiniteOutput.FunctionError::SampleIndexOutOfRange— type 0 internal invariant.- Type 4 runtime errors:
FunctionError::StackOverflow,FunctionError::StackUnderflow,FunctionError::PostScriptType,FunctionError::PostScriptRange,FunctionError::UndefinedResult,FunctionError::StepLimit,FunctionError::OutputArity,FunctionError::NonNumericOutput.