Avoid overloading the separate classes of writeField ops

This commit is contained in:
Zahary Karadjov 2022-06-19 12:38:44 +03:00
parent 95399caff3
commit bedbe6595a
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
3 changed files with 23 additions and 17 deletions

View File

@ -1,14 +1,14 @@
import std/options, ../../json_serialization/[reader, writer, lexer]
export options
template writeField*(w: var JsonWriter,
record: auto,
fieldName: static string,
field: Option) =
mixin writeField
template writeObjectField*(w: var JsonWriter,
record: auto,
fieldName: static string,
field: Option) =
mixin writeObjectField
if field.isSome:
writeField(w, record, fieldName, field.get)
writeObjectField(w, record, fieldName, field.get)
proc writeValue*(writer: var JsonWriter, value: Option) =
mixin writeValue

View File

@ -4,20 +4,26 @@ import
export
results
template writeField*[T](w: var JsonWriter,
record: auto,
fieldName: static string,
field: Result[T, void]) =
template writeObjectField*[T](w: var JsonWriter,
record: auto,
fieldName: static string,
field: Result[T, void]) =
mixin writeObjectField
if field.isOk:
writeField(w, record, fieldName, field.get)
writeObjectField(w, record, fieldName, field.get)
proc writeValue*[T](writer: var JsonWriter, value: Result[T, void]) =
mixin writeValue
if value.isOk:
writer.writeValue value.get
else:
writer.writeValue JsonString("null")
proc readValue*[T](reader: var JsonReader, value: var Result[T, void]) =
mixin readValue
let tok = reader.lexer.lazyTok
if tok == tkNull:
reset value

View File

@ -145,10 +145,10 @@ template isStringLike(v: string|cstring|openArray[char]|seq[char]): bool = true
template isStringLike[N](v: array[N, char]): bool = true
template isStringLike(v: auto): bool = false
template writeField*[FieldType, RecordType](w: var JsonWriter,
record: RecordType,
fieldName: static string,
field: FieldType) =
template writeObjectField*[FieldType, RecordType](w: var JsonWriter,
record: RecordType,
fieldName: static string,
field: FieldType) =
mixin writeFieldIMPL, writeValue
type
@ -237,8 +237,8 @@ proc writeValue*(w: var JsonWriter, value: auto) =
type RecordType = type value
w.beginRecord RecordType
value.enumInstanceSerializedFields(fieldName, field):
mixin writeField
writeField(w, value, fieldName, field)
mixin writeObjectField
writeObjectField(w, value, fieldName, field)
w.state = AfterField
w.endRecord()