]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/offset_from.rs
Stabilize File::options()
[rust.git] / src / test / ui / consts / offset_from.rs
1 // run-pass
2
3 #![feature(const_raw_ptr_deref)]
4 #![feature(const_ptr_offset_from)]
5
6 struct Struct {
7     field: (),
8 }
9
10 #[repr(C)]
11 struct Struct2 {
12     data: u8,
13     field: u8,
14 }
15
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
21     // in the future.
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) };
24     offset as usize
25 };
26
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) };
32     offset as usize
33 };
34
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) }
40 };
41
42 pub const OFFSET_EQUAL_INTS: isize = {
43     let ptr = 1 as *const u8;
44     unsafe { ptr.offset_from(ptr) }
45 };
46
47 fn main() {
48     assert_eq!(OFFSET, 0);
49     assert_eq!(OFFSET_2, 1);
50     assert_eq!(OVERFLOW, -1);
51     assert_eq!(OFFSET_EQUAL_INTS, 0);
52 }