gamozolabs / safecast

Safe casting in Rust!
MIT License
7 stars 5 forks source link

There's a trick to do the padding check at compile time #2

Open trishume opened 4 years ago

trishume commented 4 years ago

I found this trick in the implementation of fuchsia's zerocopy library and thought you might be interested in the fact it would let you get rid of the runtime safecast check:

const HAS_PADDING: bool = core::mem::size_of::<#type_ident>() != #(core::mem::size_of::<#field_types>())+*;
let _: [(); 1/(1 - HAS_PADDING as usize)];

Basically you do the same sum of the size of struct fields as you do, but then you can do the comparison to the size of the full struct at compile time and put it in a const, then you can declare an array type that will divide by zero if the boolean is true.

gamozolabs commented 2 years ago

Oh my! I didn't see this until now, this is brilliant! I'm probably gonna make a new library pretty soon here as I need a new safecast that's a bit more up to date with my current style!