1use serde::de;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6use std::str::FromStr;
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub struct Rgba {
43 pub r: u8,
45 pub g: u8,
47 pub b: u8,
49 pub a: u8,
51}
52
53impl Rgba {
54 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
56 Self { r, g, b, a: 255 }
57 }
58
59 #[allow(clippy::self_named_constructors)]
61 pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
62 Self { r, g, b, a }
63 }
64
65 pub fn from_f32(r: f32, g: f32, b: f32, a: f32) -> Self {
69 Self {
70 r: (r.clamp(0.0, 1.0) * 255.0).round() as u8,
71 g: (g.clamp(0.0, 1.0) * 255.0).round() as u8,
72 b: (b.clamp(0.0, 1.0) * 255.0).round() as u8,
73 a: (a.clamp(0.0, 1.0) * 255.0).round() as u8,
74 }
75 }
76
77 pub fn to_f32_array(&self) -> [f32; 4] {
79 [
80 self.r as f32 / 255.0,
81 self.g as f32 / 255.0,
82 self.b as f32 / 255.0,
83 self.a as f32 / 255.0,
84 ]
85 }
86
87 pub fn to_f32_tuple(&self) -> (f32, f32, f32, f32) {
89 (
90 self.r as f32 / 255.0,
91 self.g as f32 / 255.0,
92 self.b as f32 / 255.0,
93 self.a as f32 / 255.0,
94 )
95 }
96}
97
98impl fmt::Display for Rgba {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 if self.a == 255 {
101 write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
102 } else {
103 write!(
104 f,
105 "#{:02x}{:02x}{:02x}{:02x}",
106 self.r, self.g, self.b, self.a
107 )
108 }
109 }
110}
111
112impl FromStr for Rgba {
113 type Err = String;
114
115 fn from_str(s: &str) -> Result<Self, Self::Err> {
116 let hex = s.strip_prefix('#').unwrap_or(s);
117
118 if hex.is_empty() {
119 return Err("empty hex color string".to_string());
120 }
121
122 match hex.len() {
123 3 => {
125 let r = u8::from_str_radix(&hex[0..1], 16)
126 .map_err(|e| format!("invalid red component: {e}"))?;
127 let g = u8::from_str_radix(&hex[1..2], 16)
128 .map_err(|e| format!("invalid green component: {e}"))?;
129 let b = u8::from_str_radix(&hex[2..3], 16)
130 .map_err(|e| format!("invalid blue component: {e}"))?;
131 Ok(Rgba::rgb(r * 17, g * 17, b * 17))
132 }
133 4 => {
135 let r = u8::from_str_radix(&hex[0..1], 16)
136 .map_err(|e| format!("invalid red component: {e}"))?;
137 let g = u8::from_str_radix(&hex[1..2], 16)
138 .map_err(|e| format!("invalid green component: {e}"))?;
139 let b = u8::from_str_radix(&hex[2..3], 16)
140 .map_err(|e| format!("invalid blue component: {e}"))?;
141 let a = u8::from_str_radix(&hex[3..4], 16)
142 .map_err(|e| format!("invalid alpha component: {e}"))?;
143 Ok(Rgba::rgba(r * 17, g * 17, b * 17, a * 17))
144 }
145 6 => {
147 let r = u8::from_str_radix(&hex[0..2], 16)
148 .map_err(|e| format!("invalid red component: {e}"))?;
149 let g = u8::from_str_radix(&hex[2..4], 16)
150 .map_err(|e| format!("invalid green component: {e}"))?;
151 let b = u8::from_str_radix(&hex[4..6], 16)
152 .map_err(|e| format!("invalid blue component: {e}"))?;
153 Ok(Rgba::rgb(r, g, b))
154 }
155 8 => {
157 let r = u8::from_str_radix(&hex[0..2], 16)
158 .map_err(|e| format!("invalid red component: {e}"))?;
159 let g = u8::from_str_radix(&hex[2..4], 16)
160 .map_err(|e| format!("invalid green component: {e}"))?;
161 let b = u8::from_str_radix(&hex[4..6], 16)
162 .map_err(|e| format!("invalid blue component: {e}"))?;
163 let a = u8::from_str_radix(&hex[6..8], 16)
164 .map_err(|e| format!("invalid alpha component: {e}"))?;
165 Ok(Rgba::rgba(r, g, b, a))
166 }
167 other => Err(format!(
168 "invalid hex color length {other}: expected 3, 4, 6, or 8 hex digits"
169 )),
170 }
171 }
172}
173
174impl Serialize for Rgba {
175 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
176 serializer.serialize_str(&self.to_string())
177 }
178}
179
180impl<'de> Deserialize<'de> for Rgba {
181 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
182 let s = String::deserialize(deserializer)?;
183 Rgba::from_str(&s).map_err(de::Error::custom)
184 }
185}
186
187#[cfg(test)]
188#[allow(clippy::unwrap_used, clippy::expect_used)]
189mod tests {
190 use super::*;
191
192 #[test]
195 fn rgb_constructor_sets_alpha_255() {
196 let c = Rgba::rgb(61, 174, 233);
197 assert_eq!(
198 c,
199 Rgba {
200 r: 61,
201 g: 174,
202 b: 233,
203 a: 255
204 }
205 );
206 }
207
208 #[test]
209 fn rgba_constructor_sets_all_fields() {
210 let c = Rgba::rgba(61, 174, 233, 128);
211 assert_eq!(
212 c,
213 Rgba {
214 r: 61,
215 g: 174,
216 b: 233,
217 a: 128
218 }
219 );
220 }
221
222 #[test]
225 fn parse_6_digit_hex_with_hash() {
226 let c: Rgba = "#3daee9".parse().unwrap();
227 assert_eq!(c, Rgba::rgb(61, 174, 233));
228 }
229
230 #[test]
231 fn parse_8_digit_hex_with_hash() {
232 let c: Rgba = "#3daee980".parse().unwrap();
233 assert_eq!(c, Rgba::rgba(61, 174, 233, 128));
234 }
235
236 #[test]
237 fn parse_6_digit_hex_without_hash() {
238 let c: Rgba = "3daee9".parse().unwrap();
239 assert_eq!(c, Rgba::rgb(61, 174, 233));
240 }
241
242 #[test]
243 fn parse_3_digit_shorthand() {
244 let c: Rgba = "#abc".parse().unwrap();
245 assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
246 }
247
248 #[test]
249 fn parse_4_digit_shorthand() {
250 let c: Rgba = "#abcd".parse().unwrap();
251 assert_eq!(c, Rgba::rgba(0xaa, 0xbb, 0xcc, 0xdd));
252 }
253
254 #[test]
255 fn parse_uppercase_hex() {
256 let c: Rgba = "#AABBCC".parse().unwrap();
257 assert_eq!(c, Rgba::rgb(0xaa, 0xbb, 0xcc));
258 }
259
260 #[test]
261 fn parse_empty_string_is_error() {
262 assert!("".parse::<Rgba>().is_err());
263 }
264
265 #[test]
266 fn parse_invalid_hex_chars_is_error() {
267 assert!("#gggggg".parse::<Rgba>().is_err());
268 }
269
270 #[test]
271 fn parse_invalid_length_5_chars_is_error() {
272 assert!("#12345".parse::<Rgba>().is_err());
273 }
274
275 #[test]
278 fn display_omits_alpha_when_255() {
279 assert_eq!(Rgba::rgb(61, 174, 233).to_string(), "#3daee9");
280 }
281
282 #[test]
283 fn display_includes_alpha_when_not_255() {
284 assert_eq!(Rgba::rgba(61, 174, 233, 128).to_string(), "#3daee980");
285 }
286
287 #[test]
290 fn serde_json_round_trip() {
291 let c = Rgba::rgb(61, 174, 233);
292 let json = serde_json::to_string(&c).unwrap();
293 assert_eq!(json, "\"#3daee9\"");
294 let deserialized: Rgba = serde_json::from_str(&json).unwrap();
295 assert_eq!(deserialized, c);
296 }
297
298 #[test]
299 fn serde_toml_round_trip() {
300 #[derive(Debug, PartialEq, Serialize, Deserialize)]
301 struct Wrapper {
302 color: Rgba,
303 }
304 let w = Wrapper {
305 color: Rgba::rgba(61, 174, 233, 128),
306 };
307 let toml_str = toml::to_string(&w).unwrap();
308 let deserialized: Wrapper = toml::from_str(&toml_str).unwrap();
309 assert_eq!(deserialized, w);
310 }
311
312 #[test]
315 fn to_f32_array_black() {
316 let arr = Rgba::rgb(0, 0, 0).to_f32_array();
317 assert_eq!(arr, [0.0, 0.0, 0.0, 1.0]);
318 }
319
320 #[test]
321 fn to_f32_array_white_transparent() {
322 let arr = Rgba::rgba(255, 255, 255, 0).to_f32_array();
323 assert_eq!(arr, [1.0, 1.0, 1.0, 0.0]);
324 }
325
326 #[test]
329 fn rgba_is_copy() {
330 let a = Rgba::rgb(1, 2, 3);
331 let b = a; assert_eq!(a, b); }
334
335 #[test]
336 fn rgba_default_is_transparent_black() {
337 let d = Rgba::default();
338 assert_eq!(
339 d,
340 Rgba {
341 r: 0,
342 g: 0,
343 b: 0,
344 a: 0
345 }
346 );
347 }
348
349 #[test]
350 fn rgba_is_hash() {
351 use std::collections::HashSet;
352 let mut set = HashSet::new();
353 set.insert(Rgba::rgb(1, 2, 3));
354 assert!(set.contains(&Rgba::rgb(1, 2, 3)));
355 }
356
357 #[test]
360 fn from_f32_basic() {
361 let c = Rgba::from_f32(1.0, 0.5, 0.0, 1.0);
362 assert_eq!(c.r, 255);
363 assert_eq!(c.g, 128); assert_eq!(c.b, 0);
365 assert_eq!(c.a, 255);
366 }
367
368 #[test]
369 fn from_f32_clamps_out_of_range() {
370 let c = Rgba::from_f32(-0.5, 1.5, 0.0, 0.0);
371 assert_eq!(c.r, 0);
372 assert_eq!(c.g, 255);
373 }
374
375 #[test]
378 fn to_f32_tuple_matches_array() {
379 let c = Rgba::rgb(128, 64, 32);
380 let arr = c.to_f32_array();
381 let tup = c.to_f32_tuple();
382 assert_eq!(tup, (arr[0], arr[1], arr[2], arr[3]));
383 }
384}