]> git.lizzy.rs Git - rust.git/blob - tests/ui/union/union-unsafe.rs
Auto merge of #106711 - albertlarsan68:use-ci-llvm-when-lld, r=jyn514
[rust.git] / tests / ui / union / union-unsafe.rs
1 // revisions: mir thir
2 // [thir]compile-flags: -Z thir-unsafeck
3
4 use std::mem::ManuallyDrop;
5 use std::cell::RefCell;
6
7 union U1 {
8     a: u8
9 }
10
11 union U2 {
12     a: ManuallyDrop<String>
13 }
14
15 union U3<T> {
16     a: ManuallyDrop<T>
17 }
18
19 union U4<T: Copy> {
20     a: T
21 }
22
23 union URef {
24     p: &'static mut i32,
25 }
26
27 union URefCell { // field that does not drop but is not `Copy`, either
28     a: (ManuallyDrop<RefCell<i32>>, i32),
29 }
30
31 fn deref_union_field(mut u: URef) {
32     // Not an assignment but an access to the union field!
33     *(u.p) = 13; //~ ERROR access to union field is unsafe
34 }
35
36 fn assign_noncopy_union_field(mut u: URefCell) {
37     // FIXME(thir-unsafeck)
38     u.a = (ManuallyDrop::new(RefCell::new(0)), 1); // OK (assignment does not drop)
39     u.a.0 = ManuallyDrop::new(RefCell::new(0)); // OK (assignment does not drop)
40     u.a.1 = 1; // OK
41 }
42
43 fn generic_noncopy<T: Default>() {
44     let mut u3 = U3 { a: ManuallyDrop::new(T::default()) };
45     u3.a = ManuallyDrop::new(T::default()); // OK (assignment does not drop)
46     *u3.a = T::default(); //~ ERROR access to union field is unsafe
47 }
48
49 fn generic_copy<T: Copy + Default>() {
50     let mut u3 = U3 { a: ManuallyDrop::new(T::default()) };
51     u3.a = ManuallyDrop::new(T::default()); // OK
52     *u3.a = T::default(); //~ ERROR access to union field is unsafe
53
54     let mut u4 = U4 { a: T::default() };
55     u4.a = T::default(); // OK
56 }
57
58 fn main() {
59     let mut u1 = U1 { a: 10 }; // OK
60     let a = u1.a; //~ ERROR access to union field is unsafe
61     u1.a = 11; // OK
62
63     let U1 { a } = u1; //~ ERROR access to union field is unsafe
64     if let U1 { a: 12 } = u1 {} //~ ERROR access to union field is unsafe
65     // let U1 { .. } = u1; // OK
66
67     let mut u2 = U2 { a: ManuallyDrop::new(String::from("old")) }; // OK
68     u2.a = ManuallyDrop::new(String::from("new")); // OK (assignment does not drop)
69     *u2.a = String::from("new"); //~ ERROR access to union field is unsafe
70
71     let mut u3 = U3 { a: ManuallyDrop::new(0) }; // OK
72     u3.a = ManuallyDrop::new(1); // OK
73     *u3.a = 1; //~ ERROR access to union field is unsafe
74
75     let mut u3 = U3 { a: ManuallyDrop::new(String::from("old")) }; // OK
76     u3.a = ManuallyDrop::new(String::from("new")); // OK (assignment does not drop)
77     *u3.a = String::from("new"); //~ ERROR access to union field is unsafe
78 }