File: arbitrary_enum_discriminant.rs

package info (click to toggle)
rustc-web 1.78.0%2Bdfsg1-2~deb12u3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,245,420 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 (43 lines) | stat: -rw-r--r-- 977 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
//@ run-pass
#![feature(test)]

extern crate test;

use test::black_box;

#[allow(dead_code)]
#[repr(u8)]
enum Enum {
    Unit = 3,
    Tuple(u16) = 2,
    Struct {
        a: u8,
        b: u16,
    } = 1,
}

impl Enum {
    const unsafe fn tag(&self) -> u8 {
        *(self as *const Self as *const u8)
    }
}

fn main() {
    const UNIT: Enum = Enum::Unit;
    const TUPLE: Enum = Enum::Tuple(5);
    const STRUCT: Enum = Enum::Struct{a: 7, b: 11};

    // Ensure discriminants are correct during runtime execution
    assert_eq!(3, unsafe { black_box(UNIT).tag() });
    assert_eq!(2, unsafe { black_box(TUPLE).tag() });
    assert_eq!(1, unsafe { black_box(STRUCT).tag() });

    // Ensure discriminants are correct during CTFE
    const UNIT_TAG: u8 = unsafe { UNIT.tag() };
    const TUPLE_TAG: u8 = unsafe { TUPLE.tag() };
    const STRUCT_TAG: u8 = unsafe { STRUCT.tag() };

    assert_eq!(3, UNIT_TAG);
    assert_eq!(2, TUPLE_TAG);
    assert_eq!(1, STRUCT_TAG);
}