From 9864b35da32d3377a2bb76ac48c9e1e803abf8d7 Mon Sep 17 00:00:00 2001 From: Asthowen Date: Tue, 14 Jan 2025 18:54:27 +0100 Subject: [PATCH] Add support for arbitrary ANSI color --- CHANGELOG.md | 1 + src/color.rs | 4 ++++ src/lib.rs | 14 ++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 577c8b2..63faf81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ # Unreleased +- Added methods `ansi_color` and `on_ansi_color` to `Colorize`. # 3.0.0 - **[BREAKING CHANGE]:** Upgrade MSRV to 1.80 and remove the then unnecessary lazy_static dependency. diff --git a/src/color.rs b/src/color.rs index 3406ad0..0c411e8 100644 --- a/src/color.rs +++ b/src/color.rs @@ -21,6 +21,7 @@ pub enum Color { BrightCyan, BrightWhite, TrueColor { r: u8, g: u8, b: u8 }, + AnsiColor(u8), } fn truecolor_support() -> bool { @@ -56,6 +57,7 @@ impl Color { self.closest_color_euclidean().to_fg_str() } Color::TrueColor { r, g, b } => format!("38;2;{};{};{}", r, g, b).into(), + Color::AnsiColor(code) => format!("38;5;{}", code).into(), } } @@ -81,6 +83,7 @@ impl Color { self.closest_color_euclidean().to_bg_str() } Color::TrueColor { r, g, b } => format!("48;2;{};{};{}", r, g, b).into(), + Color::AnsiColor(code) => format!("48;5;{}", code).into(), } } @@ -195,6 +198,7 @@ impl Color { b: 255, }, TrueColor { r, g, b } => TrueColor { r, g, b }, + AnsiColor(color) => AnsiColor(color), } } } diff --git a/src/lib.rs b/src/lib.rs index 4c5aab1..f672f02 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -268,6 +268,13 @@ pub trait Colorize { b: color.b, }) } + fn ansi_color(self, color: T) -> ColoredString + where + Self: Sized, + T: Into, + { + self.color(Color::AnsiColor(color.into())) + } fn color>(self, color: S) -> ColoredString; // Background Colors fn on_black(self) -> ColoredString @@ -397,6 +404,13 @@ pub trait Colorize { b: color.b, }) } + fn on_ansi_color(self, color: T) -> ColoredString + where + Self: Sized, + T: Into, + { + self.on_color(Color::AnsiColor(color.into())) + } fn on_color>(self, color: S) -> ColoredString; // Styles fn clear(self) -> ColoredString;