#Combine two enums during comptime

1 messages · Page 1 of 1 (latest)

karmic tapir
#

Is there any function from std that is used to combine enums during comptime?

slender cobalt
#

nothing in std, no

#

pretty easy to write though

karmic tapir
#

That was my hunch, working on an implementation.

#

@slender cobalt Btw, do you know if enum entries are allowed to hold the same value this would be valid, why?

const foo = enum(u8) {
  bar = 255,
  BAR = 255,
}
slender cobalt
#

no, that is not valid

#

enum fields must have unique values

karmic tapir
#

Ok error shows when I run, not with zls.

slender cobalt
#

zls doesn't show compile errors, only ast-check errors

blissful marsh
#

I made some notes for the combine_enums.zig file you posted in #zig yesterday.

  • at comptime use @compileError instead of returning an error
  • don't need to hash names, the compiler will make sure they're unique
  • non exhaustive (is_exhaustive == false) means the enum can have non-named values. just set it to true indicating that the resulting enum can't have unnamed values.
  • instead of main() with asserts, use a test block with std.testing.expectEqualStrings for field names and std.testing.expectEqual for values
  • use if instead of switch for simple greater than comparison
    if (len > 255) @compileError("Supports up to 255 for combined field lengths.");
    var fields: [len]std.builtin.Type.EnumField = undefined;
    @memcpy(fields[0..a_fields.len], a_fields);
    for (0..b_fields.len) |i| {
        fields[a_fields.len + i] = .{ .name = b_fields[i].name, .value = a_fields.len + i };
    }

    return @Type(.{ .Enum = .{
        .tag_type = u8,
        .fields = &fields,
        .decls = &.{},
        .is_exhaustive = true,
    } });
blissful marsh
#

@karmic tapir ☝️

karmic tapir
#

@blissful marsh I sent you the file I have been working on, I wish for feedback whenever you have time over.

blissful marsh
karmic tapir
#

right

blissful marsh
#

i still don't see any reason for hashing. just search previously assigned fields.

#

also, decls must always be empty so no reason for that code.

karmic tapir
#

ok I will improve it

blissful marsh
#

other than that, looks ok.

#

compiler won't allow duplicate values so code that compares values isn't necessary either.

karmic tapir
#

Will it the compiler auto increment from 0 those who are not overridden, do you know?

#

I will test