Add CreateVector overload to accept array like (#7095)

This commit is contained in:
Derek Bailey
2022-02-09 22:16:46 -08:00
committed by GitHub
parent ed6ae8d322
commit faadbc10ea
2 changed files with 15 additions and 4 deletions

View File

@@ -485,7 +485,7 @@ class FlatBufferBuilder {
return CreateString(str.c_str(), str.length());
}
// clang-format off
// clang-format off
#ifdef FLATBUFFERS_HAS_STRING_VIEW
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const string_view to copy in to the buffer.
@@ -625,7 +625,7 @@ class FlatBufferBuilder {
AssertScalarT<T>();
StartVector(len, sizeof(T));
if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
// clang-format off
// clang-format off
#if FLATBUFFERS_LITTLEENDIAN
PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
#else
@@ -641,6 +641,17 @@ class FlatBufferBuilder {
return Offset<Vector<T>>(EndVector(len));
}
/// @brief Serialize an array like object into a FlatBuffer `vector`.
/// @tparam T The data type of the array elements.
/// @tparam C The type of the array.
/// @param[in] array A reference to an array like object of type `T` to
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, class C> Offset<Vector<T>> CreateVector(const C &array) {
return CreateVector(array.data(), array.size());
}
template<typename T>
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
StartVector(len, sizeof(Offset<T>));

View File

@@ -3405,11 +3405,11 @@ void CreateSharedStringTest() {
TEST_EQ(null_b1.o, null_b2.o);
// Put the strings into an array for round trip verification.
const flatbuffers::Offset<flatbuffers::String> array[7] = {
std::array<flatbuffers::Offset<flatbuffers::String>, 7> array = {
one1, two, one2, onetwo, null_b1, null_c, null_b2
};
const auto vector_offset =
builder.CreateVector(array, flatbuffers::uoffset_t(7));
builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(array);
MonsterBuilder monster_builder(builder);
monster_builder.add_name(two);
monster_builder.add_testarrayofstring(vector_offset);