I’ve been working on a lightweight database/kernel of sorts, and I’ve really come to enjoy the semantics of payload captures in switch statements on tagged unions. The only thing that makes me a bit sad is that I don’t think Zig supports like auto layout awareness outside the type’s scope so Cmd goes from ideal 16 bytes to 20, and Resp goes from ideal 8 bytes to 12.
I know that if the compiler tried to do this without any help, a new child struct that contains the parent would create a dependency mess and incremental compilation and complexity would blow up, but I was thinking, what if there was an inline keyword in the subfield to say “hey, this struct and its child are 1:1 correlated and optimize them together”, which keeps the problem scoped well.
I know this is a help request (I just joined Ziggit, so I don’t have Brainstorm perms), but I was just thinking that this would be super nice to have or maybe there is already some way to do it I’m not quite sure.
EDIT: We were discussing this on the Zig discord, and I wanted to clarify that tag is not the enum tag, it’s like inflight number used so I can support asynchrounous commands and batching, kinda like io_uring user_data field.
What I’m thinking is something along the lines of: action: inline union(enum(u8))
pub const Cmd = struct {
tag: u8,
action: union(enum(u8)) {
alloc,
alloc_mult: u16,
free: mem.PageId,
free_mult: mem.PageId,
read: struct { table: Table, key: u32 },
modify: struct { table: Table, key: u32, page: mem.PageId },
append: struct { table: Table, page: mem.PageId },
},
};
pub const Resp = struct {
tag: u8,
action: union(enum(u8)) {
alloc: mem.PageId,
alloc_mult: mem.PageId,
free,
free_mult,
read: mem.PageId,
modify,
append: u32, // key
},
};
comptime {
@compileLog("", @sizeOf(Table)); // 1
@compileLog("", @sizeOf(mem.PageId)); // 4
@compileLog("", @sizeOf(Cmd)); // 20
@compileLog("", @sizeOf(Resp)); // 12
}