From 995ee86a6ed1840190d5142089b5014b66d2a13d Mon Sep 17 00:00:00 2001 From: Wouter van Oortmerssen Date: Fri, 18 Dec 2015 17:01:34 -0800 Subject: [PATCH] Added an IsFieldPresent helper function. This is implemented as a template function, since Table::CheckField is not reachable by subclasses of Table (private base class). Change-Id: I1ed4d47ce7cb672460ccab61cf7442eb9136b0f1 Tested: on Linux. Bug: 26273432 --- include/flatbuffers/flatbuffers.h | 12 ++++++++++++ tests/test.cpp | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 569c72b31..b6b84030f 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -1187,6 +1187,18 @@ class Table { uint8_t data_[1]; }; +// Helper function to test if a field is present, using any of the field +// enums in the generated code. +// `table` must be a generated table type. Since this is a template parameter, +// this is not typechecked to be a subclass of Table, so beware! +// Note: this function will return false for fields equal to the default +// value, since they're not stored in the buffer (unless force_defaults was +// used). +template bool IsFieldPresent(const T *table, voffset_t field) { + // Cast, since Table is a private baseclass of any table types. + return reinterpret_cast(table)->CheckField(field); +} + // Utility function for reverse lookups on the EnumNames*() functions // (in the generated C++ code) // names must be NULL terminated. diff --git a/tests/test.cpp b/tests/test.cpp index f27b9bdfc..10435e3eb 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -221,6 +221,10 @@ void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length) { for (auto it = tests->begin(); it != tests->end(); ++it) { TEST_EQ(it->a() == 10 || it->a() == 30, true); // Just testing iterators. } + + // Checking for presence of fields: + TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true); + TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false); } // Change a FlatBuffer in-place, after it has been constructed.