From 1188da926ff4cddd5818d85d45b087f6207dfef9 Mon Sep 17 00:00:00 2001 From: tgschultz Date: Sun, 9 Dec 2018 20:52:16 -0600 Subject: [PATCH] Minor change to custom (de)serializer to allow them to be defined outside of the struct and aliased inside it. This will enable alternate generic serializers (i.e. one that follows pointers) on a struct-by-struct basis. --- std/io.zig | 6 +++--- std/io_test.zig | 10 +++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/std/io.zig b/std/io.zig index 5f710a5033..c397ff6ede 100644 --- a/std/io.zig +++ b/std/io.zig @@ -1146,7 +1146,7 @@ pub fn Deserializer(endian: builtin.Endian, is_packed: bool, comptime Error: typ const child_type_id = @typeId(C); //custom deserializer: fn(self: *Self, deserializer: var) !void - if (comptime trait.hasFn("deserialize")(C)) return ptr.deserialize(self); + if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self); if (comptime trait.isPacked(C) and !is_packed) { var packed_deserializer = Deserializer(endian, true, Error).init(self.in_stream); @@ -1308,8 +1308,8 @@ pub fn Serializer(endian: builtin.Endian, is_packed: bool, comptime Error: type) return; } - //custom serializer: fn(self: *const Self, serializer: var) !void - if (comptime trait.hasFn("serialize")(T)) return value.serialize(self); + //custom serializer: fn(self: Self, serializer: var) !void + if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self); if (comptime trait.isPacked(T) and !is_packed) { var packed_serializer = Serializer(endian, true, Error).init(self.out_stream); diff --git a/std/io_test.zig b/std/io_test.zig index 71d46b0874..0bee0ddaf0 100644 --- a/std/io_test.zig +++ b/std/io_test.zig @@ -416,6 +416,10 @@ test "Serializer/Deserializer Int: Inf/NaN" { try testIntSerializerDeserializerInfNaN(builtin.Endian.Little, true); } +fn testAlternateSerializer(self: var, serializer: var) !void { + try serializer.serialize(self.f_f16); +} + fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime is_packed: bool) !void { const ColorType = enum(u4) { RGB8 = 1, @@ -448,6 +452,8 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime is_packe f_u2: u2, }; + + //to test custom serialization const Custom = struct { f_f16: f16, @@ -458,9 +464,7 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime is_packe self.f_unused_u32 = 47; } - pub fn serialize(self: *const @This(), serializer: var) !void { - try serializer.serialize(self.f_f16); - } + pub const serialize = testAlternateSerializer; }; const MyStruct = struct {