Feature: Support parsing `TrueColor` from RGB string
dhruvkb opened this issue · comments
Problem
Currently the from_str
function supports parsing color names to Color
enum based on the names. But this function does not parse TrueColor
.
https://github.com/mackwic/colored/blob/11ffd20e7b5d1b48e4de7bb78ced26131ae5e114/src/color.rs#L88
Expectation
Given a string like rgb(<u8>,<u8>,<u8>)
, from_str
should support parsing it to a Color::TrueColor
instance.
Suggestion
In a project of mine, I've used a regex check to determine if the string matches the specific pattern and converts it to Color::TrueColor
. A refined version of this could be added in the crate to be supported out-of-the-box.
let true_color = Regex::new(r"(?x)^
(?:bg:)?
rgb\(
(?P<red>\d{1,3}),\s?
(?P<green>\d{1,3}),\s?
(?P<blue>\d{1,3})
\)
$").unwrap();
let mut color: Option<Color> = None;
if let Some(caps) = true_color.captures(style) { // RGB colors
let channels: Vec<u8> = vec!["red", "green", "blue"]
.into_iter()
.map(|x| caps[x].parse().expect("Must be int between 0 and 255."))
.collect();
color = Some(Color::TrueColor { r: channels[0], g: channels[1], b: channels[2] });
}
It kind of looks like you're parsing a CSS color format into a Color
instance. IMO it might be better for some sort of Color::from_str
implementation to support all CSS color formats, so rgb(0, 0, 0)
, #000000
, and black
would all parse to Color::TrueColor{ r: 0, g: 0, b: 0 }
.
BTW there are crates that handle the bulk of the work, like cssparser
and css-color
from a quick search, if this is reasonable. Maybe locked behind a feature called parsing
or something?