radicle_term/ansi/color.rs
1use std::fmt;
2
3use super::{Paint, Style};
4
5/// An enum representing an ANSI color code.
6#[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
7pub enum Color {
8 /// No color has been set. Nothing is changed when applied.
9 #[default]
10 Unset,
11 /// Black #0 (foreground code `30`, background code `40`).
12 Black,
13 /// Red: #1 (foreground code `31`, background code `41`).
14 Red,
15 /// Green: #2 (foreground code `32`, background code `42`).
16 Green,
17 /// Yellow: #3 (foreground code `33`, background code `43`).
18 Yellow,
19 /// Blue: #4 (foreground code `34`, background code `44`).
20 Blue,
21 /// Magenta: #5 (foreground code `35`, background code `45`).
22 Magenta,
23 /// Cyan: #6 (foreground code `36`, background code `46`).
24 Cyan,
25 /// White: #7 (foreground code `37`, background code `47`).
26 White,
27 /// A color number from 0 to 255, for use in 256-color terminals.
28 Fixed(u8),
29 /// A 24-bit RGB color, as specified by ISO-8613-3.
30 RGB(u8, u8, u8),
31}
32
33impl Color {
34 /// Constructs a new `Paint` structure that encapsulates `item` with the
35 /// foreground color set to the color `self`.
36 #[inline]
37 pub fn paint<T>(self, item: T) -> Paint<T> {
38 Paint::new(item).fg(self)
39 }
40
41 /// Constructs a new `Style` structure with the foreground color set to the
42 /// color `self`.
43 #[inline]
44 pub const fn style(self) -> Style {
45 Style::new(self)
46 }
47
48 pub(crate) fn ansi_fmt(&self, f: &mut dyn fmt::Write) -> fmt::Result {
49 match *self {
50 Color::Unset => Ok(()),
51 Color::Black => write!(f, "0"),
52 Color::Red => write!(f, "1"),
53 Color::Green => write!(f, "2"),
54 Color::Yellow => write!(f, "3"),
55 Color::Blue => write!(f, "4"),
56 Color::Magenta => write!(f, "5"),
57 Color::Cyan => write!(f, "6"),
58 Color::White => write!(f, "7"),
59 Color::Fixed(num) => write!(f, "8;5;{num}"),
60 Color::RGB(r, g, b) => write!(f, "8;2;{r};{g};{b}"),
61 }
62 }
63}