google / google/zerocopy

`IntoBytes` derives fails with (even unused) generics + packed(n > 1)

Open
#2,533 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

Here is an MRE for my problem:

```rust
use zerocopy::{Immutable, IntoBytes};

#[repr(C, packed(4))]
#[derive(Debug, Clone, Copy, Immutable, IntoBytes)]
pub struct Header {
pub a: u32,
pub b: u32,
}
const _: () = assert!(std::mem::size_of::() == 8);

#[repr(C, packed(4))]
#[derive(Debug, Clone, Copy, Immutable, IntoBytes)]
pub struct Data {
pub a: i64,
pub b: u8,
pub c: u8,
pub d: u16,
pub e: f32,
pub f: u16,
pub g: u16,
pub h: [u16; 4],
pub i: u16,
pub _padding: u16,
}
const _: () = assert!(std::mem::size_of::() == 32);

#[repr(C, packed(4))]
#[derive(Debug, Clone, Copy, Immutable, IntoBytes)]
pub struct Packet {
pub header: Header,
pub data: Data,
//moredata: [u16; S], // Flexible array member
}
//const _: () = assert!(std::mem::size_of::>() == 40);
```

The error:
```
error[E0277]: the trait bound `Data: zerocopy::Unaligned` is not satisfied
--> src/lib.rs:28:41
|
28 | #[derive(Debug, Clone, Copy, Immutable, IntoBytes)]
| ^^^^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `Data`
|
= note: Consider adding `#[derive(Unaligned)]` to `Data`
= help: the following other types implement trait `zerocopy::Unaligned`:
()
AtomicBool
AtomicI8
AtomicU8
Cell
F32
F64
I128
and 25 others
= help: see issue #48214
= note: this error originates in the derive macro `IntoBytes` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: the trait bound `Header: zerocopy::Unaligned` is not satisfied
--> src/lib.rs:28:41
|
28 | #[derive(Debug, Clone, Copy, Immutable, IntoBytes)]
| ^^^^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `Header`
|
= note: Consider adding `#[derive(Unaligned)]` to `Header`
= help: the following other types implement trait `zerocopy::Unaligned`:
()
AtomicBool
AtomicI8
AtomicU8
Cell
F32
F64
I128
and 25 others
= help: see issue #48214
= note: this error originates in the derive macro `IntoBytes` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (lib) due to 2 previous errors
```

If I remove the generic parameter on `Packet` entirely, the code compiles, although it is unused in the actual layout (the FAM is commented out).

Replacing `packed(4)` with `packed` works (even with the generic).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.