Function constmuck::try_cast_slice_alt [−][src]
pub const fn try_cast_slice_alt<T, U>(
from: &[T],
_bounds: (IsPod<T>, IsPod<U>)
) -> Result<&[U], PodCastError>
Expand description
Tries to cast &[T]
to &[U]
Requires both T
and U
to implement Pod
.
Errors
This function returns errors in these cases:
-
The alignment of
T
is larger thanU
, returning aErr(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
.
(using this instead ofPodCastError::AlignmentMismatch
because that is not returned bybytemuck::try_cast_slice
) -
The size of
T
is not equal toU
, returning aErr(PodCastError::SizeMismatch)
.
Difference with bytemuck
This function requires T
to have an alignment larger or equal to U
,
while bytemuck::try_cast_slice
only requires the from
reference
to happen to be aligned to U
.
bytemuck::try_cast_slice
allows the size of T
to be different than U
if
it divides evenly into it, this function does not due to limitations in stable const fns.
Example
use constmuck::PodCastError;
use constmuck::{infer, try_cast_slice_alt};
type Res<T> = Result<T, PodCastError>;
const I8S: Res<&[i8]> = try_cast_slice_alt(&[100u8, 254, 255], infer!());
const ERR_SIZE : Res<&[u8]> = try_cast_slice_alt(&[0u16], infer!());
assert_eq!(I8S, Ok(&[100i8, -2, -1][..]));
assert_eq!(ERR_SIZE, Err(PodCastError::SizeMismatch));