| ... | ... | @@ -709,6 +709,14 @@ pub fn zeroInit(comptime T: type, init: anytype) T { |
| 709 | 709 | .Struct => |init_info| { |
| 710 | 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 | 720 | inline for (init_info.fields) |field| { |
| 713 | 721 | if (!@hasField(T, field.name)) { |
| 714 | 722 | @compileError("Encountered an initializer for `" ++ field.name ++ "`, but it is not a field of " ++ @typeName(T)); |
| ... | ... | @@ -760,7 +768,7 @@ test "zeroInit" { |
| 760 | 768 | .a = 42, |
| 761 | 769 | }); |
| 762 | 770 | |
| 763 | | testing.expectEqual(s, S{ |
| 771 | testing.expectEqual(S{ |
| 764 | 772 | .a = 42, |
| 765 | 773 | .b = null, |
| 766 | 774 | .c = .{ |
| ... | ... | @@ -768,7 +776,22 @@ test "zeroInit" { |
| 768 | 776 | }, |
| 769 | 777 | .e = [3]u8{ 0, 0, 0 }, |
| 770 | 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 | 797 | /// Compares two slices of numbers lexicographically. O(n). |