Add support for hex colors

This commit is contained in:
Barnabas 2020-12-29 16:19:46 +01:00 committed by Ferran Basora
parent b97519170b
commit 25d410497e
4 changed files with 31 additions and 0 deletions

1
Cargo.lock generated
View File

@ -164,6 +164,7 @@ version = "0.5.0"
dependencies = [
"base64",
"clap",
"lazy_static",
"regex",
"termion",
"unicode-width",

View File

@ -14,6 +14,7 @@ regex = "1.3.1"
clap = "2.33.0"
base64 = "0.11.0"
unicode-width = "0.1.7"
lazy_static = "1.4.0"
[[bin]]
name = "thumbs"

View File

@ -1,6 +1,19 @@
use regex::Regex;
use termion::color;
pub fn get_color(color_name: &str) -> Box<dyn color::Color> {
lazy_static! {
static ref RGB: Regex = Regex::new(r"#([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})").unwrap();
}
if let Some(captures) = RGB.captures(color_name) {
let r = u8::from_str_radix(captures.get(1).unwrap().as_str(), 16).unwrap();
let g = u8::from_str_radix(captures.get(2).unwrap().as_str(), 16).unwrap();
let b = u8::from_str_radix(captures.get(3).unwrap().as_str(), 16).unwrap();
return Box::new(color::Rgb(r, g, b));
}
match color_name {
"black" => Box::new(color::Black),
"red" => Box::new(color::Red),
@ -27,6 +40,20 @@ mod tests {
assert_eq!(text1, text2);
}
#[test]
fn parse_rgb() {
let text1 = println!("{}{}", color::Fg(&*get_color("#1b1cbf")), "foo");
let text2 = println!("{}{}", color::Fg(color::Rgb(27, 28, 191)), "foo");
assert_eq!(text1, text2);
}
#[test]
#[should_panic]
fn parse_invalid_rgb() {
println!("{}{}", color::Fg(&*get_color("#1b1cbj")), "foo");
}
#[test]
#[should_panic]
fn no_match_color() {

View File

@ -1,3 +1,5 @@
#[macro_use]
extern crate lazy_static;
extern crate base64;
extern crate clap;
extern crate termion;