about summary refs log tree commit diff
path: root/src/tools/miri/tests/pass/union.rs
blob: 8a6dd49f45038788fbc26674f83a703a2456e270 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
fn main() {
    a();
    b();
    c();
    d();
}

fn a() {
    #[allow(dead_code)]
    union U {
        f1: u32,
        f2: f32,
    }
    let mut u = U { f1: 1 };
    unsafe {
        let b1 = &mut u.f1;
        *b1 = 5;
    }
    assert_eq!(unsafe { u.f1 }, 5);
}

fn b() {
    #[derive(Copy, Clone)]
    struct S {
        x: u32,
        y: u32,
    }

    #[allow(dead_code)]
    union U {
        s: S,
        both: u64,
    }
    let mut u = U { s: S { x: 1, y: 2 } };
    unsafe {
        let bx = &mut u.s.x;
        let by = &mut u.s.y;
        *bx = 5;
        *by = 10;
    }
    assert_eq!(unsafe { u.s.x }, 5);
    assert_eq!(unsafe { u.s.y }, 10);
}

fn c() {
    #[repr(u32)]
    enum Tag {
        I,
        F,
    }

    #[repr(C)]
    union U {
        i: i32,
        f: f32,
    }

    #[repr(C)]
    struct Value {
        tag: Tag,
        u: U,
    }

    fn is_zero(v: Value) -> bool {
        unsafe {
            match v {
                Value { tag: Tag::I, u: U { i: 0 } } => true,
                Value { tag: Tag::F, u: U { f } } => f == 0.0,
                _ => false,
            }
        }
    }
    assert!(is_zero(Value { tag: Tag::I, u: U { i: 0 } }));
    assert!(is_zero(Value { tag: Tag::F, u: U { f: 0.0 } }));
    assert!(!is_zero(Value { tag: Tag::I, u: U { i: 1 } }));
    assert!(!is_zero(Value { tag: Tag::F, u: U { f: 42.0 } }));
}

fn d() {
    union MyUnion {
        f1: u32,
        f2: f32,
    }
    let u = MyUnion { f1: 10 };
    unsafe {
        match u {
            MyUnion { f1: 10 } => {}
            MyUnion { f2: _f2 } => panic!("foo"),
        }
    }
}