Skip to main content

PdfFunction

Struct PdfFunction 

Source
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

Source

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

Source

pub const fn function_type(&self) -> FunctionType

Which of the four types this is.

Source

pub fn inputs(&self) -> usize

m — the number of input values this function takes.

Source

pub fn outputs(&self) -> usize

n — the number of output values this function produces.

Source

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.

Source

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).

Source

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

Source

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]);
Source

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:

  1. every input is clipped to its /Domain pair before dispatch;
  2. every output is clipped to its /Range pair afterwards — and, when /Range is 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

Trait Implementations§

Source§

impl Clone for PdfFunction

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PdfFunction

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for PdfFunction

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for PdfFunction

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.