summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--base/values.h18
-rw-r--r--base/values_unittest.cc37
2 files changed, 55 insertions, 0 deletions
diff --git a/base/values.h b/base/values.h
index 90cc40c..aa26b3e 100644
--- a/base/values.h
+++ b/base/values.h
@@ -342,6 +342,24 @@ class BASE_EXPORT DictionaryValue : public Value {
key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); }
key_iterator end_keys() const { return key_iterator(dictionary_.end()); }
+ // This class provides an iterator over both keys and values in the
+ // dictionary. It can't be used to modify the dictionary.
+ class Iterator {
+ public:
+ explicit Iterator(const DictionaryValue& target)
+ : target_(target), it_(target.dictionary_.begin()) {}
+
+ bool HasNext() const { return it_ != target_.dictionary_.end(); }
+ void Advance() { ++it_; }
+
+ const std::string& key() const { return it_->first; }
+ const Value& value() const { return *it_->second; }
+
+ private:
+ const DictionaryValue& target_;
+ ValueMap::const_iterator it_;
+ };
+
// Overridden from Value:
virtual DictionaryValue* DeepCopy() const OVERRIDE;
virtual bool Equals(const Value* other) const OVERRIDE;
diff --git a/base/values_unittest.cc b/base/values_unittest.cc
index 458a4e1..806347c 100644
--- a/base/values_unittest.cc
+++ b/base/values_unittest.cc
@@ -702,4 +702,41 @@ TEST(ValuesTest, MergeDictionary) {
EXPECT_EQ("sub_merge_key_value_merge", sub_merge_key_value); // Merged in.
}
+TEST(ValuesTest, DictionaryIterator) {
+ DictionaryValue dict;
+ for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
+ ADD_FAILURE();
+ }
+
+ StringValue value1("value1");
+ dict.Set("key1", value1.DeepCopy());
+ bool seen1 = false;
+ for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
+ EXPECT_FALSE(seen1);
+ EXPECT_EQ("key1", it.key());
+ EXPECT_TRUE(value1.Equals(&it.value()));
+ seen1 = true;
+ }
+ EXPECT_TRUE(seen1);
+
+ StringValue value2("value2");
+ dict.Set("key2", value2.DeepCopy());
+ bool seen2 = seen1 = false;
+ for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
+ if (it.key() == "key1") {
+ EXPECT_FALSE(seen1);
+ EXPECT_TRUE(value1.Equals(&it.value()));
+ seen1 = true;
+ } else if (it.key() == "key2") {
+ EXPECT_FALSE(seen2);
+ EXPECT_TRUE(value2.Equals(&it.value()));
+ seen2 = true;
+ } else {
+ ADD_FAILURE();
+ }
+ }
+ EXPECT_TRUE(seen1);
+ EXPECT_TRUE(seen2);
+}
+
} // namespace base