Skip to content

Commit 17e7e4d

Browse files
[derive] Fix bug with KnownLayout on repr(packed) (#2307) (#2317)
Fixes #2302 gherrit-pr-id: If68c1724be15c4df3ec936a12cf854908650a639 Co-authored-by: Joshua Liebow-Feeser <[email protected]>
1 parent 66d39a9 commit 17e7e4d

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
@@ -326,7 +326,15 @@ fn derive_known_layout_inner(ast: &DeriveInput, _top_level: Trait) -> Result<Tok
326326
::zerocopy::util::macro_util::Field<#leading_field_indices>
327327
>::Type
328328
>,)*
329-
<#trailing_field_ty as ::zerocopy::KnownLayout>::MaybeUninit
329+
// NOTE(#2302): We wrap in `ManuallyDrop` here in case the
330+
// type we're operating on is both generic and
331+
// `repr(packed)`. In that case, Rust needs to know that the
332+
// type is *either* `Sized` or has a trivial `Drop`.
333+
// `ManuallyDrop` has a trivial `Drop`, and so satisfies
334+
// this requirement.
335+
::zerocopy::util::macro_util::core_reexport::mem::ManuallyDrop<
336+
<#trailing_field_ty as ::zerocopy::KnownLayout>::MaybeUninit
337+
>
330338
)
331339
where
332340
#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
@@ -195,12 +195,14 @@ fn test_known_layout() {
195195
::zerocopy::util::macro_util::core_reexport::mem::MaybeUninit<
196196
<Foo<T, U> as ::zerocopy::util::macro_util::Field<__Zerocopy_Field_0>>::Type,
197197
>,
198-
<<Foo<
199-
T,
200-
U,
201-
> as ::zerocopy::util::macro_util::Field<
202-
__Zerocopy_Field_1,
203-
>>::Type as ::zerocopy::KnownLayout>::MaybeUninit,
198+
::zerocopy::util::macro_util::core_reexport::mem::ManuallyDrop<
199+
<<Foo<
200+
T,
201+
U,
202+
> as ::zerocopy::util::macro_util::Field<
203+
__Zerocopy_Field_1,
204+
>>::Type as ::zerocopy::KnownLayout>::MaybeUninit
205+
>,
204206
)
205207
where
206208
<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)