Trait cosmic::cosmic_theme::palette::convert::FromColorMut
source · pub trait FromColorMut<T>where
T: FromColorMut<Self> + ?Sized,{
// Required method
fn from_color_mut(color: &mut T) -> FromColorMutGuard<'_, Self, T>;
}
Expand description
Temporarily convert colors in place.
It allows colors to be converted without using more additional memory than what is necessary for the conversion, itself. The conversion will however have to be reverted at some point, since the memory space is borrowed and has to be restored to its original format. This is enforced by a scope guard that does the opposite conversion when it’s dropped.
See also IntoColorMut
and FromColorUnclampedMut
.
use palette::{FromColorMut, ShiftHueAssign, Srgb, Hsv};
let mut rgb = [
Srgb::new(1.0, 0.0, 0.0),
Srgb::new(0.0, 1.0, 0.0),
Srgb::new(0.0, 0.0, 1.0),
];
{
let mut hsv = <[Hsv]>::from_color_mut(&mut rgb);
// All of the colors in `rgb` have been converted to `Hsv`:
assert_eq!(
*hsv,
[
Hsv::new(0.0, 1.0, 1.0),
Hsv::new(120.0, 1.0, 1.0),
Hsv::new(240.0, 1.0, 1.0),
]
);
hsv.shift_hue_assign(60.0);
} // The guard is dropped here and the colors are restored to `Srgb`.
// Notice how the colors in `rgb` have changed:
assert_eq!(
rgb,
[
Srgb::new(1.0, 1.0, 0.0),
Srgb::new(0.0, 1.0, 1.0),
Srgb::new(1.0, 0.0, 1.0),
]
);
The scope guard, FromColorMutGuard
, has a few extra methods that can
make multiple conversion steps more efficient. One of those is
FromColorMutGuard::then_into_color_mut
, which works like
IntoColorMut::into_color_mut
, but does not add an extra step when
restoring to the original color type. This example will convert Srgb → Hsv → Hsl → Srgb
instead of Srgb → Hsv → Hsl → Hsv → Srgb
:
use palette::{FromColorMut, ShiftHueAssign, LightenAssign, Srgb, Hsv, Hsl};
let mut rgb = [
Srgb::new(1.0, 0.0, 0.0),
Srgb::new(0.0, 1.0, 0.0),
Srgb::new(0.0, 0.0, 1.0),
];
{
let mut hsv = <[Hsv]>::from_color_mut(&mut rgb);
hsv.shift_hue_assign(60.0);
let mut hsl = hsv.then_into_color_mut::<[Hsl]>();
hsl.lighten_assign(0.5);
} // `then_into_color_mut` makes the guard restore directly to `Srgb` here.
// Notice how the colors in `rgb` have changed:
assert_eq!(
rgb,
[
Srgb::new(1.0, 1.0, 0.5),
Srgb::new(0.5, 1.0, 1.0),
Srgb::new(1.0, 0.5, 1.0),
]
);
§Note
The reused memory space could end up with unexpected values if the
conversion panics or if the scope guard’s drop
function doesn’t run. The
default implementations of FromColorMut
uses ArrayCast
, which is only
implemented for color types that can safely accept and recover from any
value. Other color types will have to provide their own implementations that
can handle this case.
Required Methods§
sourcefn from_color_mut(color: &mut T) -> FromColorMutGuard<'_, Self, T>
fn from_color_mut(color: &mut T) -> FromColorMutGuard<'_, Self, T>
Temporarily convert from another color type in place.
This reuses the memory space, and the returned scope guard will restore the converted colors to their original type when it’s dropped.