authorgravatar for evan@lagerdata.comEvan Haas <evan@lagerdata.com> 2022-02-05 22:18:31-08:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2022-02-07 11:34:20+02:00
loge382e7be2b7a4c40a8db78dca0de38141dad8c67
treece716c94b22473d51781ce929625fff4ecd49236
parent435beb4e1dec117136ef9541530ebd3e70c2319d

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
......@@ -309,9 +309,7 @@ pub fn zeroes(comptime T: type) T {
309309 if (comptime meta.containerLayout(T) == .Extern) {
310310 // The C language specification states that (global) unions
311311 // should be zero initialized to the first named member.
312 var item: T = undefined;
313 @field(item, info.fields[0].name) = zeroes(@TypeOf(@field(item, info.fields[0].name)));
314 return item;
312 return @unionInit(T, info.fields[0].name, zeroes(info.fields[0].field_type));
315313 }
316314
317315 @compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
......@@ -417,6 +415,9 @@ test "mem.zeroes" {
417415
418416 var c = zeroes(C_union);
419417 try testing.expectEqual(@as(u8, 0), c.a);
418
419 comptime var comptime_union = zeroes(C_union);
420 try testing.expectEqual(@as(u8, 0), comptime_union.a);
420421}
421422
422423/// 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 {
18191819 \\ return 0;
18201820 \\}
18211821 , "");
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 , "");
18221832}