Skip to content

Commit d76fe56

Browse files
committed
Implement Value::demand()
1 parent eb7bd95 commit d76fe56

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

include/json/value.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,7 @@ Json::Value obj_value(Json::objectValue); // {}
524524
/// Most general and efficient version of object-mutators.
525525
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
526526
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
527-
Value const* demand(char const* begin, char const* end);
527+
Value* demand(char const* begin, char const* end);
528528
/// \brief Remove and return the named member.
529529
///
530530
/// Do nothing if it did not exist.

src/lib_json/json_value.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,12 @@ Value const* Value::find(char const* begin, char const* end) const {
11261126
return nullptr;
11271127
return &(*it).second;
11281128
}
1129+
Value* Value::demand(char const* begin, char const* end) {
1130+
JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
1131+
"in Json::Value::demand(begin, end): requires "
1132+
"objectValue or nullValue");
1133+
return &resolveReference(begin, end);
1134+
}
11291135
const Value& Value::operator[](const char* key) const {
11301136
Value const* found = find(key, key + strlen(key));
11311137
if (!found)

src/test_lib_json/main.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,15 @@ JSONTEST_FIXTURE(ValueTest, objects) {
214214
const Json::Value* foundUnknownId = object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey));
215215
JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId);
216216

217+
const char yetAnotherIdKey[] = "yet another id";
218+
const Json::Value* foundYetAnotherId = object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
219+
JSONTEST_ASSERT_EQUAL(nullptr, foundYetAnotherId);
220+
Json::Value* demandedYetAnotherId = object1_.demand(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
221+
JSONTEST_ASSERT(demandedYetAnotherId != nullptr);
222+
*demandedYetAnotherId = "baz";
223+
224+
JSONTEST_ASSERT_EQUAL(Json::Value("baz"), object1_["yet another id"]);
225+
217226
// Access through non-const reference
218227
JSONTEST_ASSERT_EQUAL(Json::Value(1234), object1_["id"]);
219228
JSONTEST_ASSERT_EQUAL(Json::Value(), object1_["unknown id"]);

0 commit comments

Comments
 (0)