Skip to content

Commit

Permalink
Add support for optional sequences and arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
zah committed Mar 14, 2023
1 parent b189c10 commit 86d4771
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
11 changes: 6 additions & 5 deletions toml_serialization/private/array_reader.nim
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ const

proc totalArrayFieldsImpl(T: type): int =
mixin enumAllSerializedFields

enumAllSerializedFields(T):
when FieldType is (seq or array):
when isArrayLike(FieldType):
inc result

template totalArrayFields*(T: type): int =
Expand All @@ -36,9 +37,9 @@ proc makeArrayReadersTable(RecordType, Reader: distinct type, L: static[int]):
array[L, ArrayReader[RecordType, Reader]] =
var fieldPos = 0
enumAllSerializedFields(RecordType):
when FieldType is (seq or array):
proc readArray(obj: var RecordType, reader: var Reader, idx: int)
{.gcsafe, nimcall, raises: [SerializationError, Defect].} =
when isArrayLike(FieldType):
proc readArrayFieldImpl(obj: var RecordType, reader: var Reader, idx: int)
{.gcsafe, nimcall, raises: [SerializationError, Defect].} =
mixin readValue

when RecordType is tuple:
Expand All @@ -59,7 +60,7 @@ proc makeArrayReadersTable(RecordType, Reader: distinct type, L: static[int]):
when RecordType is tuple: obj[i] else: field(obj, realFieldName),
err)

result[fieldPos] = (0, fieldName, readArray)
result[fieldPos] = (0, fieldName, readArrayFieldImpl)
inc fieldPos

template arrayReadersTable*(RecordType, Reader: distinct type): auto =
Expand Down
4 changes: 4 additions & 0 deletions toml_serialization/reader.nim
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ proc readValue*[T](r: var TomlReader, value: var T, numRead: int)
readValue(r, value[numRead])
elif T is array:
readValue(r, value[numRead])
elif isOptionalInToml(T):
if value.isNone:
value = some default(typeof(value.get))
readValue(r, value.get, numRead)
else:
const typeName = typetraits.name(T)
{.error: "Failed to convert from TOML an unsupported type: " & typeName.}
Expand Down
15 changes: 15 additions & 0 deletions toml_serialization/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,21 @@ type
of TomlKind.Table, TomlKind.InlineTable:
tableVal*: TomlTableRef

template isOptionalInToml*(T: type): bool = false
template isOptionalInToml*[X](T: type Option[X]): bool = true

template BaseType*[X](T: type Option[X]): type = X

template isArrayLike*(T: type): bool =
mixin isOptionalInToml, BaseType

when T is seq|array:
true
elif isOptionalInToml(T):
BaseType(T) is seq|array
else:
false

when tomlOrderedTable:
template withValue*(x: TomlTable, key: string,
value, body1, body2: untyped) =
Expand Down

0 comments on commit 86d4771

Please sign in to comment.