use core::fmt::Result;
use crate::{CodeWriter, ColorTarget, color::WriteColorCodes};
pub type RGB = RGBColor;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RGBColor {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl RGBColor {
#[must_use]
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
}
impl WriteColorCodes for RGBColor {
fn write_color_codes(self, target: ColorTarget, writer: &mut CodeWriter) -> Result {
let target_code = match target {
ColorTarget::Foreground => 38,
ColorTarget::Background => 48,
ColorTarget::Underline => 58,
};
writer.write_code(target_code)?;
writer.write_code(2)?;
writer.write_code(self.r)?;
writer.write_code(self.g)?;
writer.write_code(self.b)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::{
AppliedTo as _, Style, ToStyle as _, ToStyleSet as _, test_color_kind_methods,
test_to_style_set_methods_with_foreground_assumed,
};
use super::*;
test_color_kind_methods!(
RGBColor::new(0, 128, 255),
Color::RGB(RGBColor::new(0, 128, 255))
);
test_to_style_set_methods_with_foreground_assumed!(RGBColor::new(0, 128, 255));
#[test]
fn rgb() {
let color_1 = RGBColor {
r: 0,
g: 128,
b: 255,
};
assert_eq!(color_1.r, 0u8);
assert_eq!(color_1.g, 128u8);
assert_eq!(color_1.b, 255u8);
let color_2 = RGBColor::new(0, 128, 255);
assert_eq!(color_2.r, 0u8);
assert_eq!(color_2.g, 128u8);
assert_eq!(color_2.b, 255u8);
assert_eq!(color_1, color_2);
}
#[test]
fn applied_to() {
let stld = RGBColor::new(0, 128, 255).applied_to("CONTENT");
assert_eq!(stld.get_content(), &"CONTENT");
assert_eq!(
stld.get_style(),
Style::new().fg(RGBColor::new(0, 128, 255))
);
}
#[test]
fn to_style() {
assert_eq!(
RGBColor::new(0, 128, 255).to_style(),
Style::new().fg(RGBColor::new(0, 128, 255))
);
}
}