From d76fe5687dd448a1b466bcf73729147e6046c31e Mon Sep 17 00:00:00 2001 From: Frank Richter Date: Sat, 23 Mar 2019 14:31:06 +0100 Subject: [PATCH] Implement Value::demand() --- include/json/value.h | 2 +- src/lib_json/json_value.cpp | 6 ++++++ src/test_lib_json/main.cpp | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/include/json/value.h b/include/json/value.h index 69a0ed2..277cd45 100644 --- a/include/json/value.h +++ b/include/json/value.h @@ -524,7 +524,7 @@ Json::Value obj_value(Json::objectValue); // {} /// Most general and efficient version of object-mutators. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. - Value const* demand(char const* begin, char const* end); + Value* demand(char const* begin, char const* end); /// \brief Remove and return the named member. /// /// Do nothing if it did not exist. diff --git a/src/lib_json/json_value.cpp b/src/lib_json/json_value.cpp index f21b231..b046c19 100644 --- a/src/lib_json/json_value.cpp +++ b/src/lib_json/json_value.cpp @@ -1126,6 +1126,12 @@ Value const* Value::find(char const* begin, char const* end) const { return nullptr; return &(*it).second; } +Value* Value::demand(char const* begin, char const* end) { + JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue, + "in Json::Value::demand(begin, end): requires " + "objectValue or nullValue"); + return &resolveReference(begin, end); +} const Value& Value::operator[](const char* key) const { Value const* found = find(key, key + strlen(key)); if (!found) diff --git a/src/test_lib_json/main.cpp b/src/test_lib_json/main.cpp index c2d0f2e..1a337bc 100644 --- a/src/test_lib_json/main.cpp +++ b/src/test_lib_json/main.cpp @@ -214,6 +214,15 @@ JSONTEST_FIXTURE(ValueTest, objects) { const Json::Value* foundUnknownId = object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey)); JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId); + const char yetAnotherIdKey[] = "yet another id"; + const Json::Value* foundYetAnotherId = object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey)); + JSONTEST_ASSERT_EQUAL(nullptr, foundYetAnotherId); + Json::Value* demandedYetAnotherId = object1_.demand(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey)); + JSONTEST_ASSERT(demandedYetAnotherId != nullptr); + *demandedYetAnotherId = "baz"; + + JSONTEST_ASSERT_EQUAL(Json::Value("baz"), object1_["yet another id"]); + // Access through non-const reference JSONTEST_ASSERT_EQUAL(Json::Value(1234), object1_["id"]); JSONTEST_ASSERT_EQUAL(Json::Value(), object1_["unknown id"]);