Trait palette::cast::TryComponentsAs

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

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

Trait for trying to cast a reference to collection of color components into a reference to 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::TryComponentsAs, Srgb};

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

let colors: Result<&[Srgb<u8>], _> = array.try_components_as();
assert_eq!(colors, Ok(&[Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)][..]));

let colors: Result<&[Srgb<u8>], _> = slice.try_components_as();
assert_eq!(colors, Ok(&[Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)][..]));

let colors: Result<&[Srgb<u8>], _> = vec.try_components_as();
assert_eq!(colors, Ok(&[Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)][..]));

This produces an error:

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

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

Required Associated Types§

source

type Error

The error for when try_components_as fails to cast.

Required Methods§

source

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

Try to cast this collection of color components into a reference to 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.

Implementations on Foreign Types§

source§

impl<'a, T, C, const N: usize> TryComponentsAs<[C]> for [T]
where C: ArrayCast<Array = [T; N]>,

source§

impl<'a, T, C, const N: usize> TryComponentsAs<[C]> for Box<[T]>
where C: ArrayCast<Array = [T; N]>,

source§

impl<'a, T, C, const N: usize> TryComponentsAs<[C]> for Vec<T>
where C: ArrayCast<Array = [T; N]>,

source§

impl<'a, T, C, const N: usize, const M: usize> TryComponentsAs<[C]> for [T; M]
where C: ArrayCast<Array = [T; N]>,

Implementors§