File: union-pat-refutability.rs

package info (click to toggle)
rustc-web 1.78.0%2Bdfsg1-2~deb11u3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,245,360 kB
  • sloc: xml: 147,985; javascript: 18,022; sh: 11,083; python: 10,265; ansic: 6,172; cpp: 5,023; asm: 4,390; makefile: 4,269
file content (57 lines) | stat: -rw-r--r-- 785 bytes parent folder | download | duplicates (8)
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
//@ run-pass

#![allow(dead_code)]

#[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: 0.0 } } => true,
            _ => false,
        }
    }
}

union W {
    a: u8,
    b: u8,
}

fn refut(w: W) {
    unsafe {
        match w {
            W { a: 10 } => {
                panic!();
            }
            W { b } => {
                assert_eq!(b, 11);
            }
        }
    }
}

fn main() {
    let v = Value { tag: Tag::I, u: U { i: 1 } };
    assert_eq!(is_zero(v), false);

    let w = W { a: 11 };
    refut(w);
}