Skip to content

make packed structs versatile #3133

@andrewrk

Description

@andrewrk

Currently, packed structs are always align(1) and each field of a packed struct is either align(1) or a special kind of alignment that indicates bit offsets. I propose the following changes:

  • implement ability to specify explicit field alignment of packed structs (related to ability to set alignment on struct fields #1512), including even bit offsets. This can cause padding to be inserted (possibly even just bits to the next byte).
  • packed structs, like normal structs, have the alignment of the most-aligned field. Minimum 1 byte.
  • without explicit alignment specified, fields get bit packed. However fields can be specified to be byte aligned and pointers to these fields can even be naturally aligned. A packed struct with every field like this: field: T align(T), would be equivalent to an extern struct.
  • ability for packed structs to have fields that are normal structs. In this case whether a packed struct has well-defined memory layout is determined by whether or not all the fields it has have well-defined memory layout. Normal structs and types can still be bit-packed though!
  • when a packed struct has no well-defined memory layout, it can participate in debug safety features (see add safety checks for pointer casting #2414). Perhaps there could even be a special type that could be used as a field, that allows Zig to put the debug safety in that field's location, and packed structs would have well-defined memory layout until the first field that does not have well defined memory layout. This would allow putting this debug safety field at the end, and still doing @bitCast, @ptrCast, or other useful things with packed structs.
  • fix the issues regarding packed structs not ending with byte-alignment. This should be handled semantically equivalent to, for example, u7.

Related bug: #2627

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    Status

    To do

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions