From 25d410497e9ba8571a5502162de8c1a2fee049cb Mon Sep 17 00:00:00 2001 From: Barnabas Date: Tue, 29 Dec 2020 16:19:46 +0100 Subject: [PATCH] Add support for hex colors --- Cargo.lock | 1 + Cargo.toml | 1 + src/colors.rs | 27 +++++++++++++++++++++++++++ src/main.rs | 2 ++ 4 files changed, 31 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 3ba2277..7ce2aaf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -164,6 +164,7 @@ version = "0.5.0" dependencies = [ "base64", "clap", + "lazy_static", "regex", "termion", "unicode-width", diff --git a/Cargo.toml b/Cargo.toml index 37b8475..ade08d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/colors.rs b/src/colors.rs index 3ee0364..1801278 100644 --- a/src/colors.rs +++ b/src/colors.rs @@ -1,6 +1,19 @@ +use regex::Regex; use termion::color; pub fn get_color(color_name: &str) -> Box { + 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() { diff --git a/src/main.rs b/src/main.rs index db89864..a810286 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +#[macro_use] +extern crate lazy_static; extern crate base64; extern crate clap; extern crate termion;