Make MetricKey hashable

This commit is contained in:
2025-08-28 17:10:56 -04:00
parent 9c89eba6c8
commit ca5b299da8
2 changed files with 29 additions and 5 deletions

View File

@@ -4,8 +4,35 @@
#include <thread>
#include <unordered_map>
#include <vector>
namespace metric {
struct MetricKey {
std::string_view name;
std::vector<std::pair<std::string, std::string>> labels;
bool operator==(const MetricKey &other) const {
return name == other.name && labels == other.labels;
}
};
} // namespace metric
namespace std {
template <> struct hash<metric::MetricKey> {
std::size_t operator()(const metric::MetricKey &k) const {
thread_local std::vector<size_t> parts;
parts.clear();
parts.push_back(std::hash<std::string_view>{}(k.name));
for (const auto &p : k.labels) {
parts.push_back(std::hash<std::string>{}(p.first));
parts.push_back(std::hash<std::string>{}(p.second));
}
return std::hash<std::string_view>{}(
std::string_view{reinterpret_cast<const char *>(parts.data()),
parts.size() * sizeof(size_t)});
}
};
} // namespace std
namespace metric {
struct Counter::State {};
struct Gauge::State {};
struct Histogram::State {};
@@ -13,11 +40,6 @@ struct Metric {
static std::mutex mutex;
struct MetricKey {
std::string_view name;
std::vector<std::pair<std::string, std::string>> labels;
};
struct PerThreadState {
std::unordered_map<MetricKey, Counter::State> counters;
std::unordered_map<MetricKey, Histogram::State> histograms;