From 51367e0c7952419984cf485cdc180b97734a3d70 Mon Sep 17 00:00:00 2001 From: andri lim Date: Wed, 23 Oct 2024 12:05:43 +0700 Subject: [PATCH] Automatic toObjectType for ref or ptr object in useDefault***In (#77) --- serialization/formats.nim | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/serialization/formats.nim b/serialization/formats.nim index c3ed72d..e79ba62 100644 --- a/serialization/formats.nim +++ b/serialization/formats.nim @@ -41,28 +41,46 @@ template createFlavor*(ModifiedFormat, FlavorName: untyped) = template PreferredOutputType*(T: type FlavorName): type = PreferredOutputType(ModifiedFormat) template mimeType*(T: type FlavorName): string = mimeType(ModifiedFormat) +template toObjectType(T: type): untyped = + typeof(T()[]) + +template toObjectTypeIfNecessary(T: type): untyped = + when T is ref|ptr: + toObjectType(T) + else: + T + +# useDefault***In or useDefault***For only works for +# object|ref object|ptr object + template useDefaultSerializationIn*(T: untyped, Flavor: type) = mixin Reader, Writer - template readValue*(r: var Reader(Flavor), value: var T) = + type TT = toObjectTypeIfNecessary(T) + + template readValue*(r: var Reader(Flavor), value: var TT) = mixin readRecordValue readRecordValue(r, value) - template writeValue*(w: var Writer(Flavor), value: T) = + template writeValue*(w: var Writer(Flavor), value: TT) = mixin writeRecordValue writeRecordValue(w, value) template useDefaultWriterIn*(T: untyped, Flavor: type) = mixin Writer - template writeValue*(w: var Writer(Flavor), value: T) = + type TT = toObjectTypeIfNecessary(T) + + template writeValue*(w: var Writer(Flavor), value: TT) = mixin writeRecordValue writeRecordValue(w, value) template useDefaultReaderIn*(T: untyped, Flavor: type) = mixin Reader - template readValue*(r: var Reader(Flavor), value: var T) = + type TT = toObjectTypeIfNecessary(T) + + template readValue*(r: var Reader(Flavor), value: var TT) = mixin readRecordValue readRecordValue(r, value) @@ -83,4 +101,3 @@ macro useDefaultReaderFor*(Flavor: type, types: varargs[untyped])= for T in types: result.add newCall(bindSym "useDefaultReaderIn", T, Flavor) -