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.
|
|
|
|
|
2022-06-16 17:14:00 +03:00
|
|
|
import
|
|
|
|
stew/results, ../../json_serialization/[reader, writer, lexer]
|
|
|
|
|
|
|
|
export
|
|
|
|
results
|
|
|
|
|
2022-06-19 12:38:44 +03:00
|
|
|
template writeObjectField*[T](w: var JsonWriter,
|
|
|
|
record: auto,
|
|
|
|
fieldName: static string,
|
2022-07-15 12:23:35 +02:00
|
|
|
field: Result[T, void]): bool =
|
2022-06-19 12:38:44 +03:00
|
|
|
mixin writeObjectField
|
|
|
|
|
2022-06-16 17:14:00 +03:00
|
|
|
if field.isOk:
|
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*[T](
|
|
|
|
writer: var JsonWriter, value: Result[T, void]) {.raises: [IOError].} =
|
2023-12-19 12:00:24 +02:00
|
|
|
mixin writeValue, flavorOmitsOptionalFields
|
|
|
|
type Flavor = JsonWriter.Flavor
|
2022-06-19 12:38:44 +03:00
|
|
|
|
2022-06-16 17:14:00 +03:00
|
|
|
if value.isOk:
|
|
|
|
writer.writeValue value.get
|
2023-12-19 12:00:24 +02:00
|
|
|
elif not flavorOmitsOptionalFields(Flavor):
|
2022-06-16 17:14:00 +03:00
|
|
|
writer.writeValue JsonString("null")
|
|
|
|
|
|
|
|
proc readValue*[T](reader: var JsonReader, value: var Result[T, void]) =
|
2022-06-19 12:38:44 +03:00
|
|
|
mixin readValue
|
|
|
|
|
2023-12-18 11:05:12 +07:00
|
|
|
if reader.tokKind == JsonValueKind.Null:
|
2022-06-16 17:14:00 +03:00
|
|
|
reset value
|
2023-12-18 11:05:12 +07:00
|
|
|
reader.parseNull()
|
2022-06-16 17:14:00 +03:00
|
|
|
else:
|
|
|
|
value.ok reader.readValue(T)
|
2022-07-14 15:14:10 +03:00
|
|
|
|
|
|
|
func isFieldExpected*[T, E](_: type[Result[T, E]]): bool {.compileTime.} =
|
|
|
|
false
|