authorgravatar for evan@lagerdata.comEvan Haas <evan@lagerdata.com> 2022-02-05 22:18:31-08:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-02-07 12:23:56-07:00
loga8bd36c3d27f0829a1fd9b58b76175e7306a717b
tree91ed90749aa6fc6c783bac1c6612130a6417c4eb
parent2e95bb0e29aa0b058958689607ef5c0d64d31672

std: Allow `mem.zeroes` to work at comptime with extern union

Fixes #10797

2 files changed, 14 insertions(+), 3 deletions(-)

lib/std/mem.zig+4-3
...@@ -308,9 +308,7 @@ pub fn zeroes(comptime T: type) T {...@@ -308,9 +308,7 @@ pub fn zeroes(comptime T: type) T {
308 if (comptime meta.containerLayout(T) == .Extern) {308 if (comptime meta.containerLayout(T) == .Extern) {
309 // The C language specification states that (global) unions309 // The C language specification states that (global) unions
310 // should be zero initialized to the first named member.310 // should be zero initialized to the first named member.
311 var item: T = undefined;311 return @unionInit(T, info.fields[0].name, zeroes(info.fields[0].field_type));
312 @field(item, info.fields[0].name) = zeroes(@TypeOf(@field(item, info.fields[0].name)));
313 return item;
314 }312 }
315313
316 @compileError("Can't set a " ++ @typeName(T) ++ " to zero.");314 @compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
...@@ -416,6 +414,9 @@ test "mem.zeroes" {...@@ -416,6 +414,9 @@ test "mem.zeroes" {
416414
417 var c = zeroes(C_union);415 var c = zeroes(C_union);
418 try testing.expectEqual(@as(u8, 0), c.a);416 try testing.expectEqual(@as(u8, 0), c.a);
417
418 comptime var comptime_union = zeroes(C_union);
419 try testing.expectEqual(@as(u8, 0), comptime_union.a);
419}420}
420421
421/// Initializes all fields of the struct with their default value, or zero values if no default value is present.422/// Initializes all fields of the struct with their default value, or zero values if no default value is present.
test/run_translated_c.zig+10
...@@ -1819,4 +1819,14 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {...@@ -1819,4 +1819,14 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
1819 \\ return 0;1819 \\ return 0;
1820 \\}1820 \\}
1821 , "");1821 , "");
1822
1823 cases.add("Zero-initialization of global union. Issue #10797",
1824 \\#include <stdlib.h>
1825 \\union U { int x; double y; };
1826 \\union U u;
1827 \\int main(void) {
1828 \\ if (u.x != 0) abort();
1829 \\ return 0;
1830 \\}
1831 , "");
1822}1832}