From b7cb91c34e873aa53dbf547156dfa930e4e55556 Mon Sep 17 00:00:00 2001 From: Wouter van Oortmerssen Date: Wed, 7 Jan 2015 11:35:17 -0800 Subject: [PATCH] Made CreateUninitializedVector return the buffer. Previously, obtaining the buffer was unclear and required multiple casts. Change-Id: I18e01c9e669886ac250e83aad10623cbddd629b6 Tested: on Linux. --- include/flatbuffers/flatbuffers.h | 18 ++++++++++-------- tests/test.cpp | 6 ++++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index e1999f90a..88ea9ad0e 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -646,21 +646,23 @@ class FlatBufferBuilder FLATBUFFERS_FINAL_CLASS { return Offset>(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 Offset> CreateUninitializedVector(size_t len) { - return CreateUninitializedVector(len, sizeof(T)); + template Offset> CreateUninitializedVector( + size_t len, T **buf) { + return CreateUninitializedVector(len, sizeof(T), + reinterpret_cast(buf)); } - template Offset> CreateVector(const std::vector &v){ + template Offset> CreateVector(const std::vector &v) { return CreateVector(v.data(), v.size()); } diff --git a/tests/test.cpp b/tests/test.cpp index eb55df7c0..1abbfdcdd 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -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( + // 10, &inv_buf); + // memcpy(inv_buf, inv_data, 10); + Test tests[] = { Test(10, 20), Test(30, 40) }; auto testv = builder.CreateVectorOfStructs(tests, 2);