alpha-blend 0.3.0

Alpha blending and compositing
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Normalized color channel arithmetic.
//!
//! A [`Channel`] is one component of a color, interpreted as a number in `0..=1` regardless of
//! how it is stored. [`u8`] stores that range as `0..=255`; [`f32`] stores it directly. Every
//! operation in this module is defined on the normalized value, so `u8` and `f32` produce the
//! same answer up to the precision of the storage type.
//!
//! This is what makes [`BlendMode`](crate::BlendMode) and
//! [`CompositeMode`](crate::CompositeMode) generic: they are written once against [`Channel`]
//! and each storage type supplies its own exact implementation, rather than the integer path
//! detouring through floats.
//!
//! ## Rounding
//!
//! Integer channels **round to nearest, ties away from zero**. Every integer operation here
//! rounds exactly once, at the end, from a widened intermediate. There is no truncating variant
//! and no accumulating downward bias: `scale(255, 255) == 255`, and compositing an opaque pixel
//! any number of times is idempotent.
//!
//! Division by 255 is spelled `(v + 127) / 255`, which is exactly `round(v / 255)` for every
//! `v` this crate can produce (verified exhaustively in this module's tests). The better known
//! `(v + 128 + ((v + 128) >> 8)) >> 8` shift trick is *not* used, because it stops agreeing with
//! round-to-nearest at `v = 65663`, and [`Channel::sum_of_products`] reaches `130050`. `u32 / 255` by a
//! constant compiles to a multiply and a shift on every target this crate supports, so the
//! division is not a cost.

use crate::math;

/// One normalized color component, stored as [`u8`] or [`f32`].
///
/// Implementations must treat the value as a number in `0..=1`, where [`Channel::ZERO`] is `0`
/// and [`Channel::ONE`] is `1`. Integer implementations round to nearest, exactly once per
/// operation; see the [module docs](self) for why.
///
/// This trait is deliberately not sealed. A downstream crate can add a channel type (`u16`,
/// fixed-point, or a `f16`) and get every blend and composite mode for free. It is
/// `#[non_exhaustive]`-in-spirit: methods may be added in minor releases, so implement it only
/// if you are prepared for that.
pub trait Channel: Copy + PartialEq + PartialOrd {
    /// The normalized value `0`, stored as `0u8` or `0.0f32`.
    ///
    /// Deliberately not called `MIN`: an associated const named `MIN` would be shadowed by the
    /// inherent [`f32::MIN`] (which is `-3.4e38`, not `0.0`) at every use site inside a generic
    /// impl, silently and without a warning.
    const ZERO: Self;

    /// The normalized value `1`, stored as `255u8` or `1.0f32`.
    ///
    /// See [`Channel::ZERO`] for why this is not called `MAX`.
    const ONE: Self;

    /// The largest representable value that is still `<= 0.5` when normalized.
    ///
    /// For [`f32`] this is exactly `0.5`. For [`u8`] it is `127`, because `127 / 255` is
    /// `0.498` and `128 / 255` is `0.502`; the W3C blend modes branch on `Cs <= 0.5`, and
    /// `127` is the last value on the low side of that test.
    const HALF: Self;

    /// Returns `self * rhs`, normalized.
    ///
    /// Exact at both endpoints: `MAX.scale(x) == x` and `MIN.scale(x) == MIN`.
    #[must_use]
    fn scale(self, rhs: Self) -> Self;

    /// Returns `a * b + c * d`, normalized and saturated to `ZERO..=ONE`.
    ///
    /// This is the fused primitive the compositing formula is built from. Integer
    /// implementations must round **once**, from a widened intermediate, rather than rounding
    /// each product. Rounding twice is where a systematic bias creeps in.
    ///
    /// Named for what it computes rather than `mul_add`, which would shadow the inherent
    /// [`f32::mul_add`] (a different operation with a different arity).
    #[must_use]
    fn sum_of_products(a: Self, b: Self, c: Self, d: Self) -> Self;

    /// Returns `self / rhs`, normalized and saturated to `ZERO..=ONE`.
    ///
    /// Returns [`Channel::ONE`] when `rhs` is [`Channel::ZERO`], matching the `min(1, x / 0)`
    /// convention the W3C blend modes use for [`ColorDodge`](crate::BlendMode::ColorDodge).
    #[must_use]
    fn div_normalized(self, rhs: Self) -> Self;

    /// Returns the square root of the normalized value.
    #[must_use]
    fn sqrt_normalized(self) -> Self;

    /// Returns the W3C `D(Cb)` helper used by [`SoftLight`](crate::BlendMode::SoftLight).
    ///
    /// ```text
    /// D(Cb) = ((16 * Cb - 12) * Cb + 4) * Cb   if Cb <= 0.25
    ///         sqrt(Cb)                         otherwise
    /// ```
    ///
    /// This is on the trait rather than inlined into the blend mode so integer channels can
    /// evaluate it exactly without a float detour.
    #[must_use]
    fn soft_light_d(self) -> Self;

    /// Returns `1 - self`.
    #[must_use]
    fn complement(self) -> Self;

    /// Returns `self + rhs`, saturating at [`Channel::ONE`].
    #[must_use]
    fn saturating_add(self, rhs: Self) -> Self;

    /// Returns `2 * self - 1`, saturating at [`Channel::ZERO`].
    ///
    /// The upper half of the [`HardLight`](crate::BlendMode::HardLight) and
    /// [`SoftLight`](crate::BlendMode::SoftLight) branches needs this. Computing it as
    /// `self - (1 - self)` rather than `2 * self - 1` avoids saturating the doubled
    /// intermediate, which would clamp away the very value being extracted.
    #[must_use]
    fn double_minus_one(self) -> Self {
        self.saturating_sub(self.complement())
    }

    /// Returns `self - rhs`, saturating at [`Channel::ZERO`].
    #[must_use]
    fn saturating_sub(self, rhs: Self) -> Self;

    /// Returns `|self - rhs|`.
    #[must_use]
    fn abs_diff(self, rhs: Self) -> Self;

    /// Converts to a normalized [`f32`] in `0.0..=1.0`.
    #[must_use]
    fn to_f32(self) -> f32;

    /// Converts from a normalized [`f32`], clamping and rounding as the storage type requires.
    #[must_use]
    fn from_f32(value: f32) -> Self;

    /// Linearly interpolates from `self` to `to` by `t`.
    ///
    /// Exact at both endpoints: `t == MIN` returns `self` and `t == MAX` returns `to`.
    #[must_use]
    fn lerp(self, to: Self, t: Self) -> Self {
        Self::sum_of_products(self, t.complement(), to, t)
    }

    /// Returns the smaller of `self` and `rhs`.
    #[must_use]
    fn min_channel(self, rhs: Self) -> Self {
        if self < rhs { self } else { rhs }
    }

    /// Returns the larger of `self` and `rhs`.
    #[must_use]
    fn max_channel(self, rhs: Self) -> Self {
        if self > rhs { self } else { rhs }
    }

    /// Returns `true` if this is exactly [`Channel::ZERO`].
    #[must_use]
    fn is_zero(self) -> bool {
        self == Self::ZERO
    }

    /// Returns `true` if this is exactly [`Channel::ONE`].
    #[must_use]
    fn is_one(self) -> bool {
        self == Self::ONE
    }
}

// ---------------------------------------------------------------------------
// u8
// ---------------------------------------------------------------------------

/// Divides by 255 with round-to-nearest, for any `v` up to `2 * 255 * 255`.
///
/// Exact for every input in that range; see the [module docs](self) for why this and not the
/// usual shift trick.
//
// TODO(retroglyph#547): `gem::rgb::scale_u8` and `retroglyph_core::tint::scale` compute the
// same thing. They must use this same round-to-nearest rule; if any of them truncates, the
// pipeline reintroduces the per-composite darkening this crate just removed. Consider
// consolidating on one implementation once gem's channel helpers land.
#[allow(clippy::cast_possible_truncation)]
pub(crate) const fn div255(v: u32) -> u8 {
    debug_assert!(v <= 2 * 255 * 255);
    let q = (v + 127) / 255;
    // Saturate rather than wrap: `sum_of_products` can legitimately exceed 1 (`Plus` does).
    if q > 255 { 255 } else { q as u8 }
}

/// Returns `round(sqrt(v))` for `v` up to `u32::MAX / 4`.
const fn sqrt_round(v: u32) -> u32 {
    // round(sqrt(v)) == ceil(floor(sqrt(4v)) / 2), using only integer square roots.
    (4 * v).isqrt().div_ceil(2)
}

impl Channel for u8 {
    const ZERO: Self = 0;
    const ONE: Self = 255;
    const HALF: Self = 127;

    fn scale(self, rhs: Self) -> Self {
        div255(u32::from(self) * u32::from(rhs))
    }

    fn sum_of_products(a: Self, b: Self, c: Self, d: Self) -> Self {
        div255(u32::from(a) * u32::from(b) + u32::from(c) * u32::from(d))
    }

    #[allow(clippy::cast_possible_truncation)]
    fn div_normalized(self, rhs: Self) -> Self {
        if rhs == 0 {
            return Self::ONE;
        }
        let rhs = u32::from(rhs);
        let q = (u32::from(self) * 255 + rhs / 2) / rhs;
        if q > 255 { 255 } else { q as Self }
    }

    #[allow(clippy::cast_possible_truncation)]
    fn sqrt_normalized(self) -> Self {
        // sqrt(v / 255) * 255 == sqrt(v * 255), and the product is at most 65025.
        sqrt_round(u32::from(self) * 255) as Self
    }

    fn soft_light_d(self) -> Self {
        // 0.25 normalized is 63.75, so 63 is the last value on the polynomial side.
        if self > 63 {
            return self.sqrt_normalized();
        }
        // ((16x - 12)x + 4)x with x = v/255, rescaled by 255 and reduced over a common
        // denominator: (16v^3 - 12*255*v^2 + 4*255^2*v) / 255^2. Non-negative and at most
        // 8241912 for v in 0..=63, so u32 is plenty.
        let v = u32::from(self);
        let num = 16 * v * v * v + 260_100 * v - 3060 * v * v;
        #[allow(clippy::cast_possible_truncation)]
        {
            ((2 * num + 65025) / (2 * 65025)) as Self
        }
    }

    fn complement(self) -> Self {
        255 - self
    }

    // Spelled out rather than delegating to the inherent `u8` methods of the same name, so
    // that method resolution cannot quietly pick the trait method and recurse forever.
    #[allow(clippy::cast_possible_truncation)]
    fn saturating_add(self, rhs: Self) -> Self {
        let sum = u16::from(self) + u16::from(rhs);
        if sum > 255 { 255 } else { sum as Self }
    }

    // Method resolution prefers the inherent `u8` methods over the trait ones being defined
    // here, so these delegate rather than recurse.
    fn saturating_sub(self, rhs: Self) -> Self {
        Self::saturating_sub(self, rhs)
    }

    fn abs_diff(self, rhs: Self) -> Self {
        Self::abs_diff(self, rhs)
    }

    fn to_f32(self) -> f32 {
        f32::from(self) / 255.0
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    fn from_f32(value: f32) -> Self {
        if value <= 0.0 {
            return 0;
        }
        if value >= 1.0 {
            return 255;
        }
        math::round(value * 255.0) as Self
    }
}

// ---------------------------------------------------------------------------
// f32
// ---------------------------------------------------------------------------

/// Clamps to `0.0..=1.0` without `f32::clamp`, which is not available in `core`.
const fn saturate(v: f32) -> f32 {
    if v < 0.0 {
        0.0
    } else if v > 1.0 {
        1.0
    } else {
        v
    }
}

impl Channel for f32 {
    const ZERO: Self = 0.0;
    const ONE: Self = 1.0;
    const HALF: Self = 0.5;

    fn scale(self, rhs: Self) -> Self {
        self * rhs
    }

    #[allow(clippy::suboptimal_flops)]
    fn sum_of_products(a: Self, b: Self, c: Self, d: Self) -> Self {
        saturate(a * b + c * d)
    }

    fn div_normalized(self, rhs: Self) -> Self {
        if rhs == 0.0 {
            return Self::ONE;
        }
        saturate(self / rhs)
    }

    fn sqrt_normalized(self) -> Self {
        math::sqrt(self)
    }

    #[allow(clippy::suboptimal_flops)]
    fn soft_light_d(self) -> Self {
        if self > 0.25 {
            return self.sqrt_normalized();
        }
        ((16.0 * self - 12.0) * self + 4.0) * self
    }

    fn complement(self) -> Self {
        1.0 - self
    }

    fn saturating_add(self, rhs: Self) -> Self {
        saturate(self + rhs)
    }

    fn saturating_sub(self, rhs: Self) -> Self {
        saturate(self - rhs)
    }

    fn abs_diff(self, rhs: Self) -> Self {
        if self > rhs { self - rhs } else { rhs - self }
    }

    fn to_f32(self) -> f32 {
        self
    }

    fn from_f32(value: f32) -> Self {
        saturate(value)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::float_cmp,
    clippy::suboptimal_flops
)]
mod tests {
    use super::*;

    /// The reference: `round(v / 255)` computed without floats, ties away from zero.
    const fn div255_reference(v: u32) -> u32 {
        (2 * v + 255) / 510
    }

    /// `(v + 127) / 255` must be exactly round-to-nearest over the entire range `sum_of_products` can
    /// reach. This is the load-bearing claim of the whole integer path.
    #[test]
    fn div255_is_exactly_round_to_nearest() {
        for v in 0..=(2 * 255 * 255) {
            assert_eq!(
                u32::from(div255(v)).min(255),
                div255_reference(v).min(255),
                "v = {v}",
            );
        }
    }

    /// The shift trick this crate deliberately does not use. Documenting the exact point where
    /// it diverges, so nobody "optimizes" `div255` back into it.
    #[test]
    fn shift_trick_diverges_above_65662() {
        const fn shift_trick(v: u32) -> u32 {
            let p = v + 128;
            (p + (p >> 8)) >> 8
        }
        for v in 0..=65662 {
            assert_eq!(shift_trick(v), div255_reference(v), "v = {v}");
        }
        assert_ne!(shift_trick(65663), div255_reference(65663));
    }

    /// The bug this crate shipped in 0.2.x: `(v + (v >> 8) + 1) >> 8` is `floor`, not `round`.
    #[test]
    fn legacy_source_over_trick_was_truncating() {
        const fn legacy(v: u32) -> u32 {
            (v + (v >> 8) + 1) >> 8
        }
        let mut differ = 0;
        for v in 0..=65025u32 {
            assert_eq!(legacy(v), v / 255, "legacy is exactly floor; v = {v}");
            if legacy(v) != div255_reference(v) {
                differ += 1;
            }
        }
        // Half of all inputs were rounded the wrong way.
        assert_eq!(differ, 32385);
    }

    // --- u8 exactness ---

    #[test]
    fn u8_scale_matches_exact_rational() {
        for a in 0..=255u8 {
            for b in 0..=255u8 {
                let expected = div255_reference(a as u32 * b as u32) as u8;
                assert_eq!(a.scale(b), expected, "{a} * {b}");
            }
        }
    }

    #[test]
    fn u8_scale_endpoints_are_exact() {
        for v in 0..=255u8 {
            assert_eq!(v.scale(255), v, "MAX is the multiplicative identity");
            assert_eq!(v.scale(0), 0);
        }
    }

    /// The property `Tint::scale` in retroglyph was written to guarantee, now guaranteed here.
    #[test]
    fn u8_scale_by_max_never_drifts() {
        let mut v = 200u8;
        for _ in 0..1000 {
            v = v.scale(255);
        }
        assert_eq!(v, 200);
    }

    #[test]
    fn u8_sum_of_products_rounds_once() {
        for a in (0..=255u8).step_by(17) {
            for b in (0..=255u8).step_by(13) {
                for c in (0..=255u8).step_by(19) {
                    for d in (0..=255u8).step_by(11) {
                        let wide = a as u32 * b as u32 + c as u32 * d as u32;
                        let expected = div255_reference(wide).min(255) as u8;
                        assert_eq!(
                            <u8 as Channel>::sum_of_products(a, b, c, d),
                            expected,
                            "{a}*{b} + {c}*{d}",
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn u8_sum_of_products_saturates() {
        assert_eq!(<u8 as Channel>::sum_of_products(255, 255, 255, 255), 255);
    }

    #[test]
    fn u8_lerp_endpoints_are_exact() {
        for a in 0..=255u8 {
            for b in (0..=255u8).step_by(5) {
                assert_eq!(a.lerp(b, 0), a, "t = MIN returns self");
                assert_eq!(a.lerp(b, 255), b, "t = MAX returns to");
            }
        }
    }

    #[test]
    fn u8_lerp_midpoint() {
        assert_eq!(0u8.lerp(255, 127), 127);
        assert_eq!(0u8.lerp(255, 128), 128);
        assert_eq!(100u8.lerp(200, 128), 150);
    }

    #[test]
    fn u8_div_normalized() {
        assert_eq!(128u8.div_normalized(255), 128);
        assert_eq!(
            255u8.div_normalized(128),
            255,
            "saturates instead of wrapping"
        );
        // 64/128 is exactly 0.5, which is 127.5 in u8 and rounds up.
        assert_eq!(64u8.div_normalized(128), 128);
        assert_eq!(1u8.div_normalized(0), 255, "divide by zero is ONE");
        assert_eq!(0u8.div_normalized(0), 255);
    }

    #[test]
    fn double_minus_one() {
        assert_eq!(255u8.double_minus_one(), 255);
        assert_eq!(128u8.double_minus_one(), 1);
        assert_eq!(127u8.double_minus_one(), 0, "saturates at ZERO");
        assert_eq!(0u8.double_minus_one(), 0);
        assert_eq!(1.0f32.double_minus_one(), 1.0);
        assert_eq!(0.75f32.double_minus_one(), 0.5);
        assert_eq!(0.25f32.double_minus_one(), 0.0);
    }

    /// The naive `2 * x` then subtract `ONE` saturates the intermediate and loses the value.
    /// This is the shape of a bug that shipped in a draft of this module.
    #[test]
    fn double_minus_one_does_not_saturate_the_intermediate() {
        for v in 128..=255u8 {
            let naive = Channel::saturating_sub(Channel::saturating_add(v, v), 255u8);
            assert_eq!(
                naive, 0,
                "the doubled intermediate always clamps to ONE first"
            );
            assert_eq!(
                v.double_minus_one(),
                (2 * u16::from(v) - 255) as u8,
                "v={v}"
            );
        }
    }

    #[test]
    fn u8_div_normalized_inverts_scale() {
        // Exact only where the product is representable, so allow the storage error.
        for a in (0..=255u8).step_by(7) {
            for b in (1..=255u8).step_by(7) {
                let round_trip = a.scale(b).div_normalized(b);
                let expected = a;
                let tolerance = 255 / u16::from(b);
                assert!(
                    u16::from(round_trip).abs_diff(u16::from(expected)) <= tolerance + 1,
                    "{a} scaled by {b} then divided back gave {round_trip}",
                );
            }
        }
    }

    #[test]
    fn u8_sqrt_normalized_matches_float() {
        for v in 0..=255u8 {
            let expected = math::round(math::sqrt(f32::from(v) / 255.0) * 255.0) as u8;
            assert_eq!(v.sqrt_normalized(), expected, "sqrt({v})");
        }
    }

    #[test]
    fn u8_sqrt_normalized_endpoints() {
        assert_eq!(0u8.sqrt_normalized(), 0);
        assert_eq!(255u8.sqrt_normalized(), 255);
        assert_eq!(64u8.sqrt_normalized(), 128, "sqrt(0.25) == 0.5");
    }

    #[test]
    fn u8_soft_light_d_matches_float_reference() {
        for v in 0..=255u8 {
            let x = f32::from(v) / 255.0;
            let expected = if x <= 0.25 {
                ((16.0 * x - 12.0) * x + 4.0) * x
            } else {
                math::sqrt(x)
            };
            let expected = math::round(expected * 255.0) as u8;
            assert!(
                v.soft_light_d().abs_diff(expected) <= 1,
                "D({v}) = {}, expected {expected}",
                v.soft_light_d(),
            );
        }
    }

    #[test]
    fn u8_soft_light_d_is_continuous_at_the_boundary() {
        // The polynomial branch ends at 63 and the sqrt branch starts at 64; they must meet.
        assert_eq!(63u8.soft_light_d(), 127);
        assert_eq!(64u8.soft_light_d(), 128);
    }

    #[test]
    fn u8_soft_light_d_never_darkens() {
        for v in 0..=255u8 {
            assert!(v.soft_light_d() >= v, "D({v}) must be >= {v}");
        }
    }

    #[test]
    fn u8_complement_and_saturation() {
        assert_eq!(0u8.complement(), 255);
        assert_eq!(255u8.complement(), 0);
        assert_eq!(200u8.saturating_add(100), 255);
        assert_eq!(50u8.saturating_sub(100), 0);
        assert_eq!(50u8.abs_diff(100), 50);
        assert_eq!(100u8.abs_diff(50), 50);
    }

    #[test]
    fn u8_f32_round_trip() {
        for v in 0..=255u8 {
            assert_eq!(u8::from_f32(v.to_f32()), v);
        }
        assert_eq!(u8::from_f32(-1.0), 0, "clamps below");
        assert_eq!(u8::from_f32(2.0), 255, "clamps above");
    }

    #[test]
    fn u8_half_straddles_one_half() {
        assert!(f32::from(<u8 as Channel>::HALF) / 255.0 <= 0.5);
        assert!(f32::from(<u8 as Channel>::HALF + 1) / 255.0 > 0.5);
    }

    // --- f32 ---

    #[test]
    fn f32_basics() {
        assert_eq!(0.5f32.scale(0.5), 0.25);
        assert_eq!(<f32 as Channel>::sum_of_products(0.5, 0.5, 0.25, 1.0), 0.5);
        assert_eq!(
            <f32 as Channel>::sum_of_products(1.0, 1.0, 1.0, 1.0),
            1.0,
            "saturates",
        );
        assert_eq!(0.25f32.div_normalized(0.5), 0.5);
        assert_eq!(0.5f32.div_normalized(0.0), 1.0);
        assert_eq!(0.25f32.sqrt_normalized(), 0.5);
        assert_eq!(0.25f32.complement(), 0.75);
        assert_eq!(0.75f32.saturating_add(0.75), 1.0);
        assert_eq!(0.25f32.saturating_sub(0.75), 0.0);
        assert_eq!(0.25f32.abs_diff(0.75), 0.5);
        assert_eq!(Channel::min_channel(0.25f32, 0.75), 0.25);
        assert_eq!(Channel::max_channel(0.25f32, 0.75), 0.75);
        assert!(0.0f32.is_zero());
        assert!(1.0f32.is_one());
    }

    #[test]
    fn f32_conversion_is_the_identity_but_clamps() {
        assert_eq!(0.25f32.to_f32(), 0.25);
        assert_eq!(f32::from_f32(0.25), 0.25);
        assert_eq!(f32::from_f32(-1.0), 0.0);
        assert_eq!(f32::from_f32(2.0), 1.0);
    }

    #[test]
    fn f32_lerp_endpoints_are_exact() {
        assert_eq!(0.25f32.lerp(0.75, 0.0), 0.25);
        assert_eq!(0.25f32.lerp(0.75, 1.0), 0.75);
        assert_eq!(0.0f32.lerp(1.0, 0.5), 0.5);
    }

    #[test]
    fn f32_soft_light_d() {
        assert_eq!(0.25f32.soft_light_d(), 0.5, "polynomial meets sqrt at 0.25");
        assert_eq!(1.0f32.soft_light_d(), 1.0);
        assert_eq!(0.0f32.soft_light_d(), 0.0);
    }

    /// `u8` and `f32` are the same function, evaluated at different precisions.
    #[test]
    fn u8_and_f32_agree_within_storage_precision() {
        for a in (0..=255u8).step_by(3) {
            for b in (0..=255u8).step_by(3) {
                let int = a.scale(b).to_f32();
                let flt = a.to_f32().scale(b.to_f32());
                assert!(
                    (int - flt).abs() <= 0.5 / 255.0,
                    "{a} * {b}: {int} vs {flt}"
                );
            }
        }
    }
}