Skip to content

Syntax for manual padding/alignment within packed struct #676

Closed
@skyfex

Description

@skyfex

When packed structs describe memory-mapped registers or binary files/protocols, it is often necessary to pad the struct to correctly position the fields within the struct. In C this has normally been solved by creating special padding fields. An example is:

const GpioConf = struct {
  direction: u1,
  _reserved1: u3,
  pull: u1
  _reserved2: u3,
 ....
}

The downside is that you have to name something you're not interested in naming, and specify a type that has no meaning other than its bit-width. You'll have to manually maintain some kind of numbering scheme for the reserved/padding fields.

In addition, since Zig requires you to specify every field when instantiating a struct, you end up having to fill in the padding fields as well:

pinCnf = GpioConf { .direction = 1, ._reserved1 = 0, .pull = 1 , .... };

It would be very useful to have a special syntax for specifying padding. An example might be:

const GpioConf = struct {
  direction: u1,
  padding(3),
  pull: u1,
  padding(3),
  ...
};

Or maybe it should be "@padding(3)". You could also use a type name (u3) instead of a number to specify bit size. But then there's more than one way to specify padding ("u3", "i3", etc.)

Another solution would be that Zig to just treat fields named with a special prefix differently. E.g., when prefixed with "_", field names don't collide, refering to them is illegal, and you don't have to specify them in instantiations. Less special syntax, and you could choose a descriptive field name ("_reserved", "_padding", "_deprecated", etc.) but you'd have to specify a type.

A good idea might be to consider how this syntax could be extended in the future. If you use the function-call like syntax, can you call any compile-time function? Can a compile-time function return a field, or list of fields to be inserted into a struct?

This issue was spawned by a discussion in #488

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

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions