From 360c34467c2f707ec5de80f416cb4e8f41a0d18c Mon Sep 17 00:00:00 2001 From: Manuel Kroiss Date: Thu, 27 Jul 2017 17:06:02 +0100 Subject: [PATCH] Adding accessors for IsBlob and Blob.data (#4398) --- include/flatbuffers/flexbuffers.h | 6 ++++-- tests/test.cpp | 11 ++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h index 153603755..4b722babe 100644 --- a/include/flatbuffers/flexbuffers.h +++ b/include/flatbuffers/flexbuffers.h @@ -230,14 +230,15 @@ class String : public Sized { class Blob : public Sized { public: - Blob(const uint8_t *data, uint8_t byte_width) - : Sized(data, byte_width) {} + Blob(const uint8_t *data_buf, uint8_t byte_width) + : Sized(data_buf, byte_width) {} static Blob EmptyBlob() { static const uint8_t empty_blob[] = { 0/*len*/ }; return Blob(empty_blob + 1, 1); } bool IsTheEmptyBlob() const { return data_ == EmptyBlob().data_; } + const uint8_t *data() const { return data_; } }; class Vector : public Sized { @@ -360,6 +361,7 @@ class Reference { bool IsKey() const { return type_ == TYPE_KEY; } bool IsVector() const { return type_ == TYPE_VECTOR || type_ == TYPE_MAP; } bool IsMap() const { return type_ == TYPE_MAP; } + bool IsBlob() const { return type_ == TYPE_BLOB; } // Reads any type as a int64_t. Never fails, does most sensible conversion. // Truncates floats, strings are attempted to be parsed for a number, diff --git a/tests/test.cpp b/tests/test.cpp index c6cfcaec9..23996fb3b 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -1599,6 +1599,8 @@ void FlexBuffersTest() { slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100); slb += "Fred"; slb.IndirectFloat(4.0f); + uint8_t blob[] = { 77 }; + slb.Blob(blob, 1); }); int ints[] = { 1, 2, 3 }; slb.Vector("bar", ints, 3); @@ -1616,6 +1618,8 @@ void FlexBuffersTest() { slb3 += -100; // Equivalent to slb.Add(-100) or slb.Int(-100); slb3 += "Fred"; slb3.IndirectFloat(4.0f); + uint8_t blob[] = { 77 }; + slb3.Blob(blob, 1); }, slb2); int ints[] = { 1, 2, 3 }; slb2.Vector("bar", ints, 3); @@ -1635,7 +1639,7 @@ void FlexBuffersTest() { auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap(); TEST_EQ(map.size(), 5); auto vec = map["vec"].AsVector(); - TEST_EQ(vec.size(), 3); + TEST_EQ(vec.size(), 4); TEST_EQ(vec[0].AsInt64(), -100); TEST_EQ_STR(vec[1].AsString().c_str(), "Fred"); TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed. @@ -1643,6 +1647,11 @@ void FlexBuffersTest() { TEST_EQ(vec[2].AsString().IsTheEmptyString(), true); // Wrong Type. TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though. TEST_EQ_STR(vec[2].ToString().c_str(), "4.0"); // Or have it converted. + // Test that the blob can be accessed. + TEST_EQ(vec[3].IsBlob(), true); + auto blob = vec[3].AsBlob(); + TEST_EQ(blob.size(), 1); + TEST_EQ(blob.data()[0], 77); auto tvec = map["bar"].AsTypedVector(); TEST_EQ(tvec.size(), 3); TEST_EQ(tvec[2].AsInt8(), 3);