lib: add a TaggedUnion helper to create C ABI compatible tagged unions

This commit is contained in:
Mitchell Hashimoto
2025-10-23 14:03:34 -07:00
parent fb5b8d7968
commit 099dcbe04d
6 changed files with 214 additions and 6 deletions

31
src/lib/struct.zig Normal file
View File

@@ -0,0 +1,31 @@
const std = @import("std");
const Target = @import("target.zig").Target;
pub fn Struct(
comptime target: Target,
comptime Zig: type,
) type {
return switch (target) {
.zig => Zig,
.c => c: {
const info = @typeInfo(Zig).@"struct";
var fields: [info.fields.len]std.builtin.Type.StructField = undefined;
for (info.fields, 0..) |field, i| {
fields[i] = .{
.name = field.name,
.type = field.type,
.default_value_ptr = field.default_value_ptr,
.is_comptime = field.is_comptime,
.alignment = field.alignment,
};
}
break :c @Type(.{ .@"struct" = .{
.layout = .@"extern",
.fields = &fields,
.decls = &.{},
.is_tuple = info.is_tuple,
} });
},
};
}