zig-toml icon indicating copy to clipboard operation
zig-toml copied to clipboard

[Feature] Deserializing unions

Open Daru-san opened this issue 3 months ago • 4 comments

Hello. I am putting together a configuration struct that has a union value as an option.

So far, deserializing enums does not work. Like in the example below.

const Direction = enum {
    Left,
    Right,
};

const Action = enum(union) {
     Walk: Direction,
     Jump: u32,
     Speak: []const u8,
};

I found that serializing unions is possible, but deserializing is not as it isn't handled currently.

Could this feature be implemented? Thank you.

Daru-san avatar Nov 15 '25 23:11 Daru-san

Great call out. Sure, I'll look into it.

sam701 avatar Nov 16 '25 09:11 sam701

It's not just a single way how to represent tagged unions. Here is how Rust handles that: https://serde.rs/enum-representations.html

sam701 avatar Nov 16 '25 20:11 sam701

I see. I have attempted to put together a union parsing strategy, similar to the externally tagged representation. It does not deal with fields that aren't found though, in that case it would return an invalid union value, but I have an idea of how to prevent that.

https://github.com/sam701/zig-toml/compare/zig-0.15...Daru-san:zig-toml:zig-0.15?expand=1

Daru-san avatar Nov 17 '25 14:11 Daru-san

I’m short on time now, but I’ll try to look into this week.

sam701 avatar Nov 18 '25 09:11 sam701

@Daru-san thanks a bunch for your patch!! I slightly adjusted the test and fixed the union serialization. I've pushed the changes to the main branch that tracks zig-master.

sam701 avatar Nov 23 '25 15:11 sam701