rasterrocket-color 1.0.1

Pixel types and colour math for the rasterrocket PDF renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Shared arithmetic primitives used throughout the rasterizer.
//!
//! All compositing math lives here — never copy-pasted into callers.
//!
//! # Functions
//!
//! **Integer blend math**
//! - [`div255`] — fast approximate division by 255
//! - [`lerp_u8`] — bilinear interpolation between two bytes
//!
//! **Color-space conversion (u8 domain)**
//! - [`cmyk_to_rgb`] — simple subtractive CMYK → RGB
//! - [`cmyk_to_rgb_reflectance`] — reflectance formula for raw JPEG/CMYK pixels
//!
//! **Color-space conversion (f64 → u8, normalised PDF values)**
//! - [`gray_to_u8`] — normalised grey \[0,1\] → byte
//! - [`rgb_to_bytes`] — normalised RGB \[0,1\] → 3-byte array
//! - [`cmyk_to_rgb_bytes`] — normalised CMYK \[0,1\] → RGB bytes via PDF §10.3.3
//!
//! **Geometry rounding**
//! - [`splash_floor`] — floor toward −∞, returns i32
//! - [`splash_ceil`] — ceil toward +∞, returns i32
//! - [`splash_round`] — round half-integers toward +∞

// ── Integer blend math ────────────────────────────────────────────────────────

/// Fast approximate division by 255.
///
/// Uses the identity `(x + (x >> 8) + 0x80) >> 8` which gives the nearest
/// integer to `x / 255.0` for all `x` in the valid input range.
///
/// # Valid input range
///
/// `x` must be in \[0, 65535\]. Inputs larger than 65535 are not meaningful
/// (the maximum product of two u8 values is 255 × 255 = 65025), and values
/// above 65279 saturate: the formula yields 256 which is clamped to 255.
///
/// # Output range
///
/// Always \[0, 255\].
///
/// # Saturation note
///
/// For `x` in \[65280, 65535\] the unmasked result would be 256; the `.min(255)`
/// clamp makes those values return 255. In practice `x` is always a product
/// `a * b` with `a, b ∈ [0, 255]`, so the maximum is 65025 and the clamp is
/// never reached.
#[inline]
#[must_use]
pub fn div255(x: u32) -> u8 {
    // The intermediate value (x + (x>>8) + 0x80) can reach at most
    // 65535 + 255 + 128 = 65918, which fits in u32. The right-shift by 8
    // gives at most 257; clamping to 255 makes the cast to u8 always safe.
    let shifted = (x + (x >> 8) + 0x80) >> 8;
    // `shifted ≤ 257` before clamping; `.min(255)` makes the `as u8` cast lossless.
    shifted.min(255) as u8
}

/// Bilinear interpolation between two `u8` values.
///
/// Computes `a * (1 − t/256) + b * (t/256)` using integer arithmetic via
/// [`div255`].
///
/// # Valid input range
///
/// `t` must be in \[0, 256\]. Values outside this range are a caller bug:
/// `256 - t` would wrap (u32 subtraction), producing a nonsensical result.
/// A `debug_assert!` catches this in debug builds.
///
/// # Output range
///
/// Always \[0, 255\].
///
/// # Endpoints
///
/// - `t = 0` → `div255(a * 256)`, which equals `a` within ±1.  The `div255`
///   approximation means the result can be off by 1 for some values of `a`
///   (e.g. `lerp_u8(128, _, 0)` returns 129). If callers need exact identity
///   at `t = 0` they should special-case it.
/// - `t = 256` → `a * 0 + b * 256`; after `div255` this rounds to `b` within
///   ±1 (inherent to the `div255` approximation).
#[inline]
#[must_use]
pub fn lerp_u8(a: u8, b: u8, t: u32) -> u8 {
    debug_assert!(t <= 256, "lerp_u8: t={t} out of range [0, 256]");
    div255(u32::from(a) * (256 - t) + u32::from(b) * t)
}

// ── Color space conversion ────────────────────────────────────────────────────

/// CMYK → RGB using the simple subtractive model.
///
/// `R = 255 − (C + K)`, clamped to \[0, 255\], and similarly for G and B.
///
/// # Arguments
///
/// All inputs in \[0, 255\].
///
/// # Output range
///
/// Each output channel is in \[0, 255\].
///
/// # Saturation note
///
/// When `c + k > 255` the sum would exceed 255, so `saturating_sub` clamps
/// the result to 0. This correctly models full ink coverage producing black.
///
/// # Distinction from other CMYK variants
///
/// - [`cmyk_to_rgb_reflectance`]: uses the reflectance formula
///   `R = (255−C)×(255−K)/255` (rounded), for raw JPEG/CMYK pixel data.
/// - `rasterrocket_interp::renderer::color::cmyk_to_rgb_bytes`: takes normalised f64
///   inputs per PDF §10.3.3 (`R = 1−min(1, C+K)`), for PDF colour operators.
#[inline]
#[must_use]
pub const fn cmyk_to_rgb(c: u8, m: u8, y: u8, k: u8) -> (u8, u8, u8) {
    // Chained `u8::saturating_sub` stays in `u8` space — once a channel
    // saturates to 0, the second subtraction is a no-op, so the result
    // equals `255u32.saturating_sub(c + k)` clamped to `u8`.
    (
        255u8.saturating_sub(c).saturating_sub(k),
        255u8.saturating_sub(m).saturating_sub(k),
        255u8.saturating_sub(y).saturating_sub(k),
    )
}

/// Blend one ink channel against the key: `((255−ink) × (255−k) + 127) / 255`.
///
/// Max product is `255 × 255 + 127 = 65 152`, which divides to 255 — fits `u8`.
#[inline]
fn reflectance_blend(ink: u8, inv_k: u32) -> u8 {
    // `(255−ink)×(255−k) ≤ 65025` and `+127` then `/255` keeps the result
    // in `[0, 255]`. `.expect` matches the workspace convention for proving
    // small-domain u32→u8 narrowings (see `color::transfer`, `raster::state`).
    u8::try_from((u32::from(255 - ink) * inv_k + 127) / 255)
        .expect("reflectance_blend: ((255−ink)×inv_k+127)/255 ≤ 255")
}

/// CMYK → RGB via the reflectance formula: `R = (255−C)×(255−K)/255` (rounded).
///
/// Used for raw JPEG/CMYK pixel data where channels represent ink density.
/// The `+127` bias before dividing by 255 removes truncation error; the
/// numerator `(255−ch)×(255−k)+127 ≤ 255×255+127 = 65152` fits in `u32`.
///
/// # Distinction from other CMYK variants
///
/// - [`cmyk_to_rgb`]: simple saturating-subtract `R = 255−(C+K)`.
///   Faster but less accurate for mid-tones.
/// - [`cmyk_to_rgb_bytes`]: takes normalised `f64` inputs per PDF §10.3.3.
///
/// All inputs and outputs in \[0, 255\].
#[inline]
#[must_use]
pub fn cmyk_to_rgb_reflectance(c: u8, m: u8, y: u8, k: u8) -> (u8, u8, u8) {
    let inv_k = u32::from(255 - k);
    (
        reflectance_blend(c, inv_k),
        reflectance_blend(m, inv_k),
        reflectance_blend(y, inv_k),
    )
}

// ── f64 → u8 conversions ─────────────────────────────────────────────────────

/// Convert a normalised PDF value \[0.0, 1.0\] to a `u8` byte.
///
/// Clamps then rounds. `f64::clamp(NaN, 0.0, 1.0)` returns `NaN` (clamp does
/// not sanitise NaN); the subsequent `as u8` cast then saturates `NaN` to 0
/// per Rust's float-to-int rules, so NaN inputs map to 0.
/// Used for PDF colour operators where channel components are normalised floats.
#[inline]
#[must_use]
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "value is clamped to [0, 1] and scaled to [0.0, 255.0]; round() output fits u8"
)]
pub fn gray_to_u8(v: f64) -> u8 {
    (v.clamp(0.0, 1.0) * 255.0).round() as u8
}

/// Convert three normalised PDF RGB components to `[r, g, b]` bytes.
///
/// Each channel is clamped to \[0.0, 1.0\] independently.
#[inline]
#[must_use]
pub fn rgb_to_bytes(r: f64, g: f64, b: f64) -> [u8; 3] {
    [gray_to_u8(r), gray_to_u8(g), gray_to_u8(b)]
}

/// Convert PDF CMYK \[0.0, 1.0\] to RGB bytes via PDF §10.3.3 formula.
///
/// `R = 1 − min(1, C + K)`, clamped per channel.
///
/// # Distinction from other CMYK variants
///
/// - [`cmyk_to_rgb`]: takes `u8` inputs with saturating-subtract.
/// - [`cmyk_to_rgb_reflectance`]: takes `u8` inputs with reflectance product formula.
/// - This function: takes normalised `f64` inputs for use with PDF colour operators.
#[inline]
#[must_use]
#[expect(
    clippy::many_single_char_names,
    reason = "CMYK and RGB are conventional single-letter colour channel names"
)]
pub fn cmyk_to_rgb_bytes(c: f64, m: f64, y: f64, k: f64) -> [u8; 3] {
    let k = k.clamp(0.0, 1.0);
    let r = 1.0 - (c.clamp(0.0, 1.0) + k).min(1.0);
    let g = 1.0 - (m.clamp(0.0, 1.0) + k).min(1.0);
    let b = 1.0 - (y.clamp(0.0, 1.0) + k).min(1.0);
    rgb_to_bytes(r, g, b)
}

// ── Geometry rounding (matching SplashMath.h portable fallbacks) ──────────────

/// Saturating cast of an integer-valued `f64` to `i32`.
///
/// Non-finite inputs map to `i32::MAX` for `+∞` and `i32::MIN` for `-∞` / NaN.
/// Finite values outside the `i32` range saturate at the nearest endpoint.
#[inline]
fn saturate_f64_to_i32(x: f64) -> i32 {
    if !x.is_finite() {
        return if x == f64::INFINITY {
            i32::MAX
        } else {
            i32::MIN
        };
    }
    // x is finite: casting to i64 is well-defined for any finite f64 whose
    // magnitude fits in i64 (which covers all practical PDF coordinates);
    // try_from saturates the rare case of very large floats.
    #[expect(
        clippy::cast_possible_truncation,
        reason = "f64 → i64 cast; try_from on the next line saturates out-of-range values"
    )]
    let v = x as i64;
    i32::try_from(v).unwrap_or(if v > 0 { i32::MAX } else { i32::MIN })
}

/// Floor toward −∞, returning `i32`.
///
/// Equivalent to C++ `splashFloor` — matches the portable fallback path.
///
/// # Valid input range
///
/// Any `f64`. For PDF coordinates, values are always finite and well within
/// i32 range.
///
/// # Edge cases
///
/// - Finite values outside \[`i32::MIN`, `i32::MAX`\]: saturate to
///   `i32::MIN` or `i32::MAX` respectively.
/// - `NaN` or ±infinity: `is_finite()` check returns `i32::MIN` for any
///   non-finite input (conservatively safe — callers must not rely on this
///   specific value for non-finite inputs).
///
/// # Panic
///
/// Never panics.
#[inline]
#[must_use]
pub fn splash_floor(x: f64) -> i32 {
    saturate_f64_to_i32(x.floor())
}

/// Ceil toward +∞, returning `i32`.
///
/// Equivalent to C++ `splashCeil` — matches the portable fallback path.
///
/// # Valid input range
///
/// Any `f64`. See [`splash_floor`] for edge-case behaviour.
///
/// # Edge cases
///
/// Same as [`splash_floor`]: non-finite inputs return `i32::MAX` (for +∞) or
/// `i32::MIN` (for −∞ and NaN).
///
/// # Panic
///
/// Never panics.
#[inline]
#[must_use]
pub fn splash_ceil(x: f64) -> i32 {
    saturate_f64_to_i32(x.ceil())
}

/// Round half-integers toward +∞, returning `i32`.
///
/// Implements `floor(x + 0.5)`. This means:
/// - 0.5 rounds to 1 (toward +∞).
/// - −0.5 rounds to 0 (toward +∞, i.e. not away from zero).
///
/// Equivalent to C++ `splashRound`.
///
/// # Valid input range
///
/// Any `f64`. See [`splash_floor`] for edge-case behaviour on non-finite inputs.
///
/// # Panic
///
/// Never panics.
#[inline]
#[must_use]
pub fn splash_round(x: f64) -> i32 {
    splash_floor(x + 0.5)
}

// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn div255_exhaustive() {
        for x in 0u32..=65535 {
            let got = f64::from(div255(x));
            // div255 returns u8, so saturate the expected value at 255.
            let expected = (f64::from(x) / 255.0).round().min(255.0);
            assert!(
                (got - expected).abs() <= 1.0,
                "div255({x}) = {got}, expected ≈ {expected}"
            );
        }
    }

    #[test]
    fn div255_boundary_products() {
        // all a*b products where a,b ∈ [0,255]
        for a in 0u32..=255 {
            for b in 0u32..=255 {
                let got = f64::from(div255(a * b));
                let expected = (f64::from(a) * f64::from(b) / 255.0).round();
                assert!(
                    (got - expected).abs() <= 1.0,
                    "div255({a}*{b}) = {got}, expected ≈ {expected}"
                );
            }
        }
    }

    #[test]
    fn lerp_endpoints() {
        // t=0 must return exactly a.
        assert_eq!(lerp_u8(100, 200, 0), 100);
        // t=256: a*(256-256) + b*256; div255(200*256) = div255(51200).
        // 51200/255 ≈ 200.78, rounds to 201 — within ±1 of b=200.
        let v = lerp_u8(100, 200, 256);
        assert!(
            (i32::from(v) - 200).abs() <= 1,
            "lerp t=256 gave {v}, expected ≈200"
        );
    }

    /// `lerp_u8` with `t=0` returns `div255(a * 256)`, which is within ±1 of `a`.
    /// The result must not depend on `b`.
    #[test]
    fn lerp_t0_near_a() {
        for a in 0u8..=255 {
            let v0 = lerp_u8(a, 0, 0);
            let v255 = lerp_u8(a, 255, 0);
            // Result must be independent of b.
            assert_eq!(
                v0, v255,
                "lerp_u8({a}, b, 0) must not depend on b: got {v0} vs {v255}"
            );
            // Result must be within ±1 of a (div255 approximation).
            assert!(
                (i32::from(v0) - i32::from(a)).abs() <= 1,
                "lerp_u8({a}, _, 0) = {v0}, expected within ±1 of {a}"
            );
        }
    }

    #[test]
    fn splash_floor_ceil_round() {
        let cases = [
            (0.0f64, 0, 0, 0),
            (0.5, 0, 1, 1),
            (0.9, 0, 1, 1),
            (1.0, 1, 1, 1),
            (-0.1, -1, 0, 0),
            (-0.5, -1, 0, 0),
            (-0.6, -1, 0, -1),
            (-1.0, -1, -1, -1),
        ];
        for (x, fl, ce, ro) in cases {
            assert_eq!(splash_floor(x), fl, "floor({x})");
            assert_eq!(splash_ceil(x), ce, "ceil({x})");
            assert_eq!(splash_round(x), ro, "round({x})");
        }
    }

    /// Half-integer tie-breaking: 0.5 → 1, −0.5 → 0 (toward +∞).
    #[test]
    fn splash_round_half_integers() {
        assert_eq!(splash_round(0.5), 1, "0.5 rounds toward +inf");
        assert_eq!(splash_round(-0.5), 0, "-0.5 rounds toward +inf (i.e. 0)");
        assert_eq!(splash_round(1.5), 2);
        assert_eq!(splash_round(-1.5), -1);
    }

    /// Non-finite inputs must not invoke UB and must return a defined sentinel.
    #[test]
    fn splash_floor_ceil_round_non_finite() {
        // +∞ — INFINITY + 0.5 is still INFINITY, so splash_round goes to i32::MAX.
        assert_eq!(splash_floor(f64::INFINITY), i32::MAX);
        assert_eq!(splash_ceil(f64::INFINITY), i32::MAX);
        assert_eq!(splash_round(f64::INFINITY), i32::MAX);
        // −∞
        assert_eq!(splash_floor(f64::NEG_INFINITY), i32::MIN);
        assert_eq!(splash_ceil(f64::NEG_INFINITY), i32::MIN);
        assert_eq!(splash_round(f64::NEG_INFINITY), i32::MIN);
        // NaN — treated as non-positive (returns i32::MIN). NaN + 0.5 is NaN
        // so splash_round also returns i32::MIN.
        assert_eq!(splash_floor(f64::NAN), i32::MIN);
        assert_eq!(splash_ceil(f64::NAN), i32::MIN);
        assert_eq!(splash_round(f64::NAN), i32::MIN);
    }

    // ── gray_to_u8 ────────────────────────────────────────────────────────────

    #[test]
    fn gray_extremes() {
        assert_eq!(gray_to_u8(0.0), 0);
        assert_eq!(gray_to_u8(1.0), 255);
    }

    #[test]
    fn gray_clamped() {
        assert_eq!(gray_to_u8(-1.0), 0);
        assert_eq!(gray_to_u8(2.0), 255);
    }

    /// NaN must map to 0 — `f64::clamp` returns NaN unchanged, then Rust's
    /// float-to-int saturation maps NaN → 0.
    #[test]
    fn gray_nan_is_zero() {
        assert_eq!(gray_to_u8(f64::NAN), 0);
    }

    // ── cmyk_to_rgb_bytes ─────────────────────────────────────────────────────

    #[test]
    fn cmyk_bytes_black() {
        assert_eq!(cmyk_to_rgb_bytes(0.0, 0.0, 0.0, 1.0), [0, 0, 0]);
    }

    #[test]
    fn cmyk_bytes_white() {
        assert_eq!(cmyk_to_rgb_bytes(0.0, 0.0, 0.0, 0.0), [255, 255, 255]);
    }

    /// NaN inputs in the formula `1 − min(c+k, 1)` go through `f64::min`,
    /// which returns the non-NaN argument (`1.0`), so `1 − 1 = 0` lands in
    /// the affected channel. With `k = NaN`, every channel's expression
    /// involves the NaN, so every output byte is 0.
    #[test]
    fn cmyk_bytes_nan_channel_is_zero() {
        assert_eq!(cmyk_to_rgb_bytes(f64::NAN, 0.0, 0.0, 0.0), [0, 255, 255]);
        assert_eq!(cmyk_to_rgb_bytes(0.0, 0.0, 0.0, f64::NAN), [0, 0, 0]);
    }

    // ── cmyk_to_rgb_reflectance ───────────────────────────────────────────────

    /// `cmyk_to_rgb_reflectance` — all-zero ink (no ink) must produce white.
    #[test]
    fn cmyk_reflectance_no_ink_is_white() {
        assert_eq!(cmyk_to_rgb_reflectance(0, 0, 0, 0), (255, 255, 255));
    }

    /// `cmyk_to_rgb_reflectance` — full K (key/black) must produce black.
    #[test]
    fn cmyk_reflectance_full_k_is_black() {
        assert_eq!(cmyk_to_rgb_reflectance(0, 0, 0, 255), (0, 0, 0));
    }

    /// `cmyk_to_rgb_reflectance` — C=255, no K → R=0, G=B=255.
    #[test]
    fn cmyk_reflectance_full_cyan_no_k() {
        let (r, g, b) = cmyk_to_rgb_reflectance(255, 0, 0, 0);
        assert_eq!(r, 0);
        assert_eq!(g, 255);
        assert_eq!(b, 255);
    }

    /// `cmyk_to_rgb_reflectance` — midtone C=128 gives R ≈ 127–128.
    #[test]
    fn cmyk_reflectance_midtone() {
        let (r, g, b) = cmyk_to_rgb_reflectance(128, 0, 0, 0);
        assert!((127..=128).contains(&r), "r={r}");
        assert_eq!(g, 255);
        assert_eq!(b, 255);
    }

    /// `cmyk_to_rgb` saturation: when c+k > 255 the channel must be 0.
    #[test]
    fn cmyk_saturation() {
        // c=200, k=200 → c+k=400 → saturating_sub → 0, red=clip255(0)=0
        let (r, g, b) = cmyk_to_rgb(200, 0, 0, 200);
        assert_eq!(r, 0, "saturated red channel must be 0");
        assert_eq!(g, 55, "green = 255 - 200 = 55");
        assert_eq!(b, 55, "blue  = 255 - 200 = 55");

        // Full black: all channels 0.
        let (r, g, b) = cmyk_to_rgb(0, 0, 0, 255);
        assert_eq!((r, g, b), (0, 0, 0));

        // No ink: all channels 255.
        let (r, g, b) = cmyk_to_rgb(0, 0, 0, 0);
        assert_eq!((r, g, b), (255, 255, 255));
    }
}