Skip to content

Improve ergonomics of IntoBytes on unsized types #1708

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
Tracked by #671
joshlf opened this issue Sep 20, 2024 · 0 comments · Fixed by #1713
Closed
Tracked by #671

Improve ergonomics of IntoBytes on unsized types #1708

joshlf opened this issue Sep 20, 2024 · 0 comments · Fixed by #1713

Comments

@joshlf
Copy link
Member

joshlf commented Sep 20, 2024

This source code:

#[derive(IntoBytes)]
#[repr(C)]
struct IntoBytes4 {
    a: u8,
    b: [u8],
}

...results in this error:

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
   --> tests/ui-nightly/struct.rs:125:8
    |
125 | struct IntoBytes4 {
    |        ^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: within `IntoBytes4`, the trait `Sized` is not implemented for `[u8]`, which is required by `IntoBytes4: Sized`
note: required because it appears within the type `IntoBytes4`
   --> tests/ui-nightly/struct.rs:125:8
    |
125 | struct IntoBytes4 {
    |        ^^^^^^^^^^
note: required by an implicit `Sized` bound in `std::mem::size_of`
   --> $RUST/core/src/mem/mod.rs
    |
    | pub const fn size_of<T>() -> usize {
    |                      ^ required by the implicit `Sized` requirement on this type parameter in `size_of`

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
   --> tests/ui-nightly/struct.rs:127:8
    |
127 |     b: [u8],
    |        ^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `Sized` is not implemented for `[u8]`
note: required by an implicit `Sized` bound in `std::mem::size_of`
   --> $RUST/core/src/mem/mod.rs
    |
    | pub const fn size_of<T>() -> usize {
    |                      ^ required by the implicit `Sized` requirement on this type parameter in `size_of`

What's happening here is that the derive can't tell that this type can't have padding, and so it tries to guarantee that by emitting a padding check bound (that the size of the type is equal to the sizes of its fields). However, since this type is unsized, this check can't compile because size_of requires T: Sized. Currently, the only way to make this code compile is to add #[repr(packed)].

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant