format: add a custom formatter for std::type_info
authorJérémie Galarneau <jeremie.galarneau@efficios.com>
Thu, 12 May 2022 18:32:32 +0000 (14:32 -0400)
committerJérémie Galarneau <jeremie.galarneau@efficios.com>
Mon, 13 Jun 2022 20:34:46 +0000 (16:34 -0400)
The name() returned by std::type_info is implementation-dependant. In
practice, it is typically the type's mangled name. For GCC and clang, it
is possible to use abi::__cxa_demangle to demangle the name at runtime
while formatting a string.

If this poses any compatibility problem on other platforms, we can
fallback to using name() directly.

Signed-off-by: Jérémie Galarneau <jeremie.galarneau@efficios.com>
Change-Id: Ib80babe4039c91ce6fdf6d9a9442c31645a43b08

src/common/format.hpp

index b49a793b9a83808e4ea2203dffe54e0b45f74982..73b363408f49cf499f326f601c1bdd0cd8835478 100644 (file)
@@ -9,6 +9,9 @@
 
 #include <common/macros.hpp>
 
+#include <string>
+#include <cxxabi.h>
+
 DIAGNOSTIC_PUSH
 DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
 DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
@@ -16,4 +19,19 @@ DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
 #include <vendor/fmt/core.h>
 DIAGNOSTIC_POP
 
+template <>
+struct fmt::formatter<std::type_info> : fmt::formatter<std::string> {
+       template <typename FormatCtx>
+       typename FormatCtx::iterator format(const std::type_info& type_info, FormatCtx& ctx)
+       {
+               int status;
+               auto demangled_name = abi::__cxa_demangle(type_info.name(), nullptr, 0, &status);
+               auto it = status == 0 ? fmt::formatter<std::string>::format(demangled_name, ctx) :
+                                             fmt::formatter<std::string>::format(type_info.name(), ctx);
+
+               free(demangled_name);
+               return it;
+       }
+};
+
 #endif /* LTTNG_FORMAT_H */
This page took 0.026638 seconds and 4 git commands to generate.