#[derive(Clone, Copy, Debug, Default)]
#[repr(C, align(4))]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Color {
pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0);
pub const BLACK: Self = Self::from_rgba_premultiplied(0, 0, 0, 255);
pub const WHITE: Self = Self::from_rgba_premultiplied(255, 255, 255, 255);
#[must_use]
pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
#[must_use]
pub const fn from_rgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
Self {
r: premultiply(r, a),
g: premultiply(g, a),
b: premultiply(b, a),
a,
}
}
#[must_use]
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
Self::from_rgba_premultiplied(r, g, b, 255)
}
#[must_use]
pub const fn to_array(self) -> [u8; 4] {
[self.r, self.g, self.b, self.a]
}
#[must_use]
pub const fn to_packed(self) -> u32 {
(self.r as u32) | (self.g as u32) << 8 | (self.b as u32) << 16 | (self.a as u32) << 24
}
#[must_use]
pub const fn from_packed(packed: u32) -> Self {
let [r, g, b, a] = packed.to_le_bytes();
Self { r, g, b, a }
}
#[cfg(all(test, feature = "egui"))]
pub(crate) const fn to_egui(self) -> egui::Color32 {
egui::Color32::from_rgba_premultiplied(self.r, self.g, self.b, self.a)
}
}
impl PartialEq for Color {
fn eq(&self, other: &Self) -> bool {
u32::from_ne_bytes(self.to_array()) == u32::from_ne_bytes(other.to_array())
}
}
impl Eq for Color {}
impl std::hash::Hash for Color {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.to_packed().hash(state);
}
}
#[allow(
clippy::cast_possible_truncation,
reason = "(channel * alpha + 127) / 255 is at most 255"
)]
const fn premultiply(channel: u8, alpha: u8) -> u8 {
((channel as u16 * alpha as u16 + 127) / 255) as u8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packed_layout_is_red_in_the_low_byte() {
let color = Color::from_rgba_premultiplied(0x11, 0x22, 0x33, 0x44);
assert_eq!(color.to_packed(), 0x4433_2211);
assert_eq!(Color::from_packed(0x4433_2211), color);
}
#[test]
fn unmultiplied_colors_round_to_nearest() {
assert_eq!(
Color::from_rgba_unmultiplied(255, 128, 1, 128),
Color::from_rgba_premultiplied(128, 64, 1, 128)
);
assert_eq!(
Color::from_rgba_unmultiplied(200, 100, 50, 255),
Color::from_rgb(200, 100, 50)
);
assert_eq!(
Color::from_rgba_unmultiplied(200, 100, 50, 0),
Color::TRANSPARENT
);
}
}