Skip to content

Instantly share code, notes, and snippets.

@Amanieu
Created June 23, 2016 14:30
Show Gist options
  • Save Amanieu/d110296f1775725fab75201f51da390f to your computer and use it in GitHub Desktop.
Save Amanieu/d110296f1775725fab75201f51da390f to your computer and use it in GitHub Desktop.
#[macro_export]
macro_rules! offset_of_unsafe {
($container:path, $field:ident) => {{
// Make sure the field actually exists. This line ensures that a
// compile-time error is generated if $field is accessed through a
// Deref impl.
let $container { $field : _, .. };
// Create an instance of the container and calculate the offset to its
// field. Although we are creating references to uninitialized data this
// is fine since we are not dereferencing them.
let val: $container = $crate::__core::mem::uninitialized();
let result = &val.$field as *const _ as isize - &val as *const _ as isize;
$crate::__core::mem::forget(val);
result
}};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment