| ... | @@ -709,6 +709,14 @@ pub fn zeroInit(comptime T: type, init: anytype) T { | ... | @@ -709,6 +709,14 @@ pub fn zeroInit(comptime T: type, init: anytype) T { |
| 709 | .Struct => |init_info| { | 709 | .Struct => |init_info| { |
| 710 | var value = std.mem.zeroes(T); | 710 | var value = std.mem.zeroes(T); |
| 711 | | 711 | |
| | 712 | // typeInfo won't tell us if this is a tuple |
| | 713 | if (comptime eql(u8, init_info.fields[0].name, "0")) { |
| | 714 | inline for (init_info.fields) |field, i| { |
| | 715 | @field(value, struct_info.fields[i].name) = @field(init, field.name); |
| | 716 | } |
| | 717 | return value; |
| | 718 | } |
| | 719 | |
| 712 | inline for (init_info.fields) |field| { | 720 | inline for (init_info.fields) |field| { |
| 713 | if (!@hasField(T, field.name)) { | 721 | if (!@hasField(T, field.name)) { |
| 714 | @compileError("Encountered an initializer for `" ++ field.name ++ "`, but it is not a field of " ++ @typeName(T)); | 722 | @compileError("Encountered an initializer for `" ++ field.name ++ "`, but it is not a field of " ++ @typeName(T)); |
| ... | @@ -760,7 +768,7 @@ test "zeroInit" { | ... | @@ -760,7 +768,7 @@ test "zeroInit" { |
| 760 | .a = 42, | 768 | .a = 42, |
| 761 | }); | 769 | }); |
| 762 | | 770 | |
| 763 | testing.expectEqual(s, S{ | 771 | testing.expectEqual(S{ |
| 764 | .a = 42, | 772 | .a = 42, |
| 765 | .b = null, | 773 | .b = null, |
| 766 | .c = .{ | 774 | .c = .{ |
| ... | @@ -768,7 +776,22 @@ test "zeroInit" { | ... | @@ -768,7 +776,22 @@ test "zeroInit" { |
| 768 | }, | 776 | }, |
| 769 | .e = [3]u8{ 0, 0, 0 }, | 777 | .e = [3]u8{ 0, 0, 0 }, |
| 770 | .f = -1, | 778 | .f = -1, |
| 771 | }); | 779 | }, s); |
| | 780 | |
| | 781 | const Color = struct { |
| | 782 | r: u8, |
| | 783 | g: u8, |
| | 784 | b: u8, |
| | 785 | a: u8, |
| | 786 | }; |
| | 787 | |
| | 788 | const c = zeroInit(Color, .{255, 255}); |
| | 789 | testing.expectEqual(Color{ |
| | 790 | .r = 255, |
| | 791 | .g = 255, |
| | 792 | .b = 0, |
| | 793 | .a = 0, |
| | 794 | }, c); |
| 772 | } | 795 | } |
| 773 | | 796 | |
| 774 | /// Compares two slices of numbers lexicographically. O(n). | 797 | /// Compares two slices of numbers lexicographically. O(n). |