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