authorgravatar for mason@gamesbymason.comMason Remaley <mason@gamesbymason.com> 2026-06-23 23:21:25-07:00
committergravatar for mason@gamesbymason.comMason Remaley <mason@gamesbymason.com> 2026-06-24 22:11:49-07:00
log87860e80b4859b54f846ae26c61ae09ad9803322
tree8ae21d9c382ed7d486e5e4928162fb51ebae61a3
parente4f46e7e7ac63d87319189f130629074e366164d

Adds unions support to `hasUniqueRepresentation`


1 files changed, 30 insertions(+), 0 deletions(-)

lib/std/meta.zig+30
......@@ -900,6 +900,15 @@ pub inline fn hasUniqueRepresentation(comptime T: type) bool {
900900 return @sizeOf(T) == sum_size;
901901 },
902902
903 .@"union" => |info| {
904 if (info.layout == .@"packed") return @sizeOf(T) * 8 == @bitSizeOf(T);
905 inline for (info.field_types) |field_type| {
906 if (@sizeOf(field_type) != @sizeOf(T)) return false;
907 if (!hasUniqueRepresentation(field_type)) return false;
908 }
909 return true;
910 },
911
903912 .vector => |info| hasUniqueRepresentation(info.child) and
904913 @sizeOf(T) == @sizeOf(info.child) * info.len,
905914 };
......@@ -969,6 +978,27 @@ test hasUniqueRepresentation {
969978
970979 try testing.expect(!hasUniqueRepresentation(TestUnion4));
971980
981 const TestUnion5 = extern union {
982 a: u32,
983 b: i32,
984 };
985
986 try testing.expect(hasUniqueRepresentation(TestUnion5));
987
988 const TestUnion6 = packed union(u7) {
989 a: u7,
990 b: i7,
991 };
992
993 try testing.expect(!hasUniqueRepresentation(TestUnion6));
994
995 const TestUnion7 = packed union(u8) {
996 a: u8,
997 b: i8,
998 };
999
1000 try testing.expect(hasUniqueRepresentation(TestUnion7));
1001
9721002 inline for ([_]type{ u8, i16, u32, i64 }) |T| {
9731003 try testing.expect(hasUniqueRepresentation(T));
9741004 try testing.expect(hasUniqueRepresentation(enum(T) { _ }));