]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/commitdiff
common/fmt_common: add has_fmt_print_ctx concept and formatter
authorSamuel Just <sjust@redhat.com>
Thu, 12 Oct 2023 05:13:10 +0000 (22:13 -0700)
committerSamuel Just <sjust@redhat.com>
Mon, 11 Dec 2023 04:10:17 +0000 (04:10 +0000)
fmt_print_ctx avoids creating a string.

Signed-off-by: Samuel Just <sjust@redhat.com>
src/common/fmt_common.h

index 27e488aedcebfd2ea1b1da6cc1f3cff10bae6799..5db8bac43cd7bbd4e5cbc45a81758cefb9e4a6cd 100644 (file)
@@ -22,6 +22,8 @@
  * *or*
  * std::string alt_fmt_print(bool short_format) const
  * as public member functions.
+ * *or*
+ * auto fmt_print_ctx(auto &ctx) -> decltype(ctx.out());
  */
 template<class T>
 concept has_fmt_print = requires(T t) {
@@ -31,6 +33,11 @@ template<class T>
 concept has_alt_fmt_print = requires(T t) {
   { t.alt_fmt_print(bool{}) } -> std::same_as<std::string>;
 };
+template<class T>
+concept has_fmt_print_ctx = requires(
+  T t, fmt::buffer_context<char> &ctx) {
+  { t.fmt_print_ctx(ctx) } -> std::same_as<decltype(ctx.out())>;
+};
 
 namespace fmt {
 
@@ -64,6 +71,16 @@ struct formatter<T> {
   bool verbose{true};
 };
 
+template <has_fmt_print_ctx T>
+struct formatter<T> {
+  template <typename ParseContext>
+  constexpr auto parse(ParseContext& ctx) { return ctx.begin(); }
+  template <typename FormatContext>
+  auto format(const T& k, FormatContext& ctx) const {
+    return k.fmt_print_ctx(ctx);
+  }
+};
+
 template <typename T>
 struct formatter<std::optional<T>> {
   constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }