Made CreateUninitializedVector return the buffer.

Previously, obtaining the buffer was unclear and required multiple
casts.

Change-Id: I18e01c9e669886ac250e83aad10623cbddd629b6
Tested: on Linux.
This commit is contained in:
Wouter van Oortmerssen 2015-01-07 11:35:17 -08:00
parent f79cc460f8
commit b7cb91c34e
2 changed files with 16 additions and 8 deletions

View File

@ -646,21 +646,23 @@ class FlatBufferBuilder FLATBUFFERS_FINAL_CLASS {
return Offset<Vector<T>>(EndVector(len));
}
// Specialized version for non-copying use cases. Data to be written later.
// After calling this function, GetBufferPointer() can be cast to the
// corresponding Vector<> type to write the data (through Data()).
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize) {
// Specialized version for non-copying use cases. Write the data any time
// later to the returned buffer pointer `buf`.
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
uint8_t **buf) {
NotNested();
StartVector(len, elemsize);
buf_.make_space(len * elemsize);
*buf = buf_.make_space(len * elemsize);
return EndVector(len);
}
template<typename T> Offset<Vector<T>> CreateUninitializedVector(size_t len) {
return CreateUninitializedVector(len, sizeof(T));
template<typename T> Offset<Vector<T>> CreateUninitializedVector(
size_t len, T **buf) {
return CreateUninitializedVector(len, sizeof(T),
reinterpret_cast<uint8_t **>(buf));
}
template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v){
template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
return CreateVector(v.data(), v.size());
}

View File

@ -70,6 +70,12 @@ std::string CreateFlatBufferTest() {
unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto inventory = builder.CreateVector(inv_data, 10);
// Alternatively, create the vector first, and fill in data later:
// unsigned char *inv_buf = nullptr;
// auto inventory = builder.CreateUninitializedVector<unsigned char>(
// 10, &inv_buf);
// memcpy(inv_buf, inv_data, 10);
Test tests[] = { Test(10, 20), Test(30, 40) };
auto testv = builder.CreateVectorOfStructs(tests, 2);