StormByte 3.0.0
C++26 foundation of the StormByte suite
Loading...
Searching...
No Matches
replace_token.hxx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This is the base for StormByte Suite libraries.
5 *
6 * StormByte original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte source in this repository.
20 * They do not cover other StormByte modules or any third-party material
21 * shipped with this repository (including everything under thirdparty/),
22 * which remains under its own license.
23 *
24 * Neither license grants any patent rights. Any patent licenses required
25 * to use this software or third-party components must be obtained separately
26 * from the patent holders.
27 *
28 * StormByte is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU Lesser General Public License for more details.
32 *
33 * You should have received a copy of the GNU Lesser General Public License
34 * version 3 along with StormByte. If not, see
35 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
36 *
37 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
38 */
39
40#pragma once
41
45
46#include <charconv>
47#include <cstdint>
48#include <limits>
49#include <string>
50#include <string_view>
51#include <system_error>
52#include <type_traits>
53#include <utility>
54
55namespace StormByte::Safe {
64 bool zero = false;
65 bool width_set = false;
66 unsigned width = 0;
67 bool precision_set = false;
68 int precision = 0;
69 char type = 0;
70
71 constexpr bool IsDefault() const noexcept {
72 return !zero && !width_set && !precision_set && type == 0;
73 }
74 };
75
80 template<class Char>
82 std::size_t offset = 0;
83 std::size_t length = 0;
85 };
86
95 template<class Char>
96 constexpr bool ParseReplaceTokenSpec(const Char* data, std::size_t count, ReplaceTokenSpec& out) noexcept {
98 std::size_t index = 0;
99 const auto digit = [](Char unit) noexcept {
100 return unit >= static_cast<Char>('0') && unit <= static_cast<Char>('9');
101 };
102 if (index < count && data[index] == static_cast<Char>(':'))
103 ++index;
104 else if (count != 0)
105 return false;
106 if (index < count && data[index] == static_cast<Char>('0')) {
107 spec.zero = true;
108 ++index;
109 }
110 if (index < count && digit(data[index])) {
111 unsigned width = 0;
112 spec.width_set = true;
113 while (index < count && digit(data[index])) {
114 const unsigned next = static_cast<unsigned>(data[index] - static_cast<Char>('0'));
115 if (width > (100000u - next) / 10u)
116 return false;
117 width = width * 10u + next;
118 ++index;
119 }
120 spec.width = width;
121 }
122 if (index < count && data[index] == static_cast<Char>('.')) {
123 ++index;
124 spec.precision_set = true;
125 int precision = 0;
126 while (index < count && digit(data[index])) {
127 precision = precision * 10 + static_cast<int>(data[index] - static_cast<Char>('0'));
128 if (precision > 100)
129 return false;
130 ++index;
131 }
132 spec.precision = precision;
133 }
134 if (index < count) {
135 const Char type = data[index++];
136 if (type != static_cast<Char>('d') && type != static_cast<Char>('f') && type != static_cast<Char>('g') && type != static_cast<Char>('G') && type != static_cast<Char>('x') && type != static_cast<Char>('X'))
137 return false;
138 spec.type = static_cast<char>(type);
139 }
140 if (index != count)
141 return false;
142 out = spec;
143 return true;
144 }
145
154 template<class Char>
155 std::size_t FindReplaceTokens(std::basic_string_view<Char> text, ReplaceTokenPlace<Char>* places, std::size_t capacity) noexcept {
156 std::size_t found = 0;
157 for (std::size_t index = 0; index < text.size() && found < capacity; ++index) {
158 if (text[index] != static_cast<Char>('{'))
159 continue;
160 const std::size_t close = text.find(static_cast<Char>('}'), index + 1);
161 if (close == std::basic_string_view<Char>::npos)
162 break;
163 const auto inside = text.substr(index + 1, close - index - 1);
164 if (inside.find(static_cast<Char>('{')) != std::basic_string_view<Char>::npos)
165 continue;
166 ReplaceTokenSpec spec;
167 if (!ParseReplaceTokenSpec(inside.data(), inside.size(), spec))
168 continue;
169 places[found] = ReplaceTokenPlace<Char>{index, close - index + 1, spec};
170 ++found;
171 index = close;
172 }
173 return found;
174 }
175
176 namespace {
177 inline void AppendHexDigits(std::string& out, std::uintmax_t value, bool upper) {
178 if (value == 0) {
179 out.push_back('0');
180 return;
181 }
182 char digits[sizeof(std::uintmax_t) * 2];
183 int count = 0;
184 const char* alphabet = upper ? "0123456789ABCDEF" : "0123456789abcdef";
185 while (value != 0) {
186 digits[count++] = alphabet[value & 0xF];
187 value >>= 4;
188 }
189 while (count != 0)
190 out.push_back(digits[--count]);
191 }
192
193 inline void PadAscii(std::string& text, const ReplaceTokenSpec& spec) {
194 if (!spec.width_set || text.size() >= spec.width)
195 return;
196 const std::size_t pad = spec.width - text.size();
197 if (spec.zero) {
198 const std::size_t at = (!text.empty() && (text[0] == '-' || text[0] == '+')) ? 1 : 0;
199 text.insert(at, pad, '0');
200 } else
201 text.insert(0, pad, ' ');
202 }
203
204 template<class Char>
205 void AssignAscii(std::basic_string<Char>& out, std::string_view ascii) {
206 out.assign(ascii.begin(), ascii.end());
207 }
208
209 template<class Int>
210 std::string FormatIntegerAscii(Int value, const ReplaceTokenSpec& spec) {
211 std::string ascii;
212 if (spec.type == 'x' || spec.type == 'X') {
213 std::uintmax_t bits = 0;
214 if constexpr (Type::Signed<Int>)
215 bits = static_cast<std::make_unsigned_t<Int>>(value);
216 else
217 bits = static_cast<std::uintmax_t>(value);
218 AppendHexDigits(ascii, bits, spec.type == 'X');
219 } else {
220 char buffer[64];
221 const std::to_chars_result result = std::to_chars(buffer, buffer + sizeof(buffer), value);
222 ascii.assign(buffer, result.ptr);
223 }
224 PadAscii(ascii, spec);
225 return ascii;
226 }
227
228 template<class Float>
229 std::string FormatFloatAscii(Float value, const ReplaceTokenSpec& spec) {
230 const int precision = spec.precision_set ? spec.precision : 6;
231 std::chars_format format = std::chars_format::general;
232 if (spec.type == 'f')
233 format = std::chars_format::fixed;
234 char buffer[128];
235 const std::to_chars_result result = std::to_chars(buffer, buffer + sizeof(buffer), value, format, precision);
236 std::string ascii(buffer, result.ptr == buffer ? buffer : result.ptr);
237 if (result.ec != std::errc{})
238 ascii = std::to_string(static_cast<double>(value));
239 if (spec.type == 'G') {
240 for (char& unit : ascii) {
241 if (unit >= 'a' && unit <= 'z')
242 unit = static_cast<char>(unit - 'a' + 'A');
243 }
244 }
245 PadAscii(ascii, spec);
246 return ascii;
247 }
248 }
249
257 template<class Char, class T>
260 Type::SameAs<std::remove_cvref_t<T>, std::nullptr_t> ||
264 (Type::SameAs<std::remove_cvref_t<T>, wchar_t> && Type::SameAs<Char, wchar_t>) ||
265 Type::ConvertibleTo<std::remove_cvref_t<T>, std::basic_string_view<Char>> ||
268
278 template<class Char, class T>
279 bool FormatReplaceToken(std::basic_string<Char>& out, T&& value, const ReplaceTokenSpec& spec) {
280 using Bare = std::remove_cvref_t<T>;
281 if constexpr (Type::SameAs<Bare, bool>) {
282 AssignAscii(out, value ? std::string_view("true") : std::string_view("false"));
283 return true;
285 if (value == nullptr)
286 out.clear();
287 else
288 out.assign(std::basic_string_view<Char>(value));
289 return true;
291 const void* address = nullptr;
292 if constexpr (Type::Pointer<Bare>)
293 address = reinterpret_cast<const void*>(value);
294 else if constexpr (Type::SmartPointer<Bare>)
295 address = static_cast<const void*>(value.get());
296 if (spec.IsDefault()) {
297 std::string ascii = "0x";
298 AppendHexDigits(ascii, reinterpret_cast<std::uintptr_t>(address), false);
299 AssignAscii(out, ascii);
300 } else
301 AssignAscii(out, FormatIntegerAscii(reinterpret_cast<std::uintptr_t>(address), spec));
302 return true;
303 } else if constexpr (Type::SameAs<Bare, char> && Type::SameAs<Char, char>) {
304 if (spec.IsDefault())
305 out.assign(1, static_cast<char>(value));
306 else
307 AssignAscii(out, FormatIntegerAscii(static_cast<int>(static_cast<unsigned char>(value)), spec));
308 return true;
310 if (spec.IsDefault())
311 out.assign(1, static_cast<wchar_t>(value));
312 else
313 AssignAscii(out, FormatIntegerAscii(static_cast<std::uint32_t>(value), spec));
314 return true;
316 out.assign(std::basic_string_view<Char>(std::forward<T>(value)));
317 return true;
318 } else if constexpr (Type::FloatingPoint<Bare>) {
319 if (spec.IsDefault()) {
320 if constexpr (Type::SameAs<Char, wchar_t>)
321 out = std::to_wstring(value);
322 else
323 out = std::to_string(value);
324 } else if (spec.type == 'x' || spec.type == 'X' || spec.type == 'd')
325 AssignAscii(out, FormatIntegerAscii(static_cast<long long>(value), spec));
326 else
327 AssignAscii(out, FormatFloatAscii(value, spec));
328 return true;
329 } else if constexpr (Type::Integral<Bare>) {
330 if (spec.IsDefault()) {
331 if constexpr (Type::SameAs<Char, wchar_t>)
332 out = std::to_wstring(value);
333 else
334 out = std::to_string(value);
335 } else if (spec.type == 'f' || spec.type == 'g' || spec.type == 'G')
336 AssignAscii(out, FormatFloatAscii(static_cast<double>(value), spec));
337 else
338 AssignAscii(out, FormatIntegerAscii(value, spec));
339 return true;
340 } else if constexpr (Type::Numeral<Bare>) {
341 const auto bits = static_cast<std::uint64_t>(std::forward<T>(value));
342 if (spec.IsDefault())
343 return false;
344 if (spec.type == 'f' || spec.type == 'g' || spec.type == 'G')
345 AssignAscii(out, FormatFloatAscii(static_cast<double>(bits), spec));
346 else
347 AssignAscii(out, FormatIntegerAscii(bits, spec));
348 return true;
350 if (spec.IsDefault())
351 return false;
352 AssignAscii(out, FormatIntegerAscii(static_cast<std::uint64_t>(std::forward<T>(value)), spec));
353 return true;
354 } else
355 return false;
356 }
357}
True when FormatReplaceToken always writes T and never asks for a string conversion.
Definition replace_token.hxx:258
From is implicitly convertible to To (std::is_convertible).
Definition conversions.hxx:74
From may be explicitly converted to To with static_cast.
Definition conversions.hxx:86
Floating-point type (float, double, long double).
Definition categories.hxx:197
Integral type (bool, char, int, long, …), including cv.
Definition categories.hxx:185
Host integer or suite count type.
Definition categories.hxx:257
Raw (possibly cv-qualified) pointer type.
Definition categories.hxx:131
Same type after stripping cv and references from both sides.
Definition relations.hxx:139
Smart pointer-like type: dereferenceable and exposes get().
Definition categories.hxx:147
Owned values that cross a DLL without the caller's CRT.
bool FormatReplaceToken(std::basic_string< Char > &out, T &&value, const ReplaceTokenSpec &spec)
Render one argument when it does not need an owned-string conversion.
Definition replace_token.hxx:279
std::size_t FindReplaceTokens(std::basic_string_view< Char > text, ReplaceTokenPlace< Char > *places, std::size_t capacity) noexcept
Collect up to capacity fields, in order.
Definition replace_token.hxx:155
constexpr bool ParseReplaceTokenSpec(const Char *data, std::size_t count, ReplaceTokenSpec &out) noexcept
Parse the inside of one {...}.
Definition replace_token.hxx:96
Where a field sits in the pattern, and how to render its argument.
Definition replace_token.hxx:81
ReplaceTokenSpec spec
Definition replace_token.hxx:84
std::size_t offset
Definition replace_token.hxx:82
std::size_t length
Definition replace_token.hxx:83
One ReplaceToken field.
Definition replace_token.hxx:63
unsigned width
Definition replace_token.hxx:66
constexpr bool IsDefault() const noexcept
Definition replace_token.hxx:71
bool zero
Definition replace_token.hxx:64
int precision
Definition replace_token.hxx:68
bool width_set
Definition replace_token.hxx:65
bool precision_set
Definition replace_token.hxx:67
char type
Definition replace_token.hxx:69