3 #![feature(const_ptr_sub_ptr)]
4 #![feature(ptr_sub_ptr)]
16 pub const OFFSET
: usize = {
17 let uninit
= std
::mem
::MaybeUninit
::<Struct
>::uninit();
18 let base_ptr
: *const Struct
= &uninit
as *const _
as *const Struct
;
19 // The following statement is UB (taking the address of an uninitialized field).
20 // Const eval doesn't detect this right now, but it may stop compiling at some point
22 let field_ptr
= unsafe { &(*base_ptr).field as *const () as *const u8 }
;
23 let offset
= unsafe { field_ptr.offset_from(base_ptr as *const u8) }
;
27 pub const OFFSET_2
: usize = {
28 let uninit
= std
::mem
::MaybeUninit
::<Struct2
>::uninit();
29 let base_ptr
: *const Struct2
= &uninit
as *const _
as *const Struct2
;
30 let field_ptr
= unsafe { &(*base_ptr).field as *const u8 }
;
31 let offset
= unsafe { field_ptr.offset_from(base_ptr as *const u8) }
;
35 pub const OVERFLOW
: isize = {
36 let uninit
= std
::mem
::MaybeUninit
::<Struct2
>::uninit();
37 let base_ptr
: *const Struct2
= &uninit
as *const _
as *const Struct2
;
38 let field_ptr
= unsafe { &(*base_ptr).field as *const u8 }
;
39 unsafe { (base_ptr as *const u8).offset_from(field_ptr) }
42 pub const OFFSET_EQUAL_INTS
: isize = {
43 let ptr
= 1 as *const u8;
44 unsafe { ptr.offset_from(ptr) }
47 pub const OFFSET_UNSIGNED
: usize = {
48 let a
= ['a'
, 'b'
, 'c'
];
50 unsafe { ptr.add(2).sub_ptr(ptr) }
54 assert_eq
!(OFFSET
, 0);
55 assert_eq
!(OFFSET_2
, 1);
56 assert_eq
!(OVERFLOW
, -1);
57 assert_eq
!(OFFSET_EQUAL_INTS
, 0);
58 assert_eq
!(OFFSET_UNSIGNED
, 2);