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 <quantimnot@users.noreply.github.com>
This commit is contained in:
quantimnot 2021-10-22 11:54:40 -04:00 committed by GitHub
parent d704a8c6d7
commit 75ed8e5be4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 3 deletions

View File

@ -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:
##

View File

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