rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

Add unsafe trait Transmutable

Open 0xIO32 opened this issue 8 months ago • 4 comments

Add an unsafe trait Transmutable.

If this trait is implemented for a type, it can automatically transmuted into another specified type. For example:

struct Data {
  field1: u32,
  field2: u32,
}

unsafe impl Transmutable for Data {
  type Into = [u8; size_of::<Data>()];
}

fn main() {
  let data: Data = Data {
    field1: 8,
    field2: 9,
  };
  test(&data);
}

fn test(bytes: &[u8]) {
  
}

In this example, the reference "&Data" will automatically be transmuted to &[u8]. This should also work with passing ownership.

Maybe later add a way to implement this trait without unsafe, where the compiler ensures that this is unable to cause undefined behaviour.

0xIO32 avatar Apr 24 '25 20:04 0xIO32