union-ub.rs 1.1 KB
Newer Older
O
Oliver Schneider 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12
#![allow(const_err)] // make sure we cannot allow away the errors tested here

O
Oliver Schneider 已提交
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
union DummyUnion {
    u8: u8,
    bool: bool,
}

#[repr(C)]
#[derive(Copy, Clone)]
enum Enum {
    A,
    B,
    C,
}

#[derive(Copy, Clone)]
union Foo {
    a: bool,
    b: Enum,
}

union Bar {
    foo: Foo,
    u8: u8,
}

// the value is not valid for bools
const BAD_BOOL: bool = unsafe { DummyUnion { u8: 42 }.bool};
39
//~^ ERROR it is undefined behavior to use this value
O
Oliver Schneider 已提交
40 41 42 43 44 45

// The value is not valid for any union variant, but that's fine
// unions are just a convenient way to transmute bits around
const BAD_UNION: Foo = unsafe { Bar { u8: 42 }.foo };


46
fn main() {}