]> git.lizzy.rs Git - rust.git/blob - tests/ui/consts/offset_from.rs
Rollup merge of #106949 - compiler-errors:is-poly, r=BoxyUwU
[rust.git] / tests / ui / consts / offset_from.rs
1 // run-pass
2
3 #![feature(const_ptr_sub_ptr)]
4 #![feature(ptr_sub_ptr)]
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 pub const OFFSET_UNSIGNED: usize = {
48     let a = ['a', 'b', 'c'];
49     let ptr = a.as_ptr();
50     unsafe { ptr.add(2).sub_ptr(ptr) }
51 };
52
53 fn main() {
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);
59 }