Skip to content

Commit

Permalink
Add matching fix for PrettyWriter
Browse files Browse the repository at this point in the history
PrettyWriter EndObject will now also assert if called when a key is
missing its matching value.
  • Loading branch information
StilesCrisis authored and StilesCrisis committed Feb 28, 2017
1 parent 2e9b7b1 commit fa84cd1
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
6 changes: 4 additions & 2 deletions include/rapidjson/prettywriter.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,10 @@ class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding,

bool EndObject(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray);
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); // currently inside an Array, not Object
RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top<typename Base::Level>()->valueCount % 2); // Object has a Key without a Value

bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;

if (!empty) {
Expand Down
51 changes: 51 additions & 0 deletions test/unittest/prettywritertest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,57 @@ TEST(PrettyWriter, RawValue) {
buffer.GetString());
}

TEST(PrettyWriter, InvalidEventSequence) {
// {]
{
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
writer.StartObject();
EXPECT_THROW(writer.EndArray(), AssertException);
EXPECT_FALSE(writer.IsComplete());
}

// [}
{
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
writer.StartArray();
EXPECT_THROW(writer.EndObject(), AssertException);
EXPECT_FALSE(writer.IsComplete());
}

// { 1:
{
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
writer.StartObject();
EXPECT_THROW(writer.Int(1), AssertException);
EXPECT_FALSE(writer.IsComplete());
}

// { 'a' }
{
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
writer.StartObject();
writer.Key("a");
EXPECT_THROW(writer.EndObject(), AssertException);
EXPECT_FALSE(writer.IsComplete());
}

// { 'a':'b','c' }
{
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
writer.StartObject();
writer.Key("a");
writer.String("b");
writer.Key("c");
EXPECT_THROW(writer.EndObject(), AssertException);
EXPECT_FALSE(writer.IsComplete());
}
}

#if RAPIDJSON_HAS_CXX11_RVALUE_REFS

static PrettyWriter<StringBuffer> WriterGen(StringBuffer &target) {
Expand Down

0 comments on commit fa84cd1

Please sign in to comment.