wren
Vulkan-based game engine
Loading...
Searching...
No Matches
format.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <boost/describe.hpp>
4#include <format>
5
7
8template <wren::DescribedStruct T>
9struct std::formatter<T, char> {
10 constexpr auto parse(std::format_parse_context& ctx) {
11 auto it = ctx.begin(), end = ctx.end();
12
13 if (it != end && *it != '}') {
14 throw std::runtime_error("invalid format");
15 }
16
17 return it;
18 }
19
20 auto format(const T& t, format_context& ctx) const {
21 using namespace boost::describe;
22
23 using Bd = describe_bases<T, mod_any_access>;
24 using Md = describe_members<T, mod_any_access>;
25
26 auto out = ctx.out();
27
28 *out++ = '{';
29
30 bool first = true;
31
32 boost::mp11::mp_for_each<Bd>([&](auto d) {
33 if (!first) {
34 *out++ = ',';
35 }
36
37 first = false;
38
39 out = std::format_to(out, " {}", t);
40 });
41
42 boost::mp11::mp_for_each<Md>([&](auto d) {
43 if (!first) {
44 *out++ = ',';
45 }
46
47 first = false;
48
49 out = std::format_to(out, " .{}={}", d.name, t.*d.pointer);
50 });
51
52 if (!first) {
53 *out++ = ' ';
54 }
55
56 *out++ = '}';
57
58 return out;
59 }
60};
61
62template <wren::DescribedEnum T>
63struct std::formatter<T, char> {
64 private:
65 using U = std::underlying_type_t<T>;
66
67 std::formatter<std::string_view, char> sf_;
68 std::formatter<U, char> nf_;
69
70 public:
71 constexpr auto parse(format_parse_context& ctx) {
72 auto i1 = sf_.parse(ctx);
73 auto i2 = nf_.parse(ctx);
74
75 if (i1 != i2) {
76 throw std::runtime_error("invalid format");
77 }
78
79 return i1;
80 }
81
82 auto format(const T& t, format_context& ctx) const {
83 const char* s = boost::describe::enum_to_string(t, 0);
84
85 if (s) {
86 return sf_.format(s, ctx);
87 } else {
88 return nf_.format(static_cast<U>(t), ctx);
89 }
90 }
91};
std::formatter< std::string_view, char > sf_
Definition format.hpp:67
std::formatter< U, char > nf_
Definition format.hpp:68
auto format(const T &t, format_context &ctx) const
Definition format.hpp:20
constexpr auto parse(std::format_parse_context &ctx)
Definition format.hpp:10
std::underlying_type_t< T > U
Definition format.hpp:65
constexpr auto parse(format_parse_context &ctx)
Definition format.hpp:71