From 74c3d7eba2946d82a392fc3be2f22e25e3906b56 Mon Sep 17 00:00:00 2001 From: Tyler Denniston Date: Tue, 31 Aug 2021 17:17:20 -0400 Subject: [PATCH] [C++] Add mutable version of LookupByKey and test (#6826) * [C++] Add mutable version of LookupByKey and test This adds an overload of LookupByKey to allow lookup in sorted Vectors to return a mutable instance of the object (or nullptr if not found). * Fix naming --- include/flatbuffers/flatbuffers.h | 4 ++++ tests/test.cpp | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 232299827..35d4e68bc 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -376,6 +376,10 @@ template class Vector { return IndirectHelper::Read(element, 0); } + template mutable_return_type MutableLookupByKey(K key) { + return const_cast(LookupByKey(key)); + } + protected: // This class is only used to access pre-existing data. Don't ever // try to construct these manually. diff --git a/tests/test.cpp b/tests/test.cpp index 866ba38a9..1c99b519b 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -500,6 +500,15 @@ void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) { TEST_EQ(first->hp(), 0); first->mutate_hp(1000); + // Mutate via LookupByKey + TEST_NOTNULL(tables->MutableLookupByKey("Barney")); + TEST_EQ(static_cast(nullptr), + tables->MutableLookupByKey("DoesntExist")); + TEST_EQ(tables->MutableLookupByKey("Barney")->hp(), 1000); + TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(0), true); + TEST_EQ(tables->LookupByKey("Barney")->hp(), 0); + TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(1000), true); + // Run the verifier and the regular test to make sure we didn't trample on // anything. AccessFlatBufferTest(flatbuf, length);