fluent_ansi/colors/
color.rs

1use core::fmt::Result;
2
3use crate::{
4    CodeWriter, ColorTarget,
5    colors::{BasicColor, IndexedColor, RGBColor, SimpleColor, WriteColorCodes},
6    impl_macros::color_type::impl_color_type,
7};
8
9/// An enum representing all supported color types.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Color {
12    /// A simple color (16 colors).
13    Simple(SimpleColor),
14    /// An 8-bit color (256 colors).
15    Indexed(IndexedColor),
16    /// An RGB color (24-bit/true color).
17    RGB(RGBColor),
18}
19
20impl Color {
21    /// Constant for the basic color black.
22    pub const BLACK: BasicColor = BasicColor::Black;
23    /// Constant for the basic color red.
24    pub const RED: BasicColor = BasicColor::Red;
25    /// Constant for the basic color green.
26    pub const GREEN: BasicColor = BasicColor::Green;
27    /// Constant for the basic color yellow.
28    pub const YELLOW: BasicColor = BasicColor::Yellow;
29    /// Constant for the basic color blue.
30    pub const BLUE: BasicColor = BasicColor::Blue;
31    /// Constant for the basic color magenta.
32    pub const MAGENTA: BasicColor = BasicColor::Magenta;
33    /// Constant for the basic color cyan.
34    pub const CYAN: BasicColor = BasicColor::Cyan;
35    /// Constant for the basic color white.
36    pub const WHITE: BasicColor = BasicColor::White;
37
38    /// Create an 8-bit color from the given value.
39    #[must_use]
40    pub const fn indexed(value: u8) -> IndexedColor {
41        IndexedColor::new(value)
42    }
43
44    /// Create an RGB color from the given red, green, and blue components.
45    #[must_use]
46    pub const fn rgb(r: u8, g: u8, b: u8) -> RGBColor {
47        RGBColor::new(r, g, b)
48    }
49
50    /// Helper method to return a [`None`] value.
51    ///
52    /// Use it to clear the color for some target with [`Style::set_color()`](crate::Style::set_color)
53    /// or [`Styled<C>::set_color()`](crate::Styled<C>::set_color).
54    #[must_use]
55    pub const fn none() -> Option<Color> {
56        None
57    }
58}
59
60impl_color_type!(Color {
61    args: [self];
62    to_color: SELF
63});
64
65impl WriteColorCodes for Color {
66    fn write_color_codes(self, target: ColorTarget, writer: &mut CodeWriter) -> Result {
67        match self {
68            Color::Simple(simple) => simple.write_color_codes(target, writer),
69            Color::Indexed(indexed) => indexed.write_color_codes(target, writer),
70            Color::RGB(rgb) => rgb.write_color_codes(target, writer),
71        }
72    }
73}