diff --git a/include/llvm/ADT/StringMap.h b/include/llvm/ADT/StringMap.h index fd8643fab15..840f328db79 100644 --- a/include/llvm/ADT/StringMap.h +++ b/include/llvm/ADT/StringMap.h @@ -248,6 +248,26 @@ public: return count(MapEntry.getKey()); } + /// equal - check whether both of the containers are equal. + bool operator==(const StringMap &RHS) const { + if (size() != RHS.size()) + return false; + + for (const auto &KeyValue : *this) { + auto FindInRHS = RHS.find(KeyValue.getKey()); + + if (FindInRHS == RHS.end()) + return false; + + if (!(KeyValue.getValue() == FindInRHS->getValue())) + return false; + } + + return true; + } + + bool operator!=(const StringMap &RHS) const { return !(*this == RHS); } + /// insert - Insert the specified key/value pair into the map. If the key /// already exists in the map, return false and ignore the request, otherwise /// insert it and return true. diff --git a/unittests/ADT/StringMapTest.cpp b/unittests/ADT/StringMapTest.cpp index 73c91f5fdd3..98fbd6e1df5 100644 --- a/unittests/ADT/StringMapTest.cpp +++ b/unittests/ADT/StringMapTest.cpp @@ -387,6 +387,70 @@ TEST_F(StringMapTest, MoveAssignment) { ASSERT_EQ(B.count("x"), 0u); } +TEST_F(StringMapTest, EqualEmpty) { + StringMap A; + StringMap B; + ASSERT_TRUE(A == B); + ASSERT_FALSE(A != B); + ASSERT_TRUE(A == A); // self check +} + +TEST_F(StringMapTest, EqualWithValues) { + StringMap A; + A["A"] = 1; + A["B"] = 2; + A["C"] = 3; + A["D"] = 3; + + StringMap B; + B["A"] = 1; + B["B"] = 2; + B["C"] = 3; + B["D"] = 3; + + ASSERT_TRUE(A == B); + ASSERT_TRUE(B == A); + ASSERT_FALSE(A != B); + ASSERT_FALSE(B != A); + ASSERT_TRUE(A == A); // self check +} + +TEST_F(StringMapTest, NotEqualMissingKeys) { + StringMap A; + A["A"] = 1; + A["B"] = 2; + + StringMap B; + B["A"] = 1; + B["B"] = 2; + B["C"] = 3; + B["D"] = 3; + + ASSERT_FALSE(A == B); + ASSERT_FALSE(B == A); + ASSERT_TRUE(A != B); + ASSERT_TRUE(B != A); +} + +TEST_F(StringMapTest, NotEqualWithDifferentValues) { + StringMap A; + A["A"] = 1; + A["B"] = 2; + A["C"] = 100; + A["D"] = 3; + + StringMap B; + B["A"] = 1; + B["B"] = 2; + B["C"] = 3; + B["D"] = 3; + + ASSERT_FALSE(A == B); + ASSERT_FALSE(B == A); + ASSERT_TRUE(A != B); + ASSERT_TRUE(B != A); +} + struct Countable { int &InstanceCount; int Number;