2023-12-13 16:07:57 +07:00
|
|
|
# json-serialization
|
|
|
|
# Copyright (c) 2019-2023 Status Research & Development GmbH
|
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
# at your option.
|
|
|
|
# This file may not be copied, modified, or distributed except according to
|
|
|
|
# those terms.
|
|
|
|
|
2019-06-24 17:38:37 +03:00
|
|
|
import std/options, ../../json_serialization/[reader, writer, lexer]
|
|
|
|
export options
|
|
|
|
|
2022-06-19 12:38:44 +03:00
|
|
|
template writeObjectField*(w: var JsonWriter,
|
|
|
|
record: auto,
|
|
|
|
fieldName: static string,
|
2022-07-15 12:23:35 +02:00
|
|
|
field: Option): bool =
|
2022-06-19 12:38:44 +03:00
|
|
|
mixin writeObjectField
|
2022-06-18 13:34:04 +03:00
|
|
|
|
2022-06-16 17:14:00 +03:00
|
|
|
if field.isSome:
|
2022-06-19 12:38:44 +03:00
|
|
|
writeObjectField(w, record, fieldName, field.get)
|
2022-07-15 12:23:35 +02:00
|
|
|
else:
|
|
|
|
false
|
2022-06-16 17:14:00 +03:00
|
|
|
|
2023-08-19 13:47:32 +02:00
|
|
|
proc writeValue*(writer: var JsonWriter, value: Option) {.raises: [IOError].} =
|
2023-12-19 12:00:24 +02:00
|
|
|
mixin writeValue, flavorOmitsOptionalFields
|
|
|
|
type Flavor = JsonWriter.Flavor
|
2022-06-18 13:34:04 +03:00
|
|
|
|
2019-06-24 17:38:37 +03:00
|
|
|
if value.isSome:
|
|
|
|
writer.writeValue value.get
|
2023-12-19 12:00:24 +02:00
|
|
|
elif not flavorOmitsOptionalFields(Flavor):
|
2019-06-24 17:38:37 +03:00
|
|
|
writer.writeValue JsonString("null")
|
|
|
|
|
|
|
|
proc readValue*[T](reader: var JsonReader, value: var Option[T]) =
|
2022-06-18 13:34:04 +03:00
|
|
|
mixin readValue
|
|
|
|
|
2022-05-05 17:33:40 +01:00
|
|
|
let tok = reader.lexer.lazyTok
|
2019-06-24 17:38:37 +03:00
|
|
|
if tok == tkNull:
|
|
|
|
reset value
|
|
|
|
reader.lexer.next()
|
|
|
|
else:
|
|
|
|
value = some reader.readValue(T)
|