use pdfcer_model::filters::{self, FilterError};
use pdfcer_model::graph::ObjectGraph as _;
use pdfcer_model::lexer::{LexError, Lexer, TokenKind};
use pdfcer_model::object::{Dict, Object, Stream};
use pdfcer_model::view::DocumentView;
pub const PS_STACK_LIMIT: usize = 100;
pub const MAX_PS_STEPS: usize = 1_000_000;
pub const MAX_PS_NESTING: usize = 32;
pub const MAX_SAMPLED_INPUTS: usize = 8;
pub const MAX_FUNCTION_DEPTH: usize = 8;
pub const VALID_BITS_PER_SAMPLE: [u32; 8] = [1, 2, 4, 8, 12, 16, 24, 32];
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum FunctionError {
#[error("function object is neither a dictionary nor a stream")]
NotAFunction,
#[error("/FunctionType is missing or not an integer")]
MissingFunctionType,
#[error("unknown /FunctionType {0} (ISO 32000-1 §7.10 defines 0, 2, 3 and 4 only)")]
UnknownFunctionType(i64),
#[error("/FunctionType {function_type} must be a stream, not a dictionary")]
NotAStream {
function_type: i64,
},
#[error("the function stream's data span could not be read from this document")]
StreamUnreadable,
#[error("function stream decode failed: {0}")]
Filter(#[from] FilterError),
#[error("/{key} is required for /FunctionType {function_type} and is missing")]
MissingEntry {
key: &'static str,
function_type: i64,
},
#[error("/{key} is malformed: {detail}")]
BadEntry {
key: &'static str,
detail: String,
},
#[error("/{key} has {got} elements; {expected} required for this function's dimensionality")]
BadArrayLength {
key: &'static str,
expected: usize,
got: usize,
},
#[error("/{key} pair {index} is inverted: [{low}, {high}]")]
InvertedInterval {
key: &'static str,
index: usize,
low: f64,
high: f64,
},
#[error(
"sampled function has {got} inputs; pdfcer's limit is {limit} (§7.10.2 permits an implementation limit)"
)]
TooManyInputs {
got: usize,
limit: usize,
},
#[error("/BitsPerSample {0} is not one of 1, 2, 4, 8, 12, 16, 24, 32 (§7.10.2 Table 39)")]
BadBitsPerSample(i64),
#[error(
"sample stream holds {have} bytes; {need} required by /Size, /Range and /BitsPerSample"
)]
SampleDataTooShort {
need: usize,
have: usize,
},
#[error("the sample table implied by /Size and /BitsPerSample overflows address arithmetic")]
SampleTableTooLarge,
#[error("internal: sample index {index} is outside the validated sample table")]
SampleIndexOutOfRange {
index: usize,
},
#[error("/Domain [{low}, {high}] does not constrain x for /N {n} (§7.10.3)")]
DomainIncompatibleWithExponent {
n: f64,
low: f64,
high: f64,
},
#[error("/FunctionType {function_type} takes exactly one input; /Domain declares {got}")]
NotOneInput {
function_type: i64,
got: usize,
},
#[error("/Functions is empty; a stitching function needs at least one sub-function")]
NoSubFunctions,
#[error(
"/Functions sub-function {index} produces {got} outputs; sub-function 0 produces {expected}"
)]
SubFunctionArity {
index: usize,
expected: usize,
got: usize,
},
#[error("/Bounds is not a valid partition of /Domain: {detail}")]
BadBounds {
detail: String,
},
#[error(
"function nesting exceeded pdfcer's depth limit of {limit} (cycle, or pathologically nested /Functions)"
)]
NestingTooDeep {
limit: usize,
},
#[error("type 4 program lex error: {0}")]
PostScriptLex(#[from] LexError),
#[error("type 4 program syntax error: {detail}")]
PostScriptSyntax {
detail: String,
},
#[error("unknown type 4 operator {0:?}; §7.10.5.1 Table 42 is the complete operator set")]
UnknownOperator(String),
#[error("type 4 program brace nesting exceeded pdfcer's limit of {limit}")]
PostScriptNestingTooDeep {
limit: usize,
},
#[error("type 4 operand stack overflowed the {limit}-entry limit (§7.10.5.1)")]
StackOverflow {
limit: usize,
},
#[error("type 4 stack underflow: {op} needs {needed} operand(s), {had} available")]
StackUnderflow {
op: &'static str,
needed: usize,
had: usize,
},
#[error("type 4 type error at {op}: {detail}")]
PostScriptType {
op: &'static str,
detail: &'static str,
},
#[error("type 4 range error at {op}: {detail}")]
PostScriptRange {
op: &'static str,
detail: &'static str,
},
#[error("type 4 undefined result at {op}: {detail}")]
UndefinedResult {
op: &'static str,
detail: &'static str,
},
#[error("type 4 program exceeded pdfcer's {limit}-step execution cap")]
StepLimit {
limit: usize,
},
#[error("type 4 program left {got} value(s) on the stack; /Range requires {expected}")]
OutputArity {
expected: usize,
got: usize,
},
#[error("type 4 program left a boolean in output position {index}; outputs must be numbers")]
NonNumericOutput {
index: usize,
},
#[error("this function takes {expected} input(s); {got} supplied")]
InputArity {
expected: usize,
got: usize,
},
#[error("input {index} is not finite ({value})")]
NonFiniteInput {
index: usize,
value: f64,
},
#[error("output {index} is not finite ({value}) and /Range is absent, so it cannot be clamped")]
NonFiniteOutput {
index: usize,
value: f64,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FunctionType {
Sampled,
Exponential,
Stitching,
PostScript,
}
impl FunctionType {
#[must_use]
pub const fn as_i64(self) -> i64 {
match self {
Self::Sampled => 0,
Self::Exponential => 2,
Self::Stitching => 3,
Self::PostScript => 4,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PdfFunction {
domain: Vec<[f64; 2]>,
range: Option<Vec<[f64; 2]>>,
kind: Kind,
}
#[derive(Debug, Clone, PartialEq)]
enum Kind {
Sampled(Sampled),
Exponential(Exponential),
Stitching(Stitching),
PostScript(PostScript),
}
impl PdfFunction {
pub fn load(view: &DocumentView<'_>, obj: &Object) -> Result<Self, FunctionError> {
Self::load_at_depth(view, obj, 0)
}
fn load_at_depth(
view: &DocumentView<'_>,
obj: &Object,
depth: usize,
) -> Result<Self, FunctionError> {
if depth > MAX_FUNCTION_DEPTH {
return Err(FunctionError::NestingTooDeep {
limit: MAX_FUNCTION_DEPTH,
});
}
let resolved = view.resolve(obj);
let dict = resolved.as_dict().ok_or(FunctionError::NotAFunction)?;
let function_type = entry(view, dict, b"FunctionType")
.and_then(Object::as_int)
.ok_or(FunctionError::MissingFunctionType)?;
let domain = pairs(view, dict, b"Domain")?.ok_or(FunctionError::MissingEntry {
key: "Domain",
function_type,
})?;
if domain.is_empty() {
return Err(FunctionError::BadEntry {
key: "Domain",
detail: "empty; a function needs at least one input".to_owned(),
});
}
check_ordered(&domain, "Domain")?;
let range = pairs(view, dict, b"Range")?;
if let Some(r) = range.as_deref() {
if r.is_empty() {
return Err(FunctionError::BadEntry {
key: "Range",
detail: "empty; /Range must declare at least one output".to_owned(),
});
}
check_ordered(r, "Range")?;
}
let kind = match function_type {
0 => Kind::Sampled(load_sampled(
view,
resolved,
dict,
&domain,
range.as_deref(),
)?),
2 => Kind::Exponential(load_exponential(view, dict, &domain)?),
3 => Kind::Stitching(load_stitching(
view,
dict,
&domain,
range.as_deref(),
depth,
)?),
4 => Kind::PostScript(load_postscript(view, resolved, &domain, range.as_deref())?),
other => return Err(FunctionError::UnknownFunctionType(other)),
};
if let Some(r) = range.as_deref() {
let implied = kind.outputs();
if r.len() != implied {
return Err(FunctionError::BadArrayLength {
key: "Range",
expected: implied * 2,
got: r.len() * 2,
});
}
}
Ok(Self {
domain,
range,
kind,
})
}
}
impl PdfFunction {
#[must_use]
pub const fn function_type(&self) -> FunctionType {
match self.kind {
Kind::Sampled(_) => FunctionType::Sampled,
Kind::Exponential(_) => FunctionType::Exponential,
Kind::Stitching(_) => FunctionType::Stitching,
Kind::PostScript(_) => FunctionType::PostScript,
}
}
#[must_use]
pub fn inputs(&self) -> usize {
self.domain.len()
}
#[must_use]
pub fn outputs(&self) -> usize {
self.kind.outputs()
}
#[must_use]
pub fn domain(&self) -> &[[f64; 2]] {
&self.domain
}
#[must_use]
pub fn range(&self) -> Option<&[[f64; 2]]> {
self.range.as_deref()
}
#[must_use]
pub fn cubic_downgraded(&self) -> bool {
match &self.kind {
Kind::Sampled(s) => s.order3_downgraded,
Kind::Stitching(s) => s.functions.iter().any(Self::cubic_downgraded),
Kind::Exponential(_) | Kind::PostScript(_) => false,
}
}
}
impl Kind {
fn outputs(&self) -> usize {
match self {
Self::Sampled(s) => s.decode.len(),
Self::Exponential(e) => e.c0.len(),
Self::Stitching(s) => s.outputs,
Self::PostScript(p) => p.outputs,
}
}
}
impl PdfFunction {
pub fn eval(&self, inputs: &[f64]) -> Result<Vec<f64>, FunctionError> {
let mut out = Vec::with_capacity(self.outputs());
self.eval_into(inputs, &mut out)?;
Ok(out)
}
pub fn eval_into(&self, inputs: &[f64], out: &mut Vec<f64>) -> Result<(), FunctionError> {
if inputs.len() != self.domain.len() {
return Err(FunctionError::InputArity {
expected: self.domain.len(),
got: inputs.len(),
});
}
let mut clipped: Vec<f64> = Vec::with_capacity(inputs.len());
for (index, (&x, pair)) in inputs.iter().zip(self.domain.iter()).enumerate() {
if !x.is_finite() {
return Err(FunctionError::NonFiniteInput { index, value: x });
}
clipped.push(clip(x, pair[0], pair[1]));
}
out.clear();
match &self.kind {
Kind::Sampled(s) => s.eval(&self.domain, &clipped, out)?,
Kind::Exponential(e) => e.eval(&clipped, out),
Kind::Stitching(s) => s.eval(&self.domain, &clipped, out)?,
Kind::PostScript(p) => p.eval(&clipped, out)?,
}
match self.range.as_deref() {
Some(range) => {
for (value, pair) in out.iter_mut().zip(range.iter()) {
*value = clip(*value, pair[0], pair[1]);
}
}
None => {
for (index, &value) in out.iter().enumerate() {
if !value.is_finite() {
return Err(FunctionError::NonFiniteOutput { index, value });
}
}
}
}
Ok(())
}
}
fn interpolate(x: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> f64 {
let span = xmax - xmin;
if span == 0.0 {
return ymin;
}
ymin + (x - xmin) * (ymax - ymin) / span
}
fn clip(v: f64, lo: f64, hi: f64) -> f64 {
if v < lo {
lo
} else if v > hi {
hi
} else {
v
}
}
fn entry<'v>(view: &'v DocumentView<'_>, dict: &'v Dict, key: &[u8]) -> Option<&'v Object> {
dict.get(key).map(|obj| view.resolve(obj))
}
fn numbers(
view: &DocumentView<'_>,
dict: &Dict,
key: &'static str,
) -> Result<Option<Vec<f64>>, FunctionError> {
let Some(obj) = entry(view, dict, key.as_bytes()) else {
return Ok(None);
};
let Some(items) = obj.as_array() else {
return Err(FunctionError::BadEntry {
key,
detail: "not an array".to_owned(),
});
};
let mut out = Vec::with_capacity(items.len());
for (i, item) in items.iter().enumerate() {
let Some(v) = view.resolve(item).as_number() else {
return Err(FunctionError::BadEntry {
key,
detail: format!("element {i} is not a number"),
});
};
if !v.is_finite() {
return Err(FunctionError::BadEntry {
key,
detail: format!("element {i} is not finite"),
});
}
out.push(v);
}
Ok(Some(out))
}
fn pairs(
view: &DocumentView<'_>,
dict: &Dict,
key: &'static [u8],
) -> Result<Option<Vec<[f64; 2]>>, FunctionError> {
let key_str: &'static str = match key {
b"Domain" => "Domain",
b"Range" => "Range",
b"Encode" => "Encode",
b"Decode" => "Decode",
_ => "unknown",
};
let Some(flat) = numbers(view, dict, key_str)? else {
return Ok(None);
};
if flat.len() % 2 != 0 {
return Err(FunctionError::BadEntry {
key: key_str,
detail: format!("has {} elements; a 2 × n array is required", flat.len()),
});
}
Ok(Some(
flat.as_chunks::<2>()
.0
.iter()
.map(|c| {
[
c.first().copied().unwrap_or(0.0),
c.get(1).copied().unwrap_or(0.0),
]
})
.collect(),
))
}
fn check_ordered(intervals: &[[f64; 2]], key: &'static str) -> Result<(), FunctionError> {
for (index, pair) in intervals.iter().enumerate() {
if pair[0] > pair[1] {
return Err(FunctionError::InvertedInterval {
key,
index,
low: pair[0],
high: pair[1],
});
}
}
Ok(())
}
fn stream_bytes(view: &DocumentView<'_>, stream: &Stream) -> Result<Vec<u8>, FunctionError> {
let raw = view
.slice(stream.data_span)
.ok_or(FunctionError::StreamUnreadable)?;
Ok(filters::decode_stream(&stream.dict, raw)?)
}
#[derive(Debug, Clone, PartialEq)]
struct Sampled {
size: Vec<usize>,
strides: Vec<usize>,
bits_per_sample: u32,
max_sample: f64,
encode: Vec<[f64; 2]>,
decode: Vec<[f64; 2]>,
samples: Vec<u8>,
order3_downgraded: bool,
}
fn load_sampled(
view: &DocumentView<'_>,
resolved: &Object,
dict: &Dict,
domain: &[[f64; 2]],
range: Option<&[[f64; 2]]>,
) -> Result<Sampled, FunctionError> {
let Object::Stream(stream) = resolved else {
return Err(FunctionError::NotAStream { function_type: 0 });
};
let m = domain.len();
if m > MAX_SAMPLED_INPUTS {
return Err(FunctionError::TooManyInputs {
got: m,
limit: MAX_SAMPLED_INPUTS,
});
}
let range = range.ok_or(FunctionError::MissingEntry {
key: "Range",
function_type: 0,
})?;
let n = range.len();
let size_raw = numbers(view, dict, "Size")?.ok_or(FunctionError::MissingEntry {
key: "Size",
function_type: 0,
})?;
if size_raw.len() != m {
return Err(FunctionError::BadArrayLength {
key: "Size",
expected: m,
got: size_raw.len(),
});
}
let mut size = Vec::with_capacity(m);
for (i, &s) in size_raw.iter().enumerate() {
if s < 1.0 || s.fract() != 0.0 {
return Err(FunctionError::BadEntry {
key: "Size",
detail: format!("element {i} is {s}; each must be a positive integer"),
});
}
size.push(s as usize);
}
let mut strides = Vec::with_capacity(m);
let mut acc: usize = 1;
for &s in &size {
strides.push(acc);
acc = acc
.checked_mul(s)
.ok_or(FunctionError::SampleTableTooLarge)?;
}
let total_entries = acc;
let bits_raw = entry(view, dict, b"BitsPerSample")
.and_then(Object::as_int)
.ok_or(FunctionError::MissingEntry {
key: "BitsPerSample",
function_type: 0,
})?;
let bits_per_sample = u32::try_from(bits_raw)
.ok()
.filter(|b| VALID_BITS_PER_SAMPLE.contains(b))
.ok_or(FunctionError::BadBitsPerSample(bits_raw))?;
let total_samples = total_entries
.checked_mul(n)
.ok_or(FunctionError::SampleTableTooLarge)?;
let total_bits = total_samples
.checked_mul(bits_per_sample as usize)
.ok_or(FunctionError::SampleTableTooLarge)?;
let need = total_bits
.checked_add(7)
.ok_or(FunctionError::SampleTableTooLarge)?
/ 8;
let samples = stream_bytes(view, stream)?;
if samples.len() < need {
return Err(FunctionError::SampleDataTooShort {
need,
have: samples.len(),
});
}
let encode = match pairs(view, dict, b"Encode")? {
Some(e) if e.len() != m => {
return Err(FunctionError::BadArrayLength {
key: "Encode",
expected: m * 2,
got: e.len() * 2,
});
}
Some(e) => e,
None => size
.iter()
.map(|&s| [0.0, (s.saturating_sub(1)) as f64])
.collect(),
};
let decode = match pairs(view, dict, b"Decode")? {
Some(d) if d.len() != n => {
return Err(FunctionError::BadArrayLength {
key: "Decode",
expected: n * 2,
got: d.len() * 2,
});
}
Some(d) => d,
None => range.to_vec(),
};
let order = entry(view, dict, b"Order")
.and_then(Object::as_int)
.unwrap_or(1);
if order != 1 && order != 3 {
return Err(FunctionError::BadEntry {
key: "Order",
detail: format!("{order} is not 1 (linear) or 3 (cubic spline)"),
});
}
let order3_downgraded = order == 3 && size.iter().any(|&s| s >= 4);
Ok(Sampled {
size,
strides,
bits_per_sample,
max_sample: (2f64).powi(bits_per_sample as i32) - 1.0,
encode,
decode,
samples,
order3_downgraded,
})
}
struct Axis {
lower: usize,
upper: usize,
frac: f64,
stride: usize,
}
impl Sampled {
fn eval(
&self,
domain: &[[f64; 2]],
inputs: &[f64],
out: &mut Vec<f64>,
) -> Result<(), FunctionError> {
let n = self.decode.len();
let mut axes: Vec<Axis> = Vec::with_capacity(self.size.len());
for (((&x, dom), enc), (&size, &stride)) in inputs
.iter()
.zip(domain.iter())
.zip(self.encode.iter())
.zip(self.size.iter().zip(self.strides.iter()))
{
let top = size.saturating_sub(1);
let top_f = top as f64;
let e = clip(interpolate(x, dom[0], dom[1], enc[0], enc[1]), 0.0, top_f);
let floor = e.floor();
let lower = (floor as usize).min(top);
axes.push(Axis {
lower,
upper: (lower + 1).min(top),
frac: e - floor,
stride,
});
}
let mut acc = vec![0.0f64; n];
let corners = 1usize << axes.len();
for corner in 0..corners {
let mut weight = 1.0f64;
let mut flat = 0usize;
for (i, axis) in axes.iter().enumerate() {
let take_upper = (corner >> i) & 1 == 1;
let (index, w) = if take_upper {
(axis.upper, axis.frac)
} else {
(axis.lower, 1.0 - axis.frac)
};
weight *= w;
flat = flat.saturating_add(index.saturating_mul(axis.stride));
}
if weight == 0.0 {
continue;
}
for (j, slot) in acc.iter_mut().enumerate() {
*slot += weight * self.sample(flat, j, n)?;
}
}
for (raw, dec) in acc.into_iter().zip(self.decode.iter()) {
out.push(interpolate(raw, 0.0, self.max_sample, dec[0], dec[1]));
}
Ok(())
}
fn sample(&self, flat: usize, j: usize, n: usize) -> Result<f64, FunctionError> {
let index = flat
.checked_mul(n)
.and_then(|base| base.checked_add(j))
.ok_or(FunctionError::SampleIndexOutOfRange { index: flat })?;
let bit_offset = index
.checked_mul(self.bits_per_sample as usize)
.ok_or(FunctionError::SampleIndexOutOfRange { index })?;
let raw = read_bits(&self.samples, bit_offset, self.bits_per_sample)
.ok_or(FunctionError::SampleIndexOutOfRange { index })?;
Ok(raw as f64)
}
}
fn read_bits(data: &[u8], offset: usize, bits: u32) -> Option<u64> {
let bits_usize = bits as usize;
let end = offset.checked_add(bits_usize)?;
if end > data.len().checked_mul(8)? {
return None;
}
if bits.is_multiple_of(8) && offset.is_multiple_of(8) {
let start = offset / 8;
let stop = end / 8;
let mut acc: u64 = 0;
for &byte in data.get(start..stop)? {
acc = (acc << 8) | u64::from(byte);
}
return Some(acc);
}
let mut acc: u64 = 0;
for i in 0..bits_usize {
let bit_index = offset.checked_add(i)?;
let byte = *data.get(bit_index / 8)?;
let shift = 7 - (bit_index % 8);
acc = (acc << 1) | u64::from((byte >> shift) & 1);
}
Some(acc)
}
#[derive(Debug, Clone, PartialEq)]
struct Exponential {
c0: Vec<f64>,
c1: Vec<f64>,
n: f64,
}
fn load_exponential(
view: &DocumentView<'_>,
dict: &Dict,
domain: &[[f64; 2]],
) -> Result<Exponential, FunctionError> {
if domain.len() != 1 {
return Err(FunctionError::NotOneInput {
function_type: 2,
got: domain.len(),
});
}
let bounds = domain.first().copied().unwrap_or([0.0, 1.0]);
let exponent =
entry(view, dict, b"N")
.and_then(Object::as_number)
.ok_or(FunctionError::MissingEntry {
key: "N",
function_type: 2,
})?;
if !exponent.is_finite() {
return Err(FunctionError::BadEntry {
key: "N",
detail: "not finite".to_owned(),
});
}
let c0 = numbers(view, dict, "C0")?.unwrap_or_else(|| vec![0.0]);
let c1 = numbers(view, dict, "C1")?.unwrap_or_else(|| vec![1.0]);
if c0.is_empty() {
return Err(FunctionError::BadEntry {
key: "C0",
detail: "empty".to_owned(),
});
}
if c0.len() != c1.len() {
return Err(FunctionError::BadArrayLength {
key: "C1",
expected: c0.len(),
got: c1.len(),
});
}
if exponent.fract() != 0.0 && bounds[0] < 0.0 {
return Err(FunctionError::DomainIncompatibleWithExponent {
n: exponent,
low: bounds[0],
high: bounds[1],
});
}
if exponent < 0.0 && bounds[0] <= 0.0 && bounds[1] >= 0.0 {
return Err(FunctionError::DomainIncompatibleWithExponent {
n: exponent,
low: bounds[0],
high: bounds[1],
});
}
Ok(Exponential {
c0,
c1,
n: exponent,
})
}
impl Exponential {
fn eval(&self, inputs: &[f64], out: &mut Vec<f64>) {
let x = inputs.first().copied().unwrap_or(0.0);
let xn = if self.n.fract() == 0.0 && self.n.abs() <= f64::from(i32::MAX) {
x.powi(self.n as i32)
} else {
x.powf(self.n)
};
for (a, b) in self.c0.iter().zip(self.c1.iter()) {
out.push(a + xn * (b - a));
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct Stitching {
functions: Vec<PdfFunction>,
bounds: Vec<f64>,
encode: Vec<[f64; 2]>,
outputs: usize,
}
fn load_stitching(
view: &DocumentView<'_>,
dict: &Dict,
domain: &[[f64; 2]],
range: Option<&[[f64; 2]]>,
depth: usize,
) -> Result<Stitching, FunctionError> {
if domain.len() != 1 {
return Err(FunctionError::NotOneInput {
function_type: 3,
got: domain.len(),
});
}
let bounds_of_domain = domain.first().copied().unwrap_or([0.0, 1.0]);
let entries: Vec<Object> = entry(view, dict, b"Functions")
.and_then(Object::as_array)
.ok_or(FunctionError::MissingEntry {
key: "Functions",
function_type: 3,
})?
.to_vec();
if entries.is_empty() {
return Err(FunctionError::NoSubFunctions);
}
let mut functions = Vec::with_capacity(entries.len());
let mut outputs = 0usize;
for (index, sub) in entries.iter().enumerate() {
let f = PdfFunction::load_at_depth(view, sub, depth + 1)?;
if f.inputs() != 1 {
return Err(FunctionError::BadEntry {
key: "Functions",
detail: format!(
"sub-function {index} takes {} inputs; stitching sub-functions take one",
f.inputs()
),
});
}
if index == 0 {
outputs = f.outputs();
} else if f.outputs() != outputs {
return Err(FunctionError::SubFunctionArity {
index,
expected: outputs,
got: f.outputs(),
});
}
functions.push(f);
}
let k = functions.len();
if let Some(r) = range
&& r.len() != outputs
{
return Err(FunctionError::BadArrayLength {
key: "Range",
expected: outputs * 2,
got: r.len() * 2,
});
}
let bounds = numbers(view, dict, "Bounds")?.ok_or(FunctionError::MissingEntry {
key: "Bounds",
function_type: 3,
})?;
if bounds.len() + 1 != k {
return Err(FunctionError::BadArrayLength {
key: "Bounds",
expected: k - 1,
got: bounds.len(),
});
}
let mut previous = f64::NEG_INFINITY;
for (i, &b) in bounds.iter().enumerate() {
if b < previous {
return Err(FunctionError::BadBounds {
detail: format!(
"element {i} ({b}) is less than element {} ({previous})",
i - 1
),
});
}
if b < bounds_of_domain[0] || b > bounds_of_domain[1] {
return Err(FunctionError::BadBounds {
detail: format!(
"element {i} ({b}) is outside /Domain [{}, {}]",
bounds_of_domain[0], bounds_of_domain[1]
),
});
}
previous = b;
}
let encode = pairs(view, dict, b"Encode")?.ok_or(FunctionError::MissingEntry {
key: "Encode",
function_type: 3,
})?;
if encode.len() != k {
return Err(FunctionError::BadArrayLength {
key: "Encode",
expected: k * 2,
got: encode.len() * 2,
});
}
Ok(Stitching {
functions,
bounds,
encode,
outputs,
})
}
impl Stitching {
fn select(&self, x: f64) -> usize {
self.bounds
.iter()
.filter(|&&b| x >= b)
.count()
.min(self.functions.len().saturating_sub(1))
}
fn eval(
&self,
domain: &[[f64; 2]],
inputs: &[f64],
out: &mut Vec<f64>,
) -> Result<(), FunctionError> {
let bounds_of_domain = domain.first().copied().unwrap_or([0.0, 1.0]);
let x = inputs.first().copied().unwrap_or(0.0);
let i = self.select(x);
let low = if i == 0 {
bounds_of_domain[0]
} else {
self.bounds
.get(i - 1)
.copied()
.unwrap_or(bounds_of_domain[0])
};
let high = self.bounds.get(i).copied().unwrap_or(bounds_of_domain[1]);
let enc = self.encode.get(i).copied().unwrap_or([0.0, 1.0]);
let encoded = interpolate(x, low, high, enc[0], enc[1]);
let Some(f) = self.functions.get(i) else {
return Err(FunctionError::NoSubFunctions);
};
f.eval_into(&[encoded], out)
}
}
#[derive(Debug, Clone, PartialEq)]
struct PostScript {
program: Vec<PsOp>,
outputs: usize,
}
#[derive(Debug, Clone, PartialEq)]
enum PsOp {
Push(PsValue),
Op(PsOperator),
If(Vec<PsOp>),
IfElse(Vec<PsOp>, Vec<PsOp>),
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum PsValue {
Int(i32),
Real(f64),
Bool(bool),
}
impl PsValue {
fn as_number(self) -> Option<f64> {
match self {
Self::Int(i) => Some(f64::from(i)),
Self::Real(r) => Some(r),
Self::Bool(_) => None,
}
}
fn as_bool(self) -> Option<bool> {
match self {
Self::Bool(b) => Some(b),
Self::Int(_) | Self::Real(_) => None,
}
}
fn as_int(self) -> Option<i32> {
match self {
Self::Int(i) => Some(i),
Self::Real(_) | Self::Bool(_) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum PsOperator {
Abs,
Add,
Atan,
Ceiling,
Cos,
Cvi,
Cvr,
Div,
Exp,
Floor,
Idiv,
Ln,
Log,
Mod,
Mul,
Neg,
Round,
Sin,
Sqrt,
Sub,
Truncate,
And,
Bitshift,
Eq,
Ge,
Gt,
Le,
Lt,
Ne,
Not,
Or,
Xor,
Copy,
Dup,
Exch,
Index,
Pop,
Roll,
}
impl PsOperator {
fn from_token(name: &[u8]) -> Option<Self> {
Some(match name {
b"abs" => Self::Abs,
b"add" => Self::Add,
b"atan" => Self::Atan,
b"ceiling" => Self::Ceiling,
b"cos" => Self::Cos,
b"cvi" => Self::Cvi,
b"cvr" => Self::Cvr,
b"div" => Self::Div,
b"exp" => Self::Exp,
b"floor" => Self::Floor,
b"idiv" => Self::Idiv,
b"ln" => Self::Ln,
b"log" => Self::Log,
b"mod" => Self::Mod,
b"mul" => Self::Mul,
b"neg" => Self::Neg,
b"round" => Self::Round,
b"sin" => Self::Sin,
b"sqrt" => Self::Sqrt,
b"sub" => Self::Sub,
b"truncate" => Self::Truncate,
b"and" => Self::And,
b"bitshift" => Self::Bitshift,
b"eq" => Self::Eq,
b"ge" => Self::Ge,
b"gt" => Self::Gt,
b"le" => Self::Le,
b"lt" => Self::Lt,
b"ne" => Self::Ne,
b"not" => Self::Not,
b"or" => Self::Or,
b"xor" => Self::Xor,
b"copy" => Self::Copy,
b"dup" => Self::Dup,
b"exch" => Self::Exch,
b"index" => Self::Index,
b"pop" => Self::Pop,
b"roll" => Self::Roll,
_ => return None,
})
}
const fn name(self) -> &'static str {
match self {
Self::Abs => "abs",
Self::Add => "add",
Self::Atan => "atan",
Self::Ceiling => "ceiling",
Self::Cos => "cos",
Self::Cvi => "cvi",
Self::Cvr => "cvr",
Self::Div => "div",
Self::Exp => "exp",
Self::Floor => "floor",
Self::Idiv => "idiv",
Self::Ln => "ln",
Self::Log => "log",
Self::Mod => "mod",
Self::Mul => "mul",
Self::Neg => "neg",
Self::Round => "round",
Self::Sin => "sin",
Self::Sqrt => "sqrt",
Self::Sub => "sub",
Self::Truncate => "truncate",
Self::And => "and",
Self::Bitshift => "bitshift",
Self::Eq => "eq",
Self::Ge => "ge",
Self::Gt => "gt",
Self::Le => "le",
Self::Lt => "lt",
Self::Ne => "ne",
Self::Not => "not",
Self::Or => "or",
Self::Xor => "xor",
Self::Copy => "copy",
Self::Dup => "dup",
Self::Exch => "exch",
Self::Index => "index",
Self::Pop => "pop",
Self::Roll => "roll",
}
}
}
fn load_postscript(
view: &DocumentView<'_>,
resolved: &Object,
domain: &[[f64; 2]],
range: Option<&[[f64; 2]]>,
) -> Result<PostScript, FunctionError> {
let Object::Stream(stream) = resolved else {
return Err(FunctionError::NotAStream { function_type: 4 });
};
let _ = domain;
let range = range.ok_or(FunctionError::MissingEntry {
key: "Range",
function_type: 4,
})?;
let source = stream_bytes(view, stream)?;
let program = parse_program(&source)?;
Ok(PostScript {
program,
outputs: range.len(),
})
}
fn parse_program(source: &[u8]) -> Result<Vec<PsOp>, FunctionError> {
let mut lexer = Lexer::new(source);
let Some(first) = lexer.next_token()? else {
return Err(FunctionError::PostScriptSyntax {
detail: "the program stream is empty".to_owned(),
});
};
if first.kind != TokenKind::BraceOpen {
return Err(FunctionError::PostScriptSyntax {
detail: "the program is not enclosed in braces (§7.10.5.1 requires `{ … }`)".to_owned(),
});
}
let block = parse_block(&mut lexer, source, 1)?;
if let Some(extra) = lexer.next_token()? {
return Err(FunctionError::PostScriptSyntax {
detail: format!(
"trailing content after the closing brace, starting at byte {}",
extra.span.start
),
});
}
Ok(block)
}
fn parse_block(
lexer: &mut Lexer<'_>,
source: &[u8],
depth: usize,
) -> Result<Vec<PsOp>, FunctionError> {
if depth > MAX_PS_NESTING {
return Err(FunctionError::PostScriptNestingTooDeep {
limit: MAX_PS_NESTING,
});
}
let mut ops: Vec<PsOp> = Vec::new();
let mut pending: Vec<Vec<PsOp>> = Vec::new();
loop {
let Some(token) = lexer.next_token()? else {
return Err(FunctionError::PostScriptSyntax {
detail: "end of stream inside a `{ … }` block".to_owned(),
});
};
match token.kind {
TokenKind::BraceClose => {
reject_pending(&pending)?;
return Ok(ops);
}
TokenKind::BraceOpen => {
if pending.len() >= 2 {
return Err(FunctionError::PostScriptSyntax {
detail: "more than two consecutive `{ … }` blocks; `ifelse` takes two"
.to_owned(),
});
}
let nested = parse_block(lexer, source, depth + 1)?;
pending.push(nested);
}
TokenKind::Integer(v) => {
reject_pending(&pending)?;
let Ok(i) = i32::try_from(v) else {
return Err(FunctionError::PostScriptSyntax {
detail: format!("integer literal {v} does not fit a 32-bit integer"),
});
};
ops.push(PsOp::Push(PsValue::Int(i)));
}
TokenKind::Real(v) => {
reject_pending(&pending)?;
if !v.is_finite() {
return Err(FunctionError::PostScriptSyntax {
detail: format!("real literal {v} is not finite"),
});
}
ops.push(PsOp::Push(PsValue::Real(v)));
}
TokenKind::Keyword => {
let name = token.lexeme(source).unwrap_or(b"");
match name {
b"true" | b"false" => {
reject_pending(&pending)?;
ops.push(PsOp::Push(PsValue::Bool(name == b"true")));
}
b"if" => {
if pending.len() != 1 {
return Err(FunctionError::PostScriptSyntax {
detail: format!(
"`if` needs exactly one preceding `{{ … }}` block; found {}",
pending.len()
),
});
}
let then_block = pending.pop().unwrap_or_default();
ops.push(PsOp::If(then_block));
}
b"ifelse" => {
if pending.len() != 2 {
return Err(FunctionError::PostScriptSyntax {
detail: format!(
"`ifelse` needs exactly two preceding `{{ … }}` blocks; found {}",
pending.len()
),
});
}
let else_block = pending.pop().unwrap_or_default();
let then_block = pending.pop().unwrap_or_default();
ops.push(PsOp::IfElse(then_block, else_block));
}
other => {
reject_pending(&pending)?;
let op = PsOperator::from_token(other).ok_or_else(|| {
FunctionError::UnknownOperator(
String::from_utf8_lossy(other).into_owned(),
)
})?;
ops.push(PsOp::Op(op));
}
}
}
other => {
return Err(FunctionError::PostScriptSyntax {
detail: format!(
"{other:?} at byte {} has no meaning in a type 4 program \
(§7.10.5.1 allows numbers, booleans, operators and braces only)",
token.span.start
),
});
}
}
}
}
fn reject_pending(pending: &[Vec<PsOp>]) -> Result<(), FunctionError> {
if pending.is_empty() {
Ok(())
} else {
Err(FunctionError::PostScriptSyntax {
detail: "a `{ … }` block must be followed immediately by `if` or `ifelse`".to_owned(),
})
}
}
#[derive(Debug)]
struct PsStack {
values: Vec<PsValue>,
}
impl PsStack {
fn new() -> Self {
Self {
values: Vec::with_capacity(PS_STACK_LIMIT),
}
}
fn push(&mut self, value: PsValue) -> Result<(), FunctionError> {
if self.values.len() >= PS_STACK_LIMIT {
return Err(FunctionError::StackOverflow {
limit: PS_STACK_LIMIT,
});
}
self.values.push(value);
Ok(())
}
fn pop(&mut self, op: &'static str) -> Result<PsValue, FunctionError> {
self.values.pop().ok_or(FunctionError::StackUnderflow {
op,
needed: 1,
had: 0,
})
}
fn pop2(&mut self, op: &'static str) -> Result<(PsValue, PsValue), FunctionError> {
if self.values.len() < 2 {
return Err(FunctionError::StackUnderflow {
op,
needed: 2,
had: self.values.len(),
});
}
let second = self.values.pop().ok_or(FunctionError::StackUnderflow {
op,
needed: 2,
had: 0,
})?;
let first = self.values.pop().ok_or(FunctionError::StackUnderflow {
op,
needed: 2,
had: 1,
})?;
Ok((first, second))
}
fn pop_number(&mut self, op: &'static str) -> Result<f64, FunctionError> {
self.pop(op)?
.as_number()
.ok_or(FunctionError::PostScriptType {
op,
detail: "expected a number, found a boolean",
})
}
fn pop2_numbers(&mut self, op: &'static str) -> Result<(f64, f64), FunctionError> {
let (a, b) = self.pop2(op)?;
let ty = FunctionError::PostScriptType {
op,
detail: "expected two numbers, found a boolean",
};
Ok((
a.as_number().ok_or_else(|| ty.clone())?,
b.as_number().ok_or(ty)?,
))
}
fn pop_int(&mut self, op: &'static str) -> Result<i32, FunctionError> {
self.pop(op)?.as_int().ok_or(FunctionError::PostScriptType {
op,
detail: "expected an integer; reals and booleans are not accepted here",
})
}
fn pop_count(&mut self, op: &'static str) -> Result<usize, FunctionError> {
let n = self.pop_int(op)?;
usize::try_from(n).map_err(|_| FunctionError::PostScriptRange {
op,
detail: "the count operand is negative",
})
}
fn len(&self) -> usize {
self.values.len()
}
}
impl PostScript {
fn eval(&self, inputs: &[f64], out: &mut Vec<f64>) -> Result<(), FunctionError> {
let mut stack = PsStack::new();
for &x in inputs {
stack.push(PsValue::Real(x))?;
}
let mut steps = 0usize;
exec_block(&self.program, &mut stack, &mut steps)?;
if stack.len() != self.outputs {
return Err(FunctionError::OutputArity {
expected: self.outputs,
got: stack.len(),
});
}
for (index, value) in stack.values.iter().enumerate() {
let Some(v) = value.as_number() else {
return Err(FunctionError::NonNumericOutput { index });
};
out.push(v);
}
Ok(())
}
}
fn exec_block(ops: &[PsOp], stack: &mut PsStack, steps: &mut usize) -> Result<(), FunctionError> {
for op in ops {
*steps += 1;
if *steps > MAX_PS_STEPS {
return Err(FunctionError::StepLimit {
limit: MAX_PS_STEPS,
});
}
match op {
PsOp::Push(v) => stack.push(*v)?,
PsOp::Op(o) => apply(*o, stack)?,
PsOp::If(then_block) => {
let cond = stack.pop("if")?;
let Some(b) = cond.as_bool() else {
return Err(FunctionError::PostScriptType {
op: "if",
detail: "the condition operand is not a boolean",
});
};
if b {
exec_block(then_block, stack, steps)?;
}
}
PsOp::IfElse(then_block, else_block) => {
let cond = stack.pop("ifelse")?;
let Some(b) = cond.as_bool() else {
return Err(FunctionError::PostScriptType {
op: "ifelse",
detail: "the condition operand is not a boolean",
});
};
if b {
exec_block(then_block, stack, steps)?;
} else {
exec_block(else_block, stack, steps)?;
}
}
}
}
Ok(())
}
pub const PS_INTEGER_BITS: u32 = 32;
const fn type_err(op: &'static str, detail: &'static str) -> FunctionError {
FunctionError::PostScriptType { op, detail }
}
const fn range_err(op: &'static str, detail: &'static str) -> FunctionError {
FunctionError::PostScriptRange { op, detail }
}
const fn undefined(op: &'static str, detail: &'static str) -> FunctionError {
FunctionError::UndefinedResult { op, detail }
}
fn arith(
op: &'static str,
a: PsValue,
b: PsValue,
int_op: fn(i32, i32) -> Option<i32>,
real_op: fn(f64, f64) -> f64,
) -> Result<PsValue, FunctionError> {
if let (PsValue::Int(x), PsValue::Int(y)) = (a, b) {
return Ok(match int_op(x, y) {
Some(v) => PsValue::Int(v),
None => PsValue::Real(real_op(f64::from(x), f64::from(y))),
});
}
let detail = "expected two numbers, found a boolean";
let x = a.as_number().ok_or(type_err(op, detail))?;
let y = b.as_number().ok_or(type_err(op, detail))?;
Ok(PsValue::Real(real_op(x, y)))
}
fn round_like(
op: &'static str,
v: PsValue,
real_op: fn(f64) -> f64,
) -> Result<PsValue, FunctionError> {
match v {
PsValue::Int(i) => Ok(PsValue::Int(i)),
PsValue::Real(r) => Ok(PsValue::Real(real_op(r))),
PsValue::Bool(_) => Err(type_err(op, "expected a number, found a boolean")),
}
}
fn round_half_up(x: f64) -> f64 {
(x + 0.5).floor()
}
fn apply(op: PsOperator, stack: &mut PsStack) -> Result<(), FunctionError> {
use PsOperator as O;
let name = op.name();
match op {
O::Add => {
let (a, b) = stack.pop2(name)?;
let v = arith(name, a, b, i32::checked_add, |x, y| x + y)?;
stack.push(v)?;
}
O::Sub => {
let (a, b) = stack.pop2(name)?;
let v = arith(name, a, b, i32::checked_sub, |x, y| x - y)?;
stack.push(v)?;
}
O::Mul => {
let (a, b) = stack.pop2(name)?;
let v = arith(name, a, b, i32::checked_mul, |x, y| x * y)?;
stack.push(v)?;
}
O::Div => {
let (a, b) = stack.pop2_numbers(name)?;
if b == 0.0 {
return Err(undefined(name, "division by zero"));
}
stack.push(PsValue::Real(a / b))?;
}
O::Idiv => {
let (a, b) = stack.pop2(name)?;
let (x, y) = (int_operand(name, a)?, int_operand(name, b)?);
let q = x
.checked_div(y)
.ok_or(undefined(name, "division by zero, or i32::MIN / -1"))?;
stack.push(PsValue::Int(q))?;
}
O::Mod => {
let (a, b) = stack.pop2(name)?;
let (x, y) = (int_operand(name, a)?, int_operand(name, b)?);
let r = x
.checked_rem(y)
.ok_or(undefined(name, "division by zero, or i32::MIN % -1"))?;
stack.push(PsValue::Int(r))?;
}
O::Neg => {
let v = stack.pop(name)?;
let r = match v {
PsValue::Int(i) => i
.checked_neg()
.map_or_else(|| PsValue::Real(-f64::from(i)), PsValue::Int),
PsValue::Real(r) => PsValue::Real(-r),
PsValue::Bool(_) => {
return Err(type_err(name, "expected a number, found a boolean"));
}
};
stack.push(r)?;
}
O::Abs => {
let v = stack.pop(name)?;
let r = match v {
PsValue::Int(i) => i
.checked_abs()
.map_or_else(|| PsValue::Real(f64::from(i).abs()), PsValue::Int),
PsValue::Real(r) => PsValue::Real(r.abs()),
PsValue::Bool(_) => {
return Err(type_err(name, "expected a number, found a boolean"));
}
};
stack.push(r)?;
}
O::Ceiling => {
let v = stack.pop(name)?;
let r = round_like(name, v, f64::ceil)?;
stack.push(r)?;
}
O::Floor => {
let v = stack.pop(name)?;
let r = round_like(name, v, f64::floor)?;
stack.push(r)?;
}
O::Round => {
let v = stack.pop(name)?;
let r = round_like(name, v, round_half_up)?;
stack.push(r)?;
}
O::Truncate => {
let v = stack.pop(name)?;
let r = round_like(name, v, f64::trunc)?;
stack.push(r)?;
}
O::Sqrt => {
let x = stack.pop_number(name)?;
if x < 0.0 {
return Err(range_err(name, "sqrt of a negative number"));
}
stack.push(PsValue::Real(x.sqrt()))?;
}
O::Sin => {
let x = stack.pop_number(name)?;
stack.push(PsValue::Real(x.to_radians().sin()))?;
}
O::Cos => {
let x = stack.pop_number(name)?;
stack.push(PsValue::Real(x.to_radians().cos()))?;
}
O::Atan => {
let (num, den) = stack.pop2_numbers(name)?;
if num == 0.0 && den == 0.0 {
return Err(undefined(name, "atan of 0 over 0"));
}
let degrees = num.atan2(den).to_degrees();
let normalised = if degrees < 0.0 {
degrees + 360.0
} else {
degrees + 0.0
};
stack.push(PsValue::Real(normalised))?;
}
O::Exp => {
let (base, exponent) = stack.pop2_numbers(name)?;
let r = base.powf(exponent);
if !r.is_finite() {
return Err(undefined(name, "exp has no finite result"));
}
stack.push(PsValue::Real(r))?;
}
O::Ln => {
let x = stack.pop_number(name)?;
if x <= 0.0 {
return Err(range_err(name, "ln of a non-positive number"));
}
stack.push(PsValue::Real(x.ln()))?;
}
O::Log => {
let x = stack.pop_number(name)?;
if x <= 0.0 {
return Err(range_err(name, "log of a non-positive number"));
}
stack.push(PsValue::Real(x.log10()))?;
}
O::Cvi => {
let x = stack.pop_number(name)?;
let truncated = x.trunc();
if !truncated.is_finite()
|| truncated < f64::from(i32::MIN)
|| truncated > f64::from(i32::MAX)
{
return Err(range_err(name, "value is outside the integer range"));
}
stack.push(PsValue::Int(truncated as i32))?;
}
O::Cvr => {
let x = stack.pop_number(name)?;
stack.push(PsValue::Real(x))?;
}
O::Eq => {
let (a, b) = stack.pop2(name)?;
stack.push(PsValue::Bool(ps_equal(a, b)))?;
}
O::Ne => {
let (a, b) = stack.pop2(name)?;
stack.push(PsValue::Bool(!ps_equal(a, b)))?;
}
O::Gt => {
let (a, b) = stack.pop2_numbers(name)?;
stack.push(PsValue::Bool(a > b))?;
}
O::Ge => {
let (a, b) = stack.pop2_numbers(name)?;
stack.push(PsValue::Bool(a >= b))?;
}
O::Lt => {
let (a, b) = stack.pop2_numbers(name)?;
stack.push(PsValue::Bool(a < b))?;
}
O::Le => {
let (a, b) = stack.pop2_numbers(name)?;
stack.push(PsValue::Bool(a <= b))?;
}
O::And => {
let (a, b) = stack.pop2(name)?;
let r = logical(name, a, b, |x, y| x && y, |x, y| x & y)?;
stack.push(r)?;
}
O::Or => {
let (a, b) = stack.pop2(name)?;
let r = logical(name, a, b, |x, y| x || y, |x, y| x | y)?;
stack.push(r)?;
}
O::Xor => {
let (a, b) = stack.pop2(name)?;
let r = logical(name, a, b, |x, y| x != y, |x, y| x ^ y)?;
stack.push(r)?;
}
O::Not => {
let v = stack.pop(name)?;
let r = match v {
PsValue::Bool(b) => PsValue::Bool(!b),
PsValue::Int(i) => PsValue::Int(!i),
PsValue::Real(_) => {
return Err(type_err(
name,
"expected a boolean or an integer, found a real",
));
}
};
stack.push(r)?;
}
O::Bitshift => {
let (a, s) = stack.pop2(name)?;
let value = int_operand(name, a)?.cast_unsigned();
let shift = int_operand(name, s)?;
let width = PS_INTEGER_BITS;
let shifted = if shift >= 0 {
let by = u32::try_from(shift).unwrap_or(width);
if by >= width { 0 } else { value << by }
} else {
let by = shift
.checked_neg()
.and_then(|m| u32::try_from(m).ok())
.unwrap_or(width);
if by >= width { 0 } else { value >> by }
};
stack.push(PsValue::Int(shifted.cast_signed()))?;
}
O::Pop => {
stack.pop(name)?;
}
O::Exch => {
let (a, b) = stack.pop2(name)?;
stack.push(b)?;
stack.push(a)?;
}
O::Dup => {
let top = *stack.values.last().ok_or(FunctionError::StackUnderflow {
op: name,
needed: 1,
had: 0,
})?;
stack.push(top)?;
}
O::Copy => {
let n = stack.pop_count(name)?;
if n > 0 {
let start = stack
.len()
.checked_sub(n)
.ok_or(range_err(name, "count exceeds the stack depth"))?;
let duplicated: Vec<PsValue> = stack
.values
.get(start..)
.ok_or(range_err(name, "count exceeds the stack depth"))?
.to_vec();
for v in duplicated {
stack.push(v)?;
}
}
}
O::Index => {
let n = stack.pop_count(name)?;
let position = stack
.len()
.checked_sub(1)
.and_then(|top| top.checked_sub(n))
.ok_or(range_err(
name,
"index reaches past the bottom of the stack",
))?;
let v = *stack.values.get(position).ok_or(range_err(
name,
"index reaches past the bottom of the stack",
))?;
stack.push(v)?;
}
O::Roll => {
let j = stack.pop_int(name)?;
let n = stack.pop_count(name)?;
if n > 0 {
let start = stack
.len()
.checked_sub(n)
.ok_or(range_err(name, "count exceeds the stack depth"))?;
let window = i64::try_from(n).unwrap_or(i64::MAX);
let by = i64::from(j).rem_euclid(window);
let by = usize::try_from(by).unwrap_or(0);
stack
.values
.get_mut(start..)
.ok_or(range_err(name, "count exceeds the stack depth"))?
.rotate_right(by);
}
}
}
Ok(())
}
fn int_operand(op: &'static str, v: PsValue) -> Result<i32, FunctionError> {
v.as_int().ok_or(type_err(
op,
"expected an integer; reals and booleans are not accepted here",
))
}
fn ps_equal(a: PsValue, b: PsValue) -> bool {
match (a, b) {
(PsValue::Bool(x), PsValue::Bool(y)) => x == y,
(PsValue::Bool(_), _) | (_, PsValue::Bool(_)) => false,
_ => a.as_number() == b.as_number(),
}
}
fn logical(
op: &'static str,
a: PsValue,
b: PsValue,
bool_op: fn(bool, bool) -> bool,
int_op: fn(i32, i32) -> i32,
) -> Result<PsValue, FunctionError> {
match (a, b) {
(PsValue::Bool(x), PsValue::Bool(y)) => Ok(PsValue::Bool(bool_op(x, y))),
(PsValue::Int(x), PsValue::Int(y)) => Ok(PsValue::Int(int_op(x, y))),
_ => Err(type_err(
op,
"expected two booleans or two integers; mixed and real operands are not accepted",
)),
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
use pdfcer_model::PdfVersion;
use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::{Name, ObjId};
use pdfcer_model::span::ByteSpan;
use std::collections::BTreeMap;
const V17: PdfVersion = PdfVersion { major: 1, minor: 7 };
#[derive(Default)]
struct TestGraph {
objects: BTreeMap<ObjId, Object>,
trailer: Dict,
}
impl ObjectGraph for TestGraph {
fn value(&self, id: ObjId) -> Option<&Object> {
self.objects.get(&id)
}
fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
self.trailer.get(key)
}
}
fn dict(entries: &[(&[u8], Object)]) -> Dict {
let mut d = Dict::new();
for (k, v) in entries {
d.insert(Name::from(*k), v.clone());
}
d
}
fn arr(values: &[f64]) -> Object {
Object::Array(values.iter().map(|&v| Object::Real(v)).collect())
}
fn load_dict(entries: &[(&[u8], Object)]) -> Result<PdfFunction, FunctionError> {
let graph = TestGraph::default();
let view = DocumentView::new(&graph, b"", V17);
PdfFunction::load(&view, &Object::Dict(dict(entries)))
}
fn load_stream(entries: &[(&[u8], Object)], data: &[u8]) -> Result<PdfFunction, FunctionError> {
let graph = TestGraph::default();
let view = DocumentView::new(&graph, data, V17);
let stream = Stream {
dict: dict(entries),
data_span: ByteSpan::new(0, data.len()),
};
PdfFunction::load(&view, &Object::Stream(stream))
}
fn ramp(domain: &[f64], c0: &[f64], c1: &[f64]) -> Object {
Object::Dict(dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(domain)),
(b"N", Object::Integer(1)),
(b"C0", arr(c0)),
(b"C1", arr(c1)),
]))
}
#[track_caller]
fn close(actual: &[f64], expected: &[f64]) {
assert_eq!(
actual.len(),
expected.len(),
"output arity: {actual:?} vs {expected:?}"
);
for (a, e) in actual.iter().zip(expected.iter()) {
assert!(
(a - e).abs() < 1e-9,
"expected {expected:?}, got {actual:?}"
);
}
}
#[test]
fn non_dictionary_object_is_refused() {
let graph = TestGraph::default();
let view = DocumentView::new(&graph, b"", V17);
let err = PdfFunction::load(&view, &Object::Integer(4)).unwrap_err();
assert_eq!(err, FunctionError::NotAFunction);
}
#[test]
fn missing_function_type_is_refused() {
let err = load_dict(&[(b"Domain", arr(&[0.0, 1.0]))]).unwrap_err();
assert_eq!(err, FunctionError::MissingFunctionType);
}
#[test]
fn function_type_one_is_unknown_like_any_other() {
for t in [1i64, 5, -3] {
let err = load_dict(&[
(b"FunctionType", Object::Integer(t)),
(b"Domain", arr(&[0.0, 1.0])),
])
.unwrap_err();
assert_eq!(err, FunctionError::UnknownFunctionType(t));
}
}
#[test]
fn missing_domain_is_refused() {
let err = load_dict(&[(b"FunctionType", Object::Integer(2))]).unwrap_err();
assert_eq!(
err,
FunctionError::MissingEntry {
key: "Domain",
function_type: 2
}
);
}
#[test]
fn odd_length_domain_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0, 2.0])),
])
.unwrap_err();
assert!(matches!(err, FunctionError::BadEntry { key: "Domain", .. }));
}
#[test]
fn inverted_domain_pair_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[1.0, 0.0])),
(b"N", Object::Integer(1)),
])
.unwrap_err();
assert!(matches!(
err,
FunctionError::InvertedInterval {
key: "Domain",
index: 0,
..
}
));
}
#[test]
fn range_inconsistent_with_c0_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[0.0, 0.0])),
(b"C1", arr(&[1.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
])
.unwrap_err();
assert!(matches!(
err,
FunctionError::BadArrayLength { key: "Range", .. }
));
}
#[test]
fn inputs_are_clipped_to_domain_at_both_ends() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[10.0])),
(b"C1", arr(&[20.0])),
])
.unwrap();
close(&f.eval(&[-5.0]).unwrap(), &[10.0]);
close(&f.eval(&[5.0]).unwrap(), &[20.0]);
close(&f.eval(&[0.5]).unwrap(), &[15.0]);
}
#[test]
fn outputs_are_clipped_to_range_at_both_ends() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[0.0])),
(b"C1", arr(&[1.0])),
(b"Range", arr(&[0.25, 0.75])),
])
.unwrap();
close(&f.eval(&[0.0]).unwrap(), &[0.25]);
close(&f.eval(&[1.0]).unwrap(), &[0.75]);
close(&f.eval(&[0.5]).unwrap(), &[0.5]);
}
#[test]
fn absent_range_means_no_output_clipping() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[-3.0])),
(b"C1", arr(&[7.0])),
])
.unwrap();
assert!(f.range().is_none());
close(&f.eval(&[0.0]).unwrap(), &[-3.0]);
close(&f.eval(&[1.0]).unwrap(), &[7.0]);
}
#[test]
fn non_finite_input_is_refused_not_clamped() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
])
.unwrap();
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let err = f.eval(&[bad]).unwrap_err();
assert!(matches!(
err,
FunctionError::NonFiniteInput { index: 0, .. }
));
}
}
#[test]
fn input_arity_mismatch_is_refused() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
])
.unwrap();
assert_eq!(
f.eval(&[]).unwrap_err(),
FunctionError::InputArity {
expected: 1,
got: 0
}
);
assert_eq!(
f.eval(&[0.1, 0.2]).unwrap_err(),
FunctionError::InputArity {
expected: 1,
got: 2
}
);
}
#[test]
fn type0_interpolates_between_eight_bit_samples() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0x00, 0xFF],
)
.unwrap();
assert_eq!(f.function_type(), FunctionType::Sampled);
assert_eq!(f.inputs(), 1);
assert_eq!(f.outputs(), 1);
close(&f.eval(&[0.0]).unwrap(), &[0.0]);
close(&f.eval(&[0.25]).unwrap(), &[0.25]);
close(&f.eval(&[1.0]).unwrap(), &[1.0]);
}
#[test]
fn type0_four_bit_samples_pack_two_per_byte_high_nibble_first() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 15.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(4)),
(b"Decode", arr(&[0.0, 15.0])),
],
&[0x05, 0xAF],
)
.unwrap();
close(&f.eval(&[0.0]).unwrap(), &[0.0]); close(&f.eval(&[1.0 / 3.0]).unwrap(), &[5.0]); close(&f.eval(&[2.0 / 3.0]).unwrap(), &[10.0]); close(&f.eval(&[1.0]).unwrap(), &[15.0]); close(&f.eval(&[0.5]).unwrap(), &[7.5]);
}
#[test]
fn type0_twelve_bit_samples_straddle_byte_boundaries() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 4095.0])),
(b"Size", Object::Array(vec![Object::Integer(3)])),
(b"BitsPerSample", Object::Integer(12)),
(b"Decode", arr(&[0.0, 4095.0])),
],
&[0x00, 0x08, 0x00, 0xFF, 0xF0],
)
.unwrap();
close(&f.eval(&[0.0]).unwrap(), &[0.0]);
close(&f.eval(&[0.5]).unwrap(), &[2048.0]);
close(&f.eval(&[1.0]).unwrap(), &[4095.0]);
}
#[test]
fn type0_sixteen_bit_samples_are_big_endian() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 65535.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(16)),
(b"Decode", arr(&[0.0, 65535.0])),
],
&[0x12, 0x34, 0xFF, 0xFF],
)
.unwrap();
close(&f.eval(&[0.0]).unwrap(), &[f64::from(0x1234u32)]);
}
#[test]
fn type0_two_input_bilinear_with_first_dimension_fastest() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(
b"Size",
Object::Array(vec![Object::Integer(2), Object::Integer(2)]),
),
(b"BitsPerSample", Object::Integer(8)),
],
&[0, 51, 102, 204],
)
.unwrap();
assert_eq!(f.inputs(), 2);
close(&f.eval(&[1.0, 0.0]).unwrap(), &[51.0 / 255.0]);
close(&f.eval(&[0.0, 1.0]).unwrap(), &[102.0 / 255.0]);
close(&f.eval(&[1.0, 1.0]).unwrap(), &[204.0 / 255.0]);
close(
&f.eval(&[0.5, 0.5]).unwrap(),
&[(0.0 + 51.0 + 102.0 + 204.0) / 4.0 / 255.0],
);
}
#[test]
fn type0_multi_output_samples_are_adjacent_per_entry() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 255.0, 0.0, 255.0, 0.0, 255.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Decode", arr(&[0.0, 255.0, 0.0, 255.0, 0.0, 255.0])),
],
&[10, 20, 30, 40, 50, 60],
)
.unwrap();
assert_eq!(f.outputs(), 3);
close(&f.eval(&[0.0]).unwrap(), &[10.0, 20.0, 30.0]);
close(&f.eval(&[1.0]).unwrap(), &[40.0, 50.0, 60.0]);
}
#[test]
fn type0_encode_defaults_to_zero_through_size_minus_one() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 3.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Decode", arr(&[0.0, 255.0])),
],
&[0, 1, 2, 3],
)
.unwrap();
close(&f.eval(&[1.0]).unwrap(), &[3.0]);
}
#[test]
fn type0_explicit_encode_can_reverse_the_table() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 255.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Encode", arr(&[3.0, 0.0])),
(b"Decode", arr(&[0.0, 255.0])),
],
&[0, 1, 2, 3],
)
.unwrap();
close(&f.eval(&[0.0]).unwrap(), &[3.0]);
close(&f.eval(&[1.0]).unwrap(), &[0.0]);
}
#[test]
fn type0_decode_defaults_to_range() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 100.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0x00, 0xFF],
)
.unwrap();
close(&f.eval(&[1.0]).unwrap(), &[100.0]);
}
#[test]
fn type0_size_one_axis_maps_every_input_to_the_single_sample() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 255.0])),
(b"Size", Object::Array(vec![Object::Integer(1)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Decode", arr(&[0.0, 255.0])),
],
&[77],
)
.unwrap();
for x in [0.0, 0.5, 1.0] {
close(&f.eval(&[x]).unwrap(), &[77.0]);
}
}
#[test]
fn type0_short_sample_stream_is_refused() {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0x00, 0xFF], )
.unwrap_err();
assert_eq!(err, FunctionError::SampleDataTooShort { need: 4, have: 2 });
}
#[test]
fn type0_invalid_bits_per_sample_is_refused() {
for bad in [0i64, 3, 5, 6, 10, 64] {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(bad)),
],
&[0; 64],
)
.unwrap_err();
assert_eq!(err, FunctionError::BadBitsPerSample(bad));
}
for good in VALID_BITS_PER_SAMPLE {
load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(i64::from(good))),
],
&[0; 64],
)
.unwrap();
}
}
#[test]
fn type0_missing_range_is_refused() {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0x00, 0xFF],
)
.unwrap_err();
assert_eq!(
err,
FunctionError::MissingEntry {
key: "Range",
function_type: 0
}
);
}
#[test]
fn type0_as_a_bare_dictionary_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
])
.unwrap_err();
assert_eq!(err, FunctionError::NotAStream { function_type: 0 });
}
#[test]
fn type0_non_positive_size_is_refused() {
for bad in [0.0, -2.0, 2.5] {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", arr(&[bad])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0; 16],
)
.unwrap_err();
assert!(matches!(err, FunctionError::BadEntry { key: "Size", .. }));
}
}
#[test]
fn type0_size_length_must_match_domain() {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(2)])),
(b"BitsPerSample", Object::Integer(8)),
],
&[0; 16],
)
.unwrap_err();
assert_eq!(
err,
FunctionError::BadArrayLength {
key: "Size",
expected: 2,
got: 1
}
);
}
#[test]
fn type0_excess_input_dimensions_are_refused() {
let m = MAX_SAMPLED_INPUTS + 1;
let domain: Vec<f64> = (0..m).flat_map(|_| [0.0, 1.0]).collect();
let size = Object::Array((0..m).map(|_| Object::Integer(2)).collect());
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&domain)),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", size),
(b"BitsPerSample", Object::Integer(8)),
],
&[0; 4096],
)
.unwrap_err();
assert_eq!(
err,
FunctionError::TooManyInputs {
got: m,
limit: MAX_SAMPLED_INPUTS
}
);
}
#[test]
fn type0_order_three_on_a_large_table_is_disclosed_as_downgraded() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Order", Object::Integer(3)),
],
&[0, 1, 2, 3],
)
.unwrap();
assert!(f.cubic_downgraded());
}
#[test]
fn type0_order_three_below_size_four_is_not_a_downgrade() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(3)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Order", Object::Integer(3)),
],
&[0, 1, 2],
)
.unwrap();
assert!(!f.cubic_downgraded());
}
#[test]
fn type0_unknown_order_is_refused() {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Order", Object::Integer(2)),
],
&[0, 1, 2, 3],
)
.unwrap_err();
assert!(matches!(err, FunctionError::BadEntry { key: "Order", .. }));
}
#[test]
fn read_bits_is_msb_first_at_every_width() {
let data = [0b1010_0110u8, 0b1100_0011, 0xFF, 0x01];
assert_eq!(read_bits(&data, 0, 1), Some(1));
assert_eq!(read_bits(&data, 1, 1), Some(0));
assert_eq!(read_bits(&data, 0, 2), Some(0b10));
assert_eq!(read_bits(&data, 2, 2), Some(0b10));
assert_eq!(read_bits(&data, 0, 4), Some(0b1010));
assert_eq!(read_bits(&data, 4, 4), Some(0b0110));
assert_eq!(read_bits(&data, 0, 8), Some(0b1010_0110));
assert_eq!(read_bits(&data, 0, 12), Some(0b1010_0110_1100));
assert_eq!(read_bits(&data, 12, 12), Some(0b0011_1111_1111));
assert_eq!(read_bits(&data, 0, 16), Some(0b1010_0110_1100_0011));
assert_eq!(read_bits(&data, 0, 24), Some(0x00A6_C3FF));
assert_eq!(read_bits(&data, 0, 32), Some(0xA6C3_FF01));
assert_eq!(read_bits(&data, 32, 1), None);
assert_eq!(read_bits(&data, 24, 16), None);
}
#[test]
fn type2_with_n_one_is_a_linear_ramp() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[0.0, 0.0, 0.0, 0.0])),
(b"C1", arr(&[0.0, 1.0, 0.6, 0.1])),
])
.unwrap();
assert_eq!(f.function_type(), FunctionType::Exponential);
assert_eq!(f.outputs(), 4);
close(&f.eval(&[0.0]).unwrap(), &[0.0, 0.0, 0.0, 0.0]);
close(&f.eval(&[0.5]).unwrap(), &[0.0, 0.5, 0.3, 0.05]);
close(&f.eval(&[1.0]).unwrap(), &[0.0, 1.0, 0.6, 0.1]);
}
#[test]
fn type2_applies_the_exponent_to_x_not_to_the_result() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(2)),
(b"C0", arr(&[1.0])),
(b"C1", arr(&[5.0])),
])
.unwrap();
close(&f.eval(&[0.5]).unwrap(), &[2.0]);
}
#[test]
fn type2_c0_and_c1_default_to_one_element_arrays() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
])
.unwrap();
assert_eq!(f.outputs(), 1);
close(&f.eval(&[0.3]).unwrap(), &[0.3]);
}
#[test]
fn type2_multi_input_domain_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
(b"N", Object::Integer(1)),
])
.unwrap_err();
assert_eq!(
err,
FunctionError::NotOneInput {
function_type: 2,
got: 2
}
);
}
#[test]
fn type2_negative_exponent_with_zero_in_domain_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Real(-1.0)),
])
.unwrap_err();
assert!(matches!(
err,
FunctionError::DomainIncompatibleWithExponent { .. }
));
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[1.0, 2.0])),
(b"N", Object::Real(-1.0)),
(b"C0", arr(&[0.0])),
(b"C1", arr(&[1.0])),
])
.unwrap();
close(&f.eval(&[2.0]).unwrap(), &[0.5]);
}
#[test]
fn type2_fractional_exponent_with_negative_domain_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[-1.0, 1.0])),
(b"N", Object::Real(0.5)),
])
.unwrap_err();
assert!(matches!(
err,
FunctionError::DomainIncompatibleWithExponent { .. }
));
}
#[test]
fn type2_mismatched_c0_c1_lengths_are_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
(b"C0", arr(&[0.0, 0.0, 0.0])),
(b"C1", arr(&[1.0, 1.0])),
])
.unwrap_err();
assert_eq!(
err,
FunctionError::BadArrayLength {
key: "C1",
expected: 3,
got: 2
}
);
}
#[test]
fn type2_missing_exponent_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
])
.unwrap_err();
assert_eq!(
err,
FunctionError::MissingEntry {
key: "N",
function_type: 2
}
);
}
#[test]
fn type3_selects_and_rescales_each_subdomain() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0], &[10.0]),
ramp(&[0.0, 1.0], &[100.0], &[200.0]),
]),
),
(b"Bounds", arr(&[0.5])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
])
.unwrap();
assert_eq!(f.function_type(), FunctionType::Stitching);
assert_eq!(f.outputs(), 1);
close(&f.eval(&[0.0]).unwrap(), &[0.0]);
close(&f.eval(&[0.25]).unwrap(), &[5.0]); close(&f.eval(&[0.75]).unwrap(), &[150.0]); close(&f.eval(&[1.0]).unwrap(), &[200.0]);
}
#[test]
fn type3_exactly_on_a_bound_selects_the_later_subfunction() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[10.0], &[10.0]),
ramp(&[0.0, 1.0], &[20.0], &[20.0]),
]),
),
(b"Bounds", arr(&[0.5])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
])
.unwrap();
close(&f.eval(&[0.499_999]).unwrap(), &[10.0]);
close(&f.eval(&[0.5]).unwrap(), &[20.0]); close(&f.eval(&[0.500_001]).unwrap(), &[20.0]);
close(&f.eval(&[1.0]).unwrap(), &[20.0]);
}
#[test]
fn type3_middle_interval_uses_both_neighbouring_bounds() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 3.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
ramp(&[0.0, 1.0], &[10.0], &[11.0]),
ramp(&[0.0, 1.0], &[20.0], &[21.0]),
]),
),
(b"Bounds", arr(&[1.0, 2.0])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0, 0.0, 1.0])),
])
.unwrap();
close(&f.eval(&[0.5]).unwrap(), &[0.5]);
close(&f.eval(&[1.5]).unwrap(), &[10.5]);
close(&f.eval(&[2.5]).unwrap(), &[20.5]);
}
#[test]
fn type3_single_subfunction_with_reversed_encode_inverts_the_domain() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![ramp(&[0.0, 1.0], &[0.0], &[1.0])]),
),
(b"Bounds", Object::Array(vec![])),
(b"Encode", arr(&[1.0, 0.0])),
])
.unwrap();
close(&f.eval(&[0.25]).unwrap(), &[0.75]);
close(&f.eval(&[0.0]).unwrap(), &[1.0]);
close(&f.eval(&[1.0]).unwrap(), &[0.0]);
}
#[test]
fn type3_last_bound_equal_to_domain_high_uses_encode_low() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 10.0], &[0.0], &[1.0]),
ramp(&[0.0, 10.0], &[0.0], &[1.0]),
]),
),
(b"Bounds", arr(&[1.0])), (b"Encode", arr(&[0.0, 1.0, 5.0, 9.0])),
])
.unwrap();
close(&f.eval(&[1.0]).unwrap(), &[5.0]);
}
#[test]
fn type3_decreasing_bounds_are_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
]),
),
(b"Bounds", arr(&[0.7, 0.3])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0, 0.0, 1.0])),
])
.unwrap_err();
assert!(matches!(err, FunctionError::BadBounds { .. }));
}
#[test]
fn type3_bound_outside_domain_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
]),
),
(b"Bounds", arr(&[1.5])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
])
.unwrap_err();
assert!(matches!(err, FunctionError::BadBounds { .. }));
}
#[test]
fn type3_bounds_length_must_be_k_minus_one() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
]),
),
(b"Bounds", arr(&[0.3, 0.6])), (b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
])
.unwrap_err();
assert_eq!(
err,
FunctionError::BadArrayLength {
key: "Bounds",
expected: 1,
got: 2
}
);
}
#[test]
fn type3_subfunctions_with_different_output_counts_are_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![
ramp(&[0.0, 1.0], &[0.0, 0.0], &[1.0, 1.0]),
ramp(&[0.0, 1.0], &[0.0], &[1.0]),
]),
),
(b"Bounds", arr(&[0.5])),
(b"Encode", arr(&[0.0, 1.0, 0.0, 1.0])),
])
.unwrap_err();
assert_eq!(
err,
FunctionError::SubFunctionArity {
index: 1,
expected: 2,
got: 1
}
);
}
#[test]
fn type3_empty_functions_array_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Functions", Object::Array(vec![])),
(b"Bounds", Object::Array(vec![])),
(b"Encode", Object::Array(vec![])),
])
.unwrap_err();
assert_eq!(err, FunctionError::NoSubFunctions);
}
#[test]
fn type3_multi_input_subfunction_is_refused() {
let two_in = Object::Dict(dict(&[
(b"FunctionType", Object::Integer(4)),
(b"Domain", arr(&[0.0, 1.0, 0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
]));
let err = load_dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Functions", Object::Array(vec![two_in])),
(b"Bounds", Object::Array(vec![])),
(b"Encode", arr(&[0.0, 1.0])),
])
.unwrap_err();
assert_eq!(err, FunctionError::NotAStream { function_type: 4 });
}
#[test]
fn type3_reference_cycle_through_functions_is_depth_limited() {
let self_ref = ObjId::new(1, 0);
let mut objects = BTreeMap::new();
objects.insert(
self_ref,
Object::Dict(dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![Object::Reference(self_ref)]),
),
(b"Bounds", Object::Array(vec![])),
(b"Encode", arr(&[0.0, 1.0])),
])),
);
let graph = TestGraph {
objects,
trailer: Dict::new(),
};
let view = DocumentView::new(&graph, b"", V17);
let err = PdfFunction::load(&view, &Object::Reference(self_ref)).unwrap_err();
assert_eq!(
err,
FunctionError::NestingTooDeep {
limit: MAX_FUNCTION_DEPTH
}
);
}
#[test]
fn type3_reports_a_nested_cubic_downgrade() {
let sampled_id = ObjId::new(2, 0);
let data: &[u8] = &[0, 1, 2, 3];
let mut objects = BTreeMap::new();
objects.insert(
sampled_id,
Object::Stream(Stream {
dict: dict(&[
(b"FunctionType", Object::Integer(0)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
(b"Size", Object::Array(vec![Object::Integer(4)])),
(b"BitsPerSample", Object::Integer(8)),
(b"Order", Object::Integer(3)),
]),
data_span: ByteSpan::new(0, data.len()),
}),
);
let graph = TestGraph {
objects,
trailer: Dict::new(),
};
let view = DocumentView::new(&graph, data, V17);
let stitch = Object::Dict(dict(&[
(b"FunctionType", Object::Integer(3)),
(b"Domain", arr(&[0.0, 1.0])),
(
b"Functions",
Object::Array(vec![Object::Reference(sampled_id)]),
),
(b"Bounds", Object::Array(vec![])),
(b"Encode", arr(&[0.0, 1.0])),
]));
let f = PdfFunction::load(&view, &stitch).unwrap();
assert!(f.cubic_downgraded());
}
#[test]
fn indirect_entries_are_resolved() {
let domain_id = ObjId::new(3, 0);
let n_id = ObjId::new(4, 0);
let mut objects = BTreeMap::new();
objects.insert(domain_id, arr(&[0.0, 1.0]));
objects.insert(n_id, Object::Integer(1));
let graph = TestGraph {
objects,
trailer: Dict::new(),
};
let view = DocumentView::new(&graph, b"", V17);
let f = PdfFunction::load(
&view,
&Object::Dict(dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", Object::Reference(domain_id)),
(b"N", Object::Reference(n_id)),
])),
)
.unwrap();
close(&f.eval(&[0.5]).unwrap(), &[0.5]);
}
#[test]
fn eval_into_clears_the_output_buffer() {
let f = load_dict(&[
(b"FunctionType", Object::Integer(2)),
(b"Domain", arr(&[0.0, 1.0])),
(b"N", Object::Integer(1)),
])
.unwrap();
let mut buf = vec![9.0, 9.0, 9.0];
f.eval_into(&[0.25], &mut buf).unwrap();
close(&buf, &[0.25]);
f.eval_into(&[0.75], &mut buf).unwrap();
close(&buf, &[0.75]);
}
fn load_ps(src: &str, m: usize, n: usize) -> Result<PdfFunction, FunctionError> {
let domain: Vec<f64> = (0..m).flat_map(|_| [0.0, 1.0]).collect();
let range: Vec<f64> = (0..n).flat_map(|_| [-1e300, 1e300]).collect();
load_stream(
&[
(b"FunctionType", Object::Integer(4)),
(b"Domain", arr(&domain)),
(b"Range", arr(&range)),
],
src.as_bytes(),
)
}
fn run_ps(src: &str, x: f64, n: usize) -> Result<Vec<f64>, FunctionError> {
load_ps(src, 1, n)?.eval(&[x])
}
#[test]
fn type4_empty_program_passes_inputs_through_as_outputs() {
let f = load_ps("{ }", 2, 2).unwrap();
close(&f.eval(&[0.25, 0.75]).unwrap(), &[0.25, 0.75]);
}
#[test]
fn type4_output_arity_mismatch_is_refused() {
let err = run_ps("{ }", 0.5, 2).unwrap_err();
assert_eq!(
err,
FunctionError::OutputArity {
expected: 2,
got: 1
}
);
}
#[test]
fn type4_boolean_left_in_output_position_is_refused() {
let err = run_ps("{ true }", 0.5, 2).unwrap_err();
assert_eq!(err, FunctionError::NonNumericOutput { index: 1 });
}
#[test]
fn type4_program_without_enclosing_braces_is_refused() {
let err = load_ps("1 2 add", 1, 1).unwrap_err();
assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
}
#[test]
fn type4_unterminated_program_is_refused() {
let err = load_ps("{ 1 2", 1, 1).unwrap_err();
assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
}
#[test]
fn type4_trailing_content_after_the_program_is_refused() {
let err = load_ps("{ } 5", 1, 1).unwrap_err();
assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
}
#[test]
fn type4_unknown_operator_is_refused_by_name() {
let err = load_ps("{ 2 wibble }", 1, 1).unwrap_err();
assert_eq!(err, FunctionError::UnknownOperator("wibble".to_owned()));
}
#[test]
fn type4_block_not_followed_by_if_or_ifelse_is_refused() {
for src in ["{ { 1 } 2 }", "{ { 1 } }", "{ { 1 } add }"] {
let err = load_ps(src, 1, 1).unwrap_err();
assert!(
matches!(err, FunctionError::PostScriptSyntax { .. }),
"{src} should be a syntax error, got {err:?}"
);
}
}
#[test]
fn type4_wrong_block_count_for_conditionals_is_refused() {
for src in ["{ true { 1 } ifelse }", "{ true { 1 } { 2 } { 3 } ifelse }"] {
let err = load_ps(src, 1, 1).unwrap_err();
assert!(
matches!(err, FunctionError::PostScriptSyntax { .. }),
"{src} should be a syntax error, got {err:?}"
);
}
let err = load_ps("{ true if }", 1, 1).unwrap_err();
assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
}
#[test]
fn type4_excessive_brace_nesting_is_refused() {
let depth = MAX_PS_NESTING + 2;
let src = format!("{}{}", "{ ".repeat(depth), " }".repeat(depth));
let err = load_ps(&src, 1, 1).unwrap_err();
assert_eq!(
err,
FunctionError::PostScriptNestingTooDeep {
limit: MAX_PS_NESTING
}
);
}
#[test]
fn type4_stack_overflow_at_one_hundred_entries_is_refused() {
let src = format!("{{ {} }}", "0 ".repeat(PS_STACK_LIMIT));
let err = run_ps(&src, 0.5, 1).unwrap_err();
assert_eq!(
err,
FunctionError::StackOverflow {
limit: PS_STACK_LIMIT
}
);
let ok = format!("{{ {} }}", "0 ".repeat(PS_STACK_LIMIT - 1));
load_ps(&ok, 1, PS_STACK_LIMIT)
.unwrap()
.eval(&[0.5])
.unwrap();
}
#[test]
fn type4_stack_underflow_is_refused() {
let err = run_ps("{ add add }", 0.5, 1).unwrap_err();
assert!(matches!(err, FunctionError::StackUnderflow { .. }));
}
#[test]
fn type4_missing_range_is_refused() {
let err = load_stream(
&[
(b"FunctionType", Object::Integer(4)),
(b"Domain", arr(&[0.0, 1.0])),
],
b"{ }",
)
.unwrap_err();
assert_eq!(
err,
FunctionError::MissingEntry {
key: "Range",
function_type: 4
}
);
}
#[test]
fn type4_as_a_bare_dictionary_is_refused() {
let err = load_dict(&[
(b"FunctionType", Object::Integer(4)),
(b"Domain", arr(&[0.0, 1.0])),
(b"Range", arr(&[0.0, 1.0])),
])
.unwrap_err();
assert_eq!(err, FunctionError::NotAStream { function_type: 4 });
}
#[test]
fn type4_non_boolean_condition_is_refused() {
let err = run_ps("{ 1 { 2 } if }", 0.5, 1).unwrap_err();
assert_eq!(
err,
FunctionError::PostScriptType {
op: "if",
detail: "the condition operand is not a boolean"
}
);
let err = run_ps("{ 1.5 { 2 } { 3 } ifelse }", 0.5, 1).unwrap_err();
assert!(matches!(
err,
FunctionError::PostScriptType { op: "ifelse", .. }
));
}
#[test]
fn type4_comments_and_irregular_whitespace_are_skipped() {
let f = load_ps("{% leading comment\n\t 1\r\n%another\n}", 1, 2).unwrap();
close(&f.eval(&[0.5]).unwrap(), &[0.5, 1.0]);
}
#[test]
fn type4_step_cap_stops_a_pathologically_long_program() {
let pairs = MAX_PS_STEPS / 2 + 8;
let src = format!("{{ {} }}", "1 pop ".repeat(pairs));
let err = run_ps(&src, 0.5, 1).unwrap_err();
assert_eq!(
err,
FunctionError::StepLimit {
limit: MAX_PS_STEPS
}
);
}
#[test]
fn type4_out_of_range_integer_literal_is_refused() {
let err = load_ps("{ 99999999999 }", 1, 2).unwrap_err();
assert!(matches!(err, FunctionError::PostScriptSyntax { .. }));
}
fn ps(body: &str, n: usize) -> Result<Vec<f64>, FunctionError> {
run_ps(&format!("{{ pop {body} }}"), 0.0, n)
}
#[track_caller]
fn ps_err(body: &str, n: usize) -> FunctionError {
ps(body, n).expect_err("expected a refusal")
}
#[test]
fn type4_ifelse_selects_the_branch_the_condition_names() {
close(&ps("0.6 0.5 gt { 11 } { 22 } ifelse", 1).unwrap(), &[11.0]);
close(&ps("0.4 0.5 gt { 11 } { 22 } ifelse", 1).unwrap(), &[22.0]);
close(&ps("7 true { 1 add } if", 1).unwrap(), &[8.0]);
close(&ps("7 false { 1 add } if", 1).unwrap(), &[7.0]);
close(
&ps(
"3 dup 2 gt { dup 5 gt { 100 } { 200 } ifelse } { 300 } ifelse exch pop",
1,
)
.unwrap(),
&[200.0],
);
}
#[test]
fn type4_evaluates_the_specs_doubledot_example() {
let f = load_stream(
&[
(b"FunctionType", Object::Integer(4)),
(b"Domain", arr(&[-1.0, 1.0, -1.0, 1.0])),
(b"Range", arr(&[-1.0, 1.0])),
],
b"{ 360 mul sin 2 div exch 360 mul sin 2 div add }",
)
.unwrap();
assert_eq!(f.inputs(), 2);
assert_eq!(f.outputs(), 1);
close(&f.eval(&[0.0, 0.0]).unwrap(), &[0.0]);
close(&f.eval(&[0.25, 0.0]).unwrap(), &[0.5]);
close(&f.eval(&[0.25, 0.25]).unwrap(), &[1.0]);
close(&f.eval(&[0.75, 0.0]).unwrap(), &[-0.5]);
}
#[test]
fn type4_sin_and_cos_take_degrees_not_radians() {
close(&ps("90 sin", 1).unwrap(), &[1.0]);
close(&ps("0 cos", 1).unwrap(), &[1.0]);
close(&ps("180 cos", 1).unwrap(), &[-1.0]);
close(&ps("180 sin", 1).unwrap(), &[0.0]);
}
#[test]
fn type4_atan_is_two_operand_degrees_and_never_negative() {
close(&ps("0 1 atan", 1).unwrap(), &[0.0]);
close(&ps("1 0 atan", 1).unwrap(), &[90.0]);
close(&ps("-100 0 atan", 1).unwrap(), &[270.0]);
close(&ps("4 4 atan", 1).unwrap(), &[45.0]);
assert!(matches!(
ps_err("0 0 atan", 1),
FunctionError::UndefinedResult { op: "atan", .. }
));
}
#[test]
fn type4_exp_is_pow_not_e_to_the_x() {
close(&ps("9 0.5 exp", 1).unwrap(), &[3.0]);
close(&ps("2 10 exp", 1).unwrap(), &[1024.0]);
}
#[test]
fn type4_log_is_base_ten_and_ln_is_natural() {
close(&ps("100 log", 1).unwrap(), &[2.0]);
close(&ps("1 ln", 1).unwrap(), &[0.0]);
close(&ps("2.718281828459045 ln", 1).unwrap(), &[1.0]);
assert!(matches!(
ps_err("0 ln", 1),
FunctionError::PostScriptRange { op: "ln", .. }
));
assert!(matches!(
ps_err("-1 log", 1),
FunctionError::PostScriptRange { op: "log", .. }
));
}
#[test]
fn type4_arithmetic_preserves_integers_but_div_always_produces_a_real() {
close(&ps("2 3 add 2 idiv", 1).unwrap(), &[2.0]);
close(&ps("10 4 sub 3 idiv", 1).unwrap(), &[2.0]);
close(&ps("3 4 mul 5 idiv", 1).unwrap(), &[2.0]);
close(&ps("4 2 div", 1).unwrap(), &[2.0]);
assert!(matches!(
ps_err("4 2 div 2 idiv", 1),
FunctionError::PostScriptType { op: "idiv", .. }
));
}
#[test]
fn type4_integer_overflow_spills_to_real_rather_than_wrapping() {
close(&ps("2000000000 2000000000 add", 1).unwrap(), &[4.0e9]);
assert!(matches!(
ps_err("2000000000 2000000000 add 2 idiv", 1),
FunctionError::PostScriptType { op: "idiv", .. }
));
}
#[test]
fn type4_rounding_operators_preserve_their_operands_type() {
close(&ps("3.7 floor", 1).unwrap(), &[3.0]);
close(&ps("3.2 ceiling", 1).unwrap(), &[4.0]);
close(&ps("-4.8 truncate", 1).unwrap(), &[-4.0]);
close(&ps("-4.8 floor", 1).unwrap(), &[-5.0]);
close(&ps("-4.8 ceiling", 1).unwrap(), &[-4.0]);
assert!(matches!(
ps_err("3.7 floor 2 idiv", 1),
FunctionError::PostScriptType { op: "idiv", .. }
));
close(&ps("99 floor 2 idiv", 1).unwrap(), &[49.0]);
}
#[test]
fn type4_round_breaks_ties_toward_the_greater_value() {
close(&ps("6.5 round", 1).unwrap(), &[7.0]);
close(&ps("-6.5 round", 1).unwrap(), &[-6.0]);
close(&ps("3.2 round", 1).unwrap(), &[3.0]);
close(&ps("-3.2 round", 1).unwrap(), &[-3.0]);
}
#[test]
fn type4_idiv_truncates_toward_zero_and_mod_follows_the_dividend() {
close(&ps("-5 2 idiv", 1).unwrap(), &[-2.0]);
close(&ps("5 2 idiv", 1).unwrap(), &[2.0]);
close(&ps("-5 3 mod", 1).unwrap(), &[-2.0]);
close(&ps("5 -3 mod", 1).unwrap(), &[2.0]);
close(&ps("5 3 mod", 1).unwrap(), &[2.0]);
}
#[test]
fn type4_cvi_truncates_toward_zero_and_yields_an_integer() {
close(&ps("-47.8 cvi", 1).unwrap(), &[-47.0]);
close(&ps("47.8 cvi", 1).unwrap(), &[47.0]);
close(&ps("-47.8 cvi 2 idiv", 1).unwrap(), &[-23.0]);
assert!(matches!(
ps_err("3000000000.0 cvi", 1),
FunctionError::PostScriptRange { op: "cvi", .. }
));
}
#[test]
fn type4_not_on_an_integer_is_the_ones_complement() {
close(&ps("52 not", 1).unwrap(), &[-53.0]);
close(&ps("0 not", 1).unwrap(), &[-1.0]);
close(&ps("true not { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
assert!(matches!(
ps_err("1.5 not", 1),
FunctionError::PostScriptType { op: "not", .. }
));
}
#[test]
fn type4_bitwise_operators_are_polymorphic_over_booleans_and_integers() {
close(&ps("52 7 and", 1).unwrap(), &[4.0]);
close(&ps("17 5 or", 1).unwrap(), &[21.0]);
close(&ps("7 3 xor", 1).unwrap(), &[4.0]);
close(&ps("true false and { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
close(&ps("true false or { 1 } { 2 } ifelse", 1).unwrap(), &[1.0]);
close(&ps("true true xor { 1 } { 2 } ifelse", 1).unwrap(), &[2.0]);
}
#[test]
fn type4_mixed_boolean_and_integer_bitwise_operands_are_refused() {
assert!(matches!(
ps_err("true 1 and", 1),
FunctionError::PostScriptType { op: "and", .. }
));
assert!(matches!(
ps_err("1.0 2.0 or", 1),
FunctionError::PostScriptType { op: "or", .. }
));
}
#[test]
fn type4_equality_accepts_any_operands_but_ordering_requires_numbers() {
close(&ps("4.0 4 eq { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
close(&ps("4 5 ne { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
close(&ps("true true eq { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
close(&ps("true 1 eq { 1 } { 0 } ifelse", 1).unwrap(), &[0.0]);
for src in [
"true false gt",
"true false lt",
"true false ge",
"true false le",
] {
assert!(
matches!(ps_err(src, 1), FunctionError::PostScriptType { .. }),
"{src} should be a type error"
);
}
close(&ps("1 2 lt { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
close(&ps("2 2 ge { 1 } { 0 } ifelse", 1).unwrap(), &[1.0]);
}
#[test]
fn type4_bitshift_is_left_on_positive_and_logically_right_on_negative() {
close(&ps("7 3 bitshift", 1).unwrap(), &[56.0]);
close(&ps("142 -3 bitshift", 1).unwrap(), &[17.0]);
close(&ps("-8 -1 bitshift", 1).unwrap(), &[2_147_483_644.0]);
close(&ps("1 32 bitshift", 1).unwrap(), &[0.0]);
close(&ps("1 -32 bitshift", 1).unwrap(), &[0.0]);
}
#[test]
fn type4_integer_only_operators_refuse_reals() {
for src in [
"3.0 2 idiv",
"3.0 2 mod",
"3.0 2 bitshift",
"3 2.0 bitshift",
] {
assert!(
matches!(ps_err(src, 1), FunctionError::PostScriptType { .. }),
"{src} should be a type error"
);
}
}
#[test]
fn type4_dup_exch_and_pop() {
close(&ps("10 dup", 2).unwrap(), &[10.0, 10.0]);
close(&ps("10 20 exch", 2).unwrap(), &[20.0, 10.0]);
close(&ps("10 20 pop", 1).unwrap(), &[10.0]);
}
#[test]
fn type4_index_counts_from_the_top_starting_at_zero() {
close(
&ps("10 20 30 0 index", 4).unwrap(),
&[10.0, 20.0, 30.0, 30.0],
);
close(
&ps("10 20 30 1 index", 4).unwrap(),
&[10.0, 20.0, 30.0, 20.0],
);
close(
&ps("10 20 30 2 index", 4).unwrap(),
&[10.0, 20.0, 30.0, 10.0],
);
assert!(matches!(
ps_err("10 5 index", 1),
FunctionError::PostScriptRange { op: "index", .. }
));
}
#[test]
fn type4_copy_duplicates_the_top_n_and_zero_is_a_legal_no_op() {
close(&ps("10 20 2 copy", 4).unwrap(), &[10.0, 20.0, 10.0, 20.0]);
close(
&ps("10 20 30 1 copy", 4).unwrap(),
&[10.0, 20.0, 30.0, 30.0],
);
close(&ps("10 20 0 copy", 2).unwrap(), &[10.0, 20.0]);
assert!(matches!(
ps_err("10 20 5 copy", 1),
FunctionError::PostScriptRange { op: "copy", .. }
));
}
#[test]
fn type4_roll_rotates_upward_for_a_positive_count() {
close(&ps("10 20 30 3 1 roll", 3).unwrap(), &[30.0, 10.0, 20.0]);
close(&ps("10 20 30 3 -1 roll", 3).unwrap(), &[20.0, 30.0, 10.0]);
close(&ps("10 20 30 3 0 roll", 3).unwrap(), &[10.0, 20.0, 30.0]);
close(&ps("10 20 30 3 3 roll", 3).unwrap(), &[10.0, 20.0, 30.0]);
close(&ps("10 20 30 3 4 roll", 3).unwrap(), &[30.0, 10.0, 20.0]);
close(
&ps("10 20 30 40 2 1 roll", 4).unwrap(),
&[10.0, 20.0, 40.0, 30.0],
);
}
#[test]
fn type4_roll_with_a_zero_window_is_the_identity() {
close(&ps("10 20 0 1 roll", 2).unwrap(), &[10.0, 20.0]);
}
#[test]
fn type4_negative_count_operands_are_range_errors() {
for src in ["10 20 -1 copy", "10 -1 index", "10 20 -1 1 roll"] {
assert!(
matches!(ps_err(src, 1), FunctionError::PostScriptRange { .. }),
"{src} should be a range error"
);
}
}
#[test]
fn type4_sqrt_of_a_negative_and_division_by_zero_are_refused() {
assert!(matches!(
ps_err("-1 sqrt", 1),
FunctionError::PostScriptRange { op: "sqrt", .. }
));
assert!(matches!(
ps_err("1 0 div", 1),
FunctionError::UndefinedResult { op: "div", .. }
));
assert!(matches!(
ps_err("1 0 idiv", 1),
FunctionError::UndefinedResult { op: "idiv", .. }
));
assert!(matches!(
ps_err("1 0 mod", 1),
FunctionError::UndefinedResult { op: "mod", .. }
));
assert!(matches!(
ps_err("0 -1 exp", 1),
FunctionError::UndefinedResult { op: "exp", .. }
));
close(&ps("4 sqrt", 1).unwrap(), &[2.0]);
}
#[test]
fn type4_neg_and_abs_preserve_the_operand_type() {
close(&ps("5 neg", 1).unwrap(), &[-5.0]);
close(&ps("-5.5 abs", 1).unwrap(), &[5.5]);
close(&ps("-5 abs 2 idiv", 1).unwrap(), &[2.0]);
close(&ps("5 neg 2 idiv", 1).unwrap(), &[-2.0]);
}
#[test]
fn type4_cvr_converts_an_integer_to_a_real() {
close(&ps("7 cvr", 1).unwrap(), &[7.0]);
assert!(matches!(
ps_err("7 cvr 2 idiv", 1),
FunctionError::PostScriptType { op: "idiv", .. }
));
}
#[test]
fn type4_every_table_42_operator_is_recognised() {
const TABLE_42: [&str; 42] = [
"abs", "add", "atan", "ceiling", "cos", "cvi", "cvr", "div", "exp", "floor", "idiv",
"ln", "log", "mod", "mul", "neg", "round", "sin", "sqrt", "sub", "truncate", "and",
"bitshift", "eq", "false", "ge", "gt", "le", "lt", "ne", "not", "or", "true", "xor",
"if", "ifelse", "copy", "dup", "exch", "index", "pop", "roll",
];
for token in TABLE_42 {
let structural = matches!(token, "true" | "false" | "if" | "ifelse");
assert_eq!(
PsOperator::from_token(token.as_bytes()).is_some(),
!structural,
"{token} classified wrongly"
);
}
for token in TABLE_42 {
if let Some(op) = PsOperator::from_token(token.as_bytes()) {
assert_eq!(op.name(), token);
}
}
}
}