mod hsl;
mod rgb;
pub use hsl::HSL;
pub use rgb::RGB;
use crate::{ANSIColorCode, TargetGround};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
Color256(u8),
TrueColor(RGB),
}
impl Color {
#[inline]
const fn order(&self) -> u8 {
match *self {
Self::Black | Self::BrightBlack => 0,
Self::Red | Self::BrightRed => 1,
Self::Green | Self::BrightGreen => 2,
Self::Yellow | Self::BrightYellow => 3,
Self::Blue | Self::BrightBlue => 4,
Self::Magenta | Self::BrightMagenta => 5,
Self::Cyan | Self::BrightCyan => 6,
Self::White | Self::BrightWhite => 7,
Self::Color256(n) if n < 16 => n % 8,
_ => 8,
}
}
#[inline]
const fn intensity(&self) -> u8 {
match *self {
Self::BrightBlack
| Self::BrightRed
| Self::BrightGreen
| Self::BrightYellow
| Self::BrightBlue
| Self::BrightMagenta
| Self::BrightCyan
| Self::BrightWhite => 60,
Self::Color256(n) if 7 < n && n < 16 => 60,
_ => 0,
}
}
}
impl From<RGB> for Color {
fn from(rgb: RGB) -> Self {
Self::TrueColor(rgb)
}
}
impl From<HSL> for Color {
fn from(hsl: HSL) -> Self {
Self::TrueColor(hsl.as_rgb())
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\x1B[{}m \x1B[0m", self.ansi_color_code(TargetGround::Background))
}
}
impl ANSIColorCode for Color {
fn ansi_color_code(&self, target: TargetGround) -> String {
match *self {
Color::TrueColor(c) => c.ansi_color_code(target),
Color::Color256(n) if 15 < n => format!("{};5;{}", target.code() + 8, n),
c @ _ => (c.order() + c.intensity() + target.code()).to_string(),
}
}
}