.gitignore: ignore local vscode workspace settings file
[lttng-tools.git] / src / common / format.hpp
index 67509c275bad365ee23c2bd86ec7ab6fe44df5aa..2ba6cef125ab735ae8977c88dde7298c0c889f93 100644 (file)
@@ -9,8 +9,9 @@
 
 #include <common/macros.hpp>
 
-#include <string>
 #include <cxxabi.h>
+#include <string>
+#include <utility>
 
 DIAGNOSTIC_PUSH
 DIAGNOSTIC_IGNORE_SUGGEST_ATTRIBUTE_FORMAT
@@ -19,6 +20,8 @@ DIAGNOSTIC_IGNORE_DUPLICATED_BRANCHES
 #include <vendor/fmt/core.h>
 DIAGNOSTIC_POP
 
+#include <common/make-unique-wrapper.hpp>
+
 /*
  * Due to a bug in g++ < 7.1, this specialization must be enclosed in the fmt namespace,
  * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480.
@@ -31,15 +34,30 @@ struct formatter<std::type_info> : formatter<std::string> {
                                                    FormatContextType& ctx)
        {
                int status;
-               auto demangled_name =
-                       abi::__cxa_demangle(type_info.name(), nullptr, nullptr, &status);
-               auto it = status == 0 ? formatter<std::string>::format(demangled_name, ctx) :
-                                       formatter<std::string>::format(type_info.name(), ctx);
+               /*
+                * The documentation of __cxa_demangle mentions the returned string is allocated
+                * using malloc (not new), hence the use of lttng::memory::free.
+                */
+               const auto demangled_name = lttng::make_unique_wrapper<char, lttng::memory::free>(
+                       abi::__cxa_demangle(type_info.name(), nullptr, nullptr, &status));
 
-               free(demangled_name);
+               auto it = status == 0 ? formatter<std::string>::format(demangled_name.get(), ctx) :
+                                       formatter<std::string>::format(type_info.name(), ctx);
                return it;
        }
 };
 } /* namespace fmt */
 
+namespace lttng {
+template <typename... FormattingArguments>
+std::string format(FormattingArguments&&...args)
+{
+       try {
+               return fmt::format(std::forward<FormattingArguments>(args)...);
+       } catch (const fmt::format_error& ex) {
+               return std::string("Failed to format string: ") += ex.what();
+       }
+}
+} /* namespace lttng */
+
 #endif /* LTTNG_FORMAT_H */
This page took 0.023158 seconds and 4 git commands to generate.