Skip to content
This repository was archived by the owner on Jul 31, 2023. It is now read-only.

Commit 27f3e74

Browse files
authored
TagMap: assert() on duplicate keys in constructor in debug builds. (#219)
1 parent c595c24 commit 27f3e74

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

opencensus/tags/internal/tag_map.cc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
#include "opencensus/tags/tag_map.h"
1616

17+
#include <algorithm>
18+
#include <cassert>
1719
#include <functional>
1820
#include <initializer_list>
1921
#include <string>
@@ -46,6 +48,14 @@ TagMap::TagMap(std::vector<std::pair<TagKey, std::string>> tags)
4648
void TagMap::Initialize() {
4749
std::sort(tags_.begin(), tags_.end());
4850

51+
auto compare_keys = [](const std::pair<TagKey, std::string>& a,
52+
const std::pair<TagKey, std::string>& b) {
53+
return a.first == b.first;
54+
};
55+
assert(std::adjacent_find(tags_.begin(), tags_.end(), compare_keys) ==
56+
tags_.end() &&
57+
"Duplicate keys are not allowed in TagMap.");
58+
4959
std::hash<std::string> hasher;
5060
common::HashMix mixer;
5161
for (const auto& tag : tags_) {

opencensus/tags/internal/tag_map_test.cc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,15 @@ TEST(TagMapTest, DebugStringContainsTags) {
104104
EXPECT_THAT(s, HasSubstr("value2"));
105105
}
106106

107+
TEST(TagMapDeathTest, DuplicateKeysNotAllowed) {
108+
TagKey k = TagKey::Register("k");
109+
EXPECT_DEBUG_DEATH(
110+
{
111+
TagMap m({{k, "v1"}, {k, "v2"}});
112+
},
113+
"Duplicate keys are not allowed");
114+
}
115+
107116
} // namespace
108117
} // namespace tags
109118
} // namespace opencensus

0 commit comments

Comments
 (0)