From 75ed8e5be49e71d84e82a9524e910d4475e4b0d4 Mon Sep 17 00:00:00 2001 From: quantimnot <54247259+quantimnot@users.noreply.github.com> Date: Fri, 22 Oct 2021 11:54:40 -0400 Subject: [PATCH] Change serialization to omit `none(T)` fields of sparse objects (#100) * Change serialization to omit `none(T)` fields of sparse objects Co-authored-by: quantimnot --- yaml/annotations.nim | 5 +++-- yaml/serialization.nim | 7 ++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/yaml/annotations.nim b/yaml/annotations.nim index c89f770..cf3128f 100644 --- a/yaml/annotations.nim +++ b/yaml/annotations.nim @@ -27,7 +27,8 @@ template sparse*() {.pragma.} ## This annotation can be put on an object type. During deserialization, ## the input may omit any field that has an ``Option[T]`` type (for any ## concrete ``T``) and that field will be treated as if it had the annotation - ## ``{.defaultVal: none(T).}``. + ## ``{.defaultVal: none(T).}``. Fields of ``none(T)`` value are omitted + ## during serialization. ## ## Example usage: ## @@ -80,4 +81,4 @@ template implicit*() {.pragma.} ## of ckString: ## strVal: string ## of ckInt: - ## intVal: int \ No newline at end of file + ## intVal: int diff --git a/yaml/serialization.nim b/yaml/serialization.nim index 2885db6..d9b9d88 100644 --- a/yaml/serialization.nim +++ b/yaml/serialization.nim @@ -967,12 +967,17 @@ macro genRepresentObject(t: typedesc, value, childTagStyle: typed) = name = $child childAccessor = newDotExpr(value, newIdentNode(name)) result.add(quote do: - when not `childAccessor`.hasCustomPragma(transient): + template serializeImpl = when bool(`isVO`): c.put(startMapEvent()) c.put(scalarEvent(`name`, if `childTagStyle` == tsNone: yTagQuestionMark else: yTagNimField, yAnchorNone)) representChild(`childAccessor`, `childTagStyle`, c) when bool(`isVO`): c.put(endMapEvent()) + when not `childAccessor`.hasCustomPragma(transient): + when hasSparse(`t`) and `child` is Option: + if `childAccessor`.isSome: serializeImpl() + else: + serializeImpl() ) inc(fieldIndex)