From 0ffeec4b4d3c0321cac618557e829571fa997881 Mon Sep 17 00:00:00 2001 From: rohlem Date: Tue, 18 Jun 2024 19:04:16 +0200 Subject: [PATCH] fix std.meta.eql for comptime-only union switch from `inline for` with `std.mem.eql` to `inline else` and tag comparison. add previously-failing test code. --- lib/std/meta.zig | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/std/meta.zig b/lib/std/meta.zig index 0fff0aed3c..85eb6cd4d3 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -757,16 +757,13 @@ pub fn eql(a: anytype, b: @TypeOf(a)) bool { }, .Union => |info| { if (info.tag_type) |UnionTag| { - const tag_a = activeTag(a); - const tag_b = activeTag(b); + const tag_a: UnionTag = a; + const tag_b: UnionTag = b; if (tag_a != tag_b) return false; - inline for (info.fields) |field_info| { - if (@field(UnionTag, field_info.name) == tag_a) { - return eql(@field(a, field_info.name), @field(b, field_info.name)); - } - } - return false; + return switch (a) { + inline else => |val, tag| return eql(val, @field(b, @tagName(tag))), + }; } @compileError("cannot compare untagged union type " ++ @typeName(T)); @@ -858,6 +855,15 @@ test eql { try testing.expect(eql(v1, v2)); try testing.expect(!eql(v1, v3)); + + const CU = union(enum) { + a: void, + b: void, + c: comptime_int, + }; + + try testing.expect(eql(CU{ .a = {} }, .a)); + try testing.expect(!eql(CU{ .a = {} }, .b)); } test intToEnum {