This is a Zig library for encoding/decoding msgpack messages based on static types.
You can define a struct type and then serialize it using a stable binary format that is readable with any language that supports msgpack. This is useful for data files and network APIs. You can use it like protobuf, but with the advantage that you use Zig's type system instead of a foreign schema language.
There are multiple options on how to encode struct fields, in order to generate compact messages, see below for details.
Requires Zig 0.16 or 0.17.
- Add msgpack.zig as a dependency in your
build.zig.zon:
zig fetch --save "git+https://github.com/lalinsky/msgpack.zig?ref=v0.10.0"- In your
build.zig, add themsgpackmodule as a dependency you your program:
const msgpack = b.dependency("msgpack", .{
.target = target,
.optimize = optimize,
});
// the executable from your call to b.addExecutable(...)
exe.root_module.addImport("msgpack", msgpack.module("msgpack"));Basic encoding and decoding:
const std = @import("std");
const msgpack = @import("msgpack");
const Message = struct {
name: []const u8,
age: u8,
};
var buffer: std.Io.Writer.Allocating = .init(allocator);
defer buffer.deinit();
try msgpack.encode(Message{
.name = "John",
.age = 20,
}, &buffer.writer);
const decoded = try msgpack.decodeFromSlice(Message, allocator, buffer.written(), .{});
defer decoded.deinit();
std.debug.assert(std.mem.eql(u8, decoded.value.name, "John"));
std.debug.assert(decoded.value.age == 20);decodeFromSlice creates an arena of its own for the decoded value, which is what deinit frees.
If you are already decoding into memory you release in one go — a per-request arena, or a fixed
buffer — use decodeFromSliceLeaky instead. It allocates straight from the allocator you give it,
so there is nothing to deinit, and it avoids a second arena inside your own:
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const message = try msgpack.decodeFromSliceLeaky(Message, arena.allocator(), buffer.written(), .{});decodeLeaky is the same for a reader.
The last argument is msgpack.DecodeOptions. A decode reads one message, and anything after it is
error.TrailingData. To read a stream of messages, pass .{ .allow_trailing_data = true }: the
decode stops after the message and leaves the reader there, so the next decode reads the next one.
In a loop, reuse one arena and reset(.retain_capacity) between messages; the arena then stops
going back to its backing allocator entirely.
Decoding errors take their names from std.json wherever it has the same case, and are the same
as json.zig's, so code handling both formats can treat them
alike: error.SyntaxError for bytes that are not MessagePack, error.UnexpectedToken for a valid
value of the wrong kind for the type, error.UnexpectedEndOfInput for a message cut short, and so
on. msgpack.SliceDecodeError lists them all.
Nesting deeper than msgpack.max_depth (256) levels, counting the values skipped by
skip_unknown_fields, fails with error.DepthLimitExceeded, and a map that names the same field
twice fails with error.DuplicateField.
The encoded message will use field names as keys to encode the message. In order to generate more compact messages, you can change the format to use field indexes:
const std = @import("std");
const msgpack = @import("msgpack");
const Message = struct {
name: []const u8,
age: u8,
pub fn msgpackFormat() msgpack.StructFormat {
return .{ .as_map = .{ .key = .field_index } };
}
};Or you can also use field name prefixes:
const std = @import("std");
const msgpack = @import("msgpack");
const Message = struct {
name: []const u8,
age: u8,
pub fn msgpackFormat() msgpack.StructFormat {
return .{ .as_map = .{ .key = .{ .field_name_prefix = 1 } } };
}
};Both options have the disadvantage that changing the fields in the struct will have impact on the encoded message, so you need to be careful about backwards compatibility. You can also use custom protobuf-like field keys, so that renaming or reordering fields does not change the encoded message:
const std = @import("std");
const msgpack = @import("msgpack");
const Message = struct {
name: []const u8,
age: u8,
pub fn msgpackFormat() msgpack.StructFormat {
return .{ .as_map = .{ .key = .custom } };
}
pub fn msgpackFieldKey(field: std.meta.FieldEnum(@This())) u8 {
return switch (field) {
.name => 1,
.age => 2,
};
}
};Stable keys alone are not enough to read messages from a newer encoder, though: by default a key
that matches no field is an error. Set skip_unknown_fields to step over those entries instead, so
adding a field on the producer does not break existing consumers:
const Message = struct {
name: []const u8,
age: u8,
pub fn msgpackFormat() msgpack.StructFormat {
return .{ .as_map = .{ .key = .custom, .skip_unknown_fields = true } };
}
pub fn msgpackFieldKey(field: std.meta.FieldEnum(@This())) u8 {
return switch (field) {
.name => 1,
.age => 2,
};
}
};It works with every key mode, and with .as_tagged unions. Missing fields are already accepted
without any option, as long as they have a default value or are optional.
Or you can use a completely custom format:
const std = @import("std");
const msgpack = @import("msgpack");
const Message = struct {
items: []u32,
pub fn msgpackWrite(self: Message, packer: anytype) !void {
try packer.writeArray(u32, self.items);
}
pub fn msgpackRead(unpacker: anytype) !Message {
const items = try unpacker.readArray(u32);
return Message{ .items = items };
}
};