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