Macro transmute_ref
macro_rules! transmute_ref {
($e:expr) => { ... };
}
Safely transmutes a mutable or immutable reference of one type to an immutable reference of another type of the same size and compatible alignment.
This macro behaves like an invocation of this function:
fn transmute_ref<'src, 'dst, Src, Dst>(src: &'src Src) -> &'dst Dst
where
'src: 'dst,
Src: IntoBytes + Immutable + ?Sized,
Dst: FromBytes + Immutable + ?Sized,
align_of::<Src>() >= align_of::<Dst>(),
size_compatible::<Src, Dst>(),
{
# /*
...
# */
}
The types Src and Dst are inferred from the calling context; they cannot
be explicitly specified in the macro invocation.
Size compatibility
transmute_ref! supports transmuting between Sized types or between
unsized (i.e., ?Sized) types. It supports any transmutation that preserves
the number of bytes of the referent, even if doing so requires updating the
metadata stored in an unsized "fat" reference:
# use transmute_ref;
# use size_of_val; // Not in the prelude on our MSRV
let src: & = &;
let dst: & = transmute_ref!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Errors
Violations of the alignment and size compatibility checks are detected after the compiler performs monomorphization. This has two important consequences.
First, it means that generic code will never fail these conditions:
# use ;
Instead, failures will only be detected once generic code is instantiated with concrete types:
# use zerocopy::{transmute_ref, FromBytes, IntoBytes, Immutable};
#
# fn transmute_ref<Src, Dst>(src: &Src) -> &Dst
# where
# Src: IntoBytes + Immutable,
# Dst: FromBytes + Immutable,
# {
# transmute_ref!(src)
# }
let src: &u16 = &0;
let dst: &u8 = transmute_ref(src);
Second, the fact that violations are detected after monomorphization means
that cargo check will usually not detect errors, even when types are
concrete. Instead, cargo build must be used to detect such errors.
Examples
Transmuting between Sized types:
# use transmute_ref;
let one_dimensional: = ;
let two_dimensional: & = transmute_ref!;
assert_eq!;
Transmuting between unsized types:
# use ;
# type u16 = U16;
# type u32 = U32;
type Src = ;
type Dst = ;
let src = ref_from_bytes.unwrap;
let dst: &Dst = transmute_ref!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Use in const contexts
This macro can be invoked in const contexts only when Src: Sized and
Dst: Sized.