Skip to content

Commit 0451e53

Browse files
authored
[derive] Fix bug with KnownLayout on repr(packed) (#2307)
Fixes #2302 gherrit-pr-id: If68c1724be15c4df3ec936a12cf854908650a639
1 parent c93c2c0 commit 0451e53

File tree

3 files changed

+28
-7
lines changed

3 files changed

+28
-7
lines changed

zerocopy-derive/src/lib.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,15 @@ fn derive_known_layout_inner(ast: &DeriveInput, _top_level: Trait) -> Result<Tok
332332
::zerocopy::util::macro_util::Field<#leading_field_indices>
333333
>::Type
334334
>,)*
335-
<#trailing_field_ty as ::zerocopy::KnownLayout>::MaybeUninit
335+
// NOTE(#2302): We wrap in `ManuallyDrop` here in case the
336+
// type we're operating on is both generic and
337+
// `repr(packed)`. In that case, Rust needs to know that the
338+
// type is *either* `Sized` or has a trivial `Drop`.
339+
// `ManuallyDrop` has a trivial `Drop`, and so satisfies
340+
// this requirement.
341+
::zerocopy::util::macro_util::core_reexport::mem::ManuallyDrop<
342+
<#trailing_field_ty as ::zerocopy::KnownLayout>::MaybeUninit
343+
>
336344
)
337345
where
338346
#trailing_field_ty: ::zerocopy::KnownLayout,

zerocopy-derive/src/output_tests.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,12 +198,14 @@ fn test_known_layout() {
198198
::zerocopy::util::macro_util::core_reexport::mem::MaybeUninit<
199199
<Foo<T, U> as ::zerocopy::util::macro_util::Field<__Zerocopy_Field_0>>::Type,
200200
>,
201-
<<Foo<
202-
T,
203-
U,
204-
> as ::zerocopy::util::macro_util::Field<
205-
__Zerocopy_Field_1,
206-
>>::Type as ::zerocopy::KnownLayout>::MaybeUninit,
201+
::zerocopy::util::macro_util::core_reexport::mem::ManuallyDrop<
202+
<<Foo<
203+
T,
204+
U,
205+
> as ::zerocopy::util::macro_util::Field<
206+
__Zerocopy_Field_1,
207+
>>::Type as ::zerocopy::KnownLayout>::MaybeUninit
208+
>,
207209
)
208210
where
209211
<Foo<

zerocopy-derive/tests/struct_known_layout.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,14 @@ impl WithSelfReference {
101101
}
102102

103103
util_assert_impl_all!(WithSelfReference: imp::KnownLayout);
104+
105+
// Deriving `KnownLayout` should work with generic `repr(packed)` types. See
106+
// #2302.
107+
108+
#[derive(imp::KnownLayout)]
109+
#[repr(C, packed)]
110+
struct Packet<P> {
111+
payload: P,
112+
}
113+
114+
util_assert_impl_all!(Packet<imp::u8>: imp::KnownLayout);

0 commit comments

Comments
 (0)