7a3731a26214a9e8103f2f70dbf87d0dd3c7eb87
[babeltrace.git] / src / cpp-common / bt2c / fmt.hpp
1 /*
2 * Copyright (c) 2024 EfficiOS, inc.
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7 #ifndef BABELTRACE_CPP_COMMON_BT2C_FMT_HPP
8 #define BABELTRACE_CPP_COMMON_BT2C_FMT_HPP
9
10 #include "cpp-common/bt2/value.hpp"
11 #include "cpp-common/vendor/fmt/format.h" /* IWYU pragma: keep */
12 #include "cpp-common/vendor/wise-enum/wise_enum.h"
13
14 #include "uuid.hpp"
15
16 namespace internal {
17
18 template <typename T>
19 using EnableIfIsWiseEnum =
20 typename std::enable_if<wise_enum::is_wise_enum<T>::value, wise_enum::string_type>::type;
21
22 } /* namespace internal */
23
24 namespace bt2 {
25
26 template <typename T>
27 ::internal::EnableIfIsWiseEnum<T> format_as(const T val) noexcept
28 {
29 return wise_enum::to_string<T>(val);
30 }
31
32 inline std::string format_as(const bt2::ConstValue val) noexcept
33 {
34 switch (val.type()) {
35 case ValueType::Null:
36 return "null";
37
38 case ValueType::Bool:
39 return val.asBool().value() ? "true" : "false";
40
41 case ValueType::UnsignedInteger:
42 return fmt::format("{}u", val.asUnsignedInteger().value());
43
44 case ValueType::SignedInteger:
45 return fmt::format("{}", val.asSignedInteger().value());
46
47 case ValueType::Real:
48 return fmt::format("{}", val.asReal().value());
49
50 case ValueType::String:
51 return fmt::format("\"{}\"", val.asString().value());
52
53 case ValueType::Array:
54 {
55 std::string ret {'['};
56 const char *maybeComma = "";
57
58 for (const auto elem : val.asArray()) {
59 ret += fmt::format("{}{}", maybeComma, elem);
60 maybeComma = ", ";
61 }
62
63 ret += ']';
64 return ret;
65 }
66
67 case ValueType::Map:
68 {
69 std::string ret {'{'};
70 const char *maybeComma = "";
71
72 val.asMap().forEach([&](const bt2c::CStringView k, const bt2::ConstValue v) {
73 ret += fmt::format("{}{}: {}", maybeComma, k, v);
74 maybeComma = ", ";
75 });
76
77 ret += '}';
78 return ret;
79 }
80 }
81
82 bt_common_abort();
83 }
84
85 } /* namespace bt2 */
86
87 namespace bt2c {
88
89 template <typename T>
90 ::internal::EnableIfIsWiseEnum<T> format_as(const T val) noexcept
91 {
92 return wise_enum::to_string<T>(val);
93 }
94
95 inline std::string format_as(const UuidView uuid)
96 {
97 return uuid.str();
98 }
99
100 } /* namespace bt2c */
101
102 #endif /* BABELTRACE_CPP_COMMON_BT2C_FMT_HPP */
This page took 0.034583 seconds and 5 git commands to generate.