userver: userver/utils/statistics/metric_value.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
metric_value.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/statistics/metric_value.hpp
4/// @brief @copybrief utils::statistics::MetricValue
5
6#include <cstdint>
7#include <variant>
8
9#include <userver/utils/statistics/rate.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utils::statistics {
14
15/// @brief The value of a metric. Only integer and floating-point metrics are
16/// allowed.
17class MetricValue final {
18 public:
19 using RawType = std::variant<std::int64_t, double, Rate>;
20
21 MetricValue(const MetricValue&) = default;
22 MetricValue& operator=(const MetricValue&) = default;
23
24 bool operator==(const MetricValue& other) const noexcept {
25 return value_ == other.value_;
26 }
27
28 bool operator!=(const MetricValue& other) const noexcept {
29 return value_ != other.value_;
30 }
31
32 /// @brief Retrieve the value of an integer metric.
33 /// @throws std::exception on type mismatch.
34 std::int64_t AsInt() const { return std::get<std::int64_t>(value_); }
35
36 /// @brief Retrieve the value of a floating-point metric.
37 /// @throws std::exception on type mismatch.
38 double AsFloat() const { return std::get<double>(value_); }
39
40 /// @brief Retrieve the value of a Rate metric.
41 /// @throws std::exception on type mismatch.
42 Rate AsRate() const { return std::get<Rate>(value_); }
43
44 /// @brief Returns whether metric is Rate metric
45 bool IsRate() const noexcept { return std::holds_alternative<Rate>(value_); }
46
47 /// @brief Calls @p visitor with either a `std::int64_t` or a `double` value.
48 /// @returns Whatever @p visitor returns.
49 template <typename VisitorFunc>
50 decltype(auto) Visit(VisitorFunc visitor) const {
51 return std::visit(visitor, value_);
52 }
53
54 /// @cond
55 MetricValue() noexcept : value_(std::int64_t{0}) {}
56
57 explicit MetricValue(RawType value) noexcept : value_(value) {}
58 /// @endcond
59
60 private:
61 RawType value_;
62};
63
64} // namespace utils::statistics
65
66USERVER_NAMESPACE_END