rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Warn for mem::transmute of no repr(C) structs

Open leonardo-m opened this issue 1 year ago • 0 comments

What it does

Perhaps Clippy should warn in the helper2 function about doing a transmute on a struct that isn't repr(C), see code below

Advantage

No response

Drawbacks

No response

Example

#![allow(dead_code)]
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

use std::mem;

#[repr(C)]
struct Foo1 {
    a: u16,
    b: u32,
    c: u16,
}

fn helper1(data: [u8; size_of::<Foo1>()]) -> Foo1 {
    unsafe { mem::transmute(data) } // no warn
}

struct Foo2 {
    a: u16,
    b: u32,
    c: u16,
}

fn helper2(data: [u8; size_of::<Foo2>()]) -> Foo2 {
    unsafe { mem::transmute(data) } // warn here
}

fn main() {
    dbg!(size_of::<Foo1>()); // 12
    dbg!(size_of::<Foo2>()); // 8
}

leonardo-m avatar Oct 01 '24 11:10 leonardo-m