use std::fmt;
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Rgba([u8; 4]);
impl Rgba {
pub const TRANSPARENT: Self = Self([0, 0, 0, 0]);
pub const BLACK: Self = Self([0, 0, 0, 255]);
pub const WHITE: Self = Self([255, 255, 255, 255]);
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
Self([r, g, b, 255])
}
pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
Self([r, g, b, a])
}
pub const fn from_rgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
if a == 255 {
Self::from_rgb(r, g, b)
} else {
Self([premultiply(r, a), premultiply(g, a), premultiply(b, a), a])
}
}
pub const fn to_array(self) -> [u8; 4] {
self.0
}
pub const fn from_array(bytes: [u8; 4]) -> Self {
Self(bytes)
}
pub const fn r(self) -> u8 {
self.0[0]
}
pub const fn g(self) -> u8 {
self.0[1]
}
pub const fn b(self) -> u8 {
self.0[2]
}
pub const fn a(self) -> u8 {
self.0[3]
}
pub const fn is_transparent(self) -> bool {
self.0[3] == 0
}
pub fn gamma_multiply(self, factor: f32) -> Self {
let factor = factor.clamp(0.0, 1.0);
let scale = |channel: u8| (f32::from(channel) * factor).round() as u8;
Self([scale(self.0[0]), scale(self.0[1]), scale(self.0[2]), scale(self.0[3])])
}
pub fn mix(self, other: Self, t: f32) -> Self {
let t = t.clamp(0.0, 1.0);
let channel = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * t).round() as u8;
Self([
channel(self.0[0], other.0[0]),
channel(self.0[1], other.0[1]),
channel(self.0[2], other.0[2]),
channel(self.0[3], other.0[3]),
])
}
pub fn to_hex(self) -> String {
if self.0[3] == 255 {
format!("#{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2])
} else {
format!("#{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3])
}
}
pub fn from_hex(text: &str) -> Result<Self, ParseRgbaError> {
let text = text.trim().trim_start_matches('#');
if text.len() != 6 && text.len() != 8 {
return Err(ParseRgbaError::Length(text.len()));
}
let byte = |start: usize| {
text.get(start..start + 2)
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
.ok_or(ParseRgbaError::Digit(start))
};
let r = byte(0)?;
let g = byte(2)?;
let b = byte(4)?;
if text.len() == 8 {
Ok(Self::from_rgba_unmultiplied(r, g, b, byte(6)?))
} else {
Ok(Self::from_rgb(r, g, b))
}
}
pub fn relative_luminance(self) -> f32 {
let channel = |value: u8| {
let value = f32::from(value) / 255.0;
if value <= 0.040_45 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * channel(self.0[0]) + 0.7152 * channel(self.0[1]) + 0.0722 * channel(self.0[2])
}
}
const fn premultiply(channel: u8, alpha: u8) -> u8 {
((channel as u32 * alpha as u32 + 127) / 255) as u8
}
impl fmt::Debug for Rgba {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"Rgba({}, {}, {}, {})",
self.0[0], self.0[1], self.0[2], self.0[3]
)
}
}
impl fmt::Display for Rgba {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.to_hex())
}
}
impl From<Rgba> for [u8; 4] {
fn from(color: Rgba) -> Self {
color.0
}
}
impl From<[u8; 4]> for Rgba {
fn from(bytes: [u8; 4]) -> Self {
Self(bytes)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseRgbaError {
#[error("a color needs 6 or 8 hex digits, found {0}")]
Length(usize),
#[error("invalid hex digits at byte {0}")]
Digit(usize),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn premultiplication_matches_the_reference_formula() {
assert_eq!(
Rgba::from_rgba_unmultiplied(255, 0, 0, 128).to_array(),
[128, 0, 0, 128]
);
assert_eq!(
Rgba::from_rgba_unmultiplied(255, 0, 0, 255).to_array(),
[255, 0, 0, 255]
);
assert_eq!(Rgba::from_rgba_unmultiplied(1, 1, 1, 1).to_array(), [0, 0, 0, 1]);
}
#[test]
fn hexadecimal_round_trips() {
for text in ["#1f2328", "#000000", "#ffffff", "#804020"] {
assert_eq!(Rgba::from_hex(text).expect("parse").to_hex(), text);
}
assert_eq!(Rgba::from_hex("#c80000ff").expect("parse").to_hex(), "#c80000");
assert!(Rgba::from_hex("#12345").is_err());
assert!(Rgba::from_hex("#zzzzzz").is_err());
}
#[test]
fn mixing_clamps_and_rounds() {
let black = Rgba::BLACK;
let white = Rgba::WHITE;
assert_eq!(black.mix(white, 0.0), black);
assert_eq!(black.mix(white, 1.0), white);
assert_eq!(black.mix(white, 0.5), Rgba::from_rgb(128, 128, 128));
assert_eq!(black.mix(white, 2.0), white);
}
}