-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.hpp
More file actions
323 lines (272 loc) · 7.8 KB
/
Copy pathformat.hpp
File metadata and controls
323 lines (272 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
*
* @file format.hpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/rixcpp/rix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Rix
*
* Lightweight formatting utilities for rix/debug.
*
* Supported placeholders:
* - {} : automatic argument indexing
* - {0} : explicit positional indexing
* - {{ : escaped opening brace
* - }} : escaped closing brace
*
* Unsupported on purpose:
* - format specifiers such as {:>10}, {:.2f}, etc.
*
* Example:
*
* std::string s1 = rixlib::format("Hello, {}", "world");
* std::string s2 = rixlib::format("Value = {0}, name = {1}", 42, "Ada");
* std::string s3 = rixlib::format("{{ config }} = {}", "ready");
*
*/
#ifndef RIXCPP_DEBUG_INCLUDE_RIX_DEBUG_FORMAT_HPP_INCLUDED
#define RIXCPP_DEBUG_INCLUDE_RIX_DEBUG_FORMAT_HPP_INCLUDED
#include <array>
#include <cctype>
#include <cstddef>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <rix/debug/print.hpp>
namespace rixlib
{
/**
* @brief Exception type thrown on invalid format strings or invalid argument access.
*/
class format_error : public std::runtime_error
{
public:
explicit format_error(const std::string &message)
: std::runtime_error(message)
{
}
explicit format_error(const char *message)
: std::runtime_error(message)
{
}
};
namespace detail
{
/**
* @brief Convert a value to string using the Rix rendering pipeline.
*/
template <typename T>
[[nodiscard]] inline std::string format_arg_to_string(const T &value)
{
std::ostringstream oss;
auto &cfg = rixlib::default_config();
const bool old_raw_strings = cfg.raw_strings;
cfg.raw_strings = true;
try
{
rixlib::detail::write(oss, value);
}
catch (...)
{
cfg.raw_strings = old_raw_strings;
throw;
}
cfg.raw_strings = old_raw_strings;
return oss.str();
}
/**
* @brief Small non-owning view over a pre-rendered argument list.
*/
class rendered_arg_list
{
public:
template <std::size_t N>
explicit rendered_arg_list(const std::array<std::string, N> &values) noexcept
: data_(values.data()), size_(N)
{
}
[[nodiscard]] std::size_t size() const noexcept
{
return size_;
}
[[nodiscard]] const std::string &at(std::size_t index) const
{
if (index >= size_)
{
throw format_error("format argument index out of range");
}
return data_[index];
}
private:
const std::string *data_ = nullptr;
std::size_t size_ = 0;
};
/**
* @brief Parse an unsigned decimal integer from a placeholder body.
*/
[[nodiscard]] inline std::size_t parse_index(std::string_view text)
{
if (text.empty())
{
throw format_error("empty explicit format index");
}
std::size_t value = 0;
for (char ch : text)
{
if (!std::isdigit(static_cast<unsigned char>(ch)))
{
throw format_error("invalid explicit format index");
}
value = (value * 10u) + static_cast<std::size_t>(ch - '0');
}
return value;
}
/**
* @brief Render a format string into the destination string.
*/
inline void render_format_string(std::string &out,
std::string_view fmt,
const rendered_arg_list &args)
{
std::size_t i = 0;
std::size_t next_auto_index = 0;
bool used_auto_index = false;
bool used_explicit_index = false;
while (i < fmt.size())
{
const char ch = fmt[i];
if (ch == '{')
{
if ((i + 1u) < fmt.size() && fmt[i + 1u] == '{')
{
out.push_back('{');
i += 2u;
continue;
}
const std::size_t close = fmt.find('}', i + 1u);
if (close == std::string_view::npos)
{
throw format_error("unmatched '{' in format string");
}
const std::string_view token = fmt.substr(i + 1u, close - (i + 1u));
if (token.empty())
{
if (used_explicit_index)
{
throw format_error("cannot mix automatic and explicit argument indexing");
}
used_auto_index = true;
out += args.at(next_auto_index++);
}
else
{
if (used_auto_index)
{
throw format_error("cannot mix automatic and explicit argument indexing");
}
if (token.find(':') != std::string_view::npos)
{
throw format_error("format specifiers are not supported");
}
used_explicit_index = true;
out += args.at(parse_index(token));
}
i = close + 1u;
continue;
}
if (ch == '}')
{
if ((i + 1u) < fmt.size() && fmt[i + 1u] == '}')
{
out.push_back('}');
i += 2u;
continue;
}
throw format_error("single '}' encountered in format string");
}
out.push_back(ch);
++i;
}
}
/**
* @brief Estimate a useful output capacity before rendering.
*/
[[nodiscard]] inline std::size_t estimate_output_size(std::string_view fmt,
const rendered_arg_list &args)
{
std::size_t total = fmt.size();
for (std::size_t i = 0; i < args.size(); ++i)
{
total += args.at(i).size();
}
return total;
}
} // namespace detail
/**
* @brief Format values into a new string using Rix placeholder syntax.
*/
template <typename... Args>
[[nodiscard]] std::string format(std::string_view fmt, const Args &...args)
{
std::array<std::string, sizeof...(Args)> rendered_args{
detail::format_arg_to_string(args)...};
detail::rendered_arg_list rendered{rendered_args};
std::string out;
out.reserve(detail::estimate_output_size(fmt, rendered));
detail::render_format_string(out, fmt, rendered);
return out;
}
/**
* @brief Append formatted output to an existing string.
*/
template <typename... Args>
void format_append(std::string &out, std::string_view fmt, const Args &...args)
{
std::array<std::string, sizeof...(Args)> rendered_args{
detail::format_arg_to_string(args)...};
detail::rendered_arg_list rendered{rendered_args};
out.reserve(out.size() + detail::estimate_output_size(fmt, rendered));
detail::render_format_string(out, fmt, rendered);
}
/**
* @brief Replace the destination string with formatted output.
*/
template <typename... Args>
void format_to(std::string &out, std::string_view fmt, const Args &...args)
{
out.clear();
format_append(out, fmt, args...);
}
} // namespace rixlib
namespace rixlib::debug
{
/**
* @brief Object-style formatting API mounted into rixlib::debug::Debug.
*/
class Format
{
public:
template <typename... Args>
[[nodiscard]] std::string operator()(std::string_view fmt, const Args &...args) const
{
return rixlib::format(fmt, args...);
}
template <typename... Args>
void append(std::string &out, std::string_view fmt, const Args &...args) const
{
rixlib::format_append(out, fmt, args...);
}
template <typename... Args>
void to(std::string &out, std::string_view fmt, const Args &...args) const
{
rixlib::format_to(out, fmt, args...);
}
};
}
#endif // RIXCPP_DEBUG_INCLUDE_RIX_DEBUG_FORMAT_HPP_INCLUDED