Binary serialization library for arbitrary Zig types
|
|
||
|---|---|---|
| src | std.meta.Int -> @Int | |
| .gitignore | init | |
| build.zig | init | |
| build.zig.zon | std.meta.Int -> @Int | |
| README.md | init | |
pack
Binary serialization for arbitrary Zig types. Pass any value to write and reconstruct it with read or readAlloc — no per-type boilerplate required.
Usage
constpack=@import("pack");Stack-only types
For types with no pointers or slices, use write and read:
constPoint=struct{x:f32,y:f32};varwriter=std.Io.Writer.Allocating.init(allocator);deferwriter.deinit();trywrite(original,&writer.writer);trypack.write(Point{.x=1.0,.y=2.0},&writer);varreader=Io.Reader.fixed(writer.written());constpoint=trypack.read(Point,&reader);Heap-allocated types
For types containing slices or pointers, use readAlloc. You own the memory and must free it:
constMessage=struct{id:u32,text:[]constu8,payload:*Data,};// write is the same regardlesstrypack.write(msg,&writer);// readAlloc allocates slices and pointers for youconstresult=trypack.readAlloc(Message,allocator,&reader);deferallocator.free(result.text);deferallocator.destroy(result.payload);Supported types
| Type | Notes |
|---|---|
int, float, bool |
Primitives |
enum |
Tag written as smallest byte-aligned int |
optional |
Prefixed with a 0/1 byte |
struct |
Fields serialized in order |
union(enum) |
Tag written first, then active field |
[N]T, @Vector(N, T) |
Fixed-size arrays and vectors |
[]T, *T |
Slices and single pointers (alloc path only) |
Unsupported types
[*]T and [*c]T are rejected at compile time — use []T instead.
Untagged unions are also rejected; tag your union.
Format
- Integers: little-endian
- Floats: bit-cast to unsigned int, big-endian
- Slices/many-pointers:
usizelength prefix (little-endian), then elements - Optionals:
0x00for null,0x01then value for non-null - Union tags: written as the enum (smallest byte-aligned int, little-endian)