Requre a type implementing a trait be repr(packed)

Viewed 153

For some OpenGL code, I created a trait Vertex. currently it looks like this

trait Vertex: Sized + Clone {
//...
}

Because of the way Vertex's are used in my program, its very important that anything is a vertex uses the packed representation. If there is any padding it could potentially create problems. Is there any way I can constrain the Vertex trait to only types that use the packed representation? If need be, I could just define my own marker trait that I manually implement for everything that implements Vertex. It seems like something the compiler could easily surface and enforce properly, but I haven't been able to find any kind of representation trait. Thanks

1 Answers

This question gave me the impetus to finish a project I had lying around to do exactly this.

I just pushed it to crates.io. I've been using it for some similar work (dealing with some strange FFI's), but never published it.

It lets you write this code:

use repr_trait::Packed;

// Safety: Only safe to call when T has #[repr(packed)]
unsafe fn safe_when_packed<T>(_param: T) {
    unimplemented!()
}

fn safe_wrapper<T: Packed>(param: T) {
    // Safety: Safe because T is guaranteed to be #[repr(packed)]
    unsafe {
        safe_when_packed(param)
    }
}

#[derive(Packed, Default)]
#[repr(packed)]
struct PackedData(u32, u8);

safe_wrapper(PackedData(123, 45));

But this is a compile error:

#[derive(Packed)]
struct NotPacked(u32, u8);

You would write your vertex trait as:

trait Vertex: Sized + Clone + Packed {
//...
}
Related