Skip to content

Commit

Permalink
serialize unions
Browse files Browse the repository at this point in the history
  • Loading branch information
AMythicDev committed Feb 2, 2025
1 parent 0f9216f commit ba83f71
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ This is a top-down LL parser that parses directly into Zig structs.
* [x] Top level tables
* [x] Sub tables
* [x] Pointers
* [x] Date, time, DateTime, time offset
* [x] Enums
* [x] Unions

## Example
See [`example1.zig`](./examples/example1.zig) for the complete code that parses [`example.toml`](./examples/example1.toml)
Expand Down
8 changes: 6 additions & 2 deletions src/serialize/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,12 @@ fn serializeValue(state: *SerializerState, t: std.builtin.Type, value: anytype,
try serializeValue(state, @typeInfo(t.array.child), elm, writer);
try writer.print(" ]", .{});
},
.@"struct" => {
try serializeStruct(state, value, writer);
.@"struct" => try serializeStruct(state, value, writer),
.@"enum" => try writer.print("\"{s}\"", .{@tagName(value)}),
.@"union" => {
switch (value) {
inline else => |s| try serializeValue(state, @typeInfo(@TypeOf(s)), s, writer),
}
},
else => {},
}
Expand Down
32 changes: 32 additions & 0 deletions src/serialize/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,38 @@ test "pointers" {
ba.clear();
}

test "enums" {
const Color = enum {
Red,
Green,
Yellow,
Blue,
Pink,
};

const color = Color.Blue;
var ba = try std.BoundedArray(u8, 16).init(0);
var writer = ba.writer().any();
try serialize(Allocator, color, &writer);
try testing.expectEqualSlices(u8, "\"Blue\"", ba.constSlice());
ba.clear();
}

test "unions" {
const MyUnion = union(enum) {
f1: u8,
f2: u16,
f3: []const u8,
};

const u = MyUnion{ .f1 = 255 };
var ba = try std.BoundedArray(u8, 16).init(0);
var writer = ba.writer().any();
try serialize(Allocator, u, &writer);
try testing.expectEqualSlices(u8, "255", ba.constSlice());
ba.clear();
}

test "strings" {
var ba = try std.BoundedArray(u8, 16).init(0);
var writer = ba.writer().any();
Expand Down

0 comments on commit ba83f71

Please sign in to comment.