Skip to main content

rouge_theme/
color.rs

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}