diff --git a/include/api/Metrics.h b/include/api/Metrics.h index 97ee8dca599..6365f52ab96 100644 --- a/include/api/Metrics.h +++ b/include/api/Metrics.h @@ -24,6 +24,7 @@ #pragma once #include +#include #include #include #include @@ -88,6 +89,16 @@ class Metrics IdType lookup(const std::string_view name) const; IntType *lookup(IdType id, std::string_view *name = nullptr) const; + std::optional + lookupPtr(const std::string_view name) const + { + IdType id = lookup(name); + if (id != NOT_FOUND) { + return lookup(id); + } + return std::nullopt; + } + // A bit of a convenience, since we use the ptr to the atomic frequently in the core IntType * newMetricPtr(const std::string_view name) diff --git a/src/api/test_Metrics.cc b/src/api/test_Metrics.cc index 6556754c845..df8efa93585 100644 --- a/src/api/test_Metrics.cc +++ b/src/api/test_Metrics.cc @@ -62,4 +62,17 @@ TEST_CASE("Metrics", "[libtsapi][Metrics]") REQUIRE(m[0].load() == 42); } + + SECTION("lookup") + { + auto nm = m.lookupPtr("notametric"); + REQUIRE(!nm); + + auto mid = m.newMetric("ametric"); + auto fm = m.lookupPtr("ametric"); + REQUIRE(fm.has_value()); + REQUIRE(fm.value()); + REQUIRE(fm.value() == m.lookup(mid)); + REQUIRE(m.lookup("ametric") == mid); + } }