Hi, I was hoping that someone might help me with this.
Is there a smart way to iterate through a custom structured type and the determine the size of each of its elements?
In practice, what I need to do is this: I have defined a rather big custom structured type which is going to hold data loaded from an external file. Depending on the OS endianess, I might have to change the byte order of its elements — this being the reason why I need to find a way to determine the byte size of each element.
Ideally, I'd like to implement endianess correction with a loop of some kind, instead of having to manually fix the bytes of each element of the structured type, one after the other, which would result in a rather long code. Also, an iteration loop would still work if the structured type changes in the future, whereas the manual approach would have to be tweaked in this case.
I'm trying to adapt some C code to Nim. The original C code does actually reverse the bytes of each element one by one, but I was hoping Nim could provide a smarter approach via some insights into the structured type — after all, Nim is famous for providing some amazing ways to do things which look impossible in other languages.
It would be perfectly fine to do so at preprocessing or compile time, in case metaprogramming or Source Code Filters could help here.
for f in fields(myobject):
echo sizeof(f)
Read docs on fields and fieldPairs iterators
Some question is close to origin: what tools exist for generating binary parsers, with the feel like parser generators works over grammar definitions (flex/ragel/antlr/..)?
I mean some tool generates Nim (or better ANSI C) code driven by the declarative binary format specification down to the level of a single bit, arbitrary-length bit fields, and byte-order variants?
Maybe someone can advise me some lite tutorial how such alike parsers works, and how to implement binary DCG grammar parser ro code generator in Nim? (the best one is an infinite stream parser variant with error correction) https://en.wikipedia.org/wiki/Definite_clause_grammar
@dponyatov, following the links in the StackOverflow conversation you pointed out, I've found mentioned the Kaitai Struct (open source) tool:
That seems a good solution, with YAML-like definitions — and, from what I understood, you'd only have to write/port Nim support for Kaitai once, and then it could be used anywhere. Right now, Nim is not officially supported, but I'm sure that they'd welcome a Nim adaptation to include Nim in the officially supported langs.