fluent_ansi/colors/
rgb.rs

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