#Enums with additional payload

1 messages · Page 1 of 1 (latest)

glacial quail
#

I want to encode opcode data as a enum with payload. The data I need to store is index and number of arguments.

const RawOp = struct {
    idx: u8,
    name: []const u8,
    n_arg: u8,
};
const rawOps: []const RawOp = &.{
    .{ 1, "add", 2 },
    .{ 2, "sub", 2 },
};

I'd like to do in the code later:

switch(@enumFromInt(ip)) {
    .add => |n_args| {
        const idx = ip;
    },
    .sub => |n_args| ...
}

What's the idiomatic way to do it? Preferably a one where all data is defined in one place.
I could do enum with backing integer for index and store number of args separately but maybe there's a better way.

vivid bone
#

taged unions?

glacial quail
#

I explored them but I want to access all data at all times.

naive tangle
#

maybe try EnumArray

glacial quail
#

I basically looking for a nice mapping to use in a switch.

naive tangle
#

so rawOps is static data you want to map to an enum?

glacial quail
#

Yeah, I'm looking for the ergonomics in the last code block (invalid zig right now).

You get a number, match this number to an enum field and get associated n_args with that enum field.

vivid bone
#

why dont you make idx an enum?

glacial quail
#

What about n_args then?

naive tangle
#

ok, so maybe something like this

const argsFromOp = std.EnumArray(OperatorEnum, u8).init(.{
  .add = 2,
  .sub = 2,
  .ternary = 3,
});
#

you could probably replace name with @tagName

#

youd use it like const n_args = argsFromOp.get(.add);