Bitpacking for Go

gopack Build Status

Bitpacking for Go.

##Usage

// Define arbitrary structs for packing.
type color struct {
  R, G, B uint8
}

red := color{255, 0, 0}
b := make([]byte, 3)
gopack.Pack(b, red)

// Use field tags to specify custom bit widths.
type unixMode struct {
  User, Group, Other uint8 `gopack:"3"`
}

// Embed structs nested arbitrarily deep.
type file struct {
  Size uint32
  Mode unixMode
}

// Unexported fields are ignored.
type person struct {
  name string
  Age uint8
}

// Use int types and bool types.
type fileHandle struct {
  File file
  Open bool
  Seek uint32
}

##Documentation

See the documentation.

Owner
Joshua Liebow-Feeser
Joshua Liebow-Feeser
Similar Resources
Comments
  • Add an API to access the packed size of a given type.

    Add an API to access the packed size of a given type.

    This makes it easier to write generic code that uses gopack under the hood without having to hardcode the size of the structs being used by the generic code.

    This change also removes a layer of indirection in makePackerWrapper, by having the code check the input buffer is big enough directly in Pack() rather than via an extra anonymous func, which improves most encoding benchmarks by 4 to 6% (the gains are really modest in absolute terms, on the order of a few cycles, as all it's doing really is just removing an extra indirect function call).

  • gopack shouldn't panic

    gopack shouldn't panic

    The packer functions call panic() when an overflow happens, which means the callers have to always setup a defer'ed recover() to potentially recover from such panics. It might be more idiomatic to have the packer type defined as type packer func(b []byte, v reflect.Value) error (i.e. have it return an error). What do you think?

  • Add support for arrays

    Add support for arrays

    Since we have support for structs, we should also have support for arrays. Slices should probably remain unsupported, as most of the logic of creating packers/unpackers is reliant on fixed bit positions, which would no longer be a guarantee if preceding fields were variable length.

  • Add the ability to have the top-level type be any packable type

    Add the ability to have the top-level type be any packable type

    Currently, packing/unpacking only works when the type which is packed/unpacked is a struct, even though fields may be other types. We should extend the public API so that any type which can appear as a field in a packable type can itself be packed/unpacked at the top level.