1 // Copyright 2019 The Fuchsia Authors
2 //
3 // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5 // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6 // This file may not be copied, modified, or distributed except according to
7 // those terms.
8 
9 #![allow(warnings)]
10 
11 use std::{marker::PhantomData, option::IntoIter};
12 
13 use {static_assertions::assert_impl_all, zerocopy::Unaligned};
14 
15 // A union is `Unaligned` if:
16 // - `repr(align)` is no more than 1 and either
17 //   - `repr(C)` or `repr(transparent)` and
18 //     - all fields `Unaligned`
19 //   - `repr(packed)`
20 
21 #[derive(Unaligned)]
22 #[repr(C)]
23 union Foo {
24     a: u8,
25 }
26 
27 assert_impl_all!(Foo: Unaligned);
28 
29 // Transparent unions are unstable; see issue #60405
30 // <https://github.com/rust-lang/rust/issues/60405> for more information.
31 
32 // #[derive(Unaligned)]
33 // #[repr(transparent)]
34 // union Bar {
35 //     a: u8,
36 // }
37 
38 // is_unaligned!(Bar);
39 
40 #[derive(Unaligned)]
41 #[repr(packed)]
42 union Baz {
43     // NOTE: The `u16` type is not guaranteed to have alignment 2, although it
44     // does on many platforms. However, to fix this would require a custom type
45     // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not
46     // allowed to transitively contain `#[repr(align(...))]` types. Thus, we
47     // have no choice but to use `u16` here. Luckily, these tests run in CI on
48     // platforms on which `u16` has alignment 2, so this isn't that big of a
49     // deal.
50     a: u16,
51 }
52 
53 assert_impl_all!(Baz: Unaligned);
54 
55 #[derive(Unaligned)]
56 #[repr(C, align(1))]
57 union FooAlign {
58     a: u8,
59 }
60 
61 assert_impl_all!(FooAlign: Unaligned);
62 
63 #[derive(Unaligned)]
64 #[repr(C)]
65 union TypeParams<'a, T: Copy, I: Iterator>
66 where
67     I::Item: Copy,
68 {
69     a: T,
70     c: I::Item,
71     d: u8,
72     e: PhantomData<&'a [u8]>,
73     f: PhantomData<&'static str>,
74     g: PhantomData<String>,
75 }
76 
77 assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: Unaligned);
78