]> git.lizzy.rs Git - rust.git/blob - tests/ui/lint/unaligned_references.rs
make unaligned_reference a hard error
[rust.git] / tests / ui / lint / unaligned_references.rs
1 #[repr(packed)]
2 pub struct Good {
3     data: u64,
4     ptr: &'static u64,
5     data2: [u64; 2],
6     aligned: [u8; 32],
7 }
8
9 #[repr(packed(2))]
10 pub struct Packed2 {
11     x: u32,
12     y: u16,
13     z: u8,
14 }
15
16 fn main() {
17     unsafe {
18         let good = Good { data: 0, ptr: &0, data2: [0, 0], aligned: [0; 32] };
19
20         let _ = &good.ptr; //~ ERROR reference to packed field
21         let _ = &good.data; //~ ERROR reference to packed field
22         // Error even when turned into raw pointer immediately.
23         let _ = &good.data as *const _; //~ ERROR reference to packed field
24         let _: *const _ = &good.data; //~ ERROR reference to packed field
25         // Error on method call.
26         let _ = good.data.clone(); //~ ERROR reference to packed field
27         // Error for nested fields.
28         let _ = &good.data2[0]; //~ ERROR reference to packed field
29
30         let _ = &*good.ptr; // ok, behind a pointer
31         let _ = &good.aligned; // ok, has align 1
32         let _ = &good.aligned[2]; // ok, has align 1
33     }
34
35     unsafe {
36         let packed2 = Packed2 { x: 0, y: 0, z: 0 };
37         let _ = &packed2.x; //~ ERROR reference to packed field
38         let _ = &packed2.y; // ok, has align 2 in packed(2) struct
39         let _ = &packed2.z; // ok, has align 1
40     }
41
42     unsafe {
43         struct U16(u16);
44
45         impl Drop for U16 {
46             fn drop(&mut self) {
47                 println!("{:p}", self);
48             }
49         }
50
51         struct HasDrop;
52
53         impl Drop for HasDrop {
54             fn drop(&mut self) {}
55         }
56
57         #[allow(unused)]
58         struct Wrapper {
59             a: U16,
60             b: HasDrop,
61         }
62         #[allow(unused)]
63         #[repr(packed(2))]
64         struct Wrapper2 {
65             a: U16,
66             b: HasDrop,
67         }
68
69         // An outer struct with more restrictive packing than the inner struct -- make sure we
70         // notice that!
71         #[repr(packed)]
72         struct Misalign<T>(u8, T);
73
74         let m1 = Misalign(
75             0,
76             Wrapper {
77                 a: U16(10),
78                 b: HasDrop,
79             },
80         );
81         let _ref = &m1.1.a; //~ ERROR reference to packed field
82
83         let m2 = Misalign(
84             0,
85             Wrapper2 {
86                 a: U16(10),
87                 b: HasDrop,
88             },
89         );
90         let _ref = &m2.1.a; //~ ERROR reference to packed field
91     }
92 }