yansi/
color.rs

1use std::fmt;
2
3use {Paint, Style};
4
5/// An enum representing an ANSI color code.
6#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
7pub enum Color {
8    /// No color has been set. Nothing is changed when applied.
9    Unset,
10
11    /// Terminal default #9. (foreground code `39`, background code `49`).
12    Default,
13
14    /// Black #0 (foreground code `30`, background code `40`).
15    Black,
16
17    /// Red: #1 (foreground code `31`, background code `41`).
18    Red,
19
20    /// Green: #2 (foreground code `32`, background code `42`).
21    Green,
22
23    /// Yellow: #3 (foreground code `33`, background code `43`).
24    Yellow,
25
26    /// Blue: #4 (foreground code `34`, background code `44`).
27    Blue,
28
29    /// Magenta: #5 (foreground code `35`, background code `45`).
30    Magenta,
31
32    /// Cyan: #6 (foreground code `36`, background code `46`).
33    Cyan,
34
35    /// White: #7 (foreground code `37`, background code `47`).
36    White,
37
38    /// A color number from 0 to 255, for use in 256-color terminals.
39    Fixed(u8),
40
41    /// A 24-bit RGB color, as specified by ISO-8613-3.
42    RGB(u8, u8, u8),
43}
44
45impl Color {
46    /// Constructs a new `Paint` structure that encapsulates `item` with the
47    /// foreground color set to the color `self`.
48    ///
49    /// ```rust
50    /// use yansi::Color::Blue;
51    ///
52    /// println!("This is going to be blue: {}", Blue.paint("yay!"));
53    /// ```
54    #[inline]
55    pub fn paint<T>(self, item: T) -> Paint<T> {
56        Paint::new(item).fg(self)
57    }
58
59    /// Constructs a new `Style` structure with the foreground color set to the
60    /// color `self`.
61    ///
62    /// ```rust
63    /// use yansi::Color::Green;
64    ///
65    /// let success = Green.style().bold();
66    /// println!("Hey! {}", success.paint("Success!"));
67    /// ```
68    #[inline]
69    pub fn style(self) -> Style {
70        Style::new(self)
71    }
72
73    pub(crate) fn ascii_fmt(&self, f: &mut fmt::Write) -> fmt::Result {
74        match *self {
75            Color::Unset => Ok(()),
76            Color::Default => write!(f, "9"),
77            Color::Black => write!(f, "0"),
78            Color::Red => write!(f, "1"),
79            Color::Green => write!(f, "2"),
80            Color::Yellow => write!(f, "3"),
81            Color::Blue => write!(f, "4"),
82            Color::Magenta => write!(f, "5"),
83            Color::Cyan => write!(f, "6"),
84            Color::White => write!(f, "7"),
85            Color::Fixed(num) => write!(f, "8;5;{}", num),
86            Color::RGB(r, g, b) => write!(f, "8;2;{};{};{}", r, g, b),
87        }
88    }
89}
90
91impl Default for Color {
92    #[inline(always)]
93    fn default() -> Self {
94        Color::Unset
95    }
96}