return serializer table directly (#74)

This allows it to be captured in a const instead of relying on a
threadvar
This commit is contained in:
Jacek Sieka 2024-09-30 15:09:29 +02:00 committed by GitHub
parent b28eeb6714
commit 7950ac1e8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 9 additions and 12 deletions

View File

@ -251,15 +251,12 @@ proc makeFieldReadersTable(RecordType, ReaderType: distinct type,
result[idx] = (fieldName, readField)
inc idx
proc fieldReadersTable*(RecordType, ReaderType: distinct type): auto =
mixin readValue
template fieldReadersTable*(RecordType, ReaderType: distinct type): auto =
type T = RecordType
const numFields = totalSerializedFields(T)
var tbl {.threadvar.}: ref array[numFields, FieldReader[RecordType, ReaderType]]
if tbl == nil:
tbl = new typeof(tbl)
tbl[] = makeFieldReadersTable(RecordType, ReaderType, numFields)
return addr(tbl[])
makeFieldReadersTable(T, ReaderType, numFields)
template `[]`*(v: FieldReadersTable): FieldReadersTable {.deprecated.} = v
proc findFieldIdx*(fieldsTable: FieldReadersTable,
fieldName: string,

View File

@ -333,14 +333,14 @@ proc executeReaderWriterTests*(Format: type) =
suite(typetraits.name(Format) & " read/write tests"):
test "Low-level field reader test":
let barFields = fieldReadersTable(Bar, ReaderType)
const barFields = fieldReadersTable(Bar, ReaderType)
var idx = 0
var fieldReader = findFieldReader(barFields[], "b", idx)
var fieldReader = findFieldReader(barFields, "b", idx)
check fieldReader != nil and idx == 1
# check that the reader can be found again starting from a higher index
fieldReader = findFieldReader(barFields[], "b", idx)
fieldReader = findFieldReader(barFields, "b", idx)
check fieldReader != nil and idx == 1
var bytes = Format.encode("test")
@ -354,9 +354,9 @@ proc executeReaderWriterTests*(Format: type) =
test "Ignored fields should not be included in the field readers table":
var pos = 0
let bazFields = fieldReadersTable(Baz, ReaderType)
const bazFields = fieldReadersTable(Baz, ReaderType)
check:
len(bazFields[]) == 2
len(bazFields) == 2
findFieldReader(bazFields[], "f", pos) != nil
findFieldReader(bazFields[], "i", pos) != nil
findFieldReader(bazFields[], "i", pos) != nil