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.

This commit is contained in:
tgschultz 2018-12-09 20:52:16 -06:00
parent 8423bd423b
commit 1188da926f
2 changed files with 10 additions and 6 deletions

View File

@ -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);

View File

@ -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 {