From 2dd6ba57d132d34172077b637b532e21aa6dda8a Mon Sep 17 00:00:00 2001 From: Benjamin Lerman Date: Wed, 1 Feb 2017 18:22:56 +0100 Subject: [PATCH] Add utility method to build a vector of struct in-place. (#4153) Change-Id: I6df195cbae621cf2bf6b4f3b56f68be80dc23152 --- include/flatbuffers/flatbuffers.h | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index d1520f5c4..83b4fa1cd 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -1128,6 +1128,27 @@ FLATBUFFERS_FINAL_CLASS return Offset>(EndVector(len)); } + #ifndef FLATBUFFERS_CPP98_STL + /// @brief Serialize an array of structs into a FlatBuffer `vector`. + /// @tparam T The data type of the struct array elements. + /// @param[in] f A function that takes the current iteration 0..vector_size-1 + /// and a pointer to the struct that must be filled. + /// @return Returns a typed `Offset` into the serialized data indicating + /// where the vector is stored. + /// This is mostly useful when flatbuffers are generated with mutation + /// accessors. + template Offset> CreateVectorOfStructs( + size_t vector_size, const std::function &filler) { + StartVector(vector_size * sizeof(T) / AlignOf(), AlignOf()); + T *structs = reinterpret_cast(buf_.make_space(vector_size * sizeof(T))); + for (size_t i = 0; i < vector_size; i++) { + filler(i, structs); + structs++; + } + return Offset>(EndVector(vector_size)); + } + #endif + /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`. /// @tparam T The data type of the `std::vector` struct elements. /// @param[in]] v A const reference to the `std::vector` of structs to