pub fn get_ansi_from_name(short_name: &str) -> Option<String> {
match short_name {
"red" => Some("\x1B[31m".to_string()),
"green" => Some("\x1B[32m".to_string()),
"yellow" => Some("\x1B[33m".to_string()),
"blue" => Some("\x1B[34m".to_string()),
"magenta" => Some("\x1B[35m".to_string()),
"cyan" => Some("\x1B[36m".to_string()),
"white" => Some("\x1B[36m".to_string()),
_ => None,
}
}
pub fn get_ansi_bg_from_name(short_name: &str) -> Option<String> {
match short_name {
"red" => Some("\x1B[41m".to_string()),
"green" => Some("\x1B[42m".to_string()),
"yellow" => Some("\x1B[43m".to_string()),
"blue" => Some("\x1B[44m".to_string()),
"magenta" => Some("\x1B[45m".to_string()),
"cyan" => Some("\x1B[46m".to_string()),
"white" => Some("\x1B[47m".to_string()),
_ => None,
}
}
pub fn get_ansi_from_rgb(r: u8, g: u8, b: u8) -> String {
format!("\x1B[38;2;{};{};{}m", r, g, b)
}
pub trait ColorIn {
fn to_ansi(&self) -> Option<String>;
fn to_ansi_bg(&self) -> Option<String>;
}
impl ColorIn for &str {
fn to_ansi(&self) -> Option<String> {
get_ansi_from_name(self)
}
fn to_ansi_bg(&self) -> Option<String> {
get_ansi_bg_from_name(self)
}
}
impl ColorIn for (u8, u8, u8) {
fn to_ansi(&self) -> Option<String> {
let (r, g, b) = *self;
Some(format!("\x1B[38;2;{};{};{}m", r, g, b))
}
fn to_ansi_bg(&self) -> Option<String> {
let (r, g, b) = *self;
Some(format!("\x1B[48;2;{};{};{}", r, g, b))
}
}
impl ColorIn for u8 {
fn to_ansi(&self) -> Option<String> {
Some(format!("\x1B[38;5;{}m", self))
}
fn to_ansi_bg(&self) -> Option<String> {
Some(format!("\x1B[48;5;{}m", self))
}
}
pub fn reset() {
println!("\x1B[0m");
}
pub fn set_fg<C: ColorIn>(color: C, text: &str) -> String {
color
.to_ansi()
.map(|ansi_code| format!("{}{}\x1B[0m", ansi_code, text))
.unwrap_or_else(|| text.to_string())
}
pub fn set_bg<C: ColorIn>(color: C, text: &str) -> String {
color
.to_ansi_bg()
.map(|ansi_code| format!("{}{}\x1B[0m", ansi_code, text))
.unwrap_or_else(|| text.to_string())
}