]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/union.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / union.rs
1 fn main() {
2     a();
3     b();
4     c();
5     d();
6 }
7
8 fn a() {
9     #[allow(dead_code)]
10     union U {
11         f1: u32,
12         f2: f32,
13     }
14     let mut u = U { f1: 1 };
15     unsafe {
16         let b1 = &mut u.f1;
17         *b1 = 5;
18     }
19     assert_eq!(unsafe { u.f1 }, 5);
20 }
21
22 fn b() {
23     #[derive(Copy, Clone)]
24     struct S {
25         x: u32,
26         y: u32,
27     }
28
29     #[allow(dead_code)]
30     union U {
31         s: S,
32         both: u64,
33     }
34     let mut u = U { s: S { x: 1, y: 2 } };
35     unsafe {
36         let bx = &mut u.s.x;
37         let by = &mut u.s.y;
38         *bx = 5;
39         *by = 10;
40     }
41     assert_eq!(unsafe { u.s.x }, 5);
42     assert_eq!(unsafe { u.s.y }, 10);
43 }
44
45 fn c() {
46     #[repr(u32)]
47     enum Tag {
48         I,
49         F,
50     }
51
52     #[repr(C)]
53     union U {
54         i: i32,
55         f: f32,
56     }
57
58     #[repr(C)]
59     struct Value {
60         tag: Tag,
61         u: U,
62     }
63
64     fn is_zero(v: Value) -> bool {
65         unsafe {
66             match v {
67                 Value { tag: Tag::I, u: U { i: 0 } } => true,
68                 Value { tag: Tag::F, u: U { f } } => f == 0.0,
69                 _ => false,
70             }
71         }
72     }
73     assert!(is_zero(Value { tag: Tag::I, u: U { i: 0 } }));
74     assert!(is_zero(Value { tag: Tag::F, u: U { f: 0.0 } }));
75     assert!(!is_zero(Value { tag: Tag::I, u: U { i: 1 } }));
76     assert!(!is_zero(Value { tag: Tag::F, u: U { f: 42.0 } }));
77 }
78
79 fn d() {
80     union MyUnion {
81         f1: u32,
82         f2: f32,
83     }
84     let u = MyUnion { f1: 10 };
85     unsafe {
86         match u {
87             MyUnion { f1: 10 } => {}
88             MyUnion { f2: _f2 } => panic!("foo"),
89         }
90     }
91 }