Skip to main content

transmute_unchecked

Function transmute_unchecked 

Source
pub const unsafe fn transmute_unchecked<Src, Dst>(val: Src) -> Dst
Expand description

Transmute between two types.

Use this instead of core::mem::transmute when it is known that sizes are identical but this cannot be proven by the compiler.

This is equivalent to Rust’s transmute_unchecked intrinsics.

§Safety

All safety requirements of core::mem::transmute apply, plus that the size Src and Dst must match.

§Examples

This can be used when types are known to have the same size, but only at runtime.

fn to_u32<T: 'static>(v: T) -> Option<u32> {
    if TypeId::of::<T>() != TypeId::of::<u32>() {
        return None;
    }

    // `core::mem::transmute` won't work here.
    // SAFETY: We've checked that `T` is `u32`!
    Some(unsafe { kernel::mem::transmute_unchecked(v) })
}

to_u32(1u32);