]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/const-size_of-align_of.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / test / run-pass / const-size_of-align_of.rs
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.
4 //
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.
10
11 #![feature(const_fn)]
12
13 use std::mem;
14
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
18 }
19
20 const fn max_usize(a: usize, b: usize) -> usize {
21     choice_u64(a > b, a as u64, b as u64) as usize
22 }
23
24 const fn align_to(size: usize, align: usize) -> usize {
25     (size + (align - 1)) & !(align - 1)
26 }
27
28 const fn packed_union_size_of<A, B>() -> usize {
29     max_usize(mem::size_of::<A>(), mem::size_of::<B>())
30 }
31
32 const fn union_align_of<A, B>() -> usize {
33     max_usize(mem::align_of::<A>(), mem::align_of::<B>())
34 }
35
36 const fn union_size_of<A, B>() -> usize {
37     align_to(packed_union_size_of::<A, B>(), union_align_of::<A, B>())
38 }
39
40 macro_rules! fake_union {
41     ($name:ident { $a:ty, $b:ty }) => (
42         struct $name {
43             _align: ([$a; 0], [$b; 0]),
44             _bytes: [u8; union_size_of::<$a, $b>()]
45         }
46     )
47 }
48
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] });
52
53 fn test(u: U) {
54     assert_eq!(mem::size_of_val(&u._bytes), 4);
55 }
56
57 fn main() {
58     assert_eq!(mem::size_of::<U>(), 4);
59     assert_eq!(mem::align_of::<U>(), 2);
60 }