Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / functions_part3.rs

functions_part3.rs455 lines · 19.9 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4
5 #[test]
6 fn exponential_eval() {
7 let f = PdfFunction::Exponential {
8 domain: [0.0, 1.0],
9 range: Vec::new(),
10 c0: vec![0.0, 0.0, 0.0],
11 c1: vec![1.0, 0.5, 0.0],
12 n: 1.0,
13 };
14 let out = f.eval(&[0.5]);
15 assert_eq!(out.len(), 3);
16 assert!((out[0] - 0.5).abs() < 1e-9);
17 assert!((out[1] - 0.25).abs() < 1e-9);
18 assert!((out[2] - 0.0).abs() < 1e-9);
19 }
20
21 // 7.10.4: subdomain i is [Bounds_i-1, Bounds_i) (with Domain_0 / Domain_1 at the
22 // ends), and x is then mapped LINEARLY from that subdomain onto Encode_i. Asserting
23 // only "somewhere strictly between 0 and 1" let an off-by-one in either the
24 // selection or the sub-interval through; those produce a hard colour discontinuity
25 // at a stop, so pin the exact values.
26 #[test]
27 fn stitching_selects_subfunction() {
28 let ramp = |lo: f64, hi: f64| PdfFunction::Exponential {
29 domain: [0.0, 1.0],
30 range: Vec::new(),
31 c0: vec![lo],
32 c1: vec![hi],
33 n: 1.0,
34 };
35 let f = PdfFunction::Stitching {
36 domain: [0.0, 1.0],
37 range: Vec::new(),
38 functions: vec![ramp(0.0, 1.0), ramp(1.0, 0.0)],
39 bounds: vec![0.5],
40 encode: vec![[0.0, 1.0], [0.0, 1.0]],
41 };
42 // x=0.25 sits at the midpoint of subdomain 0 = [0, 0.5) -> encoded 0.5 -> 0.5.
43 assert!((f.eval(&[0.25])[0] - 0.5).abs() < 1e-9);
44 // x=0.75 sits at the midpoint of subdomain 1 = [0.5, 1] -> encoded 0.5 -> 0.5.
45 assert!((f.eval(&[0.75])[0] - 0.5).abs() < 1e-9);
46 // The bound itself belongs to the UPPER subdomain (half-open below), so x=0.5
47 // is the START of function 1, which ramps 1 -> 0.
48 assert!((f.eval(&[0.5])[0] - 1.0).abs() < 1e-9);
49 // Just below it is the END of function 0, which ramps 0 -> 1. The two agree,
50 // i.e. the stitch is continuous rather than stepping.
51 assert!((f.eval(&[0.5 - 1e-9])[0] - 1.0).abs() < 1e-6);
52 assert!((f.eval(&[0.0])[0] - 0.0).abs() < 1e-9);
53 assert!((f.eval(&[1.0])[0] - 0.0).abs() < 1e-9);
54
55 // Three subdomains: the MIDDLE one must use [Bounds_0, Bounds_1), not Domain.
56 let g = PdfFunction::Stitching {
57 domain: [0.0, 1.0],
58 range: Vec::new(),
59 functions: vec![ramp(0.0, 0.0), ramp(0.0, 1.0), ramp(0.0, 0.0)],
60 bounds: vec![0.25, 0.75],
61 encode: vec![[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]],
62 };
63 assert!((g.eval(&[0.5])[0] - 0.5).abs() < 1e-9, "midpoint of [0.25, 0.75)");
64 assert!((g.eval(&[0.25])[0] - 0.0).abs() < 1e-9, "lower edge of the middle");
65 assert!((g.eval(&[0.75 - 1e-9])[0] - 1.0).abs() < 1e-6, "upper edge");
66 }
67
68 // 7.10.1 Table 38: when /Range is present its outputs SHALL be clipped to it. A
69 // Type 2 whose /Domain runs past 1 evaluates outside the C0..C1 interval, so this
70 // is not vacuous.
71 #[test]
72 fn exponential_clips_to_range() {
73 let mut doc = Document::with_version("1.7");
74 let id = doc.add_object(dictionary! {
75 "FunctionType" => 2,
76 "Domain" => vec![0.into(), 2.into()],
77 "Range" => vec![0.into(), 1.into()],
78 "C0" => vec![0.into()],
79 "C1" => vec![1.into()],
80 "N" => 1,
81 });
82 let f = PdfFunction::parse(&doc, &Object::Reference(id)).expect("parses");
83 assert!((f.eval(&[0.5])[0] - 0.5).abs() < 1e-9, "in range, untouched");
84 assert!((f.eval(&[2.0])[0] - 1.0).abs() < 1e-9, "t=2 gives 2.0, clipped to 1");
85 }
86
87 #[test]
88 fn sampled_linear_1d() {
89 // 2 samples, 1 in, 1 out, 8 bps: [0, 255] -> decodes to [0,1].
90 let f = PdfFunction::Sampled {
91 domain: vec![[0.0, 1.0]],
92 range: vec![[0.0, 1.0]],
93 size: vec![2],
94 bps: 8,
95 encode: vec![[0.0, 1.0]],
96 decode: vec![[0.0, 1.0]],
97 samples: vec![0, 255],
98 n_in: 1,
99 n_out: 1,
100 };
101 assert!((f.eval(&[0.0])[0] - 0.0).abs() < 1e-6);
102 assert!((f.eval(&[1.0])[0] - 1.0).abs() < 1e-6);
103 assert!((f.eval(&[0.5])[0] - 0.5).abs() < 1e-2);
104 }
105
106 #[test]
107 fn postscript_arith_and_ifelse() {
108 // { 2 mul 1 sub dup 0 lt { pop 0 } if }
109 let prog = parse_ps_program(b"{ 2 mul 1 sub dup 0 lt { pop 0 } if }").unwrap();
110 // input 1.0 -> 2*1-1 = 1.0 (not < 0)
111 let out = eval_ps(&prog, &[1.0]).unwrap();
112 assert!((out[0] - 1.0).abs() < 1e-9);
113 // input 0.0 -> 2*0-1 = -1 < 0 -> 0
114 let out2 = eval_ps(&prog, &[0.0]).unwrap();
115 assert!((out2[0] - 0.0).abs() < 1e-9);
116 }
117
118 // 7.10.5 Table 42 operand ORDER and rounding/truncation semantics. A bug in any of
119 // these shows up simultaneously as wrong gradient colours and wrong Separation
120 // colours, because both go through the same evaluator.
121 #[test]
122 fn postscript_operator_semantics_match_table_42() {
123 let run = |src: &[u8]| -> Vec<f64> {
124 eval_ps(&parse_ps_program(src).expect("parses"), &[]).expect("runs")
125 };
126 let one = |src: &[u8]| run(src)[0];
127
128 // `num1 num2 sub/div/idiv/mod` take num1 from BELOW num2 on the stack.
129 assert_eq!(one(b"{ 7 2 sub }"), 5.0);
130 assert_eq!(one(b"{ 7 2 div }"), 3.5);
131 // idiv and mod truncate toward zero and keep the dividend's sign.
132 assert_eq!(one(b"{ 7 2 idiv }"), 3.0);
133 assert_eq!(one(b"{ -7 2 idiv }"), -3.0);
134 assert_eq!(one(b"{ -7 2 mod }"), -1.0);
135 // `base exponent exp`, not the other way round.
136 assert_eq!(one(b"{ 2 10 exp }"), 1024.0);
137 // A negative base with a fractional exponent is NaN; it must not escape.
138 assert!(one(b"{ -8 0.5 exp }").is_finite());
139
140 // Angles are DEGREES, and `num den atan` returns 0..360.
141 assert!((one(b"{ 90 sin }") - 1.0).abs() < 1e-12);
142 assert!((one(b"{ 180 cos }") + 1.0).abs() < 1e-12);
143 assert!((one(b"{ 0 1 atan }") - 0.0).abs() < 1e-9);
144 assert!((one(b"{ 1 0 atan }") - 90.0).abs() < 1e-9);
145 assert!((one(b"{ -1 0 atan }") - 270.0).abs() < 1e-9, "never negative");
146
147 // truncate/cvi cut toward zero; round breaks a tie toward +infinity (PLRM),
148 // which f64::round does NOT do.
149 assert_eq!(one(b"{ -1.7 truncate }"), -1.0);
150 assert_eq!(one(b"{ -1.7 cvi }"), -1.0);
151 assert_eq!(one(b"{ -1.5 round }"), -1.0);
152 assert_eq!(one(b"{ 1.5 round }"), 2.0);
153 assert_eq!(one(b"{ -1.7 floor }"), -2.0);
154 assert_eq!(one(b"{ -1.7 ceiling }"), -1.0);
155
156 // `n j roll` moves the bottom of the n-group UPWARD for positive j.
157 assert_eq!(run(b"{ 1 2 3 3 1 roll }"), vec![3.0, 1.0, 2.0]);
158 assert_eq!(run(b"{ 1 2 3 3 -1 roll }"), vec![2.0, 3.0, 1.0]);
159 // `n index` counts down from the top, 0 being the top itself.
160 assert_eq!(run(b"{ 10 20 30 2 index }"), vec![10.0, 20.0, 30.0, 10.0]);
161 assert_eq!(run(b"{ 10 20 2 copy }"), vec![10.0, 20.0, 10.0, 20.0]);
162 // `int shift bitshift`, negative shift = right.
163 assert_eq!(one(b"{ 1 4 bitshift }"), 16.0);
164 assert_eq!(one(b"{ 16 -4 bitshift }"), 1.0);
165 }
166
167 // 7.10.5 Table 42's integer operators take their operands from a `f64 as i64`
168 // cast, which SATURATES — so any real large enough reaches i64::MIN and
169 // `i64::MIN / -1`, `i64::MIN % -1` and `-i64::MIN` all overflow. Rust panics on
170 // signed division overflow in RELEASE as well as debug, and the panic unwinds out
171 // of the whole page render. This is the sharpest example of the shared-evaluator
172 // blast radius: the same six lines serve gradient colours (§8.7.4) and
173 // Separation/DeviceN tint transforms (§8.6.6.4), so one crafted Type 4 kills both.
174 #[test]
175 fn postscript_integer_operators_saturate_instead_of_panicking() {
176 let one = |src: &[u8]| eval_ps(&parse_ps_program(src).unwrap(), &[]).unwrap()[0];
177 assert!(one(b"{ -1e300 -1 idiv }").is_finite());
178 assert!(one(b"{ -1e300 -1 mod }").is_finite());
179 assert!(one(b"{ 1 -1e300 bitshift }").is_finite());
180 assert!(one(b"{ 1 1e300 bitshift }").is_finite());
181 // Division by zero still yields 0 rather than a trap.
182 assert_eq!(one(b"{ 7 0 idiv }"), 0.0);
183 assert_eq!(one(b"{ 7 0 mod }"), 0.0);
184 assert_eq!(one(b"{ 7 0 div }"), 0.0);
185 // And the ordinary cases are unchanged.
186 assert_eq!(one(b"{ -7 2 idiv }"), -3.0);
187 assert_eq!(one(b"{ -7 2 mod }"), -1.0);
188 }
189
190 // 7.10.4's `/Functions` array and the array-of-functions form both recurse through
191 // `parse`, and nothing stops `5 0 R` naming a Type 3 whose `/Functions` is `[5 0 R]`.
192 // That recursed until the stack overflowed — which is NOT a panic, so `catch_unwind`
193 // cannot contain it and the process dies rather than the page failing to render.
194 #[test]
195 fn a_self_referential_function_is_rejected_rather_than_overflowing_the_stack() {
196 let mut doc = Document::with_version("1.7");
197 let id = doc.new_object_id();
198 doc.set_object(
199 id,
200 dictionary! {
201 "FunctionType" => 3,
202 "Domain" => vec![0.into(), 1.into()],
203 "Functions" => vec![Object::Reference(id)],
204 "Bounds" => Vec::<Object>::new(),
205 "Encode" => vec![0.into(), 1.into()],
206 },
207 );
208 assert!(PdfFunction::parse(&doc, &Object::Reference(id)).is_none());
209
210 // An array of functions that contains itself takes the other recursive path.
211 let arr = doc.new_object_id();
212 doc.set_object(arr, Object::Array(vec![Object::Reference(arr)]));
213 assert!(PdfFunction::parse(&doc, &Object::Reference(arr)).is_none());
214
215 // A mutual cycle between a Type 3 and an array goes through both arms.
216 let a = doc.new_object_id();
217 let b = doc.new_object_id();
218 doc.set_object(a, Object::Array(vec![Object::Reference(b)]));
219 doc.set_object(
220 b,
221 dictionary! {
222 "FunctionType" => 3,
223 "Domain" => vec![0.into(), 1.into()],
224 "Functions" => vec![Object::Reference(a)],
225 "Bounds" => Vec::<Object>::new(),
226 "Encode" => vec![0.into(), 1.into()],
227 },
228 );
229 assert!(PdfFunction::parse(&doc, &Object::Reference(a)).is_none());
230
231 // A legitimate one-level Type 3 over two Type 2s still parses.
232 let leaf = doc.add_object(dictionary! {
233 "FunctionType" => 2,
234 "Domain" => vec![0.into(), 1.into()],
235 "C0" => vec![0.into()],
236 "C1" => vec![1.into()],
237 "N" => 1,
238 });
239 let ok = doc.add_object(dictionary! {
240 "FunctionType" => 3,
241 "Domain" => vec![0.into(), 1.into()],
242 "Functions" => vec![Object::Reference(leaf), Object::Reference(leaf)],
243 "Bounds" => vec![Object::Real(0.5)],
244 "Encode" => vec![0.into(), 1.into(), 0.into(), 1.into()],
245 });
246 assert!(PdfFunction::parse(&doc, &Object::Reference(ok)).is_some());
247 }
248
249 // 7.10.2: sample data is ordered with the FIRST input dimension varying fastest,
250 // and the reconstruction is multilinear. Nearest-neighbour (or a transposed index)
251 // passes a 1-D two-sample test but fails here, and shows as banded gradients.
252 #[test]
253 fn sampled_is_bilinear_with_first_dimension_fastest() {
254 // 2x2 grid, one output. Sample order is (x0,y0) (x1,y0) (x0,y1) (x1,y1).
255 let f = PdfFunction::Sampled {
256 domain: vec![[0.0, 1.0], [0.0, 1.0]],
257 range: vec![[0.0, 1.0]],
258 size: vec![2, 2],
259 bps: 8,
260 encode: vec![[0.0, 1.0], [0.0, 1.0]],
261 decode: vec![[0.0, 1.0]],
262 samples: vec![0, 255, 0, 0],
263 n_in: 2,
264 n_out: 1,
265 };
266 // Corners come straight back.
267 assert!((f.eval(&[0.0, 0.0])[0] - 0.0).abs() < 1e-6);
268 assert!((f.eval(&[1.0, 0.0])[0] - 1.0).abs() < 1e-6, "x varies fastest");
269 assert!((f.eval(&[0.0, 1.0])[0] - 0.0).abs() < 1e-6);
270 assert!((f.eval(&[1.0, 1.0])[0] - 0.0).abs() < 1e-6);
271 // Interior is the bilinear blend, not a nearest corner.
272 assert!((f.eval(&[0.5, 0.0])[0] - 0.5).abs() < 1e-2);
273 assert!((f.eval(&[0.5, 0.5])[0] - 0.25).abs() < 1e-2);
274 // A quarter step must land a quarter of the way, which nearest-neighbour
275 // would snap to 0 or 1.
276 assert!((f.eval(&[0.25, 0.0])[0] - 0.25).abs() < 1e-2);
277 }
278
279 // A truncated sample stream must read as 0, not as a partially shifted value
280 // that looks like a plausible sample.
281 #[test]
282 fn read_sample_past_end_is_zero() {
283 let data = [0xFFu8]; // one byte = one 8-bit sample
284 assert!((read_sample(&data, 0, 8) - 255.0).abs() < 1e-9);
285 assert_eq!(read_sample(&data, 1, 8), 0.0, "sample past the end reads 0");
286 // A 16-bit sample straddling the end must also read 0, not 0xFF00.
287 assert_eq!(read_sample(&data, 0, 16), 0.0, "partial sample reads 0");
288 }
289
290 // A Type 2 whose C0/C1 are absent must broadcast its scalar defaults to the
291 // arity implied by /Range (7.10.3 Table 40 + Table 38), otherwise a spot colour
292 // over a 4-component alternate space receives one component and degrades.
293 #[test]
294 fn exponential_broadcasts_defaults_to_range_arity() {
295 let mut doc = Document::with_version("1.7");
296 let id = doc.add_object(dictionary! {
297 "FunctionType" => 2,
298 "Domain" => vec![0.into(), 1.into()],
299 "N" => 1,
300 // 4 pairs => j = 4, with no C0/C1 given.
301 "Range" => vec![0.into(), 1.into(), 0.into(), 1.into(),
302 0.into(), 1.into(), 0.into(), 1.into()],
303 });
304 let f = PdfFunction::parse(&doc, &Object::Reference(id)).expect("type 2 parses");
305 let out = f.eval(&[0.5]);
306 assert_eq!(out.len(), 4, "arity comes from /Range when C0/C1 are absent");
307 for v in &out {
308 assert!((v - 0.5).abs() < 1e-9, "each component ramps 0 -> 1");
309 }
310 }
311
312 // /BitsPerSample outside Table 39's set is rejected at parse. bps == 0 used to
313 // divide by zero and produce NaN components that survived the Range clamp.
314 #[test]
315 fn sampled_rejects_illegal_bits_per_sample() {
316 let mk = |bps: i64| {
317 let mut doc = Document::with_version("1.7");
318 let id = doc.add_object(Stream::new(
319 dictionary! {
320 "FunctionType" => 0,
321 "Domain" => vec![0.into(), 1.into()],
322 "Range" => vec![0.into(), 1.into()],
323 "Size" => vec![2.into()],
324 "BitsPerSample" => bps,
325 },
326 vec![0u8, 255u8],
327 ));
328 PdfFunction::parse(&doc, &Object::Reference(id)).is_some()
329 };
330 assert!(mk(8), "8 bps is legal");
331 assert!(!mk(0), "0 bps must be rejected");
332 assert!(!mk(5), "5 bps is not in Table 39");
333 }
334
335 // A sampled function's input arity is taken from /Size and drives a 2^m corner
336 // loop per evaluation, so an absurd /Size must be rejected rather than hang.
337 #[test]
338 fn sampled_rejects_absurd_input_arity() {
339 let mut doc = Document::with_version("1.7");
340 let size: Vec<Object> = (0..32).map(|_| Object::Integer(2)).collect();
341 let id = doc.add_object(Stream::new(
342 dictionary! {
343 "FunctionType" => 0,
344 "Domain" => vec![0.into(), 1.into()],
345 "Range" => vec![0.into(), 1.into()],
346 "Size" => size,
347 "BitsPerSample" => 8,
348 },
349 vec![0u8; 64],
350 ));
351 assert!(
352 PdfFunction::parse(&doc, &Object::Reference(id)).is_none(),
353 "32 input dimensions would mean 2^32 corner evaluations per call"
354 );
355 }
356
357 // §11.6.5.2: an INVERTING /TR is the standard idiom for "mask out where the group is
358 // bright", so it must survive sampling into the LUT exactly. Ignoring it hides the
359 // wrong half of the content, which is the visible symptom this LUT exists to fix.
360 #[test]
361 fn inverting_transfer_function_becomes_an_inverting_lut() {
362 let mut doc = Document::with_version("1.7");
363 // { 1 exch sub } — the canonical inverter.
364 let id = doc.add_object(Stream::new(
365 dictionary! {
366 "FunctionType" => 4,
367 "Domain" => vec![0.into(), 1.into()],
368 "Range" => vec![0.into(), 1.into()],
369 },
370 b"{ 1 exch sub }".to_vec(),
371 ));
372 let lut = read_transfer_lut(&doc, &Object::Reference(id)).expect("inverting /TR is not identity");
373 assert_eq!(lut[0], 255, "0 maps to 255");
374 assert_eq!(lut[255], 0, "255 maps to 0");
375 assert!(lut[128].abs_diff(127) <= 1, "midpoint stays mid, got {}", lut[128]);
376 }
377
378 // /Identity, and anything indistinguishable from it at 8-bit precision, must report
379 // None so callers do not pay to carry or apply a no-op table.
380 #[test]
381 fn identity_transfer_function_is_none() {
382 let mut doc = Document::with_version("1.7");
383 assert!(
384 read_transfer_lut(&doc, &Object::Name(b"Identity".to_vec())).is_none(),
385 "/Identity has no effect"
386 );
387 // A Type 2 ramp 0 -> 1 with N=1 IS the identity.
388 let id = doc.add_object(dictionary! {
389 "FunctionType" => 2,
390 "Domain" => vec![0.into(), 1.into()],
391 "C0" => vec![0.into()],
392 "C1" => vec![1.into()],
393 "N" => 1,
394 });
395 assert!(
396 read_transfer_lut(&doc, &Object::Reference(id)).is_none(),
397 "a 0->1 linear ramp is the identity to within one 8-bit step"
398 );
399 // Something that is not a function at all also yields None rather than garbage.
400 assert!(read_transfer_lut(&doc, &Object::Integer(3)).is_none());
401 }
402
403 // 7.10.1 Table 38 gives no ordering guarantee on /Domain or /Range beyond their
404 // meaning, and `f64::clamp` PANICS when its low bound exceeds its high bound. A
405 // reversed pair therefore aborted the page rather than clipping.
406 #[test]
407 fn reversed_domain_and_range_clip_instead_of_panicking() {
408 let mut doc = Document::with_version("1.7");
409 let t2 = doc.add_object(dictionary! {
410 "FunctionType" => 2,
411 "Domain" => vec![1.into(), 0.into()],
412 "Range" => vec![1.into(), 0.into()],
413 "C0" => vec![0.into()],
414 "C1" => vec![1.into()],
415 "N" => 1,
416 });
417 let f = PdfFunction::parse(&doc, &Object::Reference(t2)).expect("parses");
418 assert!(f.eval(&[0.5])[0].is_finite());
419
420 let t4 = doc.add_object(Stream::new(
421 dictionary! {
422 "FunctionType" => 4,
423 "Domain" => vec![1.into(), 0.into()],
424 "Range" => vec![1.into(), 0.into()],
425 },
426 b"{ }".to_vec(),
427 ));
428 let f4 = PdfFunction::parse(&doc, &Object::Reference(t4)).expect("parses");
429 assert!(f4.eval(&[0.5])[0].is_finite());
430
431 let t0 = doc.add_object(Stream::new(
432 dictionary! {
433 "FunctionType" => 0,
434 "Domain" => vec![1.into(), 0.into()],
435 "Range" => vec![1.into(), 0.into()],
436 "Size" => vec![2.into()],
437 "BitsPerSample" => 8,
438 },
439 vec![0u8, 255u8],
440 ));
441 let f0 = PdfFunction::parse(&doc, &Object::Reference(t0)).expect("parses");
442 assert!(f0.eval(&[0.5])[0].is_finite());
443
444 let t3 = doc.add_object(dictionary! {
445 "FunctionType" => 3,
446 "Domain" => vec![1.into(), 0.into()],
447 "Functions" => vec![Object::Reference(t2)],
448 "Bounds" => Vec::<Object>::new(),
449 "Encode" => vec![0.into(), 1.into()],
450 });
451 let f3 = PdfFunction::parse(&doc, &Object::Reference(t3)).expect("parses");
452 assert!(f3.eval(&[0.5])[0].is_finite());
453 }
454
455}