1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//! Color types

pub mod hsl;
pub mod rgb;

pub use hsl::HSL;
pub use rgb::RGB;

use crate::{ANSIColorCode, TargetGround};

/// Represents terminal colors such as 8 standard colors, 256 colors and True colors
#[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.into())
    }
}

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(),
        }
    }
}