Skip to content

Commit ba341a2

Browse files
committed
Add getObjMap() helper method. Also, constify checkObject().
1 parent ceb1194 commit ba341a2

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

include/univalue.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ class UniValue {
7070
size_t size() const { return values.size(); }
7171

7272
bool getBool() const { return isTrue(); }
73-
bool checkObject(const std::map<std::string,UniValue::VType>& memberTypes);
73+
void getObjMap(std::map<std::string,UniValue>& kv) const;
74+
bool checkObject(const std::map<std::string,UniValue::VType>& memberTypes) const;
7475
const UniValue& operator[](const std::string& key) const;
7576
const UniValue& operator[](size_t index) const;
7677
bool exists(const std::string& key) const { size_t i; return findKey(key, i); }

lib/univalue.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,16 @@ bool UniValue::pushKVs(const UniValue& obj)
156156
return true;
157157
}
158158

159+
void UniValue::getObjMap(std::map<std::string,UniValue>& kv) const
160+
{
161+
if (typ != VOBJ)
162+
return;
163+
164+
kv.clear();
165+
for (size_t i = 0; i < keys.size(); i++)
166+
kv[keys[i]] = values[i];
167+
}
168+
159169
bool UniValue::findKey(const std::string& key, size_t& retIdx) const
160170
{
161171
for (size_t i = 0; i < keys.size(); i++) {
@@ -168,7 +178,7 @@ bool UniValue::findKey(const std::string& key, size_t& retIdx) const
168178
return false;
169179
}
170180

171-
bool UniValue::checkObject(const std::map<std::string,UniValue::VType>& t)
181+
bool UniValue::checkObject(const std::map<std::string,UniValue::VType>& t) const
172182
{
173183
if (typ != VOBJ)
174184
return false;

test/object.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,14 @@ BOOST_AUTO_TEST_CASE(univalue_object)
324324
obj.pushKV("age", uv);
325325
BOOST_CHECK_EQUAL(obj.size(), 1);
326326
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "43");
327+
328+
obj.pushKV("name", "foo bar");
329+
330+
std::map<std::string,UniValue> kv;
331+
obj.getObjMap(kv);
332+
BOOST_CHECK_EQUAL(kv["age"].getValStr(), "43");
333+
BOOST_CHECK_EQUAL(kv["name"].getValStr(), "foo bar");
334+
327335
}
328336

329337
static const char *json1 =

0 commit comments

Comments
 (0)