Skip to content

Commit a32d197

Browse files
committed
Fix the 'field_offset!' macro on latest nightly
I believe the old version was actually undefined behavior :(
1 parent 96e66cd commit a32d197

File tree

2 files changed

+5
-7
lines changed

2 files changed

+5
-7
lines changed

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
const_fn_fn_ptr_basics, // We use PhantomData<fn() -> T>
1616
// Used for field_offset macro
1717
const_raw_ptr_deref,
18-
const_raw_ptr_to_usize_cast,
18+
const_maybe_uninit_as_ptr,
19+
const_ptr_offset_from,
1920
)]
2021
/*
2122
* This is required on recent nightly

src/macros.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,9 @@ macro_rules! define_extern_type {
1818
macro_rules! field_offset {
1919
($target:path, $($field:ident),+) => {
2020
unsafe {
21-
/*
22-
* I'm going to assume the dereference is safe,
23-
* because of the presense of '(*uninit.as_mut_ptr()).field'
24-
* in the documentation for std::ptr::addr_of_mut
25-
*/
26-
(std::ptr::addr_of!((*(1 as *mut $target))$(.$field)*) as usize) - 1
21+
let uninit = core::mem::MaybeUninit::<$target>::uninit();
22+
let base = uninit.as_ptr();
23+
(core::ptr::addr_of!((*base)$(.$field)*).cast::<u8>().offset_from(base as *const u8))
2724
}
2825
}
2926
}

0 commit comments

Comments
 (0)