[][src]Module rfc::core::convert::transmute

🌟 Bit-preserving conversions.

Transmutation is the act of reinterpreting the bytes corresponding to a value of one type as if they corresponded to a different type. A transmutation of a Src to a Dst type is similar to defining a union with two variants:

#![feature(untagged_unions)]
union Transmute<Src, Dst> {
    src: ManuallyDrop<Src>,
    dst: ManuallyDrop<Dst>,
}

And instantiating that union with its src variant, then reading dst back out. The TransmuteFrom and TransmuteInto traits are implemented automatically for all Src and Dst types where it is sound, safe, and stable to do this conversion:

For more information on these concepts see here.

Example

Given:

use core::convert::transmute::{
    TransmuteInto,
    stability::{PromiseTransmutableInto, PromiseTransmutableFrom},
};

#[derive(PromiseTransmutableInto, PromiseTransmutableFrom)]
#[repr(C)]
pub struct Foo(pub u8, pub u16);
//                    ^ there's a padding byte here, between these fields

This transmutation accepted:

let _ : Foo = 64u32.transmute_into(); // Alchemy Achieved!
//                  ^^^^^^^^^^^^^^ provided by the `TransmuteInto` trait

But this transmutation is rejected:

This example deliberately fails to compile
let _ : u32 = Foo(16, 12).transmute_into();
// error[E0277]: the trait bound `u32: TransmuteFrom<Foo, _>` is not satisfied
//   --> src/demo.rs:15:27
//    |
// 15 | let _ : u32 = Foo(16, 12).transmute_into();
//    |                           ^^^^^^^^^^^^^^ the trait `TransmuteFrom<foo::Foo, _>` is not implemented for `u32`
//    |
//   = note: required because of the requirements on the impl of `TransmuteInto<u32, _>` for `foo::Foo`

Modules

options

Static checks that may be neglected when determining if two types are transmutable.

stability

Traits for declaring the SemVer stability of a type's layout.

Traits

TransmuteFrom

Reinterpret the bits of Src as a type Self.

TransmuteInto

Reinterpret the bits of Self as a type Dst.

Functions

safe_transmute

Reinterprets the bits of a value of one type as another type, safely.

unsafe_transmute

Reinterprets the bits of a value of one type as another type, potentially unsafely.