From 986b9fcbef990696b5574d4bb386d0d56bce9d45 Mon Sep 17 00:00:00 2001 From: Markus Date: Thu, 10 Aug 2023 14:44:02 +0200 Subject: [PATCH] C++ strict conversion fixes for flatbuffer_builder.h (#8062) Enables to compile flatbuffer_builder.h with strict settings -Wconversion -Wsign-conversion. Also, add asserts to verify the conversions. --- include/flatbuffers/flatbuffer_builder.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/include/flatbuffers/flatbuffer_builder.h b/include/flatbuffers/flatbuffer_builder.h index f3ffeb0d70a..df9ec1b2352 100644 --- a/include/flatbuffers/flatbuffer_builder.h +++ b/include/flatbuffers/flatbuffer_builder.h @@ -45,8 +45,9 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) { // Should correspond to what EndTable() below builds up. const voffset_t fixed_fields = 2 * sizeof(voffset_t); // Vtable size and Object Size. - return fixed_fields + field_id * sizeof(voffset_t); -} + size_t offset = fixed_fields + field_id * sizeof(voffset_t); + FLATBUFFERS_ASSERT(offset < std::numeric_limits::max()); + return static_cast(offset);} template> const T *data(const std::vector &v) { @@ -709,7 +710,7 @@ template class FlatBufferBuilderImpl { typename std::enable_if::type ForceVectorAlignment64( const size_t len, const size_t elemsize, const size_t alignment) { // If you hit this assertion, you are trying to force alignment on a - // vector with offset64 after serializing a 32-bit offset. + // vector with offset64 after serializing a 32-bit offset. FLATBUFFERS_ASSERT(GetSize() == length_of_64_bit_region_); // Call through. @@ -879,7 +880,9 @@ template class FlatBufferBuilderImpl { /// where the vector is stored. template Offset>> CreateVectorOfStrings(It begin, It end) { - auto size = std::distance(begin, end); + auto distance = std::distance(begin, end); + FLATBUFFERS_ASSERT(distance >= 0); + auto size = static_cast(distance); auto scratch_buffer_usage = size * sizeof(Offset); // If there is not enough space to store the offsets, there definitely won't // be enough space to store all the strings. So ensuring space for the @@ -889,7 +892,7 @@ template class FlatBufferBuilderImpl { buf_.scratch_push_small(CreateString(*it)); } StartVector>(size); - for (auto i = 1; i <= size; i++) { + for (size_t i = 1; i <= size; i++) { // Note we re-evaluate the buf location each iteration to account for any // underlying buffer resizing that may occur. PushElement(*reinterpret_cast *>(