1use std::fmt;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Color {
25 pub r: u8,
27 pub g: u8,
29 pub b: u8,
31 pub a: u8,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("expected rgba(rrggbbaa) or rgb(rrggbb) in hex, got {0:?}")]
45pub struct ColorError(pub String);
46
47impl Color {
48 pub const BLACK: Color = Color { r: 0, g: 0, b: 0, a: 0xff };
52
53 pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
57 Color { r, g, b, a }
58 }
59
60 pub fn parse(s: &str) -> Result<Color, ColorError> {
66 let bad = || ColorError(s.to_string());
67 let (body, want) = match s.strip_prefix("rgba(") {
68 Some(rest) => (rest.strip_suffix(')').ok_or_else(bad)?, 8),
69 None => (
70 s.strip_prefix("rgb(")
71 .ok_or_else(bad)?
72 .strip_suffix(')')
73 .ok_or_else(bad)?,
74 6,
75 ),
76 };
77 if body.len() != want || !body.chars().all(|c| c.is_ascii_hexdigit()) {
78 return Err(bad());
79 }
80 let byte = |i: usize| u8::from_str_radix(&body[i..i + 2], 16).map_err(|_| bad());
81 Ok(Color {
82 r: byte(0)?,
83 g: byte(2)?,
84 b: byte(4)?,
85 a: if want == 8 { byte(6)? } else { 0xff },
86 })
87 }
88
89 pub fn from_argb_hex(s: &str) -> Option<Color> {
93 if s.len() != 8 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
94 return None;
95 }
96 let byte = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
97 Some(Color { a: byte(0)?, r: byte(2)?, g: byte(4)?, b: byte(6)? })
98 }
99
100 pub fn from_argb_u32(v: u32) -> Color {
103 Color {
104 a: (v >> 24) as u8,
105 r: (v >> 16) as u8,
106 g: (v >> 8) as u8,
107 b: v as u8,
108 }
109 }
110}
111
112impl fmt::Display for Color {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 write!(f, "rgba({:02x}{:02x}{:02x}{:02x})", self.r, self.g, self.b, self.a)
115 }
116}
117
118impl serde::Serialize for Color {
119 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
120 s.serialize_str(&self.to_string())
121 }
122}
123
124impl<'de> serde::Deserialize<'de> for Color {
125 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Color, D::Error> {
126 let raw = String::deserialize(d)?;
127 Color::parse(&raw).map_err(serde::de::Error::custom)
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn the_two_accepted_spellings_parse() {
137 assert_eq!(Color::parse("rgba(bd93f9ff)").unwrap(), Color::rgba(0xbd, 0x93, 0xf9, 0xff));
138 assert_eq!(Color::parse("rgb(282a36)").unwrap(), Color::rgba(0x28, 0x2a, 0x36, 0xff));
139 assert_eq!(Color::parse("rgba(00000080)").unwrap(), Color::rgba(0, 0, 0, 0x80));
140 }
141
142 #[test]
147 fn the_digit_count_must_match_the_prefix() {
148 assert!(Color::parse("rgb(bd93f9ff)").is_err(), "eight digits in rgb(");
149 assert!(Color::parse("rgba(282a36)").is_err(), "six digits in rgba(");
150 }
151
152 #[test]
156 fn anything_else_is_refused_rather_than_guessed() {
157 for bad in [
158 "",
159 "nonsense",
160 "rgba(",
161 "rgba(zzzzzzzz)",
162 "0xffbd93f9",
163 "rgba(bd93f9ff",
164 "bd93f9ff",
165 "rgba(bd93f9ff) ",
166 ] {
167 assert!(Color::parse(bad).is_err(), "{bad:?} should not parse");
168 }
169 }
170
171 #[test]
174 fn hyprctl_spellings_move_the_alpha_to_the_end() {
175 assert_eq!(Color::from_argb_hex("ffbd93f9").unwrap().to_string(), "rgba(bd93f9ff)");
176 assert_eq!(Color::from_argb_u32(4279312947).to_string(), "rgba(112233ff)");
177 }
178
179 #[test]
180 fn a_colour_round_trips_through_its_string_form() {
181 for original in ["rgba(bd93f9ff)", "rgba(00000000)", "rgba(ffffffff)"] {
182 let parsed = Color::parse(original).unwrap();
183 assert_eq!(parsed.to_string(), original);
184 assert_eq!(Color::parse(&parsed.to_string()).unwrap(), parsed);
185 }
186 }
187
188 #[test]
189 fn colours_survive_serde_as_the_string_form() {
190 #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
191 struct Holder {
192 accent: Color,
193 }
194 let held = Holder { accent: Color::parse("rgba(bd93f9ff)").unwrap() };
195 let text = toml::to_string(&held).unwrap();
196 assert!(text.contains(r#"accent = "rgba(bd93f9ff)""#), "{text}");
197 assert_eq!(toml::from_str::<Holder>(&text).unwrap(), held);
198 }
199}