Search code examples
protocol-buffersoptional-argumentsflatbuffers

How are similar-fields that are optionally written, distinguished by flatbuffer reader?


Flatbuffer documentation mentions that the fields are optional in the data.

Each field is optional: It does not have to appear in the wire representation, and you can choose to omit fields for each individual object.

I am bit confused on how does the flatbuffer differentiates between two similar fields if one of them is not written.

For eg.

table Monster {
  hp:short;
  hpNew:short;
}

here if I write only hpNew in the data file, how will the reader know this is hpNew or hp ?


Solution

  • medium article explains that the table in memory is started with a reference to a virtual table which tells us where to find the properties.

    If there are fields that are not written (optional), this virtual table will have its offset marked as 0.

    PS: seems this is the reason tables have higher cost than structs, and also why flatbuffer is better than Cap'n Proto (which doesn't support this).