endTable method

int endTable()

End the current table and return its offset.

Implementation

int endTable() {
  if (_currentVTable == null) {
    throw new StateError('Start a table before ending it.');
  }
  // Prepare for writing the VTable.
  _prepare(_sizeofInt32, 1);
  int tableTail = _tail;
  // Prepare the size of the current table.
  _currentVTable!.tableSize = tableTail - _currentTableEndTail;
  // Prepare the VTable to use for the current table.
  int? vTableTail;
  {
    _currentVTable!.computeFieldOffsets(tableTail);
    // Try to find an existing compatible VTable.
    // Search backward - more likely to have recently used one
    for (int i = _vTables.length - 1; i >= 0; i--) {
      final int vt2Offset = _vTables[i];
      final int vt2Start = _buf.lengthInBytes - vt2Offset;
      final int vt2Size = _buf.getUint16(vt2Start, Endian.little);

      if (_currentVTable!._vTableSize == vt2Size &&
          _currentVTable!._offsetsMatch(vt2Start, _buf)) {
        vTableTail = vt2Offset;
        break;
      }
    }
    // Write a new VTable.
    if (vTableTail == null) {
      _prepare(_sizeofUint16, _currentVTable!.numOfUint16);
      vTableTail = _tail;
      _currentVTable!.tail = vTableTail;
      _currentVTable!.output(_buf, _buf.lengthInBytes - _tail);
      _vTables.add(_currentVTable!.tail);
    }
  }
  // Set the VTable offset.
  _setInt32AtTail(_buf, tableTail, vTableTail - tableTail);
  // Done with this table.
  _currentVTable = null;
  return tableTail;
}