pub trait TryFromComponents<C>: Sized {
type Error;
// Required method
fn try_from_components(components: C) -> Result<Self, Self::Error>;
}
Expand description
Trait for trying to cast a collection of colors from a collection of color components 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::TryFromComponents, 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!(
<[Srgb<u8>; 2]>::try_from_components(array),
Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)])
);
assert_eq!(
<&[Srgb<u8>]>::try_from_components(slice),
Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_ref())
);
assert_eq!(
<&mut [Srgb<u8>]>::try_from_components(slice_mut),
Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_mut())
);
assert_eq!(
Vec::<Srgb<u8>>::try_from_components(vec),
Ok(vec![Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)])
);
Owning types can be cast as slices, too:
use palette::{cast::TryFromComponents, Srgb};
let array: [_; 6] = [64, 139, 10, 93, 18, 214];
let mut vec: Vec<_> = vec![64, 139, 10, 93, 18, 214];
assert_eq!(
<&[Srgb<u8>]>::try_from_components(&array),
Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_ref())
);
assert_eq!(
<&mut [Srgb<u8>]>::try_from_components(&mut vec),
Ok([Srgb::new(64u8, 139, 10), Srgb::new(93, 18, 214)].as_mut())
);
This produces an error:
use palette::{cast::TryFromComponents, Srgb};
let components = &[64, 139, 10, 93, 18]; // Not a multiple of 3
assert!(<&[Srgb<u8>]>::try_from_components(components).is_err());
Required Associated Types§
Required Methods§
Sourcefn try_from_components(components: C) -> Result<Self, Self::Error>
fn try_from_components(components: C) -> Result<Self, Self::Error>
Try to cast a collection of color components into an collection of colors.
Return an error if the conversion can’t be done, such as when the number
of items in components
isn’t a multiple of the number of components in
the color type.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.