1use crate::{Error, Result};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct OpaqueColor {
8 red: u8,
9 green: u8,
10 blue: u8,
11}
12
13impl OpaqueColor {
14 pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
16 Self { red, green, blue }
17 }
18
19 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 pub const fn red(&self) -> u8 {
27 self.red
28 }
29
30 pub const fn green(&self) -> u8 {
32 self.green
33 }
34
35 pub const fn blue(&self) -> u8 {
37 self.blue
38 }
39
40 pub(crate) const fn as_rgb(self) -> (u8, u8, u8) {
42 (self.red, self.green, self.blue)
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct Color {
60 rgb: OpaqueColor,
61 alpha: f64,
62}
63
64impl Eq for Color {}
66
67impl Color {
68 pub(crate) const TRANSPARENT: Self = Self {
69 rgb: OpaqueColor::rgb(0, 0, 0),
70 alpha: 0.0,
71 };
72
73 pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
75 Self {
76 rgb: OpaqueColor::rgb(red, green, blue),
77 alpha: 1.0,
78 }
79 }
80
81 pub fn rgba(red: u8, green: u8, blue: u8, alpha: f64) -> Result<Self> {
83 Self::rgb(red, green, blue).alpha(alpha)
84 }
85
86 pub fn hex(value: &str) -> Result<Self> {
91 let [red, green, blue, alpha] = hex_channels(value, true)?;
92 Self::rgba(red, green, blue, f64::from(alpha) / 255.0)
93 }
94
95 pub const fn red(&self) -> u8 {
97 self.rgb.red()
98 }
99
100 pub const fn green(&self) -> u8 {
102 self.rgb.green()
103 }
104
105 pub const fn blue(&self) -> u8 {
107 self.rgb.blue()
108 }
109
110 pub const fn get_alpha(&self) -> f64 {
112 self.alpha
113 }
114
115 pub fn alpha(self, alpha: f64) -> Result<Self> {
117 Ok(Self {
118 alpha: crate::alpha::validated_alpha(alpha)?,
119 ..self
120 })
121 }
122
123 pub(crate) fn with_alpha(self, alpha: f64) -> Self {
125 self.alpha(alpha).expect("validated opacity coefficient")
126 }
127}
128
129impl From<OpaqueColor> for Color {
130 fn from(rgb: OpaqueColor) -> Self {
131 Self { rgb, alpha: 1.0 }
132 }
133}
134
135fn hex_channels(value: &str, alpha_allowed: bool) -> Result<[u8; 4]> {
136 let bytes = value.as_bytes();
137 if !(bytes.len() == 7 || (alpha_allowed && bytes.len() == 9))
138 || bytes[0] != b'#'
139 || !bytes[1..].iter().all(u8::is_ascii_hexdigit)
140 {
141 let syntax = if alpha_allowed {
142 "#RRGGBB or #RRGGBBAA"
143 } else {
144 "#RRGGBB"
145 };
146 return Err(Error::Data(
147 format!("color must be ASCII hex in exactly {syntax} form; got {value:?}").into(),
148 ));
149 }
150 let mut channels = [0, 0, 0, 255];
151 for (channel, digits) in channels.iter_mut().zip(bytes[1..].chunks_exact(2)) {
152 *channel = (hex_digit(digits[0]) << 4) | hex_digit(digits[1]);
153 }
154 Ok(channels)
155}
156
157fn hex_digit(byte: u8) -> u8 {
158 match byte {
159 b'0'..=b'9' => byte - b'0',
160 b'a'..=b'f' => byte - b'a' + 10,
161 b'A'..=b'F' => byte - b'A' + 10,
162 _ => unreachable!("hex channels validate ASCII digits before decoding"),
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 #[test]
171 fn literal_coefficients_retain_full_precision_and_validate_before_painting() {
172 let paint = Color::rgba(18, 52, 86, 0.5).unwrap();
173 assert_ne!(paint, Color::hex("#12345680").unwrap());
174 assert_eq!(paint.get_alpha().to_bits(), 0.5_f64.to_bits());
175 assert_eq!(paint.alpha(-0.0).unwrap().get_alpha().to_bits(), 0);
176 for invalid in [-0.1, 1.01, 195.0, f64::NAN, f64::INFINITY] {
177 assert!(paint.alpha(invalid).is_err());
178 assert!(Color::rgba(18, 52, 86, invalid).is_err());
179 }
180 }
181 fn channels(color: Color) -> ([u8; 3], f64) {
182 (
183 [color.red(), color.green(), color.blue()],
184 color.get_alpha(),
185 )
186 }
187
188 #[test]
189 fn encoded_hex_vectors_preserve_channels_and_reject_nonliteral_syntax() {
190 for (encoded, expected) in [
191 ("#000000", ([0, 0, 0], 1.0)),
192 ("#FFFFFF", ([255, 255, 255], 1.0)),
193 ("#01aBfE", ([1, 171, 254], 1.0)),
194 ("#12aBcD00", ([18, 171, 205], 0.0)),
195 ("#Ff8001ff", ([255, 128, 1], 1.0)),
196 ("#23456789", ([35, 69, 103], 137.0 / 255.0)),
197 ] {
198 assert_eq!(
199 channels(Color::hex(encoded).unwrap()),
200 expected,
201 "{encoded}"
202 );
203 if encoded.len() == 7 {
204 assert_eq!(
205 channels(OpaqueColor::hex(encoded).unwrap().into()),
206 expected,
207 "{encoded}"
208 );
209 } else {
210 assert!(OpaqueColor::hex(encoded).is_err(), "{encoded}");
211 }
212 }
213 for invalid in [
214 "",
215 "#123",
216 "#12345G",
217 " #123456",
218 "#123456 ",
219 "#1234567",
220 "red",
221 "rgb(1,2,3)",
222 "#123456",
223 ] {
224 assert!(Color::hex(invalid).is_err(), "{invalid:?}");
225 assert!(OpaqueColor::hex(invalid).is_err(), "{invalid:?}");
226 }
227 }
228}