From 57731356087ed2bb01c24855f5998c88faf79f33 Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Fri, 31 May 2024 13:02:28 -0400 Subject: [PATCH] cpp-common/bt2c: add {fmt} formatter for `bt2::ConstValue` 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 Reviewed-on: https://review.lttng.org/c/babeltrace/+/12831 Tested-by: jenkins Reviewed-by: Philippe Proulx --- src/cpp-common/bt2c/fmt.hpp | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/cpp-common/bt2c/fmt.hpp b/src/cpp-common/bt2c/fmt.hpp index f29a77a2..7a3731a2 100644 --- a/src/cpp-common/bt2c/fmt.hpp +++ b/src/cpp-common/bt2c/fmt.hpp @@ -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 return wise_enum::to_string(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 { -- 2.34.1