crisol-core 1.0.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! An egui-free, premultiplied sRGB color.
//!
//! [`Rgba`] stores exactly the four bytes of `egui::Color32` in the same order and with
//! the same premultiplication, so the conversion in the UI is a lossless bijection for
//! all 2³² byte combinations (PIX-COL-01).
//!
//! ```
//! use crisol_core::color;
//! ```

use std::fmt;

/// An 8-bit sRGB color with a premultiplied alpha channel.
///
/// The layout matches `egui::Color32`: `[r, g, b, a]` with each channel premultiplied
/// by `a / 255`, and `a = 255` for opaque colors. The UI converts with
/// `Color32::from_rgba_premultiplied` and `Color32::to_array`; no rounding happens in
/// either direction.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
/// # Example
///
/// ```
/// use crisol_core::color::Rgba;
/// ```
pub struct Rgba([u8; 4]);

impl Rgba {
    /// Transparent black.
    pub const TRANSPARENT: Self = Self([0, 0, 0, 0]);
    /// Opaque black.
    pub const BLACK: Self = Self([0, 0, 0, 255]);
    /// Opaque white.
    pub const WHITE: Self = Self([255, 255, 255, 255]);

    /// An opaque color.
    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        Self([r, g, b, 255])
    }

    /// A color whose channels are already premultiplied by its alpha.
    ///
    /// This is the exact constructor used for the `Color32` conversion.
    pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self([r, g, b, a])
    }

    /// A straight (non-premultiplied) color, premultiplied the same way `Color32` does.
    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])
        }
    }

    /// The four stored bytes, in `[r, g, b, a]` order.
    pub const fn to_array(self) -> [u8; 4] {
        self.0
    }

    /// A color from the four stored bytes, in `[r, g, b, a]` order.
    pub const fn from_array(bytes: [u8; 4]) -> Self {
        Self(bytes)
    }

    /// The red channel, premultiplied.
    pub const fn r(self) -> u8 {
        self.0[0]
    }

    /// The green channel, premultiplied.
    pub const fn g(self) -> u8 {
        self.0[1]
    }

    /// The blue channel, premultiplied.
    pub const fn b(self) -> u8 {
        self.0[2]
    }

    /// The alpha channel.
    pub const fn a(self) -> u8 {
        self.0[3]
    }

    /// Whether this is fully transparent.
    pub const fn is_transparent(self) -> bool {
        self.0[3] == 0
    }

    /// The color multiplied by `factor` (1.0 keeps it, 0.0 clears it), like
    /// `Color32::gamma_multiply`.
    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])])
    }

    /// The color blended towards `other` by `t` (0 = self, 1 = other), in sRGB.
    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]),
        ])
    }

    /// The color as `#rrggbb`, or `#rrggbbaa` when it is not opaque.
    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])
        }
    }

    /// Parse `#rrggbb` or `#rrggbbaa`.
    ///
    /// # Errors
    /// When the text is not a six- or eight-digit hexadecimal color.
    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))
        }
    }

    /// Relative luminance in linear light (WCAG 2.2).
    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)
    }
}

/// Why a hexadecimal color could not be parsed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::color::ParseRgbaError;
/// ```
pub enum ParseRgbaError {
    /// The text had the wrong number of digits.
    #[error("a color needs 6 or 8 hex digits, found {0}")]
    Length(usize),
    /// A pair of digits was not hexadecimal.
    #[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);
    }
}