Skip to content

Instantly share code, notes, and snippets.

@jeffs

jeffs/main.rs Secret

Last active July 26, 2021 17:14
Show Gist options
  • Save jeffs/2e55c2f5ad98201ef4fbc711f486a83c to your computer and use it in GitHub Desktop.
Save jeffs/2e55c2f5ad98201ef4fbc711f486a83c to your computer and use it in GitHub Desktop.
nested-type-alignment-rs
struct RustStruct {
a: u16, // 2 bytes
b: u32, // 4 bytes
c: u16, // 2 bytes
d: u32, // 4 bytes
}
fn address<T>(r: &T) -> isize {
r as *const _ as isize
}
fn main() {
let object = RustStruct { a: 0, b: 0, c: 0, d: 0 };
let offset = |p| p - address(&object);
println!("Rust struct:\n");
println!(" offset of a: {:2} bytes", offset(address(&object.a)));
println!(" offset of b: {:2} bytes", offset(address(&object.b)));
println!(" offset of c: {:2} bytes", offset(address(&object.c)));
println!(" offset of d: {:2} bytes", offset(address(&object.d)));
println!(" total size: {:2} bytes", std::mem::size_of::<RustStruct>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment