cpp-common/bt2c: add {fmt} formatter for `bt2::ConstValue`
authorSimon Marchi <simon.marchi@efficios.com>
Fri, 31 May 2024 17:02:28 +0000 (13:02 -0400)
committerSimon Marchi <simon.marchi@efficios.com>
Wed, 4 Sep 2024 19:05:14 +0000 (15:05 -0400)
I found this useful for debugging, but I suppose it could be used for
logging as well.

Change-Id: I83b8af3ed706c64f2f66347cf085d0291c9c09fe
Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12831
Tested-by: jenkins <jenkins@lttng.org>
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
src/cpp-common/bt2c/fmt.hpp

index f29a77a209484827ef0002c3e43494712e909e95..7a3731a26214a9e8103f2f70dbf87d0dd3c7eb87 100644 (file)
@@ -7,6 +7,7 @@
 #ifndef BABELTRACE_CPP_COMMON_BT2C_FMT_HPP
 #define BABELTRACE_CPP_COMMON_BT2C_FMT_HPP
 
+#include "cpp-common/bt2/value.hpp"
 #include "cpp-common/vendor/fmt/format.h" /* IWYU pragma: keep */
 #include "cpp-common/vendor/wise-enum/wise_enum.h"
 
@@ -28,6 +29,59 @@ template <typename T>
     return wise_enum::to_string<T>(val);
 }
 
+inline std::string format_as(const bt2::ConstValue val) noexcept
+{
+    switch (val.type()) {
+    case ValueType::Null:
+        return "null";
+
+    case ValueType::Bool:
+        return val.asBool().value() ? "true" : "false";
+
+    case ValueType::UnsignedInteger:
+        return fmt::format("{}u", val.asUnsignedInteger().value());
+
+    case ValueType::SignedInteger:
+        return fmt::format("{}", val.asSignedInteger().value());
+
+    case ValueType::Real:
+        return fmt::format("{}", val.asReal().value());
+
+    case ValueType::String:
+        return fmt::format("\"{}\"", val.asString().value());
+
+    case ValueType::Array:
+    {
+        std::string ret {'['};
+        const char *maybeComma = "";
+
+        for (const auto elem : val.asArray()) {
+            ret += fmt::format("{}{}", maybeComma, elem);
+            maybeComma = ", ";
+        }
+
+        ret += ']';
+        return ret;
+    }
+
+    case ValueType::Map:
+    {
+        std::string ret {'{'};
+        const char *maybeComma = "";
+
+        val.asMap().forEach([&](const bt2c::CStringView k, const bt2::ConstValue v) {
+            ret += fmt::format("{}{}: {}", maybeComma, k, v);
+            maybeComma = ", ";
+        });
+
+        ret += '}';
+        return ret;
+    }
+    }
+
+    bt_common_abort();
+}
+
 } /* namespace bt2 */
 
 namespace bt2c {
This page took 0.026074 seconds and 4 git commands to generate.