Added Value::find with String key (#1467) * Added Value::find with String key * Fix codestyle --------- Co-authored-by: Jordan Bayles <bayles.jordan@gmail.com> Co-authored-by: Petukhov Timofey <Timofey.Petukhov@infotecs.ru>
diff --git a/include/json/value.h b/include/json/value.h index f1232c4..c8e1aae 100644 --- a/include/json/value.h +++ b/include/json/value.h
@@ -513,6 +513,9 @@ /// and operator[]const /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 Value const* find(char const* begin, char const* end) const; + /// Most general and efficient version of isMember()const, get()const, + /// and operator[]const + Value const* find(const String& key) const; /// 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.
diff --git a/src/lib_json/json_value.cpp b/src/lib_json/json_value.cpp index a5e2dd8..5bd8d9a 100644 --- a/src/lib_json/json_value.cpp +++ b/src/lib_json/json_value.cpp
@@ -1092,6 +1092,9 @@ return nullptr; return &(*it).second; } +Value const* Value::find(const String& key) const { + return find(key.data(), key.data() + key.length()); +} Value* Value::demand(char const* begin, char const* end) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue, "in Json::Value::demand(begin, end): requires " @@ -1105,7 +1108,7 @@ return *found; } Value const& Value::operator[](const String& key) const { - Value const* found = find(key.data(), key.data() + key.length()); + Value const* found = find(key); if (!found) return nullSingleton(); return *found;
diff --git a/src/test_lib_json/main.cpp b/src/test_lib_json/main.cpp index fa41d19..55ab224 100644 --- a/src/test_lib_json/main.cpp +++ b/src/test_lib_json/main.cpp
@@ -220,11 +220,20 @@ JSONTEST_ASSERT(foundId != nullptr); JSONTEST_ASSERT_EQUAL(Json::Value(1234), *foundId); + const std::string stringIdKey = "id"; + const Json::Value* stringFoundId = object1_.find(stringIdKey); + JSONTEST_ASSERT(stringFoundId != nullptr); + JSONTEST_ASSERT_EQUAL(Json::Value(1234), *stringFoundId); + const char unknownIdKey[] = "unknown id"; const Json::Value* foundUnknownId = object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey)); JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId); + const std::string stringUnknownIdKey = "unknown id"; + const Json::Value* stringFoundUnknownId = object1_.find(stringUnknownIdKey); + JSONTEST_ASSERT_EQUAL(nullptr, stringFoundUnknownId); + // Access through demand() const char yetAnotherIdKey[] = "yet another id"; const Json::Value* foundYetAnotherId =