Skip to content

Commit

Permalink
Add FromStr for DynamicColor and static colors
Browse files Browse the repository at this point in the history
This makes it easier to parse them from a string with more concise
code and not requiring a separate import of `parse_color`.
  • Loading branch information
waywardmonkeys committed Dec 21, 2024
1 parent e203342 commit e5b88b8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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][])
Expand Down
42 changes: 40 additions & 2 deletions color/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -543,6 +545,42 @@ pub fn parse_color(s: &str) -> Result<DynamicColor, ParseError> {
}
}

impl FromStr for DynamicColor {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_color(s)
}
}

impl<CS: ColorSpace> FromStr for AlphaColor<CS> {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_color(s).map(DynamicColor::to_alpha_color)
}
}

impl<CS: ColorSpace> FromStr for OpaqueColor<CS> {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_color(s)
.map(DynamicColor::to_alpha_color)
.map(AlphaColor::discard_alpha)
}
}

impl<CS: ColorSpace> FromStr for PremulColor<CS> {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
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
Expand Down

0 comments on commit e5b88b8

Please # to comment.