Add '-' support for Create() and Set()

This commit is contained in:
miloyip 2015-05-02 21:30:40 +08:00
parent 2ece55abc7
commit 2ddbd09031
2 changed files with 34 additions and 18 deletions

View File

@ -166,14 +166,16 @@ public:
ValueType* v = &root; ValueType* v = &root;
bool exist = true; bool exist = true;
for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
if (v->GetType() != kObjectType && v->GetType() != kArrayType) { if (t->index == kPointerInvalidIndex) { // object name
if (t->index == kPointerInvalidIndex) // Handling of '-' for last element of array
v->SetObject(); if (t->name[0] == '-' && t->length == 1) {
else if (!v->IsArray())
v->SetArray(); v->SetArray(); // Change to Array
v->PushBack(Value().Move(), allocator);
v = &((*v)[v->Size() - 1]);
exist = false;
} }
else {
if (t->index == kPointerInvalidIndex) {
if (!v->IsObject()) if (!v->IsObject())
v->SetObject(); // Change to Object v->SetObject(); // Change to Object
@ -186,7 +188,8 @@ public:
else else
v = &m->value; v = &m->value;
} }
else { }
else { // array index
if (!v->IsArray()) if (!v->IsArray())
v->SetArray(); // Change to Array v->SetArray(); // Change to Array

View File

@ -280,6 +280,14 @@ TEST(Pointer, Create) {
Value* v = &Pointer("/foo/0").Create(d, d.GetAllocator()); Value* v = &Pointer("/foo/0").Create(d, d.GetAllocator());
EXPECT_EQ(&d["foo"][0], v); EXPECT_EQ(&d["foo"][0], v);
} }
{
Value* v = &Pointer("/foo/-").Create(d, d.GetAllocator());
EXPECT_EQ(&d["foo"][1], v);
}
{
Value* v = &Pointer("/foo/-/-").Create(d, d.GetAllocator());
EXPECT_EQ(&d["foo"][2][0], v);
}
} }
TEST(Pointer, Get) { TEST(Pointer, Get) {
@ -310,6 +318,8 @@ TEST(Pointer, GetWithDefault) {
EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v, a));
EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v, a));
EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v, a)); EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v, a));
EXPECT_TRUE(Value("last") == Pointer("/foo/-").GetWithDefault(d, Value("last").Move(), a));
EXPECT_STREQ("last", d["foo"][3].GetString());
} }
TEST(Pointer, Set) { TEST(Pointer, Set) {
@ -321,6 +331,9 @@ TEST(Pointer, Set) {
Pointer("/foo/0").Set(d, Value(123).Move(), a); Pointer("/foo/0").Set(d, Value(123).Move(), a);
EXPECT_EQ(123, d["foo"][0].GetInt()); EXPECT_EQ(123, d["foo"][0].GetInt());
Pointer("/foo/-").Set(d, Value(456).Move(), a);
EXPECT_EQ(456, d["foo"][2].GetInt());
Pointer("/foo/null").Set(d, Value().Move(), a); Pointer("/foo/null").Set(d, Value().Move(), a);
EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull());