pass through any reader init params in the decode/load procs

This commit is contained in:
Zahary Karadjov 2019-01-21 19:39:18 +02:00
parent 65184697ff
commit b4216704f3
1 changed files with 29 additions and 14 deletions

View File

@ -45,30 +45,45 @@ proc readValue*(reader: var auto, T: type): T =
mixin readValue mixin readValue
reader.readValue(result) reader.readValue(result)
proc readValueFromStream(Format: distinct type,
stream: ByteStream,
RecordType: distinct type): RecordType =
mixin init, ReaderType
var reader = init(ReaderType(Format), stream)
reader.readValue(RecordType)
template decode*(Format: distinct type, template decode*(Format: distinct type,
input: openarray[byte] | string, input: openarray[byte] | string,
RecordType: distinct type): auto = RecordType: distinct type,
params: varargs[untyped]): auto =
mixin init, ReaderType
var stream = memoryStream(input) var stream = memoryStream(input)
readValueFromStream(Format, stream, RecordType)
# TODO:
# Remove this when statement once the following bug is fixed:
# https://github.com/nim-lang/Nim/issues/9996
when astToStr(params) != "":
var reader = init(ReaderType(Format), stream, params)
else:
var reader = init(ReaderType(Format), stream)
reader.readValue(RecordType)
template loadFile*(Format: distinct type, template loadFile*(Format: distinct type,
filename: string, filename: string,
RecordType: distinct type): auto = RecordType: distinct type,
params: varargs[untyped]): auto =
mixin init, ReaderType
var stream = openFile(filename) var stream = openFile(filename)
readValueFromStream(Format, stream, RecordType)
# TODO:
# Remove this when statement once the following bug is fixed:
# https://github.com/nim-lang/Nim/issues/9996
when astToStr(params) != "":
var reader = init(ReaderType(Format), stream, params)
else:
var reader = init(ReaderType(Format), stream)
reader.readValue(RecordType)
template loadFile*[RecordType](Format: type, template loadFile*[RecordType](Format: type,
filename: string, filename: string,
record: var RecordType) = record: var RecordType,
var stream = openFile(filename) params: varargs[untyped]) =
record = readValueFromStream(Format, stream, type(record)) record = loadFile(Format, filename, RecordType, params)
template saveFile*(Format: type, filename: string, args: varargs[untyped]) = template saveFile*(Format: type, filename: string, args: varargs[untyped]) =
# TODO: This should use a proper output stream, instead of calling `encode` # TODO: This should use a proper output stream, instead of calling `encode`