use std::fmt;
use std::str::FromStr;
use crate::error::{ImageError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
impl Color {
pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
Self::rgba(red, green, blue, 255)
}
pub const TRANSPARENT: Color = Color::rgba(255, 255, 255, 0);
pub fn parse(input: &str) -> Result<Color> {
let value = input.trim().to_lowercase();
if value == "transparent" {
return Ok(Color::TRANSPARENT);
}
if let Some(color) = parse_hex(&value) {
return Ok(color);
}
if let Some(color) = parse_rgb(&value) {
return Ok(color);
}
Err(ImageError::ColorDecoder(format!(
"Unable to decode color from \"{input}\""
)))
}
pub fn to_hex(&self) -> String {
if self.alpha == 255 {
format!("{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
} else {
format!("{:02x}{:02x}{:02x}{:02x}", self.red, self.green, self.blue, self.alpha)
}
}
pub fn is_clear(&self) -> bool {
self.alpha == 0
}
pub fn is_opaque(&self) -> bool {
self.alpha == 255
}
pub(crate) fn to_pixel(self) -> image::Rgba<u8> {
image::Rgba([self.red, self.green, self.blue, self.alpha])
}
pub(crate) fn from_pixel(pixel: image::Rgba<u8>) -> Color {
let [red, green, blue, alpha] = pixel.0;
Color {
red,
green,
blue,
alpha,
}
}
}
impl FromStr for Color {
type Err = ImageError;
fn from_str(input: &str) -> Result<Self> {
Color::parse(input)
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.to_hex())
}
}
fn parse_hex(value: &str) -> Option<Color> {
let hex = value.strip_prefix('#').unwrap_or(value);
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let channel = |part: &str| -> Option<u8> {
match part.len() {
1 => u8::from_str_radix(&part.repeat(2), 16).ok(),
_ => u8::from_str_radix(part, 16).ok(),
}
};
let parts: Vec<&str> = match hex.len() {
3 | 4 => (0..hex.len()).map(|i| &hex[i..=i]).collect(),
6 | 8 => (0..hex.len()).step_by(2).map(|i| &hex[i..i + 2]).collect(),
_ => return None,
};
let values: Option<Vec<u8>> = parts.into_iter().map(channel).collect();
let values = values?;
Some(Color::rgba(
values[0],
values[1],
values[2],
values.get(3).copied().unwrap_or(255),
))
}
fn parse_rgb(value: &str) -> Option<Color> {
let inner = value
.strip_prefix("rgba(")
.or_else(|| value.strip_prefix("rgb("))?
.strip_suffix(')')?;
let (channels, alpha) = match inner.split_once('/') {
Some((channels, alpha)) => (channels, Some(alpha)),
None => (inner, None),
};
let mut parts: Vec<&str> = channels
.split(|c: char| c == ',' || c.is_whitespace())
.filter(|part| !part.is_empty())
.collect();
let alpha = match alpha {
Some(alpha) => Some(alpha.trim()),
None if parts.len() == 4 => parts.pop(),
None => None,
};
if parts.len() != 3 {
return None;
}
let channel = |part: &str| -> Option<u8> {
if let Some(percent) = part.strip_suffix('%') {
let percent: f64 = percent.parse().ok()?;
return (0.0..=100.0).contains(&percent).then(|| (percent * 2.55).round() as u8);
}
let value: f64 = part.parse().ok()?;
(0.0..=255.0).contains(&value).then(|| value.round() as u8)
};
let alpha = match alpha {
None => 255,
Some(alpha) => {
let normalized = match alpha.strip_suffix('%') {
Some(percent) => percent.parse::<f64>().ok()? / 100.0,
None => alpha.parse::<f64>().ok()?,
};
if !(0.0..=1.0).contains(&normalized) {
return None;
}
(normalized * 255.0).round() as u8
}
};
Some(Color::rgba(
channel(parts[0])?,
channel(parts[1])?,
channel(parts[2])?,
alpha,
))
}
#[cfg(test)]
mod tests {
use super::Color;
#[test]
fn decodes_hex_rgb_and_transparent() {
assert_eq!(Color::parse("f50").unwrap(), Color::rgb(255, 85, 0));
assert_eq!(Color::parse("#FF5500").unwrap(), Color::rgb(255, 85, 0));
assert_eq!(Color::parse("ff550080").unwrap(), Color::rgba(255, 85, 0, 128));
assert_eq!(Color::parse("#f508").unwrap(), Color::rgba(255, 85, 0, 136));
assert_eq!(Color::parse("rgb(255, 85, 0)").unwrap(), Color::rgb(255, 85, 0));
assert_eq!(
Color::parse("rgba(255, 85, 0, 0.5)").unwrap(),
Color::rgba(255, 85, 0, 128)
);
assert_eq!(Color::parse("transparent").unwrap(), Color::TRANSPARENT);
assert!(Color::parse("ffff").is_ok());
assert!(Color::parse("fffff").is_err());
assert!(Color::parse("rgb(300, 0, 0)").is_err());
assert_eq!(Color::rgb(255, 85, 0).to_hex(), "ff5500");
}
}