File: union-move.rs

package info (click to toggle)
rustc-web 1.70.0%2Bdfsg1-7~deb12u2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,517,048 kB
  • sloc: xml: 147,962; javascript: 10,210; sh: 8,590; python: 8,220; ansic: 5,901; cpp: 4,635; makefile: 4,006; asm: 2,856
file content (56 lines) | stat: -rw-r--r-- 1,321 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck

//! Test the behavior of moving out of non-`Copy` union fields.
//! Avoid types that `Drop`, we want to focus on moving.

use std::cell::RefCell;
use std::mem::ManuallyDrop;

fn move_out<T>(x: T) {}

union U1 {
    f1_nocopy: ManuallyDrop<RefCell<i32>>,
    f2_nocopy: ManuallyDrop<RefCell<i32>>,
    f3_copy: i32,
}

union U2 {
    f1_nocopy: ManuallyDrop<RefCell<i32>>,
}
impl Drop for U2 {
    fn drop(&mut self) {}
}

fn test1(x: U1) {
    // Moving out of a nocopy field prevents accessing other nocopy field.
    unsafe {
        move_out(x.f1_nocopy);
        move_out(x.f2_nocopy); //~ ERROR use of moved value: `x`
    }
}

fn test2(x: U1) {
    // "Moving" out of copy field doesn't prevent later field accesses.
    unsafe {
        move_out(x.f3_copy);
        move_out(x.f2_nocopy); // no error
    }
}

fn test3(x: U1) {
    // Moving out of a nocopy field prevents accessing other copy field.
    unsafe {
        move_out(x.f2_nocopy);
        move_out(x.f3_copy); //~ ERROR use of moved value: `x`
    }
}

fn test4(x: U2) {
    // Cannot move out of union that implements `Drop`.
    unsafe {
        move_out(x.f1_nocopy); //~ ERROR cannot move out of type `U2`, which implements the `Drop`
    }
}

fn main() {}