Skip to content

Improve ergonomics of IntoBytes on unsized types #1708

Closed
@joshlf

Description

@joshlf

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)].

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions