Skip to main content

lichtung_plot/theme/
paint.rs

1//! Immutable byte-channel paint values shared by theme resolution and rendering.
2
3use crate::{Error, Result};
4
5/// Opaque RGB identity; there is no alpha-discarding conversion from `Color`.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct OpaqueColor {
8    red: u8,
9    green: u8,
10    blue: u8,
11}
12
13impl OpaqueColor {
14    /// Construct an exact opaque RGB identity for data scales.
15    pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
16        Self { red, green, blue }
17    }
18
19    /// Parse exactly ASCII `#RRGGBB`, accepting either hex case and no alpha.
20    pub fn hex(value: &str) -> Result<Self> {
21        let [red, green, blue, _] = hex_channels(value, false)?;
22        Ok(Self::rgb(red, green, blue))
23    }
24
25    /// Inspect the red channel.
26    pub const fn red(&self) -> u8 {
27        self.red
28    }
29
30    /// Inspect the green channel.
31    pub const fn green(&self) -> u8 {
32        self.green
33    }
34
35    /// Inspect the blue channel.
36    pub const fn blue(&self) -> u8 {
37        self.blue
38    }
39
40    /// Private adaptation to the current exact-paint/backend tuple inputs.
41    pub(crate) const fn as_rgb(self) -> (u8, u8, u8) {
42        (self.red, self.green, self.blue)
43    }
44}
45
46/// Complete RGBA paint with one opaque RGB identity and one byte alpha.
47///
48/// Channels are exact bytes, including fully transparent and opaque alpha.
49/// Use [`Color::alpha`] to replace alpha without multiplying it.
50///
51/// ```
52/// use lichtung_plot::Color;
53/// let paint = Color::hex("#12345680")?;
54/// assert_eq!(paint.get_alpha(), 128);
55/// assert_eq!(paint.alpha(255), Color::rgb(18, 52, 86));
56/// # Ok::<(), lichtung_plot::Error>(())
57/// ```
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct Color {
60    rgb: OpaqueColor,
61    alpha: u8,
62}
63
64impl Color {
65    /// Construct an opaque paint from exact RGB channels.
66    pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
67        Self::rgba(red, green, blue, 255)
68    }
69
70    /// Construct a paint from exact RGB and alpha channels.
71    pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
72        Self {
73            rgb: OpaqueColor::rgb(red, green, blue),
74            alpha,
75        }
76    }
77
78    /// Parse exactly `#RRGGBB` or `#RRGGBBAA`, accepting either ASCII hex case.
79    ///
80    /// Six-digit input is opaque. Surrounding whitespace, shorthand, named
81    /// colors and other CSS syntax are rejected.
82    pub fn hex(value: &str) -> Result<Self> {
83        let [red, green, blue, alpha] = hex_channels(value, true)?;
84        Ok(Self::rgba(red, green, blue, alpha))
85    }
86
87    /// Inspect the red channel.
88    pub const fn red(&self) -> u8 {
89        self.rgb.red()
90    }
91
92    /// Inspect the green channel.
93    pub const fn green(&self) -> u8 {
94        self.rgb.green()
95    }
96
97    /// Inspect the blue channel.
98    pub const fn blue(&self) -> u8 {
99        self.rgb.blue()
100    }
101
102    /// Inspect alpha: zero is transparent and 255 is opaque.
103    pub const fn get_alpha(&self) -> u8 {
104        self.alpha
105    }
106
107    /// Replace alpha, retaining all RGB channels exactly.
108    #[must_use]
109    pub const fn alpha(self, alpha: u8) -> Self {
110        Self { alpha, ..self }
111    }
112}
113
114impl From<OpaqueColor> for Color {
115    fn from(rgb: OpaqueColor) -> Self {
116        Self { rgb, alpha: 255 }
117    }
118}
119
120fn hex_channels(value: &str, alpha_allowed: bool) -> Result<[u8; 4]> {
121    let bytes = value.as_bytes();
122    if !(bytes.len() == 7 || (alpha_allowed && bytes.len() == 9))
123        || bytes[0] != b'#'
124        || !bytes[1..].iter().all(u8::is_ascii_hexdigit)
125    {
126        let syntax = if alpha_allowed {
127            "#RRGGBB or #RRGGBBAA"
128        } else {
129            "#RRGGBB"
130        };
131        return Err(Error::Data(format!(
132            "color must be ASCII hex in exactly {syntax} form; got {value:?}"
133        )));
134    }
135    let mut channels = [0, 0, 0, 255];
136    for (channel, digits) in channels.iter_mut().zip(bytes[1..].chunks_exact(2)) {
137        *channel = (hex_digit(digits[0]) << 4) | hex_digit(digits[1]);
138    }
139    Ok(channels)
140}
141
142fn hex_digit(byte: u8) -> u8 {
143    match byte {
144        b'0'..=b'9' => byte - b'0',
145        b'a'..=b'f' => byte - b'a' + 10,
146        b'A'..=b'F' => byte - b'A' + 10,
147        _ => unreachable!("hex channels validate ASCII digits before decoding"),
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    fn channels(color: Color) -> [u8; 4] {
156        [color.red(), color.green(), color.blue(), color.get_alpha()]
157    }
158
159    #[test]
160    fn encoded_hex_vectors_preserve_channels_and_reject_nonliteral_syntax() {
161        for (encoded, expected) in [
162            ("#000000", [0, 0, 0, 255]),
163            ("#FFFFFF", [255, 255, 255, 255]),
164            ("#01aBfE", [1, 171, 254, 255]),
165            ("#12aBcD00", [18, 171, 205, 0]),
166            ("#Ff8001ff", [255, 128, 1, 255]),
167            ("#23456789", [35, 69, 103, 137]),
168        ] {
169            assert_eq!(
170                channels(Color::hex(encoded).unwrap()),
171                expected,
172                "{encoded}"
173            );
174            if encoded.len() == 7 {
175                assert_eq!(
176                    channels(OpaqueColor::hex(encoded).unwrap().into()),
177                    expected,
178                    "{encoded}"
179                );
180            } else {
181                assert!(OpaqueColor::hex(encoded).is_err(), "{encoded}");
182            }
183        }
184        for invalid in [
185            "",
186            "#123",
187            "#12345G",
188            " #123456",
189            "#123456 ",
190            "#1234567",
191            "red",
192            "rgb(1,2,3)",
193            "#123456",
194        ] {
195            assert!(Color::hex(invalid).is_err(), "{invalid:?}");
196            assert!(OpaqueColor::hex(invalid).is_err(), "{invalid:?}");
197        }
198    }
199}