From e5b88b834e376766f35b33aaeff437c098cc91b0 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Sat, 21 Dec 2024 15:56:24 -0500 Subject: [PATCH] Add `FromStr` for `DynamicColor` and static colors This makes it easier to parse them from a string with more concise code and not requiring a separate import of `parse_color`. --- CHANGELOG.md | 4 ++++ color/src/parse.rs | 42 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15a117d..09fd2f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ You can find its changes [documented below](#020-2024-12-17). This release has an [MSRV][] of 1.82. +### + +* Added `FromStr` impl for `AlphaColor`, `DynamicColor`, `OpaqueColor`, `PremulColor`. ([#111][] by [@waywardmonkeys][]) + ### Changed * Don't enable `serde`'s `std` feature when enabling our `std` feature. ([#108][] by @waywardmonkeys][]) diff --git a/color/src/parse.rs b/color/src/parse.rs index cc5a8d7..52e6cd3 100644 --- a/color/src/parse.rs +++ b/color/src/parse.rs @@ -9,7 +9,10 @@ use core::fmt; use core::str; use core::str::FromStr; -use crate::{AlphaColor, ColorSpaceTag, DynamicColor, Flags, Missing, Srgb}; +use crate::{ + AlphaColor, ColorSpace, ColorSpaceTag, DynamicColor, Flags, Missing, OpaqueColor, PremulColor, + Srgb, +}; // TODO: maybe include string offset /// Error type for parse errors. @@ -521,7 +524,6 @@ pub fn parse_color_prefix(s: &str) -> Result<(usize, DynamicColor), ParseError> } } -// Arguably this should be an implementation of FromStr. /// Parse a color string in CSS syntax into a color. /// /// This parses the entire string; trailing characters cause an @@ -543,6 +545,42 @@ pub fn parse_color(s: &str) -> Result { } } +impl FromStr for DynamicColor { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + parse_color(s) + } +} + +impl FromStr for AlphaColor { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + parse_color(s).map(DynamicColor::to_alpha_color) + } +} + +impl FromStr for OpaqueColor { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + parse_color(s) + .map(DynamicColor::to_alpha_color) + .map(AlphaColor::discard_alpha) + } +} + +impl FromStr for PremulColor { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + parse_color(s) + .map(DynamicColor::to_alpha_color) + .map(AlphaColor::premultiply) + } +} + /// Parse 4-bit color channels from a hex-encoded string. /// /// Returns the parsed channels and the byte offset to the remainder of the string (i.e., the