Trait cosmic::cosmic_theme::palette::cast::TryComponentsInto

source ·
pub trait TryComponentsInto<C>: Sized {
    type Error;

    // Required method
    fn try_components_into(self) -> Result<C, Self::Error>;
}
Expand description

Trait for trying to cast a collection of color components from a collection of colors without copying.

This trait is meant as a more convenient alternative to the free functions in cast, to allow method chaining among other things.

§Errors

The cast will return an error if the cast fails, such as when the length of the input is not a multiple of the color’s array length.

§Examples

use palette::{cast::TryComponentsInto, Srgb};

let array: [_; 6] = [64, 139, 10, 93, 18, 214];
let slice: &[_] = &[64, 139, 10, 93, 18, 214];
let slice_mut: &mut [_] = &mut [64, 139, 10, 93, 18, 214];
let vec: Vec<_> = vec![64, 139, 10, 93, 18, 214];

assert_eq!(
    array.try_components_into(),
    Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)])
);

assert_eq!(
    slice.try_components_into(),
    Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_ref())
);

assert_eq!(
    slice_mut.try_components_into(),
    Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_mut())
);

assert_eq!(
    vec.try_components_into(),
    Ok(vec![Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)])
);

Owning types can be cast as slices, too:

use palette::{cast::TryComponentsInto, Srgb};

let array: [_; 6] = [64, 139, 10, 93, 18, 214];
let mut vec: Vec<_> = vec![64, 139, 10, 93, 18, 214];

assert_eq!(
    (&array).try_components_into(),
    Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_ref())
);

assert_eq!(
    (&mut vec).try_components_into(),
    Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_mut())
);

This produces an error:

use palette::{cast::TryComponentsInto, Srgb};

let components = &[64, 139, 10, 93, 18]; // Not a multiple of 3
let colors: Result<&[Srgb<u8>], _> = components.try_components_into();
assert!(colors.is_err());

Required Associated Types§

source

type Error

The error for when try_into_colors fails to cast.

Required Methods§

source

fn try_components_into(self) -> Result<C, Self::Error>

Try to cast this collection of color components into a collection of colors.

Return an error if the conversion can’t be done, such as when the number of items in self isn’t a multiple of the number of components in the color type.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,