fluent_ansi/colors/
indexed.rs

1use core::fmt::Result;
2
3use crate::{
4    CodeWriter, ColorTarget, color::WriteColorCodes, impl_macros::color_type::impl_color_type,
5};
6
7use super::Color;
8
9/// An 8-bit color type representing colors in the 256-color ANSI palette.
10///
11/// These colors are also available from the method [`Color::indexed()`](super::Color::indexed):
12///
13/// ```
14/// use fluent_ansi::{prelude::*, color::IndexedColor};
15///
16/// assert_eq!(Color::indexed(127), IndexedColor(127));
17/// ```
18///
19/// See Wikipedia's article on [8-bit colors ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct IndexedColor(pub u8);
22
23impl IndexedColor {
24    /// Creates a new 8-bit color with the given color index (0-255).
25    #[must_use]
26    pub const fn new(index: u8) -> Self {
27        IndexedColor(index)
28    }
29
30    /// Returns the color index of this 8-bit color.
31    #[must_use]
32    pub const fn get_index(self) -> u8 {
33        self.0
34    }
35}
36
37impl_color_type!(IndexedColor {
38    args: [self];
39    to_color: { Color::Indexed(self) }
40});
41
42impl WriteColorCodes for IndexedColor {
43    fn write_color_codes(self, target: ColorTarget, writer: &mut CodeWriter) -> Result {
44        let target_code = match target {
45            ColorTarget::Foreground => 38,
46            ColorTarget::Background => 48,
47            ColorTarget::Underline => 58,
48        };
49
50        writer.write_code(target_code)?;
51        writer.write_code(5)?;
52        writer.write_code(self.0)?;
53        Ok(())
54    }
55}