From 0f6f359ac0e6c7b892ea3809a56385a1daeaf5a3 Mon Sep 17 00:00:00 2001 From: mitchmindtree Date: Sat, 13 Jul 2019 20:44:05 +0200 Subject: [PATCH] Add some missing `From` impls between Srgb and LinSrgb types I ran into an issue downstream when attempting to write a generic function that would accept any type of colour that may be converted to `Srgb`. I noticed implementations seemed to exist for all of the colour types I cared about apart from `LinSrgb`, so I thought I'd implement the missing conversions and open a PR! Let me know if there's a reason that these have been omitted that I'm overlooking, or if you have a better way in mind for adding these conversions! Unfortunately, conversions between entirely generic `Rgb` and `Rgb` are impossible due to the existing blanket `impl From for T`, but adding individual implementations for the RGB standards we care about doesn't seem so bad :) --- palette/src/rgb/mod.rs | 73 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/palette/src/rgb/mod.rs b/palette/src/rgb/mod.rs index 5fe5832f9..dd58d5e77 100644 --- a/palette/src/rgb/mod.rs +++ b/palette/src/rgb/mod.rs @@ -1,5 +1,6 @@ //!RGB types, spaces and standards. +use alpha::Alpha; use float::Float; use core::any::Any; @@ -70,3 +71,75 @@ pub trait Primaries: Any { ///Primary blue. fn blue() -> Yxy; } + +impl From> for Srgb +where + T: Component + Float, + U: Component, +{ + fn from(lin_srgb: LinSrgb) -> Self { + let non_lin = Srgb::::from_linear(lin_srgb); + non_lin.into_format() + } +} + +impl From> for LinSrgb +where + T: Component + Float, + U: Component, +{ + fn from(srgb: Srgb) -> Self { + srgb.into_linear() + .into_format() + } +} + +impl From> for Srgba +where + T: Component + Float, + U: Component, +{ + fn from(lin_srgb: LinSrgb) -> Self { + let color = lin_srgb.into(); + let alpha = U::max_intensity(); + Alpha { color, alpha } + } +} + +impl From> for Srgba +where + T: Component + Float, + U: Component, +{ + fn from(lin_srgba: LinSrgba) -> Self { + let (r, g, b, a) = lin_srgba.into(); + let color = LinSrgb::new(r, g, b).into(); + let alpha = a.convert(); + Alpha { color, alpha } + } +} + +impl From> for LinSrgba +where + T: Component + Float, + U: Component, +{ + fn from(srgb: Srgb) -> Self { + let color = srgb.into(); + let alpha = U::max_intensity(); + Alpha { color, alpha } + } +} + +impl From> for LinSrgba +where + T: Component + Float, + U: Component, +{ + fn from(srgba: Srgba) -> Self { + let (r, g, b, a) = srgba.into(); + let color = Srgb::new(r, g, b).into(); + let alpha = a.convert(); + Alpha { color, alpha } + } +}