use std::borrow::Cow;
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgba {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("invalid colour literal: {input:?}")]
pub struct ColorParseError {
pub input: String,
}
impl ColorParseError {
fn new(input: &str) -> Self {
Self { input: input.to_string() }
}
}
impl Rgba {
pub const WHITE: Rgba = Rgba::new(255, 255, 255, 255);
pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
pub fn from_hex(s: &str) -> Result<Self, ColorParseError> {
let hex = s.strip_prefix('#').ok_or_else(|| ColorParseError::new(s))?;
if hex.is_empty() || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(ColorParseError::new(s));
}
let byte = |slice: &str| -> Result<u8, ColorParseError> {
u8::from_str_radix(slice, 16).map_err(|_| ColorParseError::new(s))
};
match hex.len() {
3 => {
let r = byte(&hex[0..1])? * 17;
let g = byte(&hex[1..2])? * 17;
let b = byte(&hex[2..3])? * 17;
Ok(Self::new(r, g, b, 255))
}
6 => Ok(Self::new(byte(&hex[0..2])?, byte(&hex[2..4])?, byte(&hex[4..6])?, 255)),
8 => Ok(Self::new(
byte(&hex[0..2])?,
byte(&hex[2..4])?,
byte(&hex[4..6])?,
byte(&hex[6..8])?,
)),
_ => Err(ColorParseError::new(s)),
}
}
pub fn from_css(s: &str) -> Result<Self, ColorParseError> {
let trimmed = s.trim();
if trimmed.starts_with('#') {
return Self::from_hex(trimmed);
}
let inner = trimmed
.strip_prefix("rgba(")
.and_then(|rest| rest.strip_suffix(')'))
.ok_or_else(|| ColorParseError::new(s))?;
let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
if parts.len() != 4 {
return Err(ColorParseError::new(s));
}
let channel = |p: &str| p.parse::<u8>().map_err(|_| ColorParseError::new(s));
let r = channel(parts[0])?;
let g = channel(parts[1])?;
let b = channel(parts[2])?;
let alpha_f: f64 = parts[3].parse().map_err(|_| ColorParseError::new(s))?;
let a = if (0.0..=1.0).contains(&alpha_f) {
(alpha_f * 255.0) as u8
} else if (0.0..=255.0).contains(&alpha_f) {
alpha_f as u8
} else {
return Err(ColorParseError::new(s));
};
Ok(Self::new(r, g, b, a))
}
pub fn to_css_hex(&self) -> String {
if self.a == 255 {
format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
} else {
format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
}
}
pub fn with_alpha(self, alpha: f32) -> Self {
Self { a: round_channel(alpha), ..self }
}
pub fn mix(self, other: Rgba, t: f32) -> Self {
let t = t.clamp(0.0, 1.0);
let lerp = |from: u8, to: u8| -> u8 {
let value = from as f32 + (to as f32 - from as f32) * t;
value.round().clamp(0.0, 255.0) as u8
};
Self {
r: lerp(self.r, other.r),
g: lerp(self.g, other.g),
b: lerp(self.b, other.b),
a: lerp(self.a, other.a),
}
}
}
fn round_channel(fraction: f32) -> u8 {
(fraction.clamp(0.0, 1.0) * 255.0).round() as u8
}
impl fmt::Display for Rgba {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_css_hex())
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ColorValue {
Solid(Rgba),
Transparent,
Sentinel(&'static str),
}
impl ColorValue {
pub fn parse(s: &str) -> Result<Self, ColorParseError> {
let trimmed = s.trim();
if trimmed.eq_ignore_ascii_case("transparent") || trimmed.eq_ignore_ascii_case("none") {
return Ok(ColorValue::Transparent);
}
Rgba::from_css(trimmed).map(ColorValue::Solid)
}
pub fn to_css(&self) -> Cow<'static, str> {
match self {
ColorValue::Solid(rgba) => Cow::Owned(rgba.to_css_hex()),
ColorValue::Transparent => Cow::Borrowed("transparent"),
ColorValue::Sentinel(s) => Cow::Borrowed(s),
}
}
pub fn with_alpha(&self, alpha: f32) -> ColorValue {
match self {
ColorValue::Solid(rgba) => ColorValue::Solid(rgba.with_alpha(alpha)),
other => other.clone(),
}
}
pub fn mix(&self, other: &ColorValue, t: f32) -> ColorValue {
match (self, other) {
(ColorValue::Solid(a), ColorValue::Solid(b)) => ColorValue::Solid(a.mix(*b, t)),
(this, _) => this.clone(),
}
}
pub fn to_rgba8(&self) -> [u8; 4] {
match self {
ColorValue::Solid(rgba) => [rgba.r, rgba.g, rgba.b, rgba.a],
ColorValue::Transparent | ColorValue::Sentinel(_) => [0, 0, 0, 0],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::render::parse_color;
const EXISTING_LITERALS: &[&str] = &[
"#d1d4dc",
"#2a2e39",
"#161b22ff",
"#00000060",
"#1e222dee",
"rgba(41,98,255,0.15)",
"rgba(242,54,69,0.15)",
"rgba(255,255,255,0.06)",
"rgba(239,83,80,0.5)",
"transparent",
];
#[test]
fn hex_round_trip() {
assert_eq!(Rgba::from_hex("#d1d4dc").unwrap().to_css_hex(), "#d1d4dc");
assert_eq!(Rgba::from_hex("#00000060").unwrap().to_css_hex(), "#00000060");
assert_eq!(Rgba::from_hex("#1e222dee").unwrap().to_css_hex(), "#1e222dee");
assert_eq!(Rgba::from_hex("#abc").unwrap().to_css_hex(), "#aabbcc");
assert_eq!(Rgba::from_hex("#ABC").unwrap().to_css_hex(), "#aabbcc");
assert_eq!(Rgba::from_hex("#161b22ff").unwrap().to_css_hex(), "#161b22");
}
#[test]
fn from_hex_names_the_bad_input() {
let err = Rgba::from_hex("not-a-color").unwrap_err();
assert_eq!(err.input, "not-a-color");
assert!(Rgba::from_hex("#12").is_err());
assert!(Rgba::from_hex("abc").is_err(), "missing leading '#' must be rejected");
assert!(Rgba::from_hex("#").is_err());
}
#[test]
fn every_existing_literal_shape_parses_and_paints_the_same_pixel() {
for literal in EXISTING_LITERALS {
let expected = parse_color(literal);
let value = ColorValue::parse(literal)
.unwrap_or_else(|e| panic!("{literal} failed to parse: {e}"));
let rendered = value.to_css();
let actual = parse_color(&rendered);
assert_eq!(
actual, expected,
"{literal:?} -> {rendered:?} changed the painted pixel"
);
}
}
#[test]
fn with_alpha_rounds_to_nearest() {
let opaque = Rgba::new(10, 20, 30, 255);
assert_eq!(opaque.with_alpha(0.5).a, 128); assert_eq!(opaque.with_alpha(1.0).a, 255);
assert_eq!(opaque.with_alpha(0.0).a, 0);
assert_eq!(opaque.with_alpha(2.0).a, 255, "alpha above 1.0 clamps");
assert_eq!(opaque.with_alpha(-1.0).a, 0, "alpha below 0.0 clamps");
}
#[test]
fn mix_rounds_to_nearest_and_clamps_t() {
let black = Rgba::new(0, 0, 0, 255);
let white = Rgba::new(255, 255, 255, 255);
assert_eq!(black.mix(white, 0.5), Rgba::new(128, 128, 128, 255));
assert_eq!(black.mix(white, 0.0), black);
assert_eq!(black.mix(white, 1.0), white);
assert_eq!(black.mix(white, 2.0), white, "t above 1.0 clamps");
assert_eq!(black.mix(white, -1.0), black, "t below 0.0 clamps");
}
#[test]
fn sentinel_passes_through_untouched() {
let rainbow = ColorValue::Sentinel("rainbow");
assert_eq!(rainbow.to_css(), "rainbow");
assert_eq!(rainbow.with_alpha(0.5), rainbow);
let solid = ColorValue::Solid(Rgba::new(0, 0, 0, 255));
assert_eq!(rainbow.mix(&solid, 0.5), rainbow);
assert_eq!(solid.mix(&rainbow, 0.5), solid, "mix with a sentinel is a no-op");
}
#[test]
fn transparent_parses_case_insensitively_and_is_a_noop_under_modifiers() {
assert_eq!(ColorValue::parse("transparent").unwrap(), ColorValue::Transparent);
assert_eq!(ColorValue::parse("TRANSPARENT").unwrap(), ColorValue::Transparent);
assert_eq!(ColorValue::parse("none").unwrap(), ColorValue::Transparent);
assert_eq!(ColorValue::Transparent.with_alpha(0.2), ColorValue::Transparent);
let solid = ColorValue::Solid(Rgba::new(1, 2, 3, 255));
assert_eq!(ColorValue::Transparent.mix(&solid, 0.5), ColorValue::Transparent);
}
#[test]
fn parse_rejects_unknown_strings_and_names_them() {
let err = ColorValue::parse("rainbow").unwrap_err();
assert_eq!(err.input, "rainbow");
}
#[test]
fn to_rgba8_matches_the_parsed_channels() {
let solid = ColorValue::Solid(Rgba::new(0x2f, 0x62, 0xff, 0x55));
assert_eq!(solid.to_rgba8(), [0x2f, 0x62, 0xff, 0x55]);
assert_eq!(ColorValue::Transparent.to_rgba8(), [0, 0, 0, 0]);
assert_eq!(ColorValue::Sentinel("rainbow").to_rgba8(), [0, 0, 0, 0]);
}
}