1use serde::de;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6use std::str::FromStr;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct Rgba {
44 pub r: u8,
46 pub g: u8,
48 pub b: u8,
50 pub a: u8,
52}
53
54impl Rgba {
62 #[must_use]
64 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
65 Self { r, g, b, a: 255 }
66 }
67
68 #[must_use]
70 pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
71 Self { r, g, b, a }
72 }
73
74 pub const TRANSPARENT: Self = Self {
84 r: 0,
85 g: 0,
86 b: 0,
87 a: 0,
88 };
89
90 pub const BLACK: Self = Self {
92 r: 0,
93 g: 0,
94 b: 0,
95 a: 255,
96 };
97
98 pub const WHITE: Self = Self {
100 r: 255,
101 g: 255,
102 b: 255,
103 a: 255,
104 };
105
106 #[must_use]
114 pub fn from_f32(r: f32, g: f32, b: f32, a: f32) -> Self {
115 Self {
116 r: (r.clamp(0.0, 1.0) * 255.0).round() as u8,
117 g: (g.clamp(0.0, 1.0) * 255.0).round() as u8,
118 b: (b.clamp(0.0, 1.0) * 255.0).round() as u8,
119 a: (a.clamp(0.0, 1.0) * 255.0).round() as u8,
120 }
121 }
122
123 #[must_use]
128 pub fn to_f32_array(&self) -> [f32; 4] {
129 [
130 self.r as f32 / 255.0,
131 self.g as f32 / 255.0,
132 self.b as f32 / 255.0,
133 self.a as f32 / 255.0,
134 ]
135 }
136}
137
138impl fmt::Display for Rgba {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 if self.a == 255 {
141 write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
142 } else {
143 write!(
144 f,
145 "#{:02x}{:02x}{:02x}{:02x}",
146 self.r, self.g, self.b, self.a
147 )
148 }
149 }
150}
151
152#[derive(Debug, Clone)]
158pub struct ParseColorError(String);
159
160impl fmt::Display for ParseColorError {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.write_str(&self.0)
163 }
164}
165
166impl std::error::Error for ParseColorError {}
167
168fn hex_nibble(b: u8, label: &str) -> Result<u8, ParseColorError> {
170 char::from(b)
171 .to_digit(16)
172 .and_then(|v| u8::try_from(v).ok())
173 .ok_or_else(|| ParseColorError(format!("invalid {label} hex digit {:?}", char::from(b))))
174}
175
176fn hex_byte(hi: u8, lo: u8) -> u8 {
178 hi.wrapping_shl(4) | (lo & 0x0f)
180}
181
182fn double_nibble(n: u8) -> u8 {
185 n.wrapping_shl(4) | (n & 0x0f)
186}
187
188impl FromStr for Rgba {
189 type Err = ParseColorError;
190
191 fn from_str(s: &str) -> Result<Self, Self::Err> {
192 let hex = s.strip_prefix('#').unwrap_or(s);
193
194 if hex.is_empty() {
195 return Err(ParseColorError("empty hex color string".into()));
196 }
197
198 match hex.as_bytes() {
203 [r, g, b] => {
205 let r = hex_nibble(*r, "red")?;
206 let g = hex_nibble(*g, "green")?;
207 let b = hex_nibble(*b, "blue")?;
208 Ok(Rgba::rgb(
209 double_nibble(r),
210 double_nibble(g),
211 double_nibble(b),
212 ))
213 }
214 [r, g, b, a] => {
216 let r = hex_nibble(*r, "red")?;
217 let g = hex_nibble(*g, "green")?;
218 let b = hex_nibble(*b, "blue")?;
219 let a = hex_nibble(*a, "alpha")?;
220 Ok(Rgba::new(
221 double_nibble(r),
222 double_nibble(g),
223 double_nibble(b),
224 double_nibble(a),
225 ))
226 }
227 [r1, r2, g1, g2, b1, b2] => {
229 let r = hex_byte(hex_nibble(*r1, "red")?, hex_nibble(*r2, "red")?);
230 let g = hex_byte(hex_nibble(*g1, "green")?, hex_nibble(*g2, "green")?);
231 let b = hex_byte(hex_nibble(*b1, "blue")?, hex_nibble(*b2, "blue")?);
232 Ok(Rgba::rgb(r, g, b))
233 }
234 [r1, r2, g1, g2, b1, b2, a1, a2] => {
236 let r = hex_byte(hex_nibble(*r1, "red")?, hex_nibble(*r2, "red")?);
237 let g = hex_byte(hex_nibble(*g1, "green")?, hex_nibble(*g2, "green")?);
238 let b = hex_byte(hex_nibble(*b1, "blue")?, hex_nibble(*b2, "blue")?);
239 let a = hex_byte(hex_nibble(*a1, "alpha")?, hex_nibble(*a2, "alpha")?);
240 Ok(Rgba::new(r, g, b, a))
241 }
242 other => Err(ParseColorError(format!(
243 "invalid hex color length {}: expected 3, 4, 6, or 8 hex digits",
244 other.len()
245 ))),
246 }
247 }
248}
249
250impl Serialize for Rgba {
251 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
252 serializer.serialize_str(&self.to_string())
253 }
254}
255
256impl<'de> Deserialize<'de> for Rgba {
257 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
258 let s = String::deserialize(deserializer)?;
259 Rgba::from_str(&s).map_err(de::Error::custom)
260 }
261}
262
263#[allow(dead_code)]
273pub(crate) fn unpremultiply_alpha(buffer: &mut [u8]) {
274 for pixel in buffer.chunks_exact_mut(4) {
275 let [r, g, b, a] = pixel else { continue };
278 let a_val = u16::from(*a);
279 if (1..255).contains(&a_val) {
283 #[allow(clippy::integer_division, clippy::arithmetic_side_effects)]
284 {
285 *r = (u16::from(*r).saturating_mul(255) / a_val).min(255) as u8;
286 *g = (u16::from(*g).saturating_mul(255) / a_val).min(255) as u8;
287 *b = (u16::from(*b).saturating_mul(255) / a_val).min(255) as u8;
288 }
289 }
290 }
291}
292
293#[cfg(test)]
294#[allow(clippy::unwrap_used, clippy::expect_used)]
295mod tests {
296 use super::*;
297
298 #[test]
301 fn rgb_constructor_sets_alpha_255() {
302 let c = Rgba::rgb(61, 174, 233);
303 assert_eq!(
304 c,
305 Rgba {
306 r: 61,
307 g: 174,
308 b: 233,
309 a: 255
310 }
311 );
312 }
313
314 #[test]
315 fn rgba_constructor_sets_all_fields() {
316 let c = Rgba::new(61, 174, 233, 128);
317 assert_eq!(
318 c,
319 Rgba {
320 r: 61,
321 g: 174,
322 b: 233,
323 a: 128
324 }
325 );
326 }
327
328 #[test]
331 fn parse_6_digit_hex_with_hash() {
332 let c: Rgba = "#3daee9".parse().unwrap();
333 assert_eq!(c, Rgba::rgb(61, 174, 233));
334 }
335
336 #[test]
337 fn parse_8_digit_hex_with_hash() {
338 let c: Rgba = "#3daee980".parse().unwrap();
339 assert_eq!(c, Rgba::new(61, 174, 233, 128));
340 }
341
342 #[test]
343 fn parse_6_digit_hex_without_hash() {
344 let c: Rgba = "3daee9".parse().unwrap();
345 assert_eq!(c, Rgba::rgb(61, 174, 233));
346 }
347
348 #[test]
349 fn parse_3_digit_shorthand() {
350 let c: Rgba = "#abc".parse().unwrap();
351 assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
352 }
353
354 #[test]
355 fn parse_4_digit_shorthand() {
356 let c: Rgba = "#abcd".parse().unwrap();
357 assert_eq!(c, Rgba::new(0xaa, 0xbb, 0xcc, 0xdd));
358 }
359
360 #[test]
361 fn parse_uppercase_hex() {
362 let c: Rgba = "#AABBCC".parse().unwrap();
363 assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
364 }
365
366 #[test]
367 fn parse_empty_string_is_error() {
368 assert!("".parse::<Rgba>().is_err());
369 }
370
371 #[test]
372 fn parse_invalid_hex_chars_is_error() {
373 assert!("#gggggg".parse::<Rgba>().is_err());
374 }
375
376 #[test]
377 fn parse_invalid_length_5_chars_is_error() {
378 assert!("#12345".parse::<Rgba>().is_err());
379 }
380
381 #[test]
384 fn display_omits_alpha_when_255() {
385 assert_eq!(Rgba::rgb(61, 174, 233).to_string(), "#3daee9");
386 }
387
388 #[test]
389 fn display_includes_alpha_when_not_255() {
390 assert_eq!(Rgba::new(61, 174, 233, 128).to_string(), "#3daee980");
391 }
392
393 #[test]
396 fn serde_json_round_trip() {
397 let c = Rgba::rgb(61, 174, 233);
398 let json = serde_json::to_string(&c).unwrap();
399 assert_eq!(json, "\"#3daee9\"");
400 let deserialized: Rgba = serde_json::from_str(&json).unwrap();
401 assert_eq!(deserialized, c);
402 }
403
404 #[test]
405 fn serde_toml_round_trip() {
406 #[derive(Debug, PartialEq, Serialize, Deserialize)]
407 struct Wrapper {
408 color: Rgba,
409 }
410 let w = Wrapper {
411 color: Rgba::new(61, 174, 233, 128),
412 };
413 let toml_str = toml::to_string(&w).unwrap();
414 let deserialized: Wrapper = toml::from_str(&toml_str).unwrap();
415 assert_eq!(deserialized, w);
416 }
417
418 #[test]
421 fn to_f32_array_black() {
422 let arr = Rgba::rgb(0, 0, 0).to_f32_array();
423 assert_eq!(arr, [0.0, 0.0, 0.0, 1.0]);
424 }
425
426 #[test]
427 fn to_f32_array_white_transparent() {
428 let arr = Rgba::new(255, 255, 255, 0).to_f32_array();
429 assert_eq!(arr, [1.0, 1.0, 1.0, 0.0]);
430 }
431
432 #[test]
435 fn rgba_is_copy() {
436 let a = Rgba::rgb(1, 2, 3);
437 let b = a; assert_eq!(a, b); }
440
441 #[test]
442 fn rgba_is_hash() {
443 use std::collections::HashSet;
444 let mut set = HashSet::new();
445 set.insert(Rgba::rgb(1, 2, 3));
446 assert!(set.contains(&Rgba::rgb(1, 2, 3)));
447 }
448
449 #[test]
452 fn from_f32_basic() {
453 let c = Rgba::from_f32(1.0, 0.5, 0.0, 1.0);
454 assert_eq!(c.r, 255);
455 assert_eq!(c.g, 128); assert_eq!(c.b, 0);
457 assert_eq!(c.a, 255);
458 }
459
460 #[test]
461 fn from_f32_clamps_out_of_range() {
462 let c = Rgba::from_f32(-0.5, 1.5, 0.0, 0.0);
463 assert_eq!(c.r, 0);
464 assert_eq!(c.g, 255);
465 }
466}