From 2345d80d803e0e9590681a49743491c477d28126 Mon Sep 17 00:00:00 2001 From: Joscha Date: Sun, 1 Dec 2024 22:25:33 +0100 Subject: [PATCH] Specify palette colors in hexadecimal rbg --- mark-bin/src/main.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/mark-bin/src/main.rs b/mark-bin/src/main.rs index f6ce4f1..359c32b 100644 --- a/mark-bin/src/main.rs +++ b/mark-bin/src/main.rs @@ -103,14 +103,14 @@ struct SrgbColor(Srgb); #[derive(Debug)] enum ParseSrgbColorError { - ThreeValuesRequired, + MustBeSixHexDigits, ParseIntError(ParseIntError), } impl fmt::Display for ParseSrgbColorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ThreeValuesRequired => write!(f, "exactly three values must be specified"), + Self::MustBeSixHexDigits => write!(f, "a color must consist of six hexadecimal digits"), Self::ParseIntError(e) => e.fmt(f), } } @@ -128,12 +128,16 @@ impl FromStr for SrgbColor { type Err = ParseSrgbColorError; fn from_str(s: &str) -> Result { - let parts = s.split(',').collect::>(); - if let [r, g, b] = &*parts { - Ok(Self(Srgb::new(r.parse()?, g.parse()?, b.parse()?))) - } else { - Err(ParseSrgbColorError::ThreeValuesRequired) + if s.len() != 6 { + return Err(ParseSrgbColorError::MustBeSixHexDigits); } + if !s.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(ParseSrgbColorError::MustBeSixHexDigits); + } + let r = u8::from_str_radix(&s[0..2], 16)?; + let g = u8::from_str_radix(&s[2..4], 16)?; + let b = u8::from_str_radix(&s[4..6], 16)?; + Ok(Self(Srgb::new(r, g, b))) } } @@ -146,6 +150,7 @@ struct DitherCmd { color_space: DitherColorSpace, #[arg(long, short)] difference: DitherDifference, + /// Add a hex color to the palette used for dithering. #[arg(long, short)] palette: Vec, }