Function constmuck::try_cast_ref_alt[][src]

pub const fn try_cast_ref_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 than U, returning a Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned).
    (using this instead of PodCastError::AlignmentMismatch because that is not returned by bytemuck::try_cast_ref)

  • The size of T is not equal to U, returning a Err(PodCastError::SizeMismatch).

Difference with bytemuck

This function requires T to have an alignment larger or equal to U, while bytemuck::try_cast_ref only requires the from reference to happen to be aligned to U.

Example

use constmuck::PodCastError;
use constmuck::{infer, try_cast_ref_alt};

const U8: Result<&[u8; 2], PodCastError> = try_cast_ref_alt(&100u16.to_le(), infer!());
const ERR_SIZE : Result<&u8, PodCastError> = try_cast_ref_alt(&100u16.to_le(), infer!());
const ERR_ALIGN: Result<&u16, PodCastError> = try_cast_ref_alt(&100u8, infer!());

assert_eq!(U8, Ok(&[100u8, 0]));
assert_eq!(ERR_SIZE, Err(PodCastError::SizeMismatch));
assert_eq!(ERR_ALIGN, Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned));