]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/offset_from.rs
Merge pull request #2 from rust-lang/master
[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 #![feature(ptr_offset_from)]
6
7 struct Struct {
8     field: (),
9 }
10
11 #[repr(C)]
12 struct Struct2 {
13     data: u8,
14     field: u8,
15 }
16
17 pub const OFFSET: usize = {
18     let uninit = std::mem::MaybeUninit::<Struct>::uninit();
19     let base_ptr: *const Struct = &uninit as *const _ as *const Struct;
20     // The following statement is UB (taking the address of an uninitialized field).
21     // Const eval doesn't detect this right now, but it may stop compiling at some point
22     // in the future.
23     let field_ptr = unsafe { &(*base_ptr).field as *const () as *const u8 };
24     let offset = unsafe { field_ptr.offset_from(base_ptr as *const u8) };
25     offset as usize
26 };
27
28 pub const OFFSET_2: usize = {
29     let uninit = std::mem::MaybeUninit::<Struct2>::uninit();
30     let base_ptr: *const Struct2 = &uninit as *const _ as *const Struct2;
31     let field_ptr = unsafe { &(*base_ptr).field as *const u8 };
32     let offset = unsafe { field_ptr.offset_from(base_ptr as *const u8) };
33     offset as usize
34 };
35
36 pub const OVERFLOW: isize = {
37     let uninit = std::mem::MaybeUninit::<Struct2>::uninit();
38     let base_ptr: *const Struct2 = &uninit as *const _ as *const Struct2;
39     let field_ptr = unsafe { &(*base_ptr).field as *const u8 };
40     unsafe { (base_ptr as *const u8).offset_from(field_ptr) }
41 };
42
43 pub const OFFSET_EQUAL_INTS: isize = {
44     let ptr = 1 as *const u8;
45     unsafe { ptr.offset_from(ptr) }
46 };
47
48 fn main() {
49     assert_eq!(OFFSET, 0);
50     assert_eq!(OFFSET_2, 1);
51     assert_eq!(OVERFLOW, -1);
52     assert_eq!(OFFSET_EQUAL_INTS, 0);
53 }