]> git.lizzy.rs Git - rust.git/blob - src/test/ui/union/union-unsafe.rs
Merge commit 'b20d4c155d2fe3a8391f86dcf9a8c49e17188703' into clippyup
[rust.git] / src / test / ui / union / union-unsafe.rs
1 use std::mem::ManuallyDrop;
2
3 union U1 {
4     a: u8
5 }
6
7 union U2 {
8     a: ManuallyDrop<String>
9 }
10
11 union U3<T> {
12     a: ManuallyDrop<T>
13 }
14
15 union U4<T: Copy> {
16     a: T
17 }
18
19 fn generic_noncopy<T: Default>() {
20     let mut u3 = U3 { a: ManuallyDrop::new(T::default()) };
21     u3.a = ManuallyDrop::new(T::default()); //~ ERROR assignment to non-`Copy` union field is unsafe
22     *u3.a = T::default(); //~ ERROR access to union field is unsafe
23 }
24
25 fn generic_copy<T: Copy + Default>() {
26     let mut u3 = U3 { a: ManuallyDrop::new(T::default()) };
27     u3.a = ManuallyDrop::new(T::default()); // OK
28     *u3.a = T::default(); //~ ERROR access to union field is unsafe
29
30     let mut u4 = U4 { a: T::default() };
31     u4.a = T::default(); // OK
32 }
33
34 fn main() {
35     let mut u1 = U1 { a: 10 }; // OK
36     let a = u1.a; //~ ERROR access to union field is unsafe
37     u1.a = 11; // OK
38
39     let U1 { a } = u1; //~ ERROR access to union field is unsafe
40     if let U1 { a: 12 } = u1 {} //~ ERROR access to union field is unsafe
41     // let U1 { .. } = u1; // OK
42
43     let mut u2 = U2 { a: ManuallyDrop::new(String::from("old")) }; // OK
44     u2.a = ManuallyDrop::new(String::from("new")); //~ ERROR assignment to non-`Copy` union
45     *u2.a = String::from("new"); //~ ERROR access to union field is unsafe
46
47     let mut u3 = U3 { a: ManuallyDrop::new(0) }; // OK
48     u3.a = ManuallyDrop::new(1); // OK
49     *u3.a = 1; //~ ERROR access to union field is unsafe
50
51     let mut u3 = U3 { a: ManuallyDrop::new(String::from("old")) }; // OK
52     u3.a = ManuallyDrop::new(String::from("new")); //~ ERROR assignment to non-`Copy` union
53     *u3.a = String::from("new"); //~ ERROR access to union field is unsafe
54 }