authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-07-16 16:00:42+03:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-07-16 16:00:42+03:00
log8fe076daaf182863d116f2be7b13e3743bbcaae3
treeff713a0d78b80668d7c9066b9810efcbbc8db6d0
parent01ab167ce3c5c0db908b11451f160359230a440f
signaturelock-open Commit is signed but in an unrecognized format.

std.mem.zeroInit support initiating with tuples


1 files changed, 25 insertions(+), 2 deletions(-)

lib/std/mem.zig+25-2
...@@ -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);
711711
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 });
762770
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}
773796
774/// Compares two slices of numbers lexicographically. O(n).797/// Compares two slices of numbers lexicographically. O(n).