Skip to content

Commit 95bd775

Browse files
committed
feat core: make sure that labels are not used with integers, leading to memory corruption
Before this patch a code like `writer["metric"].ValueWithLabels(value, {{"label_name2", 2}, {"label_name3", "value3"}});` was attempting to create a `LabelView{std::string_view{"label_name2", 2}, std::string_view{"label_name3", "value3"}}`. The second string_view constructor was corrupting memory as it treated "label_name3" and "value3" as two iterators. Tests: протестировано локально commit_hash:e16d3d45a6d3f768611762a4b2fca596aba8d6c8
1 parent 296cbb9 commit 95bd775

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

core/include/userver/utils/statistics/labels.hpp

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,21 @@ class LabelView final {
1919
LabelView() = default;
2020
LabelView(Label&& label) = delete;
2121
explicit LabelView(const Label& label) noexcept;
22-
LabelView(std::string_view name, std::string_view value) noexcept : name_(name), value_(value) {}
22+
constexpr LabelView(std::string_view name, std::string_view value) noexcept : name_(name), value_(value) {}
2323

24-
explicit operator bool() const { return !name_.empty(); }
24+
template <class T, std::enable_if_t<std::is_arithmetic_v<T>>* = nullptr>
25+
constexpr LabelView(std::string_view, T) {
26+
static_assert(sizeof(T) && false, "Labels should not be arithmetic values, only strings!");
27+
}
28+
29+
constexpr explicit operator bool() const { return !name_.empty(); }
2530

26-
std::string_view Name() const { return name_; }
27-
std::string_view Value() const { return value_; }
31+
constexpr std::string_view Name() const { return name_; }
32+
constexpr std::string_view Value() const { return value_; }
2833

2934
private:
30-
std::string_view name_;
31-
std::string_view value_;
35+
std::string_view name_{};
36+
std::string_view value_{};
3237
};
3338

3439
bool operator<(const LabelView& x, const LabelView& y) noexcept;
@@ -41,6 +46,11 @@ class Label final {
4146
explicit Label(LabelView view);
4247
Label(std::string name, std::string value);
4348

49+
template <class T, std::enable_if_t<std::is_arithmetic_v<T>>* = nullptr>
50+
Label(std::string, T) {
51+
static_assert(sizeof(T) && false, "Labels should not be arithmetic values, only strings!");
52+
}
53+
4454
explicit operator bool() const { return !name_.empty(); }
4555
explicit operator LabelView() const { return {name_, value_}; }
4656

0 commit comments

Comments
 (0)