From dc80309ad88d5d2e7844cf59fb85e2dd3c18b926 Mon Sep 17 00:00:00 2001 From: Hila Friedman Date: Tue, 3 Dec 2024 17:42:17 +0200 Subject: [PATCH 1/3] std.meta.hasUniqueRepresentation to handle structs with comptime fields --- lib/std/meta.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/std/meta.zig b/lib/std/meta.zig index 44bfb65f8a04..d6bb72fa7fd4 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -1217,10 +1217,10 @@ pub inline fn hasUniqueRepresentation(comptime T: type) bool { var sum_size = @as(usize, 0); - inline for (info.fields) |field| { + inline for (info.fields) |field| if (!field.is_comptime) { if (!hasUniqueRepresentation(field.type)) return false; sum_size += @sizeOf(field.type); - } + }; return @sizeOf(T) == sum_size; }, From dc248892bf6aaaf55eeaaddc0723d6d6ad71f87e Mon Sep 17 00:00:00 2001 From: Hila Friedman Date: Tue, 3 Dec 2024 17:51:15 +0200 Subject: [PATCH 2/3] add tests --- lib/std/meta.zig | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/std/meta.zig b/lib/std/meta.zig index d6bb72fa7fd4..bf0bff0de628 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -1320,4 +1320,12 @@ test hasUniqueRepresentation { try testing.expect(hasUniqueRepresentation(@Vector(std.simd.suggestVectorLength(u8) orelse 1, u8))); try testing.expect(@sizeOf(@Vector(3, u8)) == 3 or !hasUniqueRepresentation(@Vector(3, u8))); + + const StructWithComptimeFields = struct { + comptime should_be_ignored: u64 = 42, + comptime should_also_be_ignored: [*:0]const u8 = "hope you're having a good day :)", + field: u32, + }; + + try testing.expect(hasUniqueRepresentation(StructWithComptimeFields)); } From 795c4992d9e28c79c6682cc9b1fd88045e44b348 Mon Sep 17 00:00:00 2001 From: Hila Friedman Date: Wed, 4 Dec 2024 06:23:18 +0200 Subject: [PATCH 3/3] Change wrapping if to guard clause --- lib/std/meta.zig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/std/meta.zig b/lib/std/meta.zig index bf0bff0de628..3983aadd7ec9 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -1217,10 +1217,11 @@ pub inline fn hasUniqueRepresentation(comptime T: type) bool { var sum_size = @as(usize, 0); - inline for (info.fields) |field| if (!field.is_comptime) { + inline for (info.fields) |field| { + if (field.is_comptime) continue; if (!hasUniqueRepresentation(field.type)) return false; sum_size += @sizeOf(field.type); - }; + } return @sizeOf(T) == sum_size; },