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 <type_traits>
8#include <variant>
9
10#include <userver/utils/statistics/histogram_view.hpp>
11#include <userver/utils/statistics/rate.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace utils::statistics {
16
17/// @brief The value of a metric.
18///
19/// Cheap to copy, expected to be passed around by value.
20class MetricValue final {
21 public:
22 using RawType = std::variant<std::int64_t, double, Rate, HistogramView>;
23
24 // trivially copyable
25 MetricValue(const MetricValue&) = default;
26 MetricValue& operator=(const MetricValue&) = default;
27
28 bool operator==(const MetricValue& other) const noexcept {
29 return value_ == other.value_;
30 }
31
32 bool operator!=(const MetricValue& other) const noexcept {
33 return value_ != other.value_;
34 }
35
36 /// @brief Retrieve the value of an integer metric.
37 /// @throws std::exception on type mismatch.
38 std::int64_t AsInt() const { return std::get<std::int64_t>(value_); }
39
40 /// @brief Retrieve the value of a floating-point metric.
41 /// @throws std::exception on type mismatch.
42 double AsFloat() const { return std::get<double>(value_); }
43
44 /// @brief Retrieve the value of a Rate metric.
45 /// @throws std::exception on type mismatch.
46 Rate AsRate() const { return std::get<Rate>(value_); }
47
48 /// @brief Returns whether metric is Rate metric.
49 bool IsRate() const noexcept { return std::holds_alternative<Rate>(value_); }
50
51 /// @brief Retrieve the value of a HistogramView metric.
52 /// @throws std::exception on type mismatch.
53 HistogramView AsHistogram() const { return std::get<HistogramView>(value_); }
54
55 /// @brief Returns whether metric is HistogramView metric.
56 bool IsHistogram() const noexcept {
57 return std::holds_alternative<HistogramView>(value_);
58 }
59
60 /// @brief Calls @p visitor with either a `std::int64_t` or a `double` value.
61 /// @returns Whatever @p visitor returns.
62 template <typename VisitorFunc>
63 decltype(auto) Visit(VisitorFunc visitor) const {
64 return std::visit(visitor, value_);
65 }
66
67 /// @cond
68 MetricValue() noexcept : value_(std::int64_t{0}) {}
69
70 explicit MetricValue(RawType value) noexcept : value_(value) {}
71 /// @endcond
72
73 private:
74 RawType value_;
75};
76
77} // namespace utils::statistics
78
79USERVER_NAMESPACE_END