From 9300d7b80bb9dd7764efec1194f91c9ee6d595e2 Mon Sep 17 00:00:00 2001 From: Kefu Chai Date: Sat, 9 Mar 2024 21:08:12 +0800 Subject: [PATCH] utils/human_readable: add fmt::formatter for human_readable_value before this change, we rely on the default-generated fmt::formatter created from operator<<, but fmt v10 dropped the default-generated formatter. in this change, we define formatters for `utils::human_readable_value`, and drop its operator<< Refs #13245 Signed-off-by: Kefu Chai --- utils/human_readable.cc | 17 +++++++++-------- utils/human_readable.hh | 10 ++++++---- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/utils/human_readable.cc b/utils/human_readable.cc index 76c10dbeb8..20eaddb5dd 100644 --- a/utils/human_readable.cc +++ b/utils/human_readable.cc @@ -13,14 +13,6 @@ namespace utils { -std::ostream& operator<<(std::ostream& os, const human_readable_value& val) { - os << val.value; - if (val.suffix) { - os << val.suffix; - } - return os; -} - static human_readable_value to_human_readable_value(uint64_t value, uint64_t step, uint64_t precision, const std::array& suffixes) { if (!value) { return {0, suffixes[0]}; @@ -48,3 +40,12 @@ human_readable_value to_hr_size(uint64_t size) { } } // namespace utils + +auto fmt::formatter::format(const utils::human_readable_value& val, fmt::format_context& ctx) const + -> decltype(ctx.out()) { + auto out = fmt::format_to(ctx.out(), "{}", val.value); + if (val.suffix) { + out = fmt::format_to(out, "{}", val.suffix); + } + return out; +} diff --git a/utils/human_readable.hh b/utils/human_readable.hh index 5494294d16..81c203b0b6 100644 --- a/utils/human_readable.hh +++ b/utils/human_readable.hh @@ -8,8 +8,8 @@ #pragma once -#include -#include +#include +#include namespace utils { @@ -18,8 +18,6 @@ struct human_readable_value { char suffix; // 0 -> no suffix }; -std::ostream& operator<<(std::ostream& os, const human_readable_value& val); - /// Convert a size to a human readable representation. /// /// The human-readable representation has at most 4 digits @@ -38,3 +36,7 @@ std::ostream& operator<<(std::ostream& os, const human_readable_value& val); human_readable_value to_hr_size(uint64_t size); } // namespace utils + +template <> struct fmt::formatter : fmt::formatter { + auto format(const utils::human_readable_value&, fmt::format_context& ctx) const -> decltype(ctx.out()); +};