Debian Codegraph @

.cargo/vendor/zerocopy-derive/tests/struct_unaligned.rs

raw
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 // See comment in `include.rs` for why we disable the prelude.
10 #![no_implicit_prelude]
11 #![allow(warnings)]
12
13 include!("include.rs");
14
15 // A struct 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(imp::Unaligned)]
22 #[repr(C)]
23 struct Foo {
24 a: u8,
25 }
26
27 util_assert_impl_all!(Foo: imp::Unaligned);
28
29 #[derive(imp::Unaligned)]
30 #[repr(transparent)]
31 struct Bar {
32 a: u8,
33 }
34
35 util_assert_impl_all!(Bar: imp::Unaligned);
36
37 #[derive(imp::Unaligned)]
38 #[repr(packed)]
39 struct Baz {
40 // NOTE: The `u16` type is not guaranteed to have alignment 2, although it
41 // does on many platforms. However, to fix this would require a custom type
42 // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not
43 // allowed to transitively contain `#[repr(align(...))]` types. Thus, we
44 // have no choice but to use `u16` here. Luckily, these tests run in CI on
45 // platforms on which `u16` has alignment 2, so this isn't that big of a
46 // deal.
47 a: u16,
48 }
49
50 util_assert_impl_all!(Baz: imp::Unaligned);
51
52 #[derive(imp::Unaligned)]
53 #[repr(C, align(1))]
54 struct FooAlign {
55 a: u8,
56 }
57
58 util_assert_impl_all!(FooAlign: imp::Unaligned);
59
60 #[derive(imp::Unaligned)]
61 #[repr(transparent)]
62 struct Unsized {
63 a: [u8],
64 }
65
66 util_assert_impl_all!(Unsized: imp::Unaligned);
67
68 #[derive(imp::Unaligned)]
69 #[repr(C)]
70 struct TypeParams<'a, T: ?imp::Sized, I: imp::Iterator> {
71 a: I::Item,
72 b: u8,
73 c: imp::PhantomData<&'a [::core::primitive::u8]>,
74 d: imp::PhantomData<&'static ::core::primitive::str>,
75 e: imp::PhantomData<imp::String>,
76 f: T,
77 }
78
79 util_assert_impl_all!(TypeParams<'static, (), imp::IntoIter<()>>: imp::Unaligned);
80 util_assert_impl_all!(TypeParams<'static, ::core::primitive::u8, imp::IntoIter<()>>: imp::Unaligned);
81 util_assert_impl_all!(TypeParams<'static, [::core::primitive::u8], imp::IntoIter<()>>: imp::Unaligned);
82
83 // Deriving `Unaligned` should work if the struct has bounded parameters.
84
85 #[derive(imp::Unaligned)]
86 #[repr(transparent)]
87 struct WithParams<'a: 'b, 'b: 'a, T: 'a + 'b + imp::Unaligned, const N: usize>(
88 [T; N],
89 imp::PhantomData<&'a &'b ()>,
90 )
91 where
92 'a: 'b,
93 'b: 'a,
94 T: 'a + 'b + imp::Unaligned;
95
96 util_assert_impl_all!(WithParams<'static, 'static, u8, 42>: imp::Unaligned);