#send a zig struct over the wire
1 messages · Page 1 of 1 (latest)
plain structs have no defined layout, extern structs are laid out in declaration order and will follow alignment rules for fields, packed structs are laid out in an integer, with no padding, in declaration order, starting at the least significant bit
Practically speaking, you'd want a serialization/deserialization library.
Does one exist or would I need to write one?
There's a couple of json libraries (including one in the stdlib)
There's also a protobuff library, which is usually more efficient (tho the Zig one is still new, so...)
If you're talking to a web browser, probably better to go with json serialization
Cool!
This is a pretty specific question but is it hard to convert stringified json to a struct?
I haven’t really found a way to convert a number into its string representation and That would be needed when converting a struct into stringified json
std.json has both encode & decode functions.
stringify() uses std.fmt.formatIntValue to convert integers into strings, and std.fmt.parseInt the other way.
Is there a wait to go back and forth for floats?
parseFloat for string -> float
formatFloatDecimal for float -> string
Note that the format* family of functions will print it to a Writer. So you'd want one of the buffer types with a write function.
If I'm not mistaken you can also just write align(1) next to each struct field to mimic packed struct from C
And don't forget to declare zig struct as extern struct because it guarantees that compiler wouldn't do any tricks with moving fields out of original order
I haven't tried it myself but https://github.com/Arwalk/zig-protobuf may be useful though it's WIP
@lofty hull what is a Writer?
Pretty much any type with a write function (see io.Writer for an example)