Documentation
¶
Overview ¶
bitfield is a tool to generate Pack/Unpack code for struct types whose fields are tagged with bit widths.
Given a type whose fields carry `bitfield:"<width>"` struct tags:
type Flags struct {
Opcode uint8 `bitfield:"6"`
Mode uint8 `bitfield:"2"`
Enabled bool `bitfield:"1"`
Rsvd uint8 `bitfield:"7"`
}
running this command in the same directory
bitfield -type=Flags
creates the file flags_fields.go containing:
func (v Flags) Pack() uint16 func UnpackFlags(raw uint16) Flags
The bit layout places the first field at the LSB and subsequent fields at increasing offsets. The storage type is the smallest of uint8, uint16, uint32, uint64 that holds the total width.
Supported field types: bool (always exactly 1 bit) and any type whose underlying kind is uint8, uint16, uint32, or uint64. Named types are preserved in the emitted code, so `type Mode uint8` round-trips as Mode.
Fields (exported or not) may be declared with the blank identifier `_` to reserve bits without contributing a name to Pack/Unpack:
type Color struct {
_ uint8 `bitfield:"1"` // padding
R uint8 `bitfield:"3"`
_ uint8 `bitfield:"1"`
G uint8 `bitfield:"3"`
}
When the target type itself is unexported, the generated methods follow suit: `pack` and `unpack<Type>` instead of `Pack`/`Unpack<Type>`.
Typical go:generate wiring ¶
Add a go:generate directive in your package:
//go:generate go run github.com/arl/bitfield/v2 -type=Flags
Then `go generate ./...` (re)produces flags_fields.go with Pack and Unpack<Type> for each listed type.