Skip to content

Commit

Permalink
Add some missing From impls between Srgb and LinSrgb types
Browse files Browse the repository at this point in the history
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<T>`. I noticed implementations seemed to exist for all of the
colour types I cared about apart from `LinSrgb<T>`, 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<S, T>` and `Rgb<St, U>` are impossible due to the existing blanket
`impl From<T> for T`, but adding individual implementations for the RGB
standards we care about doesn't seem so bad :)
  • Loading branch information
mitchmindtree committed Jul 13, 2019
1 parent 483b57a commit 0f6f359
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions palette/src/rgb/mod.rs
@@ -1,5 +1,6 @@
//!RGB types, spaces and standards.

use alpha::Alpha;
use float::Float;
use core::any::Any;

Expand Down Expand Up @@ -70,3 +71,75 @@ pub trait Primaries: Any {
///Primary blue.
fn blue<Wp: WhitePoint, T: Component + Float>() -> Yxy<Wp, T>;
}

impl<T, U> From<LinSrgb<T>> for Srgb<U>
where
T: Component + Float,
U: Component,
{
fn from(lin_srgb: LinSrgb<T>) -> Self {
let non_lin = Srgb::<T>::from_linear(lin_srgb);
non_lin.into_format()
}
}

impl<T, U> From<Srgb<T>> for LinSrgb<U>
where
T: Component + Float,
U: Component,
{
fn from(srgb: Srgb<T>) -> Self {
srgb.into_linear()
.into_format()
}
}

impl<T, U> From<LinSrgb<T>> for Srgba<U>
where
T: Component + Float,
U: Component,
{
fn from(lin_srgb: LinSrgb<T>) -> Self {
let color = lin_srgb.into();
let alpha = U::max_intensity();
Alpha { color, alpha }
}
}

impl<T, U> From<LinSrgba<T>> for Srgba<U>
where
T: Component + Float,
U: Component,
{
fn from(lin_srgba: LinSrgba<T>) -> 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<T, U> From<Srgb<T>> for LinSrgba<U>
where
T: Component + Float,
U: Component,
{
fn from(srgb: Srgb<T>) -> Self {
let color = srgb.into();
let alpha = U::max_intensity();
Alpha { color, alpha }
}
}

impl<T, U> From<Srgba<T>> for LinSrgba<U>
where
T: Component + Float,
U: Component,
{
fn from(srgba: Srgba<T>) -> Self {
let (r, g, b, a) = srgba.into();
let color = Srgb::new(r, g, b).into();
let alpha = a.convert();
Alpha { color, alpha }
}
}

0 comments on commit 0f6f359

Please sign in to comment.