Skip to main content

alpha_blend/
rgba.rs

1//! RGBA color representation, in straight and premultiplied alpha.
2
3#[cfg(feature = "std")]
4extern crate std;
5
6use core::fmt;
7use core::ptr;
8
9use crate::channel::{Channel, div255};
10
11/// Four-component vector type for representing RGBA colors.
12///
13/// Values use **straight (un-premultiplied) alpha**. See [`Premultiplied`] for the other
14/// convention, and [`Rgba::premultiply`] to convert.
15///
16/// ## Layout
17///
18/// The layout of the `Rgba` struct is as follows:
19///
20/// ```text
21/// +----------------+----------------+----------------+----------------+
22/// |      r         |      g         |      b         |      a         |
23/// +----------------+----------------+----------------+----------------+
24/// ```
25///
26/// As a C-style struct, it represents:
27///
28/// ```c
29/// template <typename C>
30/// struct Rgba {
31///    C r;
32///    C g;
33///    C b;
34///    C a;
35/// };
36/// ```
37///
38/// See [`U8x4Rgba`] and [`F32x4Rgba`] for type aliases with specific component types.
39#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
40#[repr(C)]
41pub struct Rgba<C>
42where
43    C: Copy,
44{
45    /// Red component.
46    pub r: C,
47
48    /// Green component.
49    pub g: C,
50
51    /// Blue component.
52    pub b: C,
53
54    /// Alpha component.
55    pub a: C,
56}
57
58/// An [`Rgba`] whose color channels have already been multiplied by its alpha.
59///
60/// Compositing is defined on premultiplied color, so this is what
61/// [`Composite::composite`](crate::Composite::composite) returns. Keeping it in a distinct type
62/// means a premultiplied pixel cannot be silently handed to something expecting straight alpha,
63/// which is the class of bug that motivated it.
64///
65/// ## Precision
66///
67/// [`Premultiplied::unpremultiply`] divides each channel by alpha. For integer channels that
68/// division is **lossy and not reversible**: `c.premultiply().unpremultiply() != c` in general,
69/// and the error grows as alpha falls. Stay premultiplied for as long as you can, and prefer
70/// [`U8x4Rgba::source_over`] over a manual round trip when all you need is source-over.
71#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
72#[repr(transparent)]
73pub struct Premultiplied<T>(T);
74
75// ---------------------------------------------------------------------------
76// `bytemuck` impls
77// ---------------------------------------------------------------------------
78
79#[cfg(feature = "bytemuck")]
80unsafe impl bytemuck::Zeroable for U8x4Rgba {}
81
82#[cfg(feature = "bytemuck")]
83unsafe impl bytemuck::Pod for U8x4Rgba {}
84
85#[cfg(feature = "bytemuck")]
86unsafe impl bytemuck::Zeroable for F32x4Rgba {}
87
88#[cfg(feature = "bytemuck")]
89unsafe impl bytemuck::Pod for F32x4Rgba {}
90
91#[cfg(feature = "bytemuck")]
92unsafe impl bytemuck::Zeroable for PremultipliedU8x4Rgba {}
93
94#[cfg(feature = "bytemuck")]
95unsafe impl bytemuck::Pod for PremultipliedU8x4Rgba {}
96
97#[cfg(feature = "bytemuck")]
98unsafe impl bytemuck::Zeroable for PremultipliedF32x4Rgba {}
99
100#[cfg(feature = "bytemuck")]
101unsafe impl bytemuck::Pod for PremultipliedF32x4Rgba {}
102
103// ---------------------------------------------------------------------------
104// Structural conversions
105// ---------------------------------------------------------------------------
106
107impl<C: Copy> From<[C; 4]> for Rgba<C> {
108    fn from([r, g, b, a]: [C; 4]) -> Self {
109        Self::new(r, g, b, a)
110    }
111}
112
113impl<C: Copy> From<Rgba<C>> for [C; 4] {
114    fn from(c: Rgba<C>) -> Self {
115        [c.r, c.g, c.b, c.a]
116    }
117}
118
119impl<C: Copy> From<(C, C, C, C)> for Rgba<C> {
120    fn from((r, g, b, a): (C, C, C, C)) -> Self {
121        Self::new(r, g, b, a)
122    }
123}
124
125impl<C: Copy> From<Rgba<C>> for (C, C, C, C) {
126    fn from(c: Rgba<C>) -> Self {
127        (c.r, c.g, c.b, c.a)
128    }
129}
130
131impl<C: Copy> AsRef<[C]> for Rgba<C> {
132    fn as_ref(&self) -> &[C] {
133        // Safety: Rgba<C> is repr(C) with 4 contiguous elements of type C.
134        unsafe { core::slice::from_raw_parts(ptr::from_ref(self).cast::<C>(), 4) }
135    }
136}
137
138impl<C: Copy> AsMut<[C]> for Rgba<C> {
139    fn as_mut(&mut self) -> &mut [C] {
140        unsafe { core::slice::from_raw_parts_mut(ptr::from_mut(self).cast::<C>(), 4) }
141    }
142}
143
144// ---------------------------------------------------------------------------
145// Display
146// ---------------------------------------------------------------------------
147
148impl fmt::Display for Rgba<u8> {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        write!(f, "rgba({}, {}, {}, {})", self.r, self.g, self.b, self.a)
151    }
152}
153
154impl fmt::Display for Rgba<f32> {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "rgba({}, {}, {}, {})", self.r, self.g, self.b, self.a)
157    }
158}
159
160impl<T: fmt::Display> fmt::Display for Premultiplied<T> {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        write!(f, "premultiplied {}", self.0)
163    }
164}
165
166// ---------------------------------------------------------------------------
167// Eq + Hash for u8
168// ---------------------------------------------------------------------------
169
170impl Eq for Rgba<u8> {}
171
172impl core::hash::Hash for Rgba<u8> {
173    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
174        self.r.hash(state);
175        self.g.hash(state);
176        self.b.hash(state);
177        self.a.hash(state);
178    }
179}
180
181impl Eq for Premultiplied<Rgba<u8>> {}
182
183impl core::hash::Hash for Premultiplied<Rgba<u8>> {
184    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
185        self.0.hash(state);
186    }
187}
188
189// ---------------------------------------------------------------------------
190// Rgba<C> inherent methods
191// ---------------------------------------------------------------------------
192
193impl<C> Rgba<C>
194where
195    C: Copy,
196{
197    /// Creates a new `Rgba` instance with the specified components.
198    pub const fn new(r: C, g: C, b: C, a: C) -> Self {
199        Self { r, g, b, a }
200    }
201
202    /// Returns the red component.
203    pub const fn red(&self) -> C {
204        self.r
205    }
206
207    /// Returns the green component.
208    pub const fn green(&self) -> C {
209        self.g
210    }
211
212    /// Returns the blue component.
213    pub const fn blue(&self) -> C {
214        self.b
215    }
216
217    /// Returns the alpha component.
218    pub const fn alpha(&self) -> C {
219        self.a
220    }
221}
222
223impl<C> Rgba<C>
224where
225    C: Channel,
226{
227    /// Converts from straight alpha to premultiplied alpha.
228    ///
229    /// `premultiplied.rgb = straight.rgb * straight.a`
230    #[must_use]
231    pub fn premultiply(self) -> Premultiplied<Self> {
232        Premultiplied(Self::new(
233            self.r.scale(self.a),
234            self.g.scale(self.a),
235            self.b.scale(self.a),
236            self.a,
237        ))
238    }
239
240    /// Linearly interpolates between `self` and `other` by `t`, clamped to `MIN..=MAX`.
241    ///
242    /// `t == Channel::ZERO` returns `self`; `t == Channel::ONE` returns `other`. Both endpoints
243    /// are exact for every channel type.
244    #[must_use]
245    pub fn lerp(self, other: Self, t: C) -> Self {
246        let t = t.max_channel(C::ZERO).min_channel(C::ONE);
247        Self::new(
248            self.r.lerp(other.r, t),
249            self.g.lerp(other.g, t),
250            self.b.lerp(other.b, t),
251            self.a.lerp(other.a, t),
252        )
253    }
254}
255
256// ---------------------------------------------------------------------------
257// Premultiplied<T>
258// ---------------------------------------------------------------------------
259
260impl<T: Copy> Premultiplied<T> {
261    /// Wraps an already-premultiplied value.
262    ///
263    /// Nothing is checked. Passing a straight-alpha value produces a
264    /// [`Premultiplied`] that lies, which is exactly what this type exists to prevent, so
265    /// prefer [`Rgba::premultiply`] unless the value came from outside this crate already
266    /// premultiplied.
267    pub const fn from_premultiplied(value: T) -> Self {
268        Self(value)
269    }
270
271    /// Returns the premultiplied components without converting.
272    pub const fn get(self) -> T {
273        self.0
274    }
275}
276
277impl<C: Channel> Premultiplied<Rgba<C>> {
278    /// Converts from premultiplied alpha back to straight alpha.
279    ///
280    /// Returns a fully transparent color when `alpha` is [`Channel::ZERO`], rather than dividing
281    /// by zero.
282    ///
283    /// **Lossy for integer channels.** See the note on [`Premultiplied`].
284    #[must_use]
285    pub fn unpremultiply(self) -> Rgba<C> {
286        let c = self.0;
287        if c.a.is_one() {
288            return c;
289        }
290        if c.a.is_zero() {
291            return Rgba::new(C::ZERO, C::ZERO, C::ZERO, C::ZERO);
292        }
293        Rgba::new(
294            c.r.div_normalized(c.a),
295            c.g.div_normalized(c.a),
296            c.b.div_normalized(c.a),
297            c.a,
298        )
299    }
300}
301
302// ---------------------------------------------------------------------------
303// Type aliases
304// ---------------------------------------------------------------------------
305
306/// Four-component RGBA color with a component type of [`u8`].
307pub type U8x4Rgba = Rgba<u8>;
308
309/// Four-component RGBA color with a component type of [`f32`].
310pub type F32x4Rgba = Rgba<f32>;
311
312/// Premultiplied four-component RGBA color with a component type of [`u8`].
313pub type PremultipliedU8x4Rgba = Premultiplied<U8x4Rgba>;
314
315/// Premultiplied four-component RGBA color with a component type of [`f32`].
316pub type PremultipliedF32x4Rgba = Premultiplied<F32x4Rgba>;
317
318// ---------------------------------------------------------------------------
319// Constants
320// ---------------------------------------------------------------------------
321
322impl U8x4Rgba {
323    /// Fully transparent black (`(0, 0, 0, 0)`).
324    pub const TRANSPARENT: Self = Self::new(0, 0, 0, 0);
325
326    /// Fully opaque black (`(0, 0, 0, 255)`).
327    pub const BLACK: Self = Self::new(0, 0, 0, 255);
328
329    /// Fully opaque white (`(255, 255, 255, 255)`).
330    pub const WHITE: Self = Self::new(255, 255, 255, 255);
331}
332
333impl F32x4Rgba {
334    /// Fully transparent black (`(0.0, 0.0, 0.0, 0.0)`).
335    pub const TRANSPARENT: Self = Self::new(0.0, 0.0, 0.0, 0.0);
336
337    /// Fully opaque black (`(0.0, 0.0, 0.0, 1.0)`).
338    pub const BLACK: Self = Self::new(0.0, 0.0, 0.0, 1.0);
339
340    /// Fully opaque white (`(1.0, 1.0, 1.0, 1.0)`).
341    pub const WHITE: Self = Self::new(1.0, 1.0, 1.0, 1.0);
342}
343
344// ---------------------------------------------------------------------------
345// U8 helpers
346// ---------------------------------------------------------------------------
347
348const MAX: f32 = 255.0;
349
350/// Computes one straight-alpha source-over channel, rounding to nearest exactly once.
351///
352/// `num / den` is the exact rational result; `den` is `out_a * 255`.
353#[allow(clippy::cast_possible_truncation)]
354const fn source_over_channel(src: u32, src_a: u32, dst: u32, dst_a: u32, inv_a: u32) -> u8 {
355    let num = src * src_a * 255 + dst * dst_a * inv_a;
356    let den = src_a * 255 + dst_a * inv_a;
357    // Round half up: floor(num / den + 1/2). Peaks at 66_325_500, well inside u32.
358    let q = (2 * num + den) / (2 * den);
359    if q > 255 { 255 } else { q as u8 }
360}
361
362impl U8x4Rgba {
363    /// Creates a new `U8x4Rgba` instance with `0` for all components.
364    #[must_use]
365    pub const fn zeroed() -> Self {
366        Self::new(0, 0, 0, 0)
367    }
368
369    /// Constructs an opaque `U8x4Rgba` from a `0x00RRGGBB` packed pixel.
370    ///
371    /// The alpha channel is set to 255 (fully opaque). The top byte of
372    /// `pixel` is ignored.
373    #[must_use]
374    pub const fn from_rgb_u32(pixel: u32) -> Self {
375        Self::new(
376            ((pixel >> 16) & 0xFF) as u8,
377            ((pixel >> 8) & 0xFF) as u8,
378            (pixel & 0xFF) as u8,
379            255,
380        )
381    }
382
383    /// Packs this color into a `0x00RRGGBB` `u32`, discarding the alpha channel.
384    #[must_use]
385    pub const fn to_rgb_u32(self) -> u32 {
386        ((self.r as u32) << 16) | ((self.g as u32) << 8) | (self.b as u32)
387    }
388
389    /// Blends `self` (source) over `dst` (destination) using integer `SourceOver`.
390    ///
391    /// Equivalent to [`Composite::NORMAL_OVER`](crate::Composite::NORMAL_OVER), specialized to
392    /// straight-alpha `u8` and computed without an intermediate premultiplied round trip:
393    ///
394    /// ```text
395    /// out_a   = src_a + dst_a * (1 - src_a)
396    /// out_rgb = (src_rgb * src_a + dst_rgb * dst_a * (1 - src_a)) / out_a
397    /// ```
398    ///
399    /// ## Rounding
400    ///
401    /// **Rounds to nearest**, once, from an exact widened intermediate. It does not truncate.
402    /// Compositing an opaque source is idempotent and repeated blends do not drift darker.
403    ///
404    /// Before 0.3.0 this used `(v + (v >> 8) + 1) >> 8`, which is exactly `floor(v / 255)` and
405    /// biased every result downward by up to a full LSB. Results changed accordingly.
406    ///
407    /// ## Correctness for translucent destinations
408    ///
409    /// Also fixed in 0.3.0: the previous implementation assumed an opaque destination and
410    /// produced wrong colors when `dst.a < 255`. The general case now takes one division per
411    /// channel; the common opaque-destination case still takes none.
412    ///
413    /// ```rust
414    /// use alpha_blend::rgba::U8x4Rgba;
415    ///
416    /// let src = U8x4Rgba::new(0, 255, 0, 128);
417    /// let dst = U8x4Rgba::new(255, 0, 0, 255);
418    /// assert_eq!(src.source_over(dst), U8x4Rgba::new(127, 128, 0, 255));
419    /// ```
420    #[must_use]
421    pub const fn source_over(self, dst: Self) -> Self {
422        let src_a = self.a as u32;
423
424        // Opaque source hides the destination entirely; transparent source changes nothing.
425        // Both are exact, and both are the overwhelmingly common case in a sprite blit.
426        if src_a == 255 {
427            return self;
428        }
429        if src_a == 0 {
430            return dst;
431        }
432
433        let inv_a = 255 - src_a;
434        let dst_a = dst.a as u32;
435
436        // Opaque destination: out_a is 255, so the divide by out_a drops out.
437        if dst_a == 255 {
438            return Self::new(
439                div255(self.r as u32 * src_a + dst.r as u32 * inv_a),
440                div255(self.g as u32 * src_a + dst.g as u32 * inv_a),
441                div255(self.b as u32 * src_a + dst.b as u32 * inv_a),
442                255,
443            );
444        }
445
446        Self::new(
447            source_over_channel(self.r as u32, src_a, dst.r as u32, dst_a, inv_a),
448            source_over_channel(self.g as u32, src_a, dst.g as u32, dst_a, inv_a),
449            source_over_channel(self.b as u32, src_a, dst.b as u32, dst_a, inv_a),
450            div255(src_a * 255 + dst_a * inv_a),
451        )
452    }
453
454    /// Returns `true` if this pixel is fully transparent (`alpha == 0`).
455    #[must_use]
456    pub const fn is_transparent(self) -> bool {
457        self.a == 0
458    }
459
460    /// Returns `true` if this pixel is fully opaque (`alpha == 255`).
461    #[must_use]
462    pub const fn is_opaque(self) -> bool {
463        self.a == 255
464    }
465}
466
467// ---------------------------------------------------------------------------
468// F32 helpers
469// ---------------------------------------------------------------------------
470
471impl F32x4Rgba {
472    /// Creates a new `F32x4Rgba` instance with `0` for all components.
473    #[must_use]
474    pub const fn zeroed() -> Self {
475        Self::new(0.0, 0.0, 0.0, 0.0)
476    }
477
478    /// Clamps all channels to `[0.0, 1.0]`.
479    ///
480    /// Blending never produces out-of-range channels (every [`Channel`] operation saturates),
481    /// so this is for colors that arrive from elsewhere.
482    #[must_use]
483    pub const fn clamp(self) -> Self {
484        // f32::clamp is not const in stable Rust, so we use manual min/max.
485        #[inline]
486        const fn clamp_f32(v: f32, lo: f32, hi: f32) -> f32 {
487            if v < lo {
488                lo
489            } else if v > hi {
490                hi
491            } else {
492                v
493            }
494        }
495        Self::new(
496            clamp_f32(self.r, 0.0, 1.0),
497            clamp_f32(self.g, 0.0, 1.0),
498            clamp_f32(self.b, 0.0, 1.0),
499            clamp_f32(self.a, 0.0, 1.0),
500        )
501    }
502
503    /// Returns `true` if this pixel is fully transparent (`alpha == 0.0`).
504    ///
505    /// An exact comparison, not an epsilon: this answers "can I skip this pixel", and skipping
506    /// a pixel with `alpha == 1e-9` would be wrong.
507    #[must_use]
508    #[allow(clippy::float_cmp)]
509    pub const fn is_transparent(self) -> bool {
510        self.a == 0.0
511    }
512
513    /// Returns `true` if this pixel is fully opaque (`alpha == 1.0`).
514    ///
515    /// An exact comparison; see [`F32x4Rgba::is_transparent`].
516    #[must_use]
517    #[allow(clippy::float_cmp)]
518    pub const fn is_opaque(self) -> bool {
519        self.a == 1.0
520    }
521}
522
523// ---------------------------------------------------------------------------
524// u8 <-> f32 conversion
525// ---------------------------------------------------------------------------
526
527impl From<U8x4Rgba> for F32x4Rgba {
528    fn from(rgba: U8x4Rgba) -> Self {
529        Self::new(
530            f32::from(rgba.red()) / MAX,
531            f32::from(rgba.green()) / MAX,
532            f32::from(rgba.blue()) / MAX,
533            f32::from(rgba.alpha()) / MAX,
534        )
535    }
536}
537
538impl From<F32x4Rgba> for U8x4Rgba {
539    fn from(rgba: F32x4Rgba) -> Self {
540        Self::new(
541            u8::from_f32(rgba.red()),
542            u8::from_f32(rgba.green()),
543            u8::from_f32(rgba.blue()),
544            u8::from_f32(rgba.alpha()),
545        )
546    }
547}
548
549impl From<PremultipliedU8x4Rgba> for PremultipliedF32x4Rgba {
550    fn from(rgba: PremultipliedU8x4Rgba) -> Self {
551        Self(rgba.0.into())
552    }
553}
554
555impl From<PremultipliedF32x4Rgba> for PremultipliedU8x4Rgba {
556    fn from(rgba: PremultipliedF32x4Rgba) -> Self {
557        Self(rgba.0.into())
558    }
559}
560
561// ---------------------------------------------------------------------------
562// Tests
563// ---------------------------------------------------------------------------
564
565#[cfg(test)]
566#[allow(
567    clippy::cast_lossless,
568    clippy::cast_possible_truncation,
569    clippy::cast_sign_loss,
570    clippy::float_cmp,
571    clippy::suboptimal_flops
572)]
573mod tests {
574    use super::*;
575
576    /// Exact rational source-over, computed in `f64` and rounded once. The oracle for every
577    /// `source_over` test below.
578    fn source_over_reference(src: U8x4Rgba, dst: U8x4Rgba) -> U8x4Rgba {
579        let (sa, da) = (f64::from(src.a) / 255.0, f64::from(dst.a) / 255.0);
580        let out_a = sa + da * (1.0 - sa);
581        if out_a == 0.0 {
582            // Color is unobservable at zero alpha; `source_over` keeps the destination's bits
583            // rather than zeroing them, which is cheaper and just as correct.
584            return dst;
585        }
586        let ch = |s: u8, d: u8| {
587            let s = f64::from(s) / 255.0;
588            let d = f64::from(d) / 255.0;
589            let co = s * sa + d * da * (1.0 - sa);
590            (co / out_a * 255.0 + 0.5) as u8
591        };
592        U8x4Rgba::new(
593            ch(src.r, dst.r),
594            ch(src.g, dst.g),
595            ch(src.b, dst.b),
596            (out_a * 255.0 + 0.5) as u8,
597        )
598    }
599
600    // --- Bug fix: field doc comments ---
601
602    #[test]
603    fn field_order_is_rgba() {
604        let c = U8x4Rgba::new(1, 2, 3, 4);
605        assert_eq!(c.r, 1);
606        assert_eq!(c.g, 2);
607        assert_eq!(c.b, 3);
608        assert_eq!(c.a, 4);
609    }
610
611    // --- u8 <-> f32 round-trip ---
612
613    #[test]
614    fn u8_to_f32() {
615        let rgba_u8 = U8x4Rgba::new(255, 128, 64, 32);
616        let rgba_f32: F32x4Rgba = rgba_u8.into();
617        assert_eq!(rgba_f32.red(), 1.0);
618        assert_eq!(rgba_f32.green(), 0.501_960_8);
619        assert_eq!(rgba_f32.blue(), 0.250_980_4);
620        assert_eq!(rgba_f32.alpha(), 0.125_490_2);
621    }
622
623    #[test]
624    fn f32_to_u8() {
625        let rgba_f32 = F32x4Rgba::new(1.0, 0.501_960_8, 0.250_980_4, 0.0);
626        let rgba_u8: U8x4Rgba = rgba_f32.into();
627        assert_eq!(rgba_u8.red(), 255);
628        assert_eq!(rgba_u8.green(), 128);
629        assert_eq!(rgba_u8.blue(), 64);
630        assert_eq!(rgba_u8.alpha(), 0);
631    }
632
633    #[test]
634    fn f32_to_u8_clamps_out_of_range() {
635        let rgba: U8x4Rgba = F32x4Rgba::new(-1.0, 2.0, 0.5, 1.0).into();
636        assert_eq!(rgba, U8x4Rgba::new(0, 255, 128, 255));
637    }
638
639    // --- Named constants ---
640
641    #[test]
642    fn zeroed_is_transparent_black() {
643        assert_eq!(U8x4Rgba::zeroed(), U8x4Rgba::TRANSPARENT);
644        assert_eq!(F32x4Rgba::zeroed(), F32x4Rgba::TRANSPARENT);
645    }
646
647    #[test]
648    fn u8_named_constants() {
649        assert_eq!(U8x4Rgba::TRANSPARENT, U8x4Rgba::new(0, 0, 0, 0));
650        assert_eq!(U8x4Rgba::BLACK, U8x4Rgba::new(0, 0, 0, 255));
651        assert_eq!(U8x4Rgba::WHITE, U8x4Rgba::new(255, 255, 255, 255));
652    }
653
654    #[test]
655    fn f32_named_constants() {
656        assert_eq!(F32x4Rgba::TRANSPARENT, F32x4Rgba::new(0.0, 0.0, 0.0, 0.0));
657        assert_eq!(F32x4Rgba::BLACK, F32x4Rgba::new(0.0, 0.0, 0.0, 1.0));
658        assert_eq!(F32x4Rgba::WHITE, F32x4Rgba::new(1.0, 1.0, 1.0, 1.0));
659    }
660
661    // --- u32 packed pixel helpers ---
662
663    #[test]
664    fn from_rgb_u32_round_trips() {
665        let pixel = 0x00FF_8040u32;
666        let rgba = U8x4Rgba::from_rgb_u32(pixel);
667        assert_eq!(rgba.r, 0xFF);
668        assert_eq!(rgba.g, 0x80);
669        assert_eq!(rgba.b, 0x40);
670        assert_eq!(rgba.a, 255);
671        assert_eq!(rgba.to_rgb_u32(), pixel);
672    }
673
674    #[test]
675    fn from_rgb_u32_ignores_top_byte() {
676        assert_eq!(
677            U8x4Rgba::from_rgb_u32(0xDEAD_BEEF).to_rgb_u32(),
678            U8x4Rgba::from_rgb_u32(0x00AD_BEEF).to_rgb_u32(),
679        );
680    }
681
682    #[test]
683    fn to_rgb_u32_discards_alpha() {
684        let rgba = U8x4Rgba::new(0x10, 0x20, 0x30, 0xAB);
685        assert_eq!(rgba.to_rgb_u32(), 0x0010_2030);
686    }
687
688    // --- integer source_over ---
689
690    #[test]
691    fn source_over_is_const() {
692        const OUT: U8x4Rgba =
693            U8x4Rgba::new(0, 255, 0, 128).source_over(U8x4Rgba::new(255, 0, 0, 255));
694        assert_eq!(OUT, U8x4Rgba::new(127, 128, 0, 255));
695    }
696
697    #[test]
698    fn source_over_opaque_src_returns_src() {
699        let src = U8x4Rgba::new(255, 0, 0, 255);
700        let dst = U8x4Rgba::new(0, 0, 255, 255);
701        assert_eq!(src.source_over(dst), src);
702    }
703
704    #[test]
705    fn source_over_transparent_src_returns_dst() {
706        let src = U8x4Rgba::new(255, 0, 0, 0);
707        let dst = U8x4Rgba::new(0, 0, 255, 255);
708        assert_eq!(src.source_over(dst), dst);
709    }
710
711    #[test]
712    fn source_over_both_transparent() {
713        let out = U8x4Rgba::TRANSPARENT.source_over(U8x4Rgba::TRANSPARENT);
714        assert_eq!(out, U8x4Rgba::TRANSPARENT);
715    }
716
717    /// The regression gate for retroglyph#547. Every reachable `(channel, src_a, dst_channel)`
718    /// against an opaque destination, compared to exact round-to-nearest, with **zero**
719    /// tolerance.
720    #[test]
721    fn source_over_opaque_dst_is_exactly_round_to_nearest() {
722        for src_a in 0..=255u8 {
723            for s in 0..=255u8 {
724                for d in (0..=255u8).step_by(5) {
725                    let out =
726                        U8x4Rgba::new(s, s, s, src_a).source_over(U8x4Rgba::new(d, d, d, 255));
727                    let v =
728                        u32::from(s) * u32::from(src_a) + u32::from(d) * (255 - u32::from(src_a));
729                    let expected = ((2 * v + 255) / 510) as u8;
730                    assert_eq!(out.r, expected, "src={s}@{src_a} dst={d}");
731                    assert_eq!(out.a, 255, "opaque destination stays opaque");
732                }
733            }
734        }
735    }
736
737    /// Translucent destinations were simply wrong before 0.3.0. Checked against an `f64` oracle.
738    #[test]
739    fn source_over_translucent_dst_matches_reference() {
740        for src_a in (0..=255u8).step_by(7) {
741            for dst_a in (0..=255u8).step_by(7) {
742                for s in (0..=255u8).step_by(17) {
743                    for d in (0..=255u8).step_by(17) {
744                        let src = U8x4Rgba::new(s, s, s, src_a);
745                        let dst = U8x4Rgba::new(d, d, d, dst_a);
746                        let out = src.source_over(dst);
747                        let want = source_over_reference(src, dst);
748                        assert!(
749                            out.r.abs_diff(want.r) <= 1 && out.a.abs_diff(want.a) <= 1,
750                            "src={src} dst={dst}: got {out}, reference {want}",
751                        );
752                        assert!(
753                            out.a >= src.a && out.a >= dst.a,
754                            "source-over never reduces coverage",
755                        );
756                    }
757                }
758            }
759        }
760    }
761
762    /// Compositing an opaque pixel over anything must be a no-op on the second application.
763    /// The 0.2.x truncating implementation failed this by construction.
764    #[test]
765    fn source_over_opaque_is_idempotent() {
766        let src = U8x4Rgba::new(200, 100, 50, 255);
767        let mut acc = U8x4Rgba::new(10, 20, 30, 255);
768        for _ in 0..1000 {
769            acc = src.source_over(acc);
770        }
771        assert_eq!(acc, src);
772    }
773
774    /// Repeatedly compositing a translucent pixel converges to the source instead of drifting
775    /// toward black. This is the test that would have caught the darkening bug.
776    #[test]
777    fn source_over_repeated_does_not_drift_darker() {
778        let src = U8x4Rgba::new(200, 100, 50, 128);
779        let mut acc = U8x4Rgba::new(200, 100, 50, 255);
780        for i in 0..1000 {
781            acc = src.source_over(acc);
782            assert_eq!(
783                acc,
784                U8x4Rgba::new(200, 100, 50, 255),
785                "drifted after {i} blends",
786            );
787        }
788    }
789
790    /// Blending a mid-gray onto itself at any alpha must return that same gray.
791    #[test]
792    fn source_over_self_is_a_fixed_point() {
793        for a in 0..=255u8 {
794            for v in (0..=255u8).step_by(3) {
795                let px = U8x4Rgba::new(v, v, v, 255);
796                let src = U8x4Rgba::new(v, v, v, a);
797                assert_eq!(src.source_over(px), px, "v={v} a={a}");
798            }
799        }
800    }
801
802    #[test]
803    fn source_over_expected_values() {
804        let cases: &[(U8x4Rgba, U8x4Rgba, U8x4Rgba)] = &[
805            (
806                U8x4Rgba::new(200, 100, 50, 255),
807                U8x4Rgba::new(10, 20, 30, 255),
808                U8x4Rgba::new(200, 100, 50, 255),
809            ),
810            (U8x4Rgba::TRANSPARENT, U8x4Rgba::WHITE, U8x4Rgba::WHITE),
811            (
812                U8x4Rgba::new(0, 255, 0, 128),
813                U8x4Rgba::new(255, 0, 0, 255),
814                U8x4Rgba::new(127, 128, 0, 255),
815            ),
816            (U8x4Rgba::WHITE, U8x4Rgba::TRANSPARENT, U8x4Rgba::WHITE),
817            // Translucent source over a fully transparent destination keeps the source color
818            // and its alpha. 0.2.x returned (128, 128, 128, 128) here.
819            (
820                U8x4Rgba::new(255, 255, 255, 128),
821                U8x4Rgba::TRANSPARENT,
822                U8x4Rgba::new(255, 255, 255, 128),
823            ),
824        ];
825        for &(src, dst, expected) in cases {
826            assert_eq!(src.source_over(dst), expected, "src={src} dst={dst}");
827        }
828    }
829
830    #[test]
831    fn is_transparent_opaque() {
832        assert!(U8x4Rgba::TRANSPARENT.is_transparent());
833        assert!(!U8x4Rgba::BLACK.is_transparent());
834        assert!(!U8x4Rgba::new(0, 0, 0, 1).is_transparent());
835        assert!(U8x4Rgba::new(255, 0, 0, 0).is_transparent());
836        assert!(F32x4Rgba::TRANSPARENT.is_transparent());
837        assert!(!F32x4Rgba::BLACK.is_transparent());
838    }
839
840    #[test]
841    fn is_opaque() {
842        assert!(U8x4Rgba::BLACK.is_opaque());
843        assert!(U8x4Rgba::WHITE.is_opaque());
844        assert!(!U8x4Rgba::TRANSPARENT.is_opaque());
845        assert!(!U8x4Rgba::new(0, 0, 0, 254).is_opaque());
846        assert!(F32x4Rgba::WHITE.is_opaque());
847        assert!(!F32x4Rgba::TRANSPARENT.is_opaque());
848    }
849
850    // --- From array / tuple / AsRef / AsMut ---
851
852    #[test]
853    fn from_array() {
854        let rgba = Rgba::from([1u8, 2, 3, 4]);
855        assert_eq!(rgba, U8x4Rgba::new(1, 2, 3, 4));
856    }
857
858    #[test]
859    fn into_array() {
860        let arr: [u8; 4] = U8x4Rgba::new(1, 2, 3, 4).into();
861        assert_eq!(arr, [1, 2, 3, 4]);
862    }
863
864    #[test]
865    fn from_tuple() {
866        let rgba = Rgba::from((1u8, 2, 3, 4));
867        assert_eq!(rgba, U8x4Rgba::new(1, 2, 3, 4));
868    }
869
870    #[test]
871    fn into_tuple() {
872        let tup: (u8, u8, u8, u8) = U8x4Rgba::new(1, 2, 3, 4).into();
873        assert_eq!(tup, (1, 2, 3, 4));
874    }
875
876    #[test]
877    fn as_ref_slice() {
878        let rgba = U8x4Rgba::new(1, 2, 3, 4);
879        assert_eq!(rgba.as_ref(), &[1u8, 2, 3, 4]);
880    }
881
882    #[test]
883    fn as_mut_slice() {
884        let mut rgba = U8x4Rgba::new(1, 2, 3, 4);
885        rgba.as_mut()[0] = 10;
886        assert_eq!(rgba.r, 10);
887    }
888
889    // --- Display ---
890
891    #[test]
892    fn display_u8() {
893        let s = format!("{}", U8x4Rgba::new(10, 20, 30, 40));
894        assert_eq!(s, "rgba(10, 20, 30, 40)");
895    }
896
897    #[test]
898    fn display_f32() {
899        let s = format!("{}", F32x4Rgba::new(0.1, 0.2, 0.3, 1.0));
900        assert_eq!(s, "rgba(0.1, 0.2, 0.3, 1)");
901    }
902
903    #[test]
904    fn display_premultiplied() {
905        let s = format!("{}", U8x4Rgba::new(10, 20, 30, 40).premultiply());
906        assert_eq!(s, "premultiplied rgba(2, 3, 5, 40)");
907    }
908
909    // --- Eq + Hash ---
910
911    #[test]
912    fn eq_hash_set() {
913        use std::collections::HashSet;
914        let mut set = HashSet::new();
915        set.insert(U8x4Rgba::new(1, 2, 3, 4));
916        set.insert(U8x4Rgba::new(1, 2, 3, 4));
917        assert_eq!(set.len(), 1);
918        set.insert(U8x4Rgba::new(5, 6, 7, 8));
919        assert_eq!(set.len(), 2);
920    }
921
922    #[test]
923    fn premultiplied_eq_hash_set() {
924        use std::collections::HashSet;
925        let mut set = HashSet::new();
926        set.insert(U8x4Rgba::new(1, 2, 3, 4).premultiply());
927        set.insert(U8x4Rgba::new(1, 2, 3, 4).premultiply());
928        assert_eq!(set.len(), 1);
929    }
930
931    // --- Premultiplied ---
932
933    /// The exact values tiny-skia's `premultiply_u8` produces, as a cross-check that this
934    /// crate's rounding matches the reference implementation everyone else uses.
935    #[test]
936    fn premultiply_u8_matches_tiny_skia() {
937        assert_eq!(
938            U8x4Rgba::new(10, 20, 30, 40).premultiply().get(),
939            U8x4Rgba::new(2, 3, 5, 40),
940        );
941        assert_eq!(
942            U8x4Rgba::new(10, 20, 30, 255).premultiply().get(),
943            U8x4Rgba::new(10, 20, 30, 255),
944        );
945    }
946
947    #[test]
948    fn premultiply_identity_when_opaque() {
949        for v in (0..=255u8).step_by(5) {
950            let c = U8x4Rgba::new(v, v, v, 255);
951            assert_eq!(c.premultiply().get(), c);
952            assert_eq!(c.premultiply().unpremultiply(), c);
953        }
954    }
955
956    #[test]
957    fn premultiply_half_alpha_f32() {
958        let c = F32x4Rgba::new(0.5, 1.0, 0.0, 0.5).premultiply().get();
959        assert_eq!(c.r, 0.25);
960        assert_eq!(c.g, 0.5);
961        assert_eq!(c.b, 0.0);
962        assert_eq!(c.a, 0.5);
963    }
964
965    #[test]
966    fn unpremultiply_round_trips_f32() {
967        let orig = F32x4Rgba::new(0.5, 0.5, 0.5, 0.5);
968        let back = orig.premultiply().unpremultiply();
969        assert!((back.r - orig.r).abs() < 1e-6);
970        assert!((back.a - orig.a).abs() < 1e-6);
971    }
972
973    #[test]
974    fn unpremultiply_transparent_returns_transparent() {
975        assert_eq!(
976            F32x4Rgba::new(0.5, 0.5, 0.5, 0.0)
977                .premultiply()
978                .unpremultiply(),
979            F32x4Rgba::TRANSPARENT,
980        );
981        assert_eq!(
982            U8x4Rgba::new(255, 255, 255, 0)
983                .premultiply()
984                .unpremultiply(),
985            U8x4Rgba::TRANSPARENT,
986        );
987    }
988
989    /// The lossiness the `Premultiplied` docs warn about, pinned so the warning stays honest.
990    #[test]
991    fn unpremultiply_u8_is_lossy_and_bounded() {
992        let mut worst = 0u8;
993        for a in 1..=255u8 {
994            for v in (0..=255u8).step_by(3) {
995                let orig = U8x4Rgba::new(v, v, v, a);
996                let back = orig.premultiply().unpremultiply();
997                worst = worst.max(back.r.abs_diff(v));
998                assert_eq!(back.a, a, "alpha survives the round trip exactly");
999            }
1000        }
1001        assert!(worst > 0, "if this is 0 the docs are wrong and can relax");
1002        assert!(worst <= 128, "worst case is at alpha = 1; got {worst}");
1003    }
1004
1005    #[test]
1006    fn from_premultiplied_wraps_without_converting() {
1007        let raw = U8x4Rgba::new(2, 3, 5, 40);
1008        assert_eq!(Premultiplied::from_premultiplied(raw).get(), raw);
1009    }
1010
1011    #[test]
1012    fn premultiplied_u8_f32_conversion() {
1013        let p = U8x4Rgba::new(10, 20, 30, 255).premultiply();
1014        let f: PremultipliedF32x4Rgba = p.into();
1015        let back: PremultipliedU8x4Rgba = f.into();
1016        assert_eq!(back, p);
1017    }
1018
1019    // --- F32 helpers ---
1020
1021    #[test]
1022    fn clamp_values() {
1023        let c = F32x4Rgba::new(1.5, -0.5, 2.0, -1.0).clamp();
1024        assert_eq!(c, F32x4Rgba::new(1.0, 0.0, 1.0, 0.0));
1025    }
1026
1027    #[test]
1028    fn clamp_noop_for_valid() {
1029        let c = F32x4Rgba::new(0.5, 0.5, 0.5, 1.0).clamp();
1030        assert_eq!(c, F32x4Rgba::new(0.5, 0.5, 0.5, 1.0));
1031    }
1032
1033    // --- lerp ---
1034
1035    #[test]
1036    fn lerp_identity() {
1037        let a = F32x4Rgba::new(0.2, 0.4, 0.6, 0.8);
1038        assert_eq!(a.lerp(F32x4Rgba::WHITE, 0.0), a);
1039    }
1040
1041    #[test]
1042    fn lerp_full() {
1043        let a = F32x4Rgba::new(0.2, 0.4, 0.6, 0.8);
1044        assert_eq!(a.lerp(F32x4Rgba::WHITE, 1.0), F32x4Rgba::WHITE);
1045    }
1046
1047    #[test]
1048    fn lerp_midpoint() {
1049        let a = F32x4Rgba::new(0.0, 0.0, 0.0, 1.0);
1050        let mid = a.lerp(F32x4Rgba::WHITE, 0.5);
1051        assert!((mid.r - 0.5).abs() < 1e-6);
1052        assert!((mid.a - 1.0).abs() < 1e-6);
1053    }
1054
1055    #[test]
1056    fn lerp_clamps_t() {
1057        let a = F32x4Rgba::BLACK;
1058        assert_eq!(a.lerp(F32x4Rgba::WHITE, 2.0), F32x4Rgba::WHITE);
1059        assert_eq!(a.lerp(F32x4Rgba::WHITE, -1.0), a);
1060    }
1061
1062    #[test]
1063    fn lerp_u8_endpoints_are_exact() {
1064        let a = U8x4Rgba::new(10, 20, 30, 40);
1065        let b = U8x4Rgba::new(200, 100, 50, 255);
1066        assert_eq!(a.lerp(b, 0), a);
1067        assert_eq!(a.lerp(b, 255), b);
1068    }
1069
1070    #[test]
1071    fn lerp_u8_midpoint() {
1072        let out = U8x4Rgba::new(0, 100, 0, 255).lerp(U8x4Rgba::new(255, 200, 0, 255), 128);
1073        assert_eq!(out, U8x4Rgba::new(128, 150, 0, 255));
1074    }
1075}