zerocopy

Macro try_transmute

Source
macro_rules! try_transmute {
    ($e:expr) => { ... };
}
Expand description

Conditionally transmutes a value of one type to a value of another type of the same size.

This macro behaves like an invocation of this function:

fn try_transmute<Src, Dst>(src: Src) -> Result<Dst, ValidityError<Src, Dst>>
where
    Src: IntoBytes,
    Dst: TryFromBytes,
    size_of::<Src>() == size_of::<Dst>(),
{
    ...
}

However, unlike a function, this macro can only be invoked when the types of Src and Dst are completely concrete. The types Src and Dst are inferred from the calling context; they cannot be explicitly specified in the macro invocation.

Note that the Src produced by the expression $e will not be dropped. Semantically, its bits will be copied into a new value of type Dst, the original Src will be forgotten, and the value of type Dst will be returned.

§Examples

// 0u8 → bool = false
assert_eq!(try_transmute!(0u8), Ok(false));

// 1u8 → bool = true
 assert_eq!(try_transmute!(1u8), Ok(true));

// 2u8 → bool = error
assert!(matches!(
    try_transmute!(2u8),
    Result::<bool, _>::Err(ValidityError { .. })
));