]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/offset_from.rs
Auto merge of #99028 - tmiasko:inline, r=estebank
[rust.git] / src / test / ui / consts / offset_from.rs
1 // run-pass
2
3 #![feature(const_ptr_offset_from)]
4 #![feature(const_ptr_sub_ptr)]
5 #![feature(ptr_sub_ptr)]
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 pub const OFFSET_UNSIGNED: usize = {
49     let a = ['a', 'b', 'c'];
50     let ptr = a.as_ptr();
51     unsafe { ptr.add(2).sub_ptr(ptr) }
52 };
53
54 fn main() {
55     assert_eq!(OFFSET, 0);
56     assert_eq!(OFFSET_2, 1);
57     assert_eq!(OVERFLOW, -1);
58     assert_eq!(OFFSET_EQUAL_INTS, 0);
59     assert_eq!(OFFSET_UNSIGNED, 2);
60 }