1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
4pub struct Rgba {
5 pub r: u8,
6 pub g: u8,
7 pub b: u8,
8 pub a: u8,
9}
10
11impl Rgba {
12 #[must_use]
13 pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
14 Self { r, g, b, a }
15 }
16
17 #[must_use]
18 #[expect(
19 clippy::cast_possible_truncation,
20 reason = "each channel is masked to one byte"
21 )]
22 pub const fn rgb(hex: u32) -> Self {
23 Self::new((hex >> 16) as u8, (hex >> 8) as u8, hex as u8, u8::MAX)
24 }
25
26 #[must_use]
27 pub const fn over(self, background: Self) -> Self {
28 #[expect(
29 clippy::cast_possible_truncation,
30 reason = "weighted u8 average fits in u8"
31 )]
32 const fn channel(foreground: u8, background: u8, alpha: u8) -> u8 {
33 let foreground = foreground as u32 * alpha as u32;
34 let background = background as u32 * (u8::MAX - alpha) as u32;
35 ((foreground + background + 127) / 255) as u8
36 }
37 Self::new(
38 channel(self.r, background.r, self.a),
39 channel(self.g, background.g, self.a),
40 channel(self.b, background.b, self.a),
41 u8::MAX,
42 )
43 }
44
45 #[must_use]
46 pub const fn mix(self, background: Self, amount: u8) -> Self {
47 Self::new(self.r, self.g, self.b, amount).over(background)
48 }
49
50 #[must_use]
51 pub fn contrast(self, other: Self) -> f32 {
52 let (a, b) = (self.luminance(), other.luminance());
53 (a.max(b) + 0.05) / (a.min(b) + 0.05)
54 }
55
56 fn luminance(self) -> f32 {
57 let linear = |channel: u8| {
58 let channel = f32::from(channel) / 255.0;
59 if channel <= 0.04045 {
60 channel / 12.92
61 } else {
62 ((channel + 0.055) / 1.055).powf(2.4)
63 }
64 };
65 0.2126 * linear(self.r) + 0.7152 * linear(self.g) + 0.0722 * linear(self.b)
66 }
67}