diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 8a07899e2..7b72319df 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -296,6 +296,12 @@ protected: uoffset_t length_; }; +// Convenient helper function to get the length of any vector, regardless +// of wether it is null or not (the field is not set). +template static inline size_t VectorLength(const Vector *v) { + return v ? v->Length() : 0; +} + struct String : public Vector { const char *c_str() const { return reinterpret_cast(Data()); } }; diff --git a/tests/test.cpp b/tests/test.cpp index f726d615e..46d3f9524 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -137,6 +137,7 @@ void AccessFlatBufferTest(const std::string &flatbuf) { TEST_EQ(pos->test3().b(), 20); auto inventory = monster->inventory(); + TEST_EQ(VectorLength(inventory), 10); // Works even if inventory is null. TEST_NOTNULL(inventory); unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (auto it = inventory->begin(); it != inventory->end(); ++it)