c++flatbuffers

Add gaps in flatbuffers vector


Is it possible to have a gap or empty element in a flatbuffers vector?

I need to transfer a (variable length) list of items, where the position of the items is of relevance. However, items can be omitted, but the existing items must still be at the correct position

Assume

table Item {
  value:string;
}

table List {
  items:[Item];
}

root_type List;
void createBuffer()
{
  auto fbb = ::flatbuffers::FlatBufferBuilder{};
    
  auto vector = std::vector<::flatbuffers::Offset<Item>>{};
  vector.push_back(CreateItem(fbb, fbb.CreateString("Test")));
  // Adds "empty" item
  vector.push_back({});
    
  auto fVector = fbb.CreateVector(vector);
  auto list = CreateList(fbb, fVector);
  fbb.Finish(list);
}

This crashes inside the fbb.CreateVector method where the FBB vector is created.

Is there any way to add "gaps" in the vector, without modifying the Item table?


Solution

  • No, this is not possible. While a table field is allowed to be non present / null, all vector elements must have the specified type.

    It is not possible to specify an "optional" vector element type in the schema.

    Your best bet is a vector of a union type. The union would include the Item type, and every union also allows the "none" value, equivalent to null. This is a bit more work though, as you will essentially store 2 vectors, one of types, and one of values.