1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![feature(const_fn, const_size_of, const_align_of)]
15 // Get around the limitations of CTFE in today's Rust.
16 const fn choice_u64(c: bool, a: u64, b: u64) -> u64 {
17 (-(c as i64) as u64) & a | (-(!c as i64) as u64) & b
20 const fn max_usize(a: usize, b: usize) -> usize {
21 choice_u64(a > b, a as u64, b as u64) as usize
24 const fn align_to(size: usize, align: usize) -> usize {
25 (size + (align - 1)) & !(align - 1)
28 const fn packed_union_size_of<A, B>() -> usize {
29 max_usize(mem::size_of::<A>(), mem::size_of::<B>())
32 const fn union_align_of<A, B>() -> usize {
33 max_usize(mem::align_of::<A>(), mem::align_of::<B>())
36 const fn union_size_of<A, B>() -> usize {
37 align_to(packed_union_size_of::<A, B>(), union_align_of::<A, B>())
40 macro_rules! fake_union {
41 ($name:ident { $a:ty, $b:ty }) => (
43 _align: ([$a; 0], [$b; 0]),
44 _bytes: [u8; union_size_of::<$a, $b>()]
49 // Check that we can (poorly) emulate unions by
50 // calling size_of and align_of at compile-time.
51 fake_union!(U { u16, [u8; 3] });
54 assert_eq!(mem::size_of_val(&u._bytes), 4);
58 assert_eq!(mem::size_of::<U>(), 4);
59 assert_eq!(mem::align_of::<U>(), 2);