rapidyaml 0.16.0
parse and emit YAML, and do it fast
Loading...
Searching...
No Matches
charconv.hpp
Go to the documentation of this file.
1#ifndef C4_CHARCONV_HPP_
2#define C4_CHARCONV_HPP_
3
4/** @file charconv.hpp Lightweight generic type-safe wrappers for
5 * converting individual values to/from strings.
6 */
7
8#include "c4/language.hpp"
9#include <inttypes.h>
10#include <type_traits>
11#include <climits>
12#include <limits>
13#include <utility>
14
15#include "c4/config.hpp"
16#include "c4/substr.hpp"
17#include "c4/std/std_fwd.hpp"
18#include "c4/memory_util.hpp"
19
20#ifndef C4CORE_NO_FAST_FLOAT
21# if (C4_CPP >= 17)
22# if defined(_MSC_VER)
23# if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019) // VS2017 and lower do not have these macros
24# include <charconv>
25# define C4CORE_HAVE_STD_TOCHARS 1
26# define C4CORE_HAVE_STD_FROMCHARS 0 // prefer fast_float with MSVC
27# define C4CORE_HAVE_FAST_FLOAT 1
28# else
29# define C4CORE_HAVE_STD_TOCHARS 0
30# define C4CORE_HAVE_STD_FROMCHARS 0
31# define C4CORE_HAVE_FAST_FLOAT 1
32# endif
33# else
34# if __has_include(<charconv>)
35# include <charconv>
36# define C4CORE_HAVE_STD_TOCHARS 1
37# define C4CORE_HAVE_STD_FROMCHARS 0 // prefer fast_float
38# define C4CORE_HAVE_FAST_FLOAT 1
39# else
40# define C4CORE_HAVE_STD_TOCHARS 0
41# define C4CORE_HAVE_STD_FROMCHARS 0
42# define C4CORE_HAVE_FAST_FLOAT 1
43# endif
44# endif
45# else
46# define C4CORE_HAVE_STD_TOCHARS 0 // this will fall back to snprintf()
47# define C4CORE_HAVE_STD_FROMCHARS 0
48# define C4CORE_HAVE_FAST_FLOAT 1
49# endif
50# if C4CORE_HAVE_FAST_FLOAT
51# include "c4/ext/fast_float.hpp"
52# endif
53#elif (C4_CPP >= 17)
54# define C4CORE_HAVE_FAST_FLOAT 0
55# if defined(_MSC_VER)
56# if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019) // VS2017 and lower do not have these macros
57# include <charconv>
58# define C4CORE_HAVE_STD_TOCHARS 1
59# define C4CORE_HAVE_STD_FROMCHARS 1
60# else
61# define C4CORE_HAVE_STD_TOCHARS 0
62# define C4CORE_HAVE_STD_FROMCHARS 0
63# endif
64# else
65# if __has_include(<charconv>)
66# include <charconv>
67# if defined(__cpp_lib_to_chars)
68# define C4CORE_HAVE_STD_TOCHARS 1
69# define C4CORE_HAVE_STD_FROMCHARS 1 // glibc uses fast_float internally
70# else
71# define C4CORE_HAVE_STD_TOCHARS 0
72# define C4CORE_HAVE_STD_FROMCHARS 0
73# endif
74# else
75# define C4CORE_HAVE_STD_TOCHARS 0
76# define C4CORE_HAVE_STD_FROMCHARS 0
77# endif
78# endif
79#else
80# define C4CORE_HAVE_STD_TOCHARS 0
81# define C4CORE_HAVE_STD_FROMCHARS 0
82# define C4CORE_HAVE_FAST_FLOAT 0
83#endif
84
85
86#if !C4CORE_HAVE_STD_FROMCHARS
87#include <cstdio>
88#endif
89
90
91#if defined(_MSC_VER) && !defined(__clang__)
92# pragma warning(push)
93# pragma warning(disable: 4996) // snprintf/scanf: this function or variable may be unsafe
94# if C4_MSVC_VERSION != C4_MSVC_VERSION_2017
95# pragma warning(disable: 4800) //'int': forcing value to bool 'true' or 'false' (performance warning)
96# endif
97#elif defined(__clang__)
98# pragma clang diagnostic push
99# pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
100# pragma clang diagnostic ignored "-Wformat-nonliteral"
101# pragma clang diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision
102# pragma clang diagnostic ignored "-Wold-style-cast"
103#elif defined(__GNUC__)
104# pragma GCC diagnostic push
105# pragma GCC diagnostic ignored "-Wformat-nonliteral"
106# pragma GCC diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision
107# pragma GCC diagnostic ignored "-Wuseless-cast"
108# pragma GCC diagnostic ignored "-Wold-style-cast"
109#endif
110
111#if defined(__clang__)
112#define C4_NO_UBSAN_IOVRFLW __attribute__((no_sanitize("signed-integer-overflow")))
113#elif defined(__GNUC__)
114#if __GNUC__ > 7
115#define C4_NO_UBSAN_IOVRFLW __attribute__((no_sanitize("signed-integer-overflow")))
116#else
117#define C4_NO_UBSAN_IOVRFLW
118#endif
119#else
120#define C4_NO_UBSAN_IOVRFLW
121#endif
122
123// NOLINTBEGIN(*-signed-bitwise)
124
125namespace c4 {
126
127/** @defgroup doc_charconv Charconv utilities
128 *
129 * Lightweight, very fast generic type-safe wrappers for converting
130 * individual values to/from strings. These are the main generic
131 * functions:
132 * - @ref doc_to_chars and its alias @ref xtoa(): implemented by calling @ref itoa() / @ref utoa() / @ref ftoa() / @ref dtoa() (or generically @ref xtoa())
133 * - @ref doc_from_chars and its alias @ref atox(): implemented by calling @ref atoi() / @ref atou() / @ref atof() / @ref atod() (or generically @ref atox())
134 * - @ref to_chars_sub()
135 * - @ref from_chars_first()
136 * - @ref xtoa() and @ref atox() are implemented in terms of @ref write_dec() / @ref read_dec() et al (see @ref doc_write / @ref doc_read())
137 *
138 * And also some modest brag is in order: these functions are really
139 * fast: faster even than C++17 `std::to_chars()` and
140 * `std::to_chars()`, and many dozens of times faster than the
141 * iostream abominations.
142 *
143 * For example, here are some benchmark comparisons for @ref
144 * doc_from_chars (link leads to the main project README, where these
145 * results are shown more systematically).
146 *
147 * <table>
148 * <caption id="atox-i64-results">atox,int64_t</caption>
149 * <tr><th>g++12, linux <th>Visual Studio 2019
150 * <tr><td> \image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-atox-mega_bytes_per_second-i64.png <td> \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-atox-mega_bytes_per_second-i64.png
151 * </table>
152 *
153 * <table>
154 * <caption id="xtoa-i64-results">xtoa,int64_t</caption>
155 * <tr><th>g++12, linux <th>Visual Studio 2019
156 * <tr><td> \image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-xtoa-mega_bytes_per_second-i64.png <td> \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-xtoa-mega_bytes_per_second-i64.png
157 * </table>
158 *
159 * To parse floating point, c4core uses
160 * [fastfloat](https://github.com/fastfloat/fast_float), which is
161 * extremely fast, by an even larger factor:
162 *
163 * <table>
164 * <caption id="atox-float-results">atox,float</caption>
165 * <tr><th>g++12, linux <th>Visual Studio 2019
166 * <tr><td> \image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-atof-mega_bytes_per_second-float.png <td> \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-atof-mega_bytes_per_second-float.png
167 * </table>
168 *
169 * @{
170 */
171
172#if C4CORE_HAVE_STD_TOCHARS
173/** @warning Use only the symbol. Do not rely on the type or naked value of this enum. */
174typedef enum : std::underlying_type<std::chars_format>::type {
175 /** print the real number in floating point format (like %f) */
176 FTOA_FLOAT = static_cast<std::underlying_type<std::chars_format>::type>(std::chars_format::fixed),
177 /** print the real number in scientific format (like %e) */
178 FTOA_SCIENT = static_cast<std::underlying_type<std::chars_format>::type>(std::chars_format::scientific),
179 /** print the real number in flexible format (like %g) */
180 FTOA_FLEX = static_cast<std::underlying_type<std::chars_format>::type>(std::chars_format::general),
181 /** print the real number in hexadecimal format (like %a) */
182 FTOA_HEXA = static_cast<std::underlying_type<std::chars_format>::type>(std::chars_format::hex),
184#else
185/** @warning Use only the symbol. Do not rely on the type or naked value of this enum. */
186typedef enum : char {
187 /** print the real number in floating point format (like %f) */
189 /** print the real number in scientific format (like %e) */
191 /** print the real number in flexible format (like %g) */
193 /** print the real number in hexadecimal format (like %a) */
196#endif
197
198/** @cond dev */
199/** in some platforms, int,unsigned int
200 * are not any of int8_t...int64_t and
201 * long,unsigned long are not any of uint8_t...uint64_t */
202template<class T>
203struct is_fixed_length
204{
205 enum : bool {
206 /** true if T is one of the fixed length signed types */
207 value_i = (std::is_integral<T>::value
208 && (std::is_same<T, int8_t>::value
209 || std::is_same<T, int16_t>::value
210 || std::is_same<T, int32_t>::value
211 || std::is_same<T, int64_t>::value)),
212 /** true if T is one of the fixed length unsigned types */
213 value_u = (std::is_integral<T>::value
214 && (std::is_same<T, uint8_t>::value
215 || std::is_same<T, uint16_t>::value
216 || std::is_same<T, uint32_t>::value
217 || std::is_same<T, uint64_t>::value)),
218 /** true if T is one of the fixed length signed or unsigned types */
219 value = value_i || value_u,
220 };
221};
222/** @endcond */
223
224
225//-----------------------------------------------------------------------------
226//-----------------------------------------------------------------------------
227//-----------------------------------------------------------------------------
228
229#if defined(_MSC_VER) && !defined(__clang__)
230# pragma warning(push)
231#elif defined(__clang__)
232# pragma clang diagnostic push
233#elif defined(__GNUC__)
234# pragma GCC diagnostic push
235# pragma GCC diagnostic ignored "-Wconversion"
236# if __GNUC__ >= 6
237# pragma GCC diagnostic ignored "-Wnull-dereference"
238# endif
239#endif
240
241/** @cond dev */
242namespace detail {
243
244/* python command to get the values below:
245def dec(v):
246 return str(v)
247for bits in (8, 16, 32, 64):
248 imin, imax, umax = (-(1 << (bits - 1))), (1 << (bits - 1)) - 1, (1 << bits) - 1
249 for vname, v in (("imin", imin), ("imax", imax), ("umax", umax)):
250 for f in (bin, oct, dec, hex):
251 print(f"{bits}b: {vname}={v} {f.__name__}: len={len(f(v)):2d}: {v} {f(v)}")
252*/
253
254// do not use the type as the template argument because in some
255// platforms long!=int32 and long!=int64. Just use the numbytes
256// which is more generic and spares lengthy SFINAE code.
257template<size_t num_bytes, bool is_signed> struct charconv_digits_;
258template<class T> using charconv_digits = charconv_digits_<sizeof(T), std::is_signed<T>::value>;
259
260template<> struct charconv_digits_<1u, true> // int8_t
261{
262 enum : size_t {
263 maxdigits_bin = 1 + 2 + 8, // -128==-0b10000000
264 maxdigits_oct = 1 + 2 + 3, // -128==-0o200
265 maxdigits_dec = 1 + 3, // -128
266 maxdigits_hex = 1 + 2 + 2, // -128==-0x80
267 maxdigits_bin_nopfx = 8, // -128==-0b10000000
268 maxdigits_oct_nopfx = 3, // -128==-0o200
269 maxdigits_dec_nopfx = 3, // -128
270 maxdigits_hex_nopfx = 2, // -128==-0x80
271 };
272 // min values without sign!
273 static constexpr csubstr min_value_dec() noexcept { return csubstr("128"); }
274 static constexpr csubstr min_value_hex() noexcept { return csubstr("80"); }
275 static constexpr csubstr min_value_oct() noexcept { return csubstr("200"); }
276 static constexpr csubstr min_value_bin() noexcept { return csubstr("10000000"); }
277 static constexpr csubstr max_value_dec() noexcept { return csubstr("127"); }
278 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 3) || (str.len == 3 && str.str[0] <= '1')); }
279};
280template<> struct charconv_digits_<1u, false> // uint8_t
281{
282 enum : size_t {
283 maxdigits_bin = 2 + 8, // 255 0b11111111
284 maxdigits_oct = 2 + 3, // 255 0o377
285 maxdigits_dec = 3, // 255
286 maxdigits_hex = 2 + 2, // 255 0xff
287 maxdigits_bin_nopfx = 8, // 255 0b11111111
288 maxdigits_oct_nopfx = 3, // 255 0o377
289 maxdigits_dec_nopfx = 3, // 255
290 maxdigits_hex_nopfx = 2, // 255 0xff
291 };
292 static constexpr csubstr max_value_dec() noexcept { return csubstr("255"); }
293 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 3) || (str.len == 3 && str.str[0] <= '3')); }
294};
295template<> struct charconv_digits_<2u, true> // int16_t
296{
297 enum : size_t {
298 maxdigits_bin = 1 + 2 + 16, // -32768 -0b1000000000000000
299 maxdigits_oct = 1 + 2 + 6, // -32768 -0o100000
300 maxdigits_dec = 1 + 5, // -32768 -32768
301 maxdigits_hex = 1 + 2 + 4, // -32768 -0x8000
302 maxdigits_bin_nopfx = 16, // -32768 -0b1000000000000000
303 maxdigits_oct_nopfx = 6, // -32768 -0o100000
304 maxdigits_dec_nopfx = 5, // -32768 -32768
305 maxdigits_hex_nopfx = 4, // -32768 -0x8000
306 };
307 // min values without sign!
308 static constexpr csubstr min_value_dec() noexcept { return csubstr("32768"); }
309 static constexpr csubstr min_value_hex() noexcept { return csubstr("8000"); }
310 static constexpr csubstr min_value_oct() noexcept { return csubstr("100000"); }
311 static constexpr csubstr min_value_bin() noexcept { return csubstr("1000000000000000"); }
312 static constexpr csubstr max_value_dec() noexcept { return csubstr("32767"); }
313 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !(str.len < 6); }
314};
315template<> struct charconv_digits_<2u, false> // uint16_t
316{
317 enum : size_t {
318 maxdigits_bin = 2 + 16, // 65535 0b1111111111111111
319 maxdigits_oct = 2 + 6, // 65535 0o177777
320 maxdigits_dec = 6, // 65535 65535
321 maxdigits_hex = 2 + 4, // 65535 0xffff
322 maxdigits_bin_nopfx = 16, // 65535 0b1111111111111111
323 maxdigits_oct_nopfx = 6, // 65535 0o177777
324 maxdigits_dec_nopfx = 6, // 65535 65535
325 maxdigits_hex_nopfx = 4, // 65535 0xffff
326 };
327 static constexpr csubstr max_value_dec() noexcept { return csubstr("65535"); }
328 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 6) || (str.len == 6 && str.str[0] <= '1')); }
329};
330template<> struct charconv_digits_<4u, true> // int32_t
331{
332 enum : size_t {
333 maxdigits_bin = 1 + 2 + 32, // len=35: -2147483648 -0b10000000000000000000000000000000
334 maxdigits_oct = 1 + 2 + 11, // len=14: -2147483648 -0o20000000000
335 maxdigits_dec = 1 + 10, // len=11: -2147483648 -2147483648
336 maxdigits_hex = 1 + 2 + 8, // len=11: -2147483648 -0x80000000
337 maxdigits_bin_nopfx = 32, // len=35: -2147483648 -0b10000000000000000000000000000000
338 maxdigits_oct_nopfx = 11, // len=14: -2147483648 -0o20000000000
339 maxdigits_dec_nopfx = 10, // len=11: -2147483648 -2147483648
340 maxdigits_hex_nopfx = 8, // len=11: -2147483648 -0x80000000
341 };
342 // min values without sign!
343 static constexpr csubstr min_value_dec() noexcept { return csubstr("2147483648"); }
344 static constexpr csubstr min_value_hex() noexcept { return csubstr("80000000"); }
345 static constexpr csubstr min_value_oct() noexcept { return csubstr("20000000000"); }
346 static constexpr csubstr min_value_bin() noexcept { return csubstr("10000000000000000000000000000000"); }
347 static constexpr csubstr max_value_dec() noexcept { return csubstr("2147483647"); }
348 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 11) || (str.len == 11 && str.str[0] <= '1')); }
349};
350template<> struct charconv_digits_<4u, false> // uint32_t
351{
352 enum : size_t {
353 maxdigits_bin = 2 + 32, // len=34: 4294967295 0b11111111111111111111111111111111
354 maxdigits_oct = 2 + 11, // len=13: 4294967295 0o37777777777
355 maxdigits_dec = 10, // len=10: 4294967295 4294967295
356 maxdigits_hex = 2 + 8, // len=10: 4294967295 0xffffffff
357 maxdigits_bin_nopfx = 32, // len=34: 4294967295 0b11111111111111111111111111111111
358 maxdigits_oct_nopfx = 11, // len=13: 4294967295 0o37777777777
359 maxdigits_dec_nopfx = 10, // len=10: 4294967295 4294967295
360 maxdigits_hex_nopfx = 8, // len=10: 4294967295 0xffffffff
361 };
362 static constexpr csubstr max_value_dec() noexcept { return csubstr("4294967295"); }
363 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 11) || (str.len == 11 && str.str[0] <= '3')); }
364};
365template<> struct charconv_digits_<8u, true> // int64_t
366{
367 enum : size_t {
368 maxdigits_bin = 1 + 2 + 64, // len=67: -9223372036854775808 -0b1000000000000000000000000000000000000000000000000000000000000000
369 maxdigits_oct = 1 + 2 + 22, // len=25: -9223372036854775808 -0o1000000000000000000000
370 maxdigits_dec = 1 + 19, // len=20: -9223372036854775808 -9223372036854775808
371 maxdigits_hex = 1 + 2 + 16, // len=19: -9223372036854775808 -0x8000000000000000
372 maxdigits_bin_nopfx = 64, // len=67: -9223372036854775808 -0b1000000000000000000000000000000000000000000000000000000000000000
373 maxdigits_oct_nopfx = 22, // len=25: -9223372036854775808 -0o1000000000000000000000
374 maxdigits_dec_nopfx = 19, // len=20: -9223372036854775808 -9223372036854775808
375 maxdigits_hex_nopfx = 16, // len=19: -9223372036854775808 -0x8000000000000000
376 };
377 static constexpr csubstr min_value_dec() noexcept { return csubstr("9223372036854775808"); }
378 static constexpr csubstr min_value_hex() noexcept { return csubstr("8000000000000000"); }
379 static constexpr csubstr min_value_oct() noexcept { return csubstr("1000000000000000000000"); }
380 static constexpr csubstr min_value_bin() noexcept { return csubstr("1000000000000000000000000000000000000000000000000000000000000000"); }
381 static constexpr csubstr max_value_dec() noexcept { return csubstr("9223372036854775807"); }
382 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !(str.len < 22); }
383};
384template<> struct charconv_digits_<8u, false> // uint64_t
385{
386 enum : size_t {
387 maxdigits_bin = 2 + 64, // len=66: 18446744073709551615 0b1111111111111111111111111111111111111111111111111111111111111111
388 maxdigits_oct = 2 + 22, // len=24: 18446744073709551615 0o1777777777777777777777
389 maxdigits_dec = 20, // len=20: 18446744073709551615 18446744073709551615
390 maxdigits_hex = 2 + 16, // len=18: 18446744073709551615 0xffffffffffffffff
391 maxdigits_bin_nopfx = 64, // len=66: 18446744073709551615 0b1111111111111111111111111111111111111111111111111111111111111111
392 maxdigits_oct_nopfx = 22, // len=24: 18446744073709551615 0o1777777777777777777777
393 maxdigits_dec_nopfx = 20, // len=20: 18446744073709551615 18446744073709551615
394 maxdigits_hex_nopfx = 16, // len=18: 18446744073709551615 0xffffffffffffffff
395 };
396 static constexpr csubstr max_value_dec() noexcept { return csubstr("18446744073709551615"); }
397 static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 22) || (str.len == 22 && str.str[0] <= '1')); }
398};
399} // namespace detail
400
401// Helper macros, undefined below
402#define c4append_(c) { if C4_LIKELY(pos < buf.len) { buf.str[pos++] = static_cast<char>(c); } else { ++pos; } }
403
404/** @endcond */
405
406
407//-----------------------------------------------------------------------------
408//-----------------------------------------------------------------------------
409//-----------------------------------------------------------------------------
410
411
412/** @defgroup doc_digits Get number of digits
413 *
414 * @note At first sight this code may look heavily branchy and
415 * therefore inefficient. However, measurements revealed this to be
416 * the fastest among the alternatives.
417 *
418 * @see https://github.com/biojppm/c4core/pull/77
419 *
420 * @{
421 */
422
423/** decimal digits for 8 bit integers */
424template<class T>
425C4_CONSTEXPR14 C4_ALWAYS_INLINE
426auto digits_dec(T v) noexcept
427 -> typename std::enable_if<sizeof(T) == 1u, unsigned>::type
428{
429 C4_STATIC_ASSERT(std::is_integral<T>::value);
430 C4_ASSERT(v >= 0);
431 return ((v >= 100) ? 3u : ((v >= 10) ? 2u : 1u));
432}
433
434/** decimal digits for 16 bit integers */
435template<class T>
436C4_CONSTEXPR14 C4_ALWAYS_INLINE
437auto digits_dec(T v) noexcept
438 -> typename std::enable_if<sizeof(T) == 2u, unsigned>::type
439{
440 C4_STATIC_ASSERT(std::is_integral<T>::value);
441 C4_ASSERT(v >= 0);
442 return ((v >= 10000) ? 5u : (v >= 1000) ? 4u : (v >= 100) ? 3u : (v >= 10) ? 2u : 1u);
443}
444
445/** decimal digits for 32 bit integers */
446template<class T>
447C4_CONSTEXPR14 C4_ALWAYS_INLINE
448auto digits_dec(T v) noexcept
449 -> typename std::enable_if<sizeof(T) == 4u, unsigned>::type
450{
451 C4_STATIC_ASSERT(std::is_integral<T>::value);
452 C4_ASSERT(v >= 0);
453 return ((v >= 1000000000) ? 10u : (v >= 100000000) ? 9u : (v >= 10000000) ? 8u :
454 (v >= 1000000) ? 7u : (v >= 100000) ? 6u : (v >= 10000) ? 5u :
455 (v >= 1000) ? 4u : (v >= 100) ? 3u : (v >= 10) ? 2u : 1u);
456}
457
458/** decimal digits for 64 bit integers */
459template<class T>
460C4_CONSTEXPR14 C4_ALWAYS_INLINE
461auto digits_dec(T v) noexcept
462 -> typename std::enable_if<sizeof(T) == 8u, unsigned>::type
463{
464 // thanks @fargies!!!
465 // https://github.com/biojppm/c4core/pull/77#issuecomment-1063753568
466 C4_STATIC_ASSERT(std::is_integral<T>::value);
467 C4_ASSERT(v >= 0);
468 if(v >= 1000000000) // 10
469 {
470 if(v >= 100000000000000) // 15 [15-20] range
471 {
472 if(v >= 100000000000000000) // 18 (15 + (20 - 15) / 2)
473 {
474 if((typename std::make_unsigned<T>::type)v >= 10000000000000000000u) // 20
475 return 20u;
476 else
477 return (v >= 1000000000000000000) ? 19u : 18u;
478 }
479 else if(v >= 10000000000000000) // 17
480 {
481 return 17u;
482 }
483 else
484 {
485 return(v >= 1000000000000000) ? 16u : 15u;
486 }
487 }
488 else if(v >= 1000000000000) // 13
489 {
490 return (v >= 10000000000000) ? 14u : 13u;
491 }
492 else if(v >= 100000000000) // 12
493 {
494 return 12;
495 }
496 else
497 {
498 return(v >= 10000000000) ? 11u : 10u;
499 }
500 }
501 else if(v >= 10000) // 5 [5-9] range
502 {
503 if(v >= 10000000) // 8
504 return (v >= 100000000) ? 9u : 8u;
505 else if(v >= 1000000) // 7
506 return 7;
507 else
508 return (v >= 100000) ? 6u : 5u;
509 }
510 else if(v >= 100)
511 {
512 return (v >= 1000) ? 4u : 3u;
513 }
514 else
515 {
516 return (v >= 10) ? 2u : 1u;
517 }
518}
519
520
521/** return the number of digits required to encode an hexadecimal number. */
522template<class T>
523C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_hex(T v) noexcept
524{
525 C4_STATIC_ASSERT(std::is_integral<T>::value);
526 C4_ASSERT(v >= 0);
527 return v ? 1u + (msb((typename std::make_unsigned<T>::type)v) >> 2u) : 1u;
528}
529
530/** return the number of digits required to encode a binary number. */
531template<class T>
532C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_bin(T v) noexcept
533{
534 C4_STATIC_ASSERT(std::is_integral<T>::value);
535 C4_ASSERT(v >= 0);
536 return v ? 1u + msb((typename std::make_unsigned<T>::type)v) : 1u;
537}
538
539/** return the number of digits required to encode an octal number. */
540template<class T>
541C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_oct(T v_) noexcept
542{
543 // TODO: is there a better way?
544 C4_STATIC_ASSERT(std::is_integral<T>::value);
545 C4_ASSERT(v_ >= 0);
546 using U = typename std::conditional<sizeof(T) <= sizeof(unsigned),
547 unsigned,
548 typename std::make_unsigned<T>::type>::type;
549 U v = (U) v_; // safe because we require v_ >= 0 // NOLINT
550 uint32_t n_ = 1;
551 enum : U {
552 b2_ = 64u,
553 b3_ = 64u * 8u,
554 b4_ = 64u * 8u * 8u,
555 };
556 while(true)
557 {
558 if(v < 8u)
559 return n_;
560 else if(v < b2_)
561 return n_ + 1;
562 else if(v < b3_)
563 return n_ + 2;
564 else if(v < b4_)
565 return n_ + 3;
566 v /= (U) b4_;
567 n_ += 4;
568 }
569}
570
571/** @} */
572
573
574//-----------------------------------------------------------------------------
575//-----------------------------------------------------------------------------
576//-----------------------------------------------------------------------------
577
578/** @cond dev */
579namespace detail {
580C4_INLINE_CONSTEXPR const char hexchars[] = "0123456789abcdef";
581C4_INLINE_CONSTEXPR const char digits0099[] =
582 "0001020304050607080910111213141516171819"
583 "2021222324252627282930313233343536373839"
584 "4041424344454647484950515253545556575859"
585 "6061626364656667686970717273747576777879"
586 "8081828384858687888990919293949596979899";
587} // namespace detail
588/** @endcond */
589
590C4_SUPPRESS_WARNING_GCC_PUSH
591C4_SUPPRESS_WARNING_GCC("-Warray-bounds") // gcc has false positives here
592#if (defined(__GNUC__) && (__GNUC__ >= 7))
593C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has false positives here
594#endif
595
596/** @defgroup doc_write_unchecked Write with known number of digits
597 *
598 * Writes a value without checking the buffer length with regards to
599 * the required number of digits to encode the value. It is the
600 * responsibility of the caller to ensure that the provided number of
601 * digits is enough to write the given value. Notwithstanding the
602 * name, assertions are liberally performed, so this code is safe.
603 *
604 * @{ */
605
606template<class T>
607C4_HOT C4_ALWAYS_INLINE
608void write_dec_unchecked(substr buf, T v, unsigned digits_v) noexcept
609{
610 C4_STATIC_ASSERT(std::is_integral<T>::value);
611 C4_ASSERT(v >= 0);
612 C4_ASSERT(buf.len >= digits_v);
613 C4_XASSERT(digits_v == digits_dec(v));
614 // in bm_xtoa: checkoncelog_singlediv_write2
615 while(v >= T(100))
616 {
617 T quo = v;
618 quo /= T(100);
619 const auto num = (v - quo * T(100)) << 1u; // NOLINT
620 v = quo;
621 buf.str[--digits_v] = detail::digits0099[num + 1];
622 buf.str[--digits_v] = detail::digits0099[num];
623 }
624 if(v >= T(10))
625 {
626 C4_ASSERT(digits_v == 2);
627 const auto num = v << 1u;
628 buf.str[1] = detail::digits0099[num + 1];
629 buf.str[0] = detail::digits0099[num];
630 }
631 else
632 {
633 C4_ASSERT(digits_v == 1);
634 buf.str[0] = (char)('0' + v);
635 }
636}
637
638
639template<class T>
640C4_HOT C4_ALWAYS_INLINE
641void write_hex_unchecked(substr buf, T v, unsigned digits_v) noexcept
642{
643 C4_STATIC_ASSERT(std::is_integral<T>::value);
644 C4_ASSERT(v >= 0);
645 C4_ASSERT(buf.len >= digits_v);
646 C4_XASSERT(digits_v == digits_hex(v));
647 do {
648 buf.str[--digits_v] = detail::hexchars[v & T(15)];
649 v >>= 4;
650 } while(v);
651 C4_ASSERT(digits_v == 0);
652}
653
654
655template<class T>
656C4_HOT C4_ALWAYS_INLINE
657void write_oct_unchecked(substr buf, T v, unsigned digits_v) noexcept
658{
659 C4_STATIC_ASSERT(std::is_integral<T>::value);
660 C4_ASSERT(v >= 0);
661 C4_ASSERT(buf.len >= digits_v);
662 C4_XASSERT(digits_v == digits_oct(v));
663 do {
664 buf.str[--digits_v] = (char)('0' + (v & T(7)));
665 v >>= 3;
666 } while(v);
667 C4_ASSERT(digits_v == 0);
668}
669
670
671template<class T>
672C4_HOT C4_ALWAYS_INLINE
673void write_bin_unchecked(substr buf, T v, unsigned digits_v) noexcept
674{
675 C4_STATIC_ASSERT(std::is_integral<T>::value);
676 C4_ASSERT(v >= 0);
677 C4_ASSERT(buf.len >= digits_v);
678 C4_XASSERT(digits_v == digits_bin(v));
679 do {
680 buf.str[--digits_v] = (char)('0' + (v & T(1)));
681 v >>= 1;
682 } while(v);
683 C4_ASSERT(digits_v == 0);
684}
685
686/** @} */ // write_unchecked
687
688
689//-----------------------------------------------------------------------------
690//-----------------------------------------------------------------------------
691//-----------------------------------------------------------------------------
692
693/** @defgroup doc_write Write a value
694 *
695 * Writes a value without checking the buffer length
696 * decimal number -- but asserting.
697 *
698 * @{ */
699
700/** write an integer to a string in decimal format. This is the
701 * lowest level (and the fastest) function to do this task.
702 * @note does not accept negative numbers
703 * @note the resulting string is NOT zero-terminated.
704 * @note it is ok to call this with an empty or too-small buffer;
705 * no writes will occur, and the required size will be returned
706 * @return the number of characters required for the buffer. */
707template<class T>
708C4_ALWAYS_INLINE size_t write_dec(substr buf, T v) noexcept
709{
710 C4_STATIC_ASSERT(std::is_integral<T>::value);
711 C4_ASSERT(v >= 0);
712 unsigned digits = digits_dec(v);
713 if C4_LIKELY(buf.len >= digits)
714 write_dec_unchecked(buf, v, digits);
715 return digits;
716}
717
718/** write an integer to a string in hexadecimal format. This is the
719 * lowest level (and the fastest) function to do this task.
720 * @note does not accept negative numbers
721 * @note does not prefix with 0x
722 * @note the resulting string is NOT zero-terminated.
723 * @note it is ok to call this with an empty or too-small buffer;
724 * no writes will occur, and the required size will be returned
725 * @return the number of characters required for the buffer. */
726template<class T>
727C4_ALWAYS_INLINE size_t write_hex(substr buf, T v) noexcept
728{
729 C4_STATIC_ASSERT(std::is_integral<T>::value);
730 C4_ASSERT(v >= 0);
731 unsigned digits = digits_hex(v);
732 if C4_LIKELY(buf.len >= digits)
733 write_hex_unchecked(buf, v, digits);
734 return digits;
735}
736
737/** write an integer to a string in octal format. This is the
738 * lowest level (and the fastest) function to do this task.
739 * @note does not accept negative numbers
740 * @note does not prefix with 0o
741 * @note the resulting string is NOT zero-terminated.
742 * @note it is ok to call this with an empty or too-small buffer;
743 * no writes will occur, and the required size will be returned
744 * @return the number of characters required for the buffer. */
745template<class T>
746C4_ALWAYS_INLINE size_t write_oct(substr buf, T v) noexcept
747{
748 C4_STATIC_ASSERT(std::is_integral<T>::value);
749 C4_ASSERT(v >= 0);
750 unsigned digits = digits_oct(v);
751 if C4_LIKELY(buf.len >= digits)
752 write_oct_unchecked(buf, v, digits);
753 return digits;
754}
755
756/** write an integer to a string in binary format. This is the
757 * lowest level (and the fastest) function to do this task.
758 * @note does not accept negative numbers
759 * @note does not prefix with 0b
760 * @note the resulting string is NOT zero-terminated.
761 * @note it is ok to call this with an empty or too-small buffer;
762 * no writes will occur, and the required size will be returned
763 * @return the number of characters required for the buffer. */
764template<class T>
765C4_ALWAYS_INLINE size_t write_bin(substr buf, T v) noexcept
766{
767 C4_STATIC_ASSERT(std::is_integral<T>::value);
768 C4_ASSERT(v >= 0);
769 unsigned digits = digits_bin(v);
770 C4_ASSERT(digits > 0);
771 if C4_LIKELY(buf.len >= digits)
772 write_bin_unchecked(buf, v, digits);
773 return digits;
774}
775
776
777/** @cond dev */
778namespace detail {
779template<class U> using NumberWriter = size_t (*)(substr, U);
780template<class T, NumberWriter<T> writer>
781size_t write_num_digits(substr buf, T v, size_t num_digits) noexcept
782{
783 C4_STATIC_ASSERT(std::is_integral<T>::value);
784 const size_t ret = writer(buf, v);
785 if(ret >= num_digits)
786 return ret;
787 else if(ret >= buf.len || num_digits > buf.len)
788 return num_digits;
789 C4_ASSERT(num_digits >= ret);
790 const size_t delta = static_cast<size_t>(num_digits - ret); // NOLINT
791 C4_ASSERT(ret + delta <= buf.len);
792 if(ret)
793 memmove(buf.str + delta, buf.str, ret);
794 if(delta)
795 memset(buf.str, '0', delta);
796 return num_digits;
797}
798} // namespace detail
799/** @endcond */
800
801
802/** same as c4::write_dec(), but pad with zeroes on the left such that
803 * the resulting string is @p num_digits wide. If the given number
804 * requires more than num_digits, then the number prevails. */
805template<class T>
806C4_ALWAYS_INLINE size_t write_dec(substr buf, T val, size_t num_digits) noexcept
807{
808 return detail::write_num_digits<T, &write_dec<T>>(buf, val, num_digits);
809}
810
811/** same as c4::write_hex(), but pad with zeroes on the left such that
812 * the resulting string is @p num_digits wide. If the given number
813 * requires more than num_digits, then the number prevails. */
814template<class T>
815C4_ALWAYS_INLINE size_t write_hex(substr buf, T val, size_t num_digits) noexcept
816{
817 return detail::write_num_digits<T, &write_hex<T>>(buf, val, num_digits);
818}
819
820/** same as c4::write_bin(), but pad with zeroes on the left such that
821 * the resulting string is @p num_digits wide. If the given number
822 * requires more than num_digits, then the number prevails. */
823template<class T>
824C4_ALWAYS_INLINE size_t write_bin(substr buf, T val, size_t num_digits) noexcept
825{
826 return detail::write_num_digits<T, &write_bin<T>>(buf, val, num_digits);
827}
828
829/** same as c4::write_oct(), but pad with zeroes on the left such that
830 * the resulting string is @p num_digits wide. If the given number
831 * requires more than num_digits, then the number prevails. */
832template<class T>
833C4_ALWAYS_INLINE size_t write_oct(substr buf, T val, size_t num_digits) noexcept
834{
835 return detail::write_num_digits<T, &write_oct<T>>(buf, val, num_digits);
836}
837
838/** @} */ // write
839
840C4_SUPPRESS_WARNING_GCC_POP
841
842
843//-----------------------------------------------------------------------------
844//-----------------------------------------------------------------------------
845//-----------------------------------------------------------------------------
846
847
848C4_SUPPRESS_WARNING_MSVC_PUSH
849C4_SUPPRESS_WARNING_MSVC(4365) // '=': conversion from 'int' to 'I', signed/unsigned mismatch
850
851/** @defgroup doc_read Read a value
852 *
853 * @{ */
854
855/** read a decimal integer from a string. This is the
856 * lowest level (and the fastest) function to do this task.
857 * @note does not accept negative numbers
858 * @note The string must be trimmed. Whitespace is not accepted.
859 * @note the string must not be empty
860 * @note there is no check for overflow; the value wraps around
861 * in a way similar to the standard C/C++ overflow behavior.
862 * For example, `read_dec<int8_t>("128", &val)` returns true
863 * and val will be set to 0 because 127 is the max i8 value.
864 * @see overflows<T>() to find out if a number string overflows a type range
865 * @return true if the conversion was successful (no overflow check) */
866template<class I>
868C4_ALWAYS_INLINE bool read_dec(csubstr s, I *C4_RESTRICT v) noexcept
869{
870 C4_STATIC_ASSERT(std::is_integral<I>::value);
871 C4_ASSERT(!s.empty());
872 *v = 0;
873 for(char c : s)
874 {
875 if C4_UNLIKELY(c < '0' || c > '9')
876 return false;
877 *v = ((*v) * I(10)) + (I(c) - I('0'));
878 }
879 return true;
880}
881
882/** read an hexadecimal integer from a string. This is the
883 * lowest level (and the fastest) function to do this task.
884 * @note does not accept negative numbers
885 * @note does not accept leading 0x or 0X
886 * @note the string must not be empty
887 * @note the string must be trimmed. Whitespace is not accepted.
888 * @note there is no check for overflow; the value wraps around
889 * in a way similar to the standard C/C++ overflow behavior.
890 * For example, `read_hex<int8_t>("80", &val)` returns true
891 * and val will be set to 0 because 7f is the max i8 value.
892 * @see overflows<T>() to find out if a number string overflows a type range
893 * @return true if the conversion was successful (no overflow check) */
894template<class I>
896C4_ALWAYS_INLINE bool read_hex(csubstr s, I *C4_RESTRICT v) noexcept
897{
898 C4_STATIC_ASSERT(std::is_integral<I>::value);
899 C4_ASSERT(!s.empty());
900 *v = 0;
901 for(char c : s)
902 {
903 I cv;
904 if(c >= '0' && c <= '9')
905 cv = I(c) - I('0');
906 else if(c >= 'a' && c <= 'f')
907 cv = I(10) + (I(c) - I('a'));
908 else if(c >= 'A' && c <= 'F')
909 cv = I(10) + (I(c) - I('A'));
910 else
911 return false;
912 *v = ((*v) * I(16)) + cv;
913 }
914 return true;
915}
916
917/** read a binary integer from a string. This is the
918 * lowest level (and the fastest) function to do this task.
919 * @note does not accept negative numbers
920 * @note does not accept leading 0b or 0B
921 * @note the string must not be empty
922 * @note the string must be trimmed. Whitespace is not accepted.
923 * @note there is no check for overflow; the value wraps around
924 * in a way similar to the standard C/C++ overflow behavior.
925 * For example, `read_bin<int8_t>("10000000", &val)` returns true
926 * and val will be set to 0 because 1111111 is the max i8 value.
927 * @see overflows<T>() to find out if a number string overflows a type range
928 * @return true if the conversion was successful (no overflow check) */
929template<class I>
931C4_ALWAYS_INLINE bool read_bin(csubstr s, I *C4_RESTRICT v) noexcept
932{
933 C4_STATIC_ASSERT(std::is_integral<I>::value);
934 C4_ASSERT(!s.empty());
935 *v = 0;
936 for(char c : s)
937 {
938 *v <<= 1;
939 if(c == '1')
940 *v |= 1;
941 else if(c != '0')
942 return false;
943 }
944 return true;
945}
946
947/** read an octal integer from a string. This is the
948 * lowest level (and the fastest) function to do this task.
949 * @note does not accept negative numbers
950 * @note does not accept leading 0o or 0O
951 * @note the string must not be empty
952 * @note the string must be trimmed. Whitespace is not accepted.
953 * @note there is no check for overflow; the value wraps around
954 * in a way similar to the standard C/C++ overflow behavior.
955 * For example, `read_oct<int8_t>("200", &val)` returns true
956 * and val will be set to 0 because 177 is the max i8 value.
957 * @see overflows<T>() to find out if a number string overflows a type range
958 * @return true if the conversion was successful (no overflow check) */
959template<class I>
961C4_ALWAYS_INLINE bool read_oct(csubstr s, I *C4_RESTRICT v) noexcept
962{
963 C4_STATIC_ASSERT(std::is_integral<I>::value);
964 C4_ASSERT(!s.empty());
965 *v = 0;
966 for(char c : s)
967 {
968 if C4_UNLIKELY(c < '0' || c > '7')
969 return false;
970 *v = ((*v) * I(8)) + (I(c) - I('0'));
971 }
972 return true;
973}
974
975/** @} */
976
977C4_SUPPRESS_WARNING_MSVC_POP
978
979
980//-----------------------------------------------------------------------------
981//-----------------------------------------------------------------------------
982//-----------------------------------------------------------------------------
983
984C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wswitch-default")
985
986/** @cond dev */
987namespace detail {
988inline size_t _itoa2buf(substr buf, size_t pos, csubstr val) noexcept
989{
990 C4_ASSERT(pos < buf.len);
991 C4_ASSERT(pos + val.len <= buf.len);
992 C4_ASSERT(val.len > 0);
993 memcpy(buf.str + pos, val.str, val.len);
994 return pos + val.len;
995}
996inline size_t _itoa2bufwithdigits(substr buf, size_t pos, size_t num_digits, csubstr val) noexcept
997{
998 num_digits = num_digits > val.len ? num_digits - val.len : 0;
999 C4_ASSERT(num_digits + val.len <= buf.len);
1000 for(size_t i = 0; i < num_digits; ++i)
1001 c4append_('0')
1002 return detail::_itoa2buf(buf, pos, val);
1003}
1004template<class I>
1005C4_NO_INLINE size_t _itoadec2buf(substr buf) noexcept
1006{
1007 using digits_type = detail::charconv_digits<I>;
1008 if C4_UNLIKELY(buf.len < digits_type::maxdigits_dec)
1009 return digits_type::maxdigits_dec;
1010 buf.str[0] = '-';
1011 return detail::_itoa2buf(buf, 1, digits_type::min_value_dec());
1012}
1013template<class I>
1014C4_NO_INLINE size_t _itoa2buf(substr buf, I radix) noexcept
1015{
1016 using digits_type = detail::charconv_digits<I>;
1017 size_t pos = 0;
1018 if C4_LIKELY(buf.len > 0)
1019 buf.str[pos++] = '-';
1020 switch(radix) // NOLINT
1021 {
1022 case I(10):
1023 if C4_UNLIKELY(buf.len < digits_type::maxdigits_dec)
1024 return digits_type::maxdigits_dec;
1025 pos =_itoa2buf(buf, pos, digits_type::min_value_dec());
1026 break;
1027 case I(16):
1028 if C4_UNLIKELY(buf.len < digits_type::maxdigits_hex)
1029 return digits_type::maxdigits_hex;
1030 buf.str[pos++] = '0';
1031 buf.str[pos++] = 'x';
1032 pos = _itoa2buf(buf, pos, digits_type::min_value_hex());
1033 break;
1034 case I( 2):
1035 if C4_UNLIKELY(buf.len < digits_type::maxdigits_bin)
1036 return digits_type::maxdigits_bin;
1037 buf.str[pos++] = '0';
1038 buf.str[pos++] = 'b';
1039 pos = _itoa2buf(buf, pos, digits_type::min_value_bin());
1040 break;
1041 case I( 8):
1042 if C4_UNLIKELY(buf.len < digits_type::maxdigits_oct)
1043 return digits_type::maxdigits_oct;
1044 buf.str[pos++] = '0';
1045 buf.str[pos++] = 'o';
1046 pos = _itoa2buf(buf, pos, digits_type::min_value_oct());
1047 break;
1048 }
1049 return pos;
1050}
1051template<class I>
1052C4_NO_INLINE size_t _itoa2buf(substr buf, I radix, size_t num_digits) noexcept
1053{
1054 using digits_type = detail::charconv_digits<I>;
1055 size_t pos = 0;
1056 size_t needed_digits = 0;
1057 if C4_LIKELY(buf.len > 0)
1058 buf.str[pos++] = '-';
1059 switch(radix) // NOLINT
1060 {
1061 case I(10):
1062 // add 1 to account for -
1063 needed_digits = num_digits+1 > digits_type::maxdigits_dec ? num_digits+1 : digits_type::maxdigits_dec;
1064 if C4_UNLIKELY(buf.len < needed_digits)
1065 return needed_digits;
1066 pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_dec());
1067 break;
1068 case I(16):
1069 // add 3 to account for -0x
1070 needed_digits = num_digits+3 > digits_type::maxdigits_hex ? num_digits+3 : digits_type::maxdigits_hex;
1071 if C4_UNLIKELY(buf.len < needed_digits)
1072 return needed_digits;
1073 buf.str[pos++] = '0';
1074 buf.str[pos++] = 'x';
1075 pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_hex());
1076 break;
1077 case I(2):
1078 // add 3 to account for -0b
1079 needed_digits = num_digits+3 > digits_type::maxdigits_bin ? num_digits+3 : digits_type::maxdigits_bin;
1080 if C4_UNLIKELY(buf.len < needed_digits)
1081 return needed_digits;
1082 C4_ASSERT(buf.len >= digits_type::maxdigits_bin);
1083 buf.str[pos++] = '0';
1084 buf.str[pos++] = 'b';
1085 pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_bin());
1086 break;
1087 case I(8):
1088 // add 3 to account for -0o
1089 needed_digits = num_digits+3 > digits_type::maxdigits_oct ? num_digits+3 : digits_type::maxdigits_oct;
1090 if C4_UNLIKELY(buf.len < needed_digits)
1091 return needed_digits;
1092 C4_ASSERT(buf.len >= digits_type::maxdigits_oct);
1093 buf.str[pos++] = '0';
1094 buf.str[pos++] = 'o';
1095 pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_oct());
1096 break;
1097 }
1098 return pos;
1099}
1100} // namespace detail
1101/** @endcond */
1102
1103
1104/** @defgroup doc_itoa itoa: signed to chars
1105 *
1106 * @{ */
1107
1108/** convert an integral signed decimal to a string.
1109 * @note the resulting string is NOT zero-terminated.
1110 * @note it is ok to call this with an empty or too-small buffer;
1111 * no writes will occur, and the needed size will be returned
1112 * @return the number of characters required for the buffer. */
1113template<class T>
1114C4_ALWAYS_INLINE size_t itoa(substr buf, T v) noexcept
1115{
1116 C4_STATIC_ASSERT(std::is_signed<T>::value);
1117 if(v >= T(0))
1118 {
1119 // write_dec() checks the buffer size, so no need to check here
1120 return write_dec(buf, v);
1121 }
1122 // when T is the min value (eg i8: -128), negating it
1123 // will overflow, so treat the min as a special case
1124 if C4_LIKELY(v != std::numeric_limits<T>::min())
1125 {
1126 v = (T)-v;
1127 unsigned digits = digits_dec(v);
1128 if C4_LIKELY(buf.len >= digits + 1u)
1129 {
1130 buf.str[0] = '-';
1131 write_dec_unchecked(buf.sub(1), v, digits);
1132 }
1133 return digits + 1u;
1134 }
1135 return detail::_itoadec2buf<T>(buf);
1136}
1137
1138/** convert an integral signed integer to a string, using a specific
1139 * radix. The radix must be 2, 8, 10 or 16.
1140 *
1141 * @note the resulting string is NOT zero-terminated.
1142 * @note it is ok to call this with an empty or too-small buffer;
1143 * no writes will occur, and the needed size will be returned
1144 * @return the number of characters required for the buffer. */
1145template<class T>
1146C4_ALWAYS_INLINE size_t itoa(substr buf, T v, T radix) noexcept
1147{
1148 C4_STATIC_ASSERT(std::is_signed<T>::value);
1149 C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
1150 C4_SUPPRESS_WARNING_GCC_PUSH
1151 #if (defined(__GNUC__) && (__GNUC__ >= 7))
1152 C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has a false positive here
1153 #endif
1154 // when T is the min value (eg i8: -128), negating it
1155 // will overflow, so treat the min as a special case
1156 if C4_LIKELY(v != std::numeric_limits<T>::min())
1157 {
1158 unsigned pos = 0;
1159 if(v < 0)
1160 {
1161 v = (T)-v;
1162 if C4_LIKELY(buf.len > 0)
1163 buf.str[pos] = '-';
1164 ++pos;
1165 }
1166 unsigned digits = 0;
1167 switch(radix) // NOLINT
1168 {
1169 case T(10):
1170 digits = digits_dec(v);
1171 if C4_LIKELY(buf.len >= pos + digits)
1172 write_dec_unchecked(buf.sub(pos), v, digits);
1173 break;
1174 case T(16):
1175 digits = digits_hex(v);
1176 if C4_LIKELY(buf.len >= pos + 2u + digits)
1177 {
1178 buf.str[pos + 0] = '0';
1179 buf.str[pos + 1] = 'x';
1180 write_hex_unchecked(buf.sub(pos + 2), v, digits);
1181 }
1182 digits += 2u;
1183 break;
1184 case T(2):
1185 digits = digits_bin(v);
1186 if C4_LIKELY(buf.len >= pos + 2u + digits)
1187 {
1188 buf.str[pos + 0] = '0';
1189 buf.str[pos + 1] = 'b';
1190 write_bin_unchecked(buf.sub(pos + 2), v, digits);
1191 }
1192 digits += 2u;
1193 break;
1194 case T(8):
1195 digits = digits_oct(v);
1196 if C4_LIKELY(buf.len >= pos + 2u + digits)
1197 {
1198 buf.str[pos + 0] = '0';
1199 buf.str[pos + 1] = 'o';
1200 write_oct_unchecked(buf.sub(pos + 2), v, digits);
1201 }
1202 digits += 2u;
1203 break;
1204 }
1205 return pos + digits;
1206 }
1207 C4_SUPPRESS_WARNING_GCC_POP
1208 // when T is the min value (eg i8: -128), negating it
1209 // will overflow
1210 return detail::_itoa2buf<T>(buf, radix);
1211}
1212
1213
1214/** same as c4::itoa(), but pad with zeroes on the left such that the
1215 * resulting string is @p num_digits wide, not accounting for radix
1216 * prefix (0x,0o,0b). The @p radix must be 2, 8, 10 or 16.
1217 *
1218 * @note the resulting string is NOT zero-terminated.
1219 * @note it is ok to call this with an empty or too-small buffer;
1220 * no writes will occur, and the needed size will be returned
1221 * @return the number of characters required for the buffer. */
1222template<class T>
1223C4_ALWAYS_INLINE size_t itoa(substr buf, T v, T radix, size_t num_digits) noexcept
1224{
1225 C4_STATIC_ASSERT(std::is_signed<T>::value);
1226 C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
1227 C4_SUPPRESS_WARNING_GCC_PUSH
1228 #if (defined(__GNUC__) && (__GNUC__ >= 7))
1229 C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has a false positive here
1230 #endif
1231 // when T is the min value (eg i8: -128), negating it
1232 // will overflow, so treat the min as a special case
1233 if C4_LIKELY(v != std::numeric_limits<T>::min())
1234 {
1235 unsigned pos = 0;
1236 if(v < 0)
1237 {
1238 v = (T)-v;
1239 if C4_LIKELY(buf.len > 0)
1240 buf.str[pos] = '-';
1241 ++pos;
1242 }
1243 unsigned total_digits = 0;
1244 switch(radix) // NOLINT
1245 {
1246 case T(10):
1247 total_digits = digits_dec(v);
1248 total_digits = pos + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1249 if C4_LIKELY(buf.len >= total_digits)
1250 write_dec(buf.sub(pos), v, num_digits);
1251 break;
1252 case T(16):
1253 total_digits = digits_hex(v);
1254 total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1255 if C4_LIKELY(buf.len >= total_digits)
1256 {
1257 buf.str[pos + 0] = '0';
1258 buf.str[pos + 1] = 'x';
1259 write_hex(buf.sub(pos + 2), v, num_digits);
1260 }
1261 break;
1262 case T(2):
1263 total_digits = digits_bin(v);
1264 total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1265 if C4_LIKELY(buf.len >= total_digits)
1266 {
1267 buf.str[pos + 0] = '0';
1268 buf.str[pos + 1] = 'b';
1269 write_bin(buf.sub(pos + 2), v, num_digits);
1270 }
1271 break;
1272 case T(8):
1273 total_digits = digits_oct(v);
1274 total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1275 if C4_LIKELY(buf.len >= total_digits)
1276 {
1277 buf.str[pos + 0] = '0';
1278 buf.str[pos + 1] = 'o';
1279 write_oct(buf.sub(pos + 2), v, num_digits);
1280 }
1281 break;
1282 }
1283 return total_digits;
1284 }
1285 C4_SUPPRESS_WARNING_GCC_POP
1286 // when T is the min value (eg i8: -128), negating it
1287 // will overflow
1288 return detail::_itoa2buf<T>(buf, radix, num_digits);
1289}
1290
1291/** @} */
1292
1293
1294//-----------------------------------------------------------------------------
1295//-----------------------------------------------------------------------------
1296//-----------------------------------------------------------------------------
1297
1298/** @defgroup doc_utoa utoa: unsigned to chars
1299 *
1300 * @{ */
1301
1302/** convert an integral unsigned decimal to a string.
1303 *
1304 * @note the resulting string is NOT zero-terminated.
1305 * @note it is ok to call this with an empty or too-small buffer;
1306 * no writes will occur, and the needed size will be returned
1307 * @return the number of characters required for the buffer. */
1308template<class T>
1309C4_ALWAYS_INLINE size_t utoa(substr buf, T v) noexcept
1310{
1311 C4_STATIC_ASSERT(std::is_unsigned<T>::value);
1312 // write_dec() does the buffer length check, so no need to check here
1313 return write_dec(buf, v);
1314}
1315
1316/** convert an integral unsigned integer to a string, using a specific
1317 * radix. The radix must be 2, 8, 10 or 16.
1318 *
1319 * @note the resulting string is NOT zero-terminated.
1320 * @note it is ok to call this with an empty or too-small buffer;
1321 * no writes will occur, and the needed size will be returned
1322 * @return the number of characters required for the buffer. */
1323template<class T>
1324C4_ALWAYS_INLINE size_t utoa(substr buf, T v, T radix) noexcept
1325{
1326 C4_STATIC_ASSERT(std::is_unsigned<T>::value);
1327 C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8);
1328 unsigned digits = 0;
1329 switch(radix) // NOLINT
1330 {
1331 case T(10):
1332 digits = digits_dec(v);
1333 if C4_LIKELY(buf.len >= digits)
1334 write_dec_unchecked(buf, v, digits);
1335 break;
1336 case T(16):
1337 digits = digits_hex(v);
1338 if C4_LIKELY(buf.len >= digits+2u)
1339 {
1340 buf.str[0] = '0';
1341 buf.str[1] = 'x';
1342 write_hex_unchecked(buf.sub(2), v, digits);
1343 }
1344 digits += 2u;
1345 break;
1346 case T(2):
1347 digits = digits_bin(v);
1348 if C4_LIKELY(buf.len >= digits+2u)
1349 {
1350 buf.str[0] = '0';
1351 buf.str[1] = 'b';
1352 write_bin_unchecked(buf.sub(2), v, digits);
1353 }
1354 digits += 2u;
1355 break;
1356 case T(8):
1357 digits = digits_oct(v);
1358 if C4_LIKELY(buf.len >= digits+2u)
1359 {
1360 buf.str[0] = '0';
1361 buf.str[1] = 'o';
1362 write_oct_unchecked(buf.sub(2), v, digits);
1363 }
1364 digits += 2u;
1365 break;
1366 }
1367 return digits;
1368}
1369
1370/** same as c4::utoa(), but pad with zeroes on the left such that the
1371 * resulting string is @p num_digits wide. The @p radix must be 2,
1372 * 8, 10 or 16.
1373 *
1374 * @note the resulting string is NOT zero-terminated.
1375 * @note it is ok to call this with an empty or too-small buffer;
1376 * no writes will occur, and the needed size will be returned
1377 * @return the number of characters required for the buffer. */
1378template<class T>
1379C4_ALWAYS_INLINE size_t utoa(substr buf, T v, T radix, size_t num_digits) noexcept
1380{
1381 C4_STATIC_ASSERT(std::is_unsigned<T>::value);
1382 C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8);
1383 unsigned total_digits = 0;
1384 switch(radix) // NOLINT
1385 {
1386 case T(10):
1387 total_digits = digits_dec(v);
1388 total_digits = (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1389 if C4_LIKELY(buf.len >= total_digits)
1390 write_dec(buf, v, num_digits);
1391 break;
1392 case T(16):
1393 total_digits = digits_hex(v);
1394 total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1395 if C4_LIKELY(buf.len >= total_digits)
1396 {
1397 buf.str[0] = '0';
1398 buf.str[1] = 'x';
1399 write_hex(buf.sub(2), v, num_digits);
1400 }
1401 break;
1402 case T(2):
1403 total_digits = digits_bin(v);
1404 total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1405 if C4_LIKELY(buf.len >= total_digits)
1406 {
1407 buf.str[0] = '0';
1408 buf.str[1] = 'b';
1409 write_bin(buf.sub(2), v, num_digits);
1410 }
1411 break;
1412 case T(8):
1413 total_digits = digits_oct(v);
1414 total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits);
1415 if C4_LIKELY(buf.len >= total_digits)
1416 {
1417 buf.str[0] = '0';
1418 buf.str[1] = 'o';
1419 write_oct(buf.sub(2), v, num_digits);
1420 }
1421 break;
1422 }
1423 return total_digits;
1424}
1425C4_SUPPRESS_WARNING_GCC_POP
1426
1427/** @} */
1428
1429
1430//-----------------------------------------------------------------------------
1431//-----------------------------------------------------------------------------
1432//-----------------------------------------------------------------------------
1433
1434/** @defgroup doc_atoi atoi: chars to signed
1435 *
1436 * @{ */
1437
1438/** Convert a trimmed string to a signed integral value. The input
1439 * string can be formatted as decimal, binary (prefix 0b or 0B), octal
1440 * (prefix 0o or 0O) or hexadecimal (prefix 0x or 0X). Strings with
1441 * leading zeroes are considered as decimal and not octal (unlike the
1442 * C/C++ convention). Every character in the input string is read for
1443 * the conversion; the input string must not contain any leading or
1444 * trailing whitespace.
1445 *
1446 * @return true if the conversion was successful.
1447 *
1448 * @note a positive sign is not accepted. ie, the string must not
1449 * start with '+'
1450 *
1451 * @note overflow is not detected: the return status is true even if
1452 * the conversion would return a value outside of the type's range, in
1453 * which case the result will wrap around the type's range. This is
1454 * similar to native behavior. See @ref doc_overflows and @ref
1455 * doc_overflow_checked for overflow checking utilities.
1456 *
1457 * @see atoi_first() if the string is not trimmed to the value to read. */
1458template<class T>
1460C4_ALWAYS_INLINE bool atoi(csubstr str, T * C4_RESTRICT v) noexcept
1461{
1462 C4_STATIC_ASSERT(std::is_integral<T>::value);
1463 C4_STATIC_ASSERT(std::is_signed<T>::value);
1464
1465 if C4_UNLIKELY(str.len == 0)
1466 return false;
1467 // no need for the assertion, but we leave it here to document
1468 // the expectation:
1469 //C4_ASSERT(str.str[0] != '+');
1470
1471 T sign = 1;
1472 size_t start = 0;
1473 if(str.str[0] == '-')
1474 {
1475 if C4_UNLIKELY(str.len == ++start)
1476 return false;
1477 sign = -1;
1478 }
1479
1480 bool parsed_ok = true;
1481 if(str.str[start] != '0') // this should be the common case, so put it first
1482 {
1483 parsed_ok = read_dec(str.sub(start), v);
1484 }
1485 else if(str.len > start + 1)
1486 {
1487 // starts with 0: is it 0x, 0o, 0b?
1488 const char pfx = str.str[start + 1];
1489 if(pfx == 'x' || pfx == 'X')
1490 parsed_ok = str.len > start + 2 && read_hex(str.sub(start + 2), v);
1491 else if(pfx == 'b' || pfx == 'B')
1492 parsed_ok = str.len > start + 2 && read_bin(str.sub(start + 2), v);
1493 else if(pfx == 'o' || pfx == 'O')
1494 parsed_ok = str.len > start + 2 && read_oct(str.sub(start + 2), v);
1495 else
1496 parsed_ok = read_dec(str.sub(start + 1), v);
1497 }
1498 else
1499 {
1500 parsed_ok = read_dec(str.sub(start), v);
1501 }
1502 if C4_LIKELY(parsed_ok)
1503 *v *= sign;
1504 return parsed_ok;
1505}
1506
1507
1508/** Select the next range of characters in the string that can be parsed
1509 * as a signed integral value, and convert it using atoi(). Leading
1510 * whitespace (space, newline, tabs) is skipped.
1511 * @return the number of characters read for conversion, or csubstr::npos if the conversion failed
1512 * @see atoi() if the string is already trimmed to the value to read.
1513 * @see csubstr::first_int_span() */
1514template<class T>
1515C4_ALWAYS_INLINE size_t atoi_first(csubstr str, T * C4_RESTRICT v)
1516{
1517 csubstr trimmed = str.first_int_span();
1518 if(trimmed.len && atoi(trimmed, v))
1519 return static_cast<size_t>(trimmed.end() - str.begin());
1520 return csubstr::npos;
1521}
1522
1523/** @} */
1524
1525
1526//-----------------------------------------------------------------------------
1527//-----------------------------------------------------------------------------
1528//-----------------------------------------------------------------------------
1529
1530/** @defgroup doc_atou atou: chars to unsigned
1531 *
1532 * @{ */
1533
1534/** Convert a trimmed string to an unsigned integral value. The string can be
1535 * formatted as decimal, binary (prefix 0b or 0B), octal (prefix 0o or 0O)
1536 * or hexadecimal (prefix 0x or 0X). Every character in the input string is read
1537 * for the conversion; it must not contain any leading or trailing whitespace.
1538 *
1539 * @return true if the conversion was successful.
1540 *
1541 * @note overflow is not detected: the return status is true even if
1542 * the conversion would return a value outside of the type's range, in
1543 * which case the result will wrap around the type's range. See @ref
1544 * doc_overflows and @ref doc_overflow_checked for overflow checking
1545 * utilities.
1546 *
1547 * @note If the string has a minus character, the return status
1548 * will be false.
1549 *
1550 * @see atou_first() if the string is not trimmed to the value to read. */
1551template<class T>
1552bool atou(csubstr str, T * C4_RESTRICT v) noexcept
1553{
1554 C4_STATIC_ASSERT(std::is_integral<T>::value);
1555
1556 if C4_UNLIKELY(str.len == 0 || str.front() == '-')
1557 return false;
1558
1559 bool parsed_ok = true;
1560 if(str.str[0] != '0')
1561 {
1562 parsed_ok = read_dec(str, v);
1563 }
1564 else
1565 {
1566 if(str.len > 1)
1567 {
1568 const char pfx = str.str[1];
1569 if(pfx == 'x' || pfx == 'X')
1570 parsed_ok = str.len > 2 && read_hex(str.sub(2), v);
1571 else if(pfx == 'b' || pfx == 'B')
1572 parsed_ok = str.len > 2 && read_bin(str.sub(2), v);
1573 else if(pfx == 'o' || pfx == 'O')
1574 parsed_ok = str.len > 2 && read_oct(str.sub(2), v);
1575 else
1576 parsed_ok = read_dec(str, v);
1577 }
1578 else
1579 {
1580 *v = 0; // we know the first character is 0
1581 }
1582 }
1583 return parsed_ok;
1584}
1585
1586
1587/** Select the next range of characters in the string that can be parsed
1588 * as an unsigned integral value, and convert it using atou(). Leading
1589 * whitespace (space, newline, tabs) is skipped.
1590 * @return the number of characters read for conversion, or csubstr::npos if the conversion faileds
1591 * @see atou() if the string is already trimmed to the value to read.
1592 * @see csubstr::first_uint_span() */
1593template<class T>
1594C4_ALWAYS_INLINE size_t atou_first(csubstr str, T *v)
1595{
1596 csubstr trimmed = str.first_uint_span();
1597 if(trimmed.len && atou(trimmed, v))
1598 return static_cast<size_t>(trimmed.end() - str.begin());
1599 return csubstr::npos;
1600}
1601
1602
1603/** @} */
1604
1605#if defined(_MSC_VER) && !defined(__clang__)
1606# pragma warning(pop)
1607#elif defined(__clang__)
1608# pragma clang diagnostic pop
1609#elif defined(__GNUC__)
1610# pragma GCC diagnostic pop
1611#endif
1612
1613
1614//-----------------------------------------------------------------------------
1615//-----------------------------------------------------------------------------
1616//-----------------------------------------------------------------------------
1617
1618/** @cond dev */
1619namespace detail {
1620inline bool check_overflow(csubstr str, csubstr limit) noexcept
1621{
1622 if(str.len != limit.len)
1623 return str.len > limit.len;
1624 for(size_t i = 0; i < limit.len; ++i)
1625 {
1626 if(str.str[i] < limit.str[i])
1627 return false;
1628 else if(str.str[i] > limit.str[i])
1629 return true;
1630 }
1631 return false;
1632}
1633} // namespace detail
1634/** @endcond */
1635
1636
1637/** @defgroup doc_overflows overflows: does a number string overflow a type
1638 *
1639 * @{ */
1640
1641/** Test if the following string would overflow when converted to
1642 * associated integral types; this function is dispatched with SFINAE
1643 * to handle differently signed and unsigned types.
1644 * @return true if number will overflow, false if it fits (or doesn't parse)
1645 * @see doc_overflow_checked for format specifiers to enforce no-overflow reads
1646 */
1647template<class T>
1648auto overflows(csubstr str) noexcept
1649 -> typename std::enable_if<std::is_unsigned<T>::value, bool>::type
1650{
1651 C4_STATIC_ASSERT(std::is_integral<T>::value);
1652
1653 if C4_UNLIKELY(str.len == 0)
1654 {
1655 return false;
1656 }
1657 else if(str.str[0] == '0')
1658 {
1659 if (str.len == 1)
1660 return false;
1661 switch (str.str[1])
1662 {
1663 case 'x':
1664 case 'X':
1665 {
1666 size_t fno = str.first_not_of('0', 2);
1667 if (fno == csubstr::npos)
1668 return false;
1669 return !(str.len <= fno + (sizeof(T) * 2));
1670 }
1671 case 'b':
1672 case 'B':
1673 {
1674 size_t fno = str.first_not_of('0', 2);
1675 if (fno == csubstr::npos)
1676 return false;
1677 return !(str.len <= fno +(sizeof(T) * 8));
1678 }
1679 case 'o':
1680 case 'O':
1681 {
1682 size_t fno = str.first_not_of('0', 2);
1683 if(fno == csubstr::npos)
1684 return false;
1685 return detail::charconv_digits<T>::is_oct_overflow(str.sub(fno));
1686 }
1687 default:
1688 {
1689 size_t fno = str.first_not_of('0', 1);
1690 if(fno == csubstr::npos)
1691 return false;
1692 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::max_value_dec());
1693 }
1694 }
1695 }
1696 else if C4_UNLIKELY(str.str[0] == '-')
1697 {
1698 return true;
1699 }
1700 else
1701 {
1702 return detail::check_overflow(str, detail::charconv_digits<T>::max_value_dec());
1703 }
1704}
1705
1706
1707/** Test if the following string would overflow when converted to
1708 * associated integral types; this function is dispatched with SFINAE
1709 * to handle differently signed and unsigned types.
1710 *
1711 * @return true if number will overflow, false if it fits (or doesn't parse)
1712 * @see doc_overflow_checked for format specifiers to enforce no-overflow reads
1713 */
1714template<class T>
1715auto overflows(csubstr str) noexcept
1716 -> typename std::enable_if<std::is_signed<T>::value, bool>::type
1717{
1718 C4_STATIC_ASSERT(std::is_integral<T>::value);
1719 if C4_UNLIKELY(str.len == 0)
1720 return false;
1721 if(str.str[0] == '-')
1722 {
1723 if(str.str[1] == '0')
1724 {
1725 if(str.len == 2)
1726 return false;
1727 switch(str.str[2])
1728 {
1729 case 'x':
1730 case 'X':
1731 {
1732 size_t fno = str.first_not_of('0', 3);
1733 if (fno == csubstr::npos)
1734 return false;
1735 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::min_value_hex());
1736 }
1737 case 'b':
1738 case 'B':
1739 {
1740 size_t fno = str.first_not_of('0', 3);
1741 if (fno == csubstr::npos)
1742 return false;
1743 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::min_value_bin());
1744 }
1745 case 'o':
1746 case 'O':
1747 {
1748 size_t fno = str.first_not_of('0', 3);
1749 if(fno == csubstr::npos)
1750 return false;
1751 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::min_value_oct());
1752 }
1753 default:
1754 {
1755 size_t fno = str.first_not_of('0', 2);
1756 if(fno == csubstr::npos)
1757 return false;
1758 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::min_value_dec());
1759 }
1760 }
1761 }
1762 else
1763 {
1764 return detail::check_overflow(str.sub(1), detail::charconv_digits<T>::min_value_dec());
1765 }
1766 }
1767 else if(str.str[0] == '0')
1768 {
1769 if (str.len == 1)
1770 return false;
1771 switch(str.str[1])
1772 {
1773 case 'x':
1774 case 'X':
1775 {
1776 size_t fno = str.first_not_of('0', 2);
1777 if (fno == csubstr::npos)
1778 return false;
1779 const size_t len = str.len - fno;
1780 return !((len < sizeof (T) * 2) || (len == sizeof(T) * 2 && str.str[fno] <= '7'));
1781 }
1782 case 'b':
1783 case 'B':
1784 {
1785 size_t fno = str.first_not_of('0', 2);
1786 if (fno == csubstr::npos)
1787 return false;
1788 return !(str.len <= fno + (sizeof(T) * 8 - 1));
1789 }
1790 case 'o':
1791 case 'O':
1792 {
1793 size_t fno = str.first_not_of('0', 2);
1794 if(fno == csubstr::npos)
1795 return false;
1796 return detail::charconv_digits<T>::is_oct_overflow(str.sub(fno));
1797 }
1798 default:
1799 {
1800 size_t fno = str.first_not_of('0', 1);
1801 if(fno == csubstr::npos)
1802 return false;
1803 return detail::check_overflow(str.sub(fno), detail::charconv_digits<T>::max_value_dec());
1804 }
1805 }
1806 }
1807 else
1808 {
1809 return detail::check_overflow(str, detail::charconv_digits<T>::max_value_dec());
1810 }
1811}
1812
1813/** @} */
1814
1815
1816//-----------------------------------------------------------------------------
1817//-----------------------------------------------------------------------------
1818//-----------------------------------------------------------------------------
1819
1820/** @cond dev */
1821namespace detail {
1822
1823
1824#if (!C4CORE_HAVE_STD_FROMCHARS)
1825/** @see http://www.exploringbinary.com/ for many good examples on float-str conversion */
1826template<size_t N>
1827void get_real_format_str(char (& C4_RESTRICT fmt)[N], int precision, RealFormat_e formatting, const char* length_modifier="")
1828{
1829 int iret;
1830 if(precision == -1)
1831 iret = snprintf(fmt, sizeof(fmt), "%%%s%c", length_modifier, formatting);
1832 else if(precision == 0)
1833 iret = snprintf(fmt, sizeof(fmt), "%%.%s%c", length_modifier, formatting);
1834 else
1835 iret = snprintf(fmt, sizeof(fmt), "%%.%d%s%c", precision, length_modifier, formatting);
1836 C4_ASSERT(iret >= 2 && size_t(iret) < sizeof(fmt));
1837 C4_UNUSED(iret);
1838}
1839
1840
1841/** @todo we're depending on snprintf()/sscanf() for converting to/from
1842 * floating point numbers. Apparently, this increases the binary size
1843 * by a considerable amount. There are some lightweight printf
1844 * implementations:
1845 *
1846 * @see http://www.sparetimelabs.com/tinyprintf/tinyprintf.php (BSD)
1847 * @see https://github.com/weiss/c99-snprintf
1848 * @see https://github.com/nothings/stb/blob/master/stb_sprintf.h
1849 * @see http://www.exploringbinary.com/
1850 * @see https://blog.benoitblanchon.fr/lightweight-float-to-string/
1851 * @see http://www.ryanjuckett.com/programming/printing-floating-point-numbers/
1852 */
1853template<class T>
1854size_t print_one(substr str, const char* full_fmt, T v)
1855{
1856#ifdef _MSC_VER
1857 /** use _snprintf() to prevent early termination of the output
1858 * for writing the null character at the last position
1859 * @see https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx */
1860 int iret = _snprintf(str.str, str.len, full_fmt, v);
1861 if(iret < 0)
1862 {
1863 /* when buf.len is not enough, VS returns a negative value.
1864 * so call it again with a negative value for getting an
1865 * actual length of the string */
1866 iret = snprintf(nullptr, 0, full_fmt, v);
1867 C4_ASSERT(iret > 0);
1868 }
1869 size_t ret = (size_t) iret;
1870 return ret;
1871#else
1872 int iret = snprintf(str.str, str.len, full_fmt, v);
1873 C4_ASSERT(iret >= 0);
1874 size_t ret = (size_t) iret;
1875 if(ret >= str.len)
1876 ++ret; /* snprintf() reserves the last character to write \0 */
1877 return ret;
1878#endif
1879}
1880#endif // (!C4CORE_HAVE_STD_FROMCHARS)
1881
1882
1883#if (!C4CORE_HAVE_STD_FROMCHARS) && (!C4CORE_HAVE_FAST_FLOAT)
1884/** scans a string using the given type format, while at the same time
1885 * allowing non-null-terminated strings AND guaranteeing that the given
1886 * string length is strictly respected, so that no buffer overflows
1887 * might occur. */
1888template<typename T>
1889inline size_t scan_one(csubstr str, const char *type_fmt, T *v)
1890{
1891 /* snscanf() is absolutely needed here as we must be sure that
1892 * str.len is strictly respected, because substr is
1893 * generally not null-terminated.
1894 *
1895 * Alas, there is no snscanf().
1896 *
1897 * So we fake it by using a dynamic format with an explicit
1898 * field size set to the length of the given span.
1899 * This trick is taken from:
1900 * https://stackoverflow.com/a/18368910/5875572 */
1901
1902 /* this is the actual format we'll use for scanning */
1903 char fmt[16];
1904
1905 /* write the length into it. Eg "%12f".
1906 * Also, get the number of characters read from the string.
1907 * So the final format ends up as "%12f%n"*/
1908 int iret = std::snprintf(fmt, sizeof(fmt), "%%" "%zu" "%s" "%%n", str.len, type_fmt);
1909 /* no nasty surprises, please! */
1910 C4_ASSERT(iret >= 0 && size_t(iret) < C4_COUNTOF(fmt));
1911
1912 /* now we scan with confidence that the span length is respected */
1913 int num_chars;
1914 iret = std::sscanf(str.str, fmt, v, &num_chars);
1915 /* scanf returns the number of successful conversions */
1916 if(iret != 1) return csubstr::npos;
1917 C4_ASSERT(num_chars >= 0);
1918 return (size_t)(num_chars);
1919}
1920#endif // (!C4CORE_HAVE_STD_FROMCHARS) && (!C4CORE_HAVE_FAST_FLOAT)
1921
1922
1923#if C4CORE_HAVE_STD_TOCHARS
1924template<class T>
1925C4_ALWAYS_INLINE size_t rtoa(substr buf, T v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept
1926{
1927 std::to_chars_result result;
1928 size_t pos = 0;
1929 if(formatting == FTOA_HEXA)
1930 {
1931 if(buf.len > size_t(2))
1932 {
1933 buf.str[0] = '0';
1934 buf.str[1] = 'x';
1935 }
1936 pos += size_t(2);
1937 }
1938 if(precision == -1)
1939 result = std::to_chars(buf.str + pos, buf.str + buf.len, v, (std::chars_format)formatting);
1940 else
1941 result = std::to_chars(buf.str + pos, buf.str + buf.len, v, (std::chars_format)formatting, precision);
1942 if(result.ec == std::errc())
1943 {
1944 // all good, no errors.
1945 C4_ASSERT(result.ptr >= buf.str);
1946 ptrdiff_t delta = result.ptr - buf.str;
1947 return static_cast<size_t>(delta);
1948 }
1949 C4_ASSERT(result.ec == std::errc::value_too_large);
1950 // This is unfortunate.
1951 //
1952 // When the result can't fit in the given buffer,
1953 // std::to_chars() returns the end pointer it was originally
1954 // given, which is useless because here we would like to know
1955 // _exactly_ how many characters the buffer must have to fit
1956 // the result.
1957 //
1958 // So we take the pessimistic view, and assume as many digits
1959 // as could ever be required:
1960 size_t ret = static_cast<size_t>(std::numeric_limits<T>::max_digits10);
1961 return ret > buf.len ? ret : buf.len + 1;
1962}
1963#endif // C4CORE_HAVE_STD_TOCHARS
1964
1965
1966#if C4CORE_HAVE_FAST_FLOAT
1967template<class T>
1968C4_ALWAYS_INLINE bool scan_rhex(csubstr s, T *C4_RESTRICT val) noexcept
1969{
1970 // no need for these asserts, but we leave them here to show
1971 // the expectation:
1972 //C4_ASSERT(s.len > 0);
1973 //C4_ASSERT(s.str[0] != '-');
1974 //C4_ASSERT(s.str[0] != '+');
1975 //C4_ASSERT(!s.begins_with("0x"));
1976 //C4_ASSERT(!s.begins_with("0X"));
1977 size_t pos = 0;
1978 // integer part
1979 for( ; pos < s.len; ++pos)
1980 {
1981 const char c = s.str[pos];
1982 if(c >= '0' && c <= '9')
1983 *val = (*val * T(16)) + T(c - '0');
1984 else if(c >= 'a' && c <= 'f')
1985 *val = (*val * T(16)) + T(c - 'a');
1986 else if(c >= 'A' && c <= 'F')
1987 *val = (*val * T(16)) + T(c - 'A');
1988 else if(c == '.')
1989 {
1990 ++pos;
1991 break; // follow on to mantissa
1992 }
1993 else if(c == 'p' || c == 'P')
1994 {
1995 ++pos;
1996 goto power; // no mantissa given, jump to power // NOLINT
1997 }
1998 else
1999 {
2000 return false;
2001 }
2002 }
2003 // mantissa
2004 {
2005 // 0.0625 == 1/16 == value of first digit after the comma
2006 for(T digit = T(0.0625); pos < s.len; ++pos, digit /= T(16)) // NOLINT
2007 {
2008 const char c = s.str[pos];
2009 if(c >= '0' && c <= '9')
2010 *val += digit * T(c - '0');
2011 else if(c >= 'a' && c <= 'f')
2012 *val += digit * T(c - 'a');
2013 else if(c >= 'A' && c <= 'F')
2014 *val += digit * T(c - 'A');
2015 else if(c == 'p' || c == 'P')
2016 {
2017 ++pos;
2018 goto power; // mantissa finished, jump to power // NOLINT
2019 }
2020 else
2021 {
2022 return false;
2023 }
2024 }
2025 }
2026 return true;
2027power:
2028 if C4_LIKELY(pos < s.len)
2029 {
2030 if(s.str[pos] == '+') // atoi() cannot handle a leading '+'
2031 ++pos;
2032 if C4_LIKELY(pos < s.len)
2033 {
2034 int16_t powval = {};
2035 if C4_LIKELY(atoi(s.sub(pos), &powval))
2036 {
2037 *val *= ipow<T, int16_t, 16>(powval);
2038 return true;
2039 }
2040 }
2041 }
2042 return false;
2043}
2044#endif
2045
2046} // namespace detail
2047/** @endcond */
2048
2049
2050#undef _c4append
2051
2052
2053/** @defgroup doc_ftoa ftoa: float32 to chars
2054 *
2055 * @{ */
2056
2057/** Convert a single-precision real number to string. The string will
2058 * in general be NOT null-terminated. For FTOA_FLEX, \p precision is
2059 * the number of significand digits. Otherwise \p precision is the
2060 * number of decimals. It is safe to call this function with an empty
2061 * or too-small buffer.
2062 *
2063 * @return the size of the buffer needed to write the number
2064 */
2065C4_ALWAYS_INLINE size_t ftoa(substr str, float v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept
2066{
2067#if C4CORE_HAVE_STD_TOCHARS
2068 return detail::rtoa(str, v, precision, formatting);
2069#else
2070 char fmt[16];
2071 detail::get_real_format_str(fmt, precision, formatting, /*length_modifier*/"");
2072 return detail::print_one(str, fmt, v);
2073#endif
2074}
2075
2076/** @} */
2077
2078
2079/** @defgroup doc_dtoa dtoa: float64 to chars
2080 *
2081 * @{ */
2082
2083/** Convert a double-precision real number to string. The string will
2084 * in general be NOT null-terminated. For FTOA_FLEX, \p precision is
2085 * the number of significand digits. Otherwise \p precision is the
2086 * number of decimals. It is safe to call this function with an empty
2087 * or too-small buffer.
2088 *
2089 * @return the size of the buffer needed to write the number
2090 */
2091C4_ALWAYS_INLINE size_t dtoa(substr str, double v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept
2092{
2093#if C4CORE_HAVE_STD_TOCHARS
2094 return detail::rtoa(str, v, precision, formatting);
2095#else
2096 char fmt[16];
2097 detail::get_real_format_str(fmt, precision, formatting, /*length_modifier*/"l");
2098 return detail::print_one(str, fmt, v);
2099#endif
2100}
2101
2102/** @} */
2103
2104
2105/** @defgroup doc_atof atof: chars to float32
2106 *
2107 * @{ */
2108
2109/** Convert a string to a single precision real number.
2110 * The input string must be trimmed to the value, ie
2111 * no leading or trailing whitespace can be present.
2112 * @return true iff the conversion succeeded
2113 * @see atof_first() if the string is not trimmed
2114 */
2115C4_ALWAYS_INLINE bool atof(csubstr str, float * C4_RESTRICT v) noexcept
2116{
2117 C4_ASSERT(str.len > 0);
2118 C4_ASSERT(str.triml(" \r\t\n").len == str.len);
2119#if C4CORE_HAVE_FAST_FLOAT
2120 // fastfloat cannot parse hexadecimal floats
2121 bool isneg = (str.str[0] == '-');
2122 csubstr rem = str.sub(isneg || str.str[0] == '+');
2123 if( ! (rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2124 {
2125 fast_float::from_chars_result result;
2126 result = fast_float::from_chars(str.str, str.str + str.len, *v);
2127 return result.ec == std::errc();
2128 }
2129 else if(detail::scan_rhex(rem.sub(2), v))
2130 {
2131 *v *= isneg ? -1.f : 1.f;
2132 return true;
2133 }
2134 return false;
2135#elif C4CORE_HAVE_STD_FROMCHARS
2136 std::from_chars_result result;
2137 result = std::from_chars(str.str, str.str + str.len, *v);
2138 return result.ec == std::errc();
2139#else
2140 csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+');
2141 if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2142 return detail::scan_one(str, "f", v) != csubstr::npos;
2143 else
2144 return detail::scan_one(str, "a", v) != csubstr::npos;
2145#endif
2146}
2147
2148
2149/** Convert a string to a single precision real number.
2150 * Leading whitespace is skipped until valid characters are found.
2151 * @return the number of characters read from the string, or npos if
2152 * conversion was not successful or if the string was empty */
2153inline size_t atof_first(csubstr str, float * C4_RESTRICT v) noexcept
2154{
2155 csubstr trimmed = str.first_real_span();
2156 if(trimmed.len == 0)
2157 return csubstr::npos;
2158 if(atof(trimmed, v))
2159 return static_cast<size_t>(trimmed.end() - str.begin());
2160 return csubstr::npos;
2161}
2162
2163/** @} */
2164
2165
2166/** @defgroup doc_atod atod: chars to float64
2167 *
2168 * @{ */
2169
2170/** Convert a string to a double precision real number.
2171 * The input string must be trimmed to the value, ie
2172 * no leading or trailing whitespace can be present.
2173 * @return true iff the conversion succeeded
2174 * @see atod_first() if the string is not trimmed
2175 */
2176C4_ALWAYS_INLINE bool atod(csubstr str, double * C4_RESTRICT v) noexcept
2177{
2178 C4_ASSERT(str.len > 0);
2179 C4_ASSERT(str.triml(" \r\t\n").len == str.len);
2180#if C4CORE_HAVE_FAST_FLOAT
2181 // fastfloat cannot parse hexadecimal floats
2182 bool isneg = (str.str[0] == '-');
2183 csubstr rem = str.sub(isneg || str.str[0] == '+');
2184 if( ! (rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2185 {
2186 fast_float::from_chars_result result;
2187 #ifndef CLANG_TIDY // suppress a false-positive error (cannot be done with NOLINT: https://stackoverflow.com/questions/62838193/ )
2188 result = fast_float::from_chars(str.str, str.str + str.len, *v);
2189 #else
2190 result = {};
2191 #endif
2192 return result.ec == std::errc();
2193 }
2194 else if(detail::scan_rhex(rem.sub(2), v))
2195 {
2196 *v *= isneg ? -1. : 1.;
2197 return true;
2198 }
2199 return false;
2200#elif C4CORE_HAVE_STD_FROMCHARS
2201 std::from_chars_result result;
2202 result = std::from_chars(str.str, str.str + str.len, *v);
2203 return result.ec == std::errc();
2204#else
2205 csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+');
2206 if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X'))))
2207 return detail::scan_one(str, "lf", v) != csubstr::npos;
2208 else
2209 return detail::scan_one(str, "la", v) != csubstr::npos;
2210#endif
2211}
2212
2213
2214/** Convert a string to a double precision real number.
2215 * Leading whitespace is skipped until valid characters are found.
2216 * @return the number of characters read from the string, or npos if
2217 * conversion was not successful or if the string was empty */
2218inline size_t atod_first(csubstr str, double * C4_RESTRICT v) noexcept
2219{
2220 csubstr trimmed = str.first_real_span();
2221 if(trimmed.len == 0)
2222 return csubstr::npos;
2223 if(atod(trimmed, v))
2224 return static_cast<size_t>(trimmed.end() - str.begin());
2225 return csubstr::npos;
2226}
2227
2228/** @} */
2229
2230
2231//-----------------------------------------------------------------------------
2232//-----------------------------------------------------------------------------
2233//-----------------------------------------------------------------------------
2234// generic versions
2235
2236/** @cond dev */
2237// on some platforms, (unsigned) int and (unsigned) long
2238// are not any of the fixed length types above
2239#define C4_IF_NOT_FIXED_LENGTH_I_(T, ty) typename std::enable_if<std:: is_signed<T>::value && !is_fixed_length<T>::value_i, ty>
2240#define C4_IF_NOT_FIXED_LENGTH_U_(T, ty) typename std::enable_if<std::is_unsigned<T>::value && !is_fixed_length<T>::value_u, ty>
2241/** @endcond*/
2242
2243
2244/** @defgroup doc_xtoa xtoa: generic value to chars
2245 *
2246 * Dispatches to the most appropriate and efficient conversion
2247 * function
2248 *
2249 * @{ */
2250C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v) noexcept { return write_dec(s, v); }
2251C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v) noexcept { return write_dec(s, v); }
2252C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v) noexcept { return write_dec(s, v); }
2253C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v) noexcept { return write_dec(s, v); }
2254C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v) noexcept { return itoa(s, v); }
2255C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v) noexcept { return itoa(s, v); }
2256C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v) noexcept { return itoa(s, v); }
2257C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v) noexcept { return itoa(s, v); }
2258C4_ALWAYS_INLINE size_t xtoa(substr s, float v) noexcept { return ftoa(s, v); }
2259C4_ALWAYS_INLINE size_t xtoa(substr s, double v) noexcept { return dtoa(s, v); }
2260
2261C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v, uint8_t radix) noexcept { return utoa(s, v, radix); }
2262C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v, uint16_t radix) noexcept { return utoa(s, v, radix); }
2263C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v, uint32_t radix) noexcept { return utoa(s, v, radix); }
2264C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v, uint64_t radix) noexcept { return utoa(s, v, radix); }
2265C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v, int8_t radix) noexcept { return itoa(s, v, radix); }
2266C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v, int16_t radix) noexcept { return itoa(s, v, radix); }
2267C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v, int32_t radix) noexcept { return itoa(s, v, radix); }
2268C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v, int64_t radix) noexcept { return itoa(s, v, radix); }
2269
2270C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v, uint8_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); }
2271C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v, uint16_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); }
2272C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v, uint32_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); }
2273C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v, uint64_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); }
2274C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v, int8_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); }
2275C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v, int16_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); }
2276C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v, int32_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); }
2277C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v, int64_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); }
2278
2279C4_ALWAYS_INLINE size_t xtoa(substr s, float v, int precision, RealFormat_e formatting=FTOA_FLEX) noexcept { return ftoa(s, v, precision, formatting); }
2280C4_ALWAYS_INLINE size_t xtoa(substr s, double v, int precision, RealFormat_e formatting=FTOA_FLEX) noexcept { return dtoa(s, v, precision, formatting); }
2281
2282template <class T> C4_ALWAYS_INLINE auto xtoa(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return itoa(buf, v); }
2283template <class T> C4_ALWAYS_INLINE auto xtoa(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return write_dec(buf, v); }
2284template <class T>
2285C4_ALWAYS_INLINE size_t xtoa(substr s, T *v) noexcept { return itoa(s, (intptr_t)v, (intptr_t)16); }
2286
2287/** @} */
2288
2289/** @defgroup doc_atox atox: generic chars to value
2290 *
2291 * Dispatches to the most appropriate and efficient conversion
2292 * function
2293 *
2294 * @{ */
2295
2296C4_ALWAYS_INLINE bool atox(csubstr s, uint8_t *C4_RESTRICT v) noexcept { return atou(s, v); }
2297C4_ALWAYS_INLINE bool atox(csubstr s, uint16_t *C4_RESTRICT v) noexcept { return atou(s, v); }
2298C4_ALWAYS_INLINE bool atox(csubstr s, uint32_t *C4_RESTRICT v) noexcept { return atou(s, v); }
2299C4_ALWAYS_INLINE bool atox(csubstr s, uint64_t *C4_RESTRICT v) noexcept { return atou(s, v); }
2300C4_ALWAYS_INLINE bool atox(csubstr s, int8_t *C4_RESTRICT v) noexcept { return atoi(s, v); }
2301C4_ALWAYS_INLINE bool atox(csubstr s, int16_t *C4_RESTRICT v) noexcept { return atoi(s, v); }
2302C4_ALWAYS_INLINE bool atox(csubstr s, int32_t *C4_RESTRICT v) noexcept { return atoi(s, v); }
2303C4_ALWAYS_INLINE bool atox(csubstr s, int64_t *C4_RESTRICT v) noexcept { return atoi(s, v); }
2304C4_ALWAYS_INLINE bool atox(csubstr s, float *C4_RESTRICT v) noexcept { return atof(s, v); }
2305C4_ALWAYS_INLINE bool atox(csubstr s, double *C4_RESTRICT v) noexcept { return atod(s, v); }
2306
2307template <class T> C4_ALWAYS_INLINE auto atox(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, bool)::type { return atoi(buf, v); }
2308template <class T> C4_ALWAYS_INLINE auto atox(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, bool)::type { return atou(buf, v); }
2309template <class T>
2310C4_ALWAYS_INLINE bool atox(csubstr s, T **v) noexcept { intptr_t tmp; bool ret = atox(s, &tmp); if(ret) { *v = (T*)tmp; } return ret; }
2311
2312/** @} */
2313
2314
2315/** @defgroup doc_to_chars to_chars: generalized chars to value
2316 *
2317 * Convert the given value, writing into the string. The resulting
2318 * string will NOT be null-terminated. Return the number of
2319 * characters needed. This function is safe to call when the string
2320 * is too small - no writes will occur beyond the string's last
2321 * character.
2322 *
2323 * Dispatches to the most appropriate and efficient conversion
2324 * function.
2325 *
2326 * @see write_dec, doc_utoa, doc_itoa, doc_ftoa, doc_dtoa
2327 *
2328 * @warning When serializing floating point values (float or double),
2329 * be aware that because it uses defaults, to_chars() may cause a
2330 * truncation of the precision. To enforce a particular precision, use
2331 * for example @ref c4::fmt::real, or call directly @ref c4::ftoa or
2332 * @ref c4::dtoa.
2333 *
2334 * @{ */
2335
2336C4_ALWAYS_INLINE size_t to_chars(substr buf, uint8_t v) noexcept { return write_dec(buf, v); }
2337C4_ALWAYS_INLINE size_t to_chars(substr buf, uint16_t v) noexcept { return write_dec(buf, v); }
2338C4_ALWAYS_INLINE size_t to_chars(substr buf, uint32_t v) noexcept { return write_dec(buf, v); }
2339C4_ALWAYS_INLINE size_t to_chars(substr buf, uint64_t v) noexcept { return write_dec(buf, v); }
2340C4_ALWAYS_INLINE size_t to_chars(substr buf, int8_t v) noexcept { return itoa(buf, v); }
2341C4_ALWAYS_INLINE size_t to_chars(substr buf, int16_t v) noexcept { return itoa(buf, v); }
2342C4_ALWAYS_INLINE size_t to_chars(substr buf, int32_t v) noexcept { return itoa(buf, v); }
2343C4_ALWAYS_INLINE size_t to_chars(substr buf, int64_t v) noexcept { return itoa(buf, v); }
2344C4_ALWAYS_INLINE size_t to_chars(substr buf, float v) noexcept { return ftoa(buf, v); }
2345C4_ALWAYS_INLINE size_t to_chars(substr buf, double v) noexcept { return dtoa(buf, v); }
2346
2347template <class T> C4_ALWAYS_INLINE auto to_chars(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return itoa(buf, v); }
2348template <class T> C4_ALWAYS_INLINE auto to_chars(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return write_dec(buf, v); }
2349template <class T>
2350C4_ALWAYS_INLINE auto to_chars(substr s, T *v) noexcept
2351 -> typename std::enable_if<!std::is_same<T, char>::value &&
2352 !std::is_same<T, const char>::value,
2353 size_t>::type
2354{
2355 return itoa(s, (intptr_t)v, (intptr_t)16);
2356}
2357
2358/** @} */
2359
2360
2361/** @defgroup doc_from_chars from_chars: generalized chars to value
2362 *
2363 * Read a value from the string, which must be trimmed to the value
2364 * (ie, no leading/trailing whitespace). return true if the
2365 * conversion succeeded. There is no check for overflow; the value
2366 * wraps around in a way similar to the standard C/C++ overflow
2367 * behavior. For example, from_chars<int8_t>("128", &val) returns true
2368 * and val will be set tot 0. See @ref doc_overflows and @ref
2369 * doc_overflow_checked for facilities enforcing no-overflow.
2370 *
2371 * Dispatches to the most appropriate and efficient conversion
2372 * function
2373 *
2374 * @see doc_from_chars_first, atou, atoi, atof, atod
2375 * @{ */
2376
2377C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint8_t *C4_RESTRICT v) noexcept { return atou(buf, v); }
2378C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint16_t *C4_RESTRICT v) noexcept { return atou(buf, v); }
2379C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint32_t *C4_RESTRICT v) noexcept { return atou(buf, v); }
2380C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint64_t *C4_RESTRICT v) noexcept { return atou(buf, v); }
2381C4_ALWAYS_INLINE bool from_chars(csubstr buf, int8_t *C4_RESTRICT v) noexcept { return atoi(buf, v); }
2382C4_ALWAYS_INLINE bool from_chars(csubstr buf, int16_t *C4_RESTRICT v) noexcept { return atoi(buf, v); }
2383C4_ALWAYS_INLINE bool from_chars(csubstr buf, int32_t *C4_RESTRICT v) noexcept { return atoi(buf, v); }
2384C4_ALWAYS_INLINE bool from_chars(csubstr buf, int64_t *C4_RESTRICT v) noexcept { return atoi(buf, v); }
2385C4_ALWAYS_INLINE bool from_chars(csubstr buf, float *C4_RESTRICT v) noexcept { return atof(buf, v); }
2386C4_ALWAYS_INLINE bool from_chars(csubstr buf, double *C4_RESTRICT v) noexcept { return atod(buf, v); }
2387
2388template <class T> C4_ALWAYS_INLINE auto from_chars(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, bool)::type { return atoi(buf, v); }
2389template <class T> C4_ALWAYS_INLINE auto from_chars(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, bool)::type { return atou(buf, v); }
2390template <class T>
2391C4_ALWAYS_INLINE bool from_chars(csubstr buf, T **v) noexcept { intptr_t tmp; bool ret = from_chars(buf, &tmp); if(ret) { *v = (T*)tmp; } return ret; }
2392
2393/** @defgroup doc_from_chars_first from_chars_first: generalized chars to value
2394 *
2395 * Read the first valid sequence of characters from the string,
2396 * skipping leading whitespace, and convert it using @ref doc_from_chars .
2397 * Return the number of characters read for converting.
2398 *
2399 * Dispatches to the most appropriate and efficient conversion
2400 * function.
2401 *
2402 * @see atou_first, atoi_first, atof_first, atod_first
2403 * @{ */
2404
2405C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint8_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); }
2406C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint16_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); }
2407C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint32_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); }
2408C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint64_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); }
2409C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int8_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); }
2410C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int16_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); }
2411C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int32_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); }
2412C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int64_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); }
2413C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, float *C4_RESTRICT v) noexcept { return atof_first(buf, v); }
2414C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, double *C4_RESTRICT v) noexcept { return atod_first(buf, v); }
2415
2416template <class T> C4_ALWAYS_INLINE auto from_chars_first(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return atoi_first(buf, v); }
2417template <class T> C4_ALWAYS_INLINE auto from_chars_first(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return atou_first(buf, v); }
2418template <class T>
2419C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, T **v) noexcept { intptr_t tmp; bool ret = from_chars_first(buf, &tmp); if(ret) { *v = (T*)tmp; } return ret; }
2420
2421/** @} */
2422
2423/** @} */
2424
2425#undef C4_IF_NOT_FIXED_LENGTH_I_
2426#undef C4_IF_NOT_FIXED_LENGTH_U_
2427
2428
2429//-----------------------------------------------------------------------------
2430//-----------------------------------------------------------------------------
2431//-----------------------------------------------------------------------------
2432/** call to_chars() and return a substr consisting of the
2433 * written portion of the input buffer. Ie, same as to_chars(),
2434 * but return a substr instead of a size_t.
2435 * Convert the given value to a string using to_chars(), and
2436 * return the resulting string, up to and including the last
2437 * written character.
2438 * @ingroup doc_to_chars
2439 * @see to_chars() */
2440template<class T>
2441C4_ALWAYS_INLINE substr to_chars_sub(substr buf, T const& C4_RESTRICT v) noexcept
2442{
2443 size_t sz = to_chars(buf, v);
2444 return buf.left_of(sz <= buf.len ? sz : buf.len);
2445}
2446
2447//-----------------------------------------------------------------------------
2448//-----------------------------------------------------------------------------
2449//-----------------------------------------------------------------------------
2450// bool implementation
2451
2452/** @ingroup doc_to_chars */
2453C4_ALWAYS_INLINE size_t to_chars(substr buf, bool v) noexcept
2454{
2455 int val = v;
2456 return to_chars(buf, val);
2457}
2458
2459/** @ingroup doc_from_chars */
2460inline bool from_chars(csubstr buf, bool * C4_RESTRICT v) noexcept
2461{
2462 switch(buf.len) // NOLINT
2463 {
2464 case 1:
2465 if(buf.str[0] == '0')
2466 {
2467 *v = false; return true;
2468 }
2469 else if(buf.str[0] == '1')
2470 {
2471 *v = true; return true;
2472 }
2473 break;
2474 case 4:
2475 if(((buf.str[0] == 't') && (0 == memcmp(buf.str + 1, "rue", 3)))
2476 ||
2477 ((buf.str[0] == 'T') && (0 == memcmp(buf.str + 1, "rue", 3) ||
2478 0 == memcmp(buf.str + 1, "RUE", 3))))
2479 {
2480 *v = true; return true;
2481 }
2482 break;
2483 case 5:
2484 if(((buf.str[0] == 'f') && (0 == memcmp(buf.str + 1, "alse", 4)))
2485 ||
2486 ((buf.str[0] == 'F') && (0 == memcmp(buf.str + 1, "alse", 4) ||
2487 0 == memcmp(buf.str + 1, "ALSE", 4))))
2488 {
2489 *v = false; return true;
2490 }
2491 break;
2492 }
2493 // fallback to c-style int bools
2494 int val = 0;
2495 bool ret = from_chars(buf, &val);
2496 if C4_LIKELY(ret)
2497 {
2498 *v = (val != 0);
2499 }
2500 return ret;
2501}
2502
2503/** @ingroup doc_from_chars_first */
2504inline size_t from_chars_first(csubstr buf, bool * C4_RESTRICT v) noexcept
2505{
2506 csubstr trimmed = buf.first_non_empty_span();
2507 if(trimmed.len == 0 || !from_chars(buf, v))
2508 return csubstr::npos;
2509 return trimmed.len;
2510}
2511
2512
2513//-----------------------------------------------------------------------------
2514// single-char implementation
2515
2516/** @ingroup doc_to_chars */
2517inline size_t to_chars(substr buf, char v) noexcept
2518{
2519 if(buf.len > 0)
2520 {
2521 C4_XASSERT(buf.str);
2522 buf.str[0] = v;
2523 }
2524 return 1;
2525}
2526
2527/** extract a single character from a substring
2528 * @note to extract a string instead and not just a single character, use the csubstr overload
2529 * @ingroup doc_from_chars
2530 * */
2531inline bool from_chars(csubstr buf, char * C4_RESTRICT v) noexcept
2532{
2533 if(buf.len != 1)
2534 return false;
2535 C4_XASSERT(buf.str);
2536 *v = buf.str[0];
2537 return true;
2538}
2539
2540/** @ingroup doc_from_chars_first */
2541inline size_t from_chars_first(csubstr buf, char * C4_RESTRICT v) noexcept
2542{
2543 if(buf.len < 1)
2544 return csubstr::npos;
2545 *v = buf.str[0];
2546 return 1;
2547}
2548
2549
2550//-----------------------------------------------------------------------------
2551// csubstr implementation
2552
2553/** @ingroup doc_to_chars */
2554inline size_t to_chars(substr buf, csubstr v) noexcept
2555{
2556 C4_ASSERT(!buf.overlaps(v));
2557 size_t len = buf.len < v.len ? buf.len : v.len;
2558 // calling memcpy with null strings is undefined behavior
2559 // and will wreak havoc in calling code's branches.
2560 // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637
2561 if(len)
2562 {
2563 C4_ASSERT(buf.str != nullptr);
2564 C4_ASSERT(v.str != nullptr);
2565 memcpy(buf.str, v.str, len);
2566 }
2567 return v.len;
2568}
2569
2570/** @ingroup doc_from_chars */
2571inline bool from_chars(csubstr buf, csubstr *C4_RESTRICT v) noexcept
2572{
2573 *v = buf;
2574 return true;
2575}
2576
2577/** @ingroup doc_from_chars_first */
2578inline size_t from_chars_first(csubstr buf, csubstr * C4_RESTRICT v) noexcept
2579{
2580 csubstr trimmed = buf.first_non_empty_span();
2581 if(trimmed.len == 0)
2582 return csubstr::npos;
2583 *v = trimmed;
2584 return static_cast<size_t>(trimmed.end() - buf.begin());
2585}
2586
2587
2588//-----------------------------------------------------------------------------
2589// substr
2590
2591/** @ingroup doc_to_chars */
2592inline size_t to_chars(substr buf, substr v) noexcept
2593{
2594 C4_ASSERT(!buf.overlaps(v));
2595 size_t len = buf.len < v.len ? buf.len : v.len;
2596 // calling memcpy zero len is undefined behavior
2597 // and will wreak havoc in calling code's branches.
2598 // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637
2599 if(len)
2600 {
2601 C4_ASSERT(buf.str != nullptr);
2602 C4_ASSERT(v.str != nullptr);
2603 memcpy(buf.str, v.str, len);
2604 }
2605 return v.len;
2606}
2607
2608/** @ingroup doc_from_chars */
2609inline bool from_chars(csubstr buf, substr * C4_RESTRICT v) noexcept
2610{
2611 C4_ASSERT(!buf.overlaps(*v));
2612 // is the destination buffer wide enough?
2613 if(v->len >= buf.len)
2614 {
2615 // calling memcpy with zero len is undefined behavior
2616 // and will wreak havoc in calling code's branches.
2617 // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637
2618 if(buf.len)
2619 {
2620 C4_ASSERT(buf.str != nullptr);
2621 C4_ASSERT(v->str != nullptr);
2622 memcpy(v->str, buf.str, buf.len);
2623 }
2624 v->len = buf.len;
2625 return true;
2626 }
2627 return false;
2628}
2629
2630/** @ingroup doc_from_chars_first */
2631inline size_t from_chars_first(csubstr buf, substr * C4_RESTRICT v) noexcept
2632{
2633 csubstr trimmed = buf.first_non_empty_span();
2634 C4_ASSERT(!trimmed.overlaps(*v));
2635 if C4_UNLIKELY(trimmed.len == 0)
2636 return csubstr::npos;
2637 size_t len = trimmed.len > v->len ? v->len : trimmed.len;
2638 // calling memcpy with zero len is undefined behavior
2639 // and will wreak havoc in calling code's branches.
2640 // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637
2641 if(len)
2642 {
2643 C4_ASSERT(buf.str != nullptr);
2644 C4_ASSERT(v->str != nullptr);
2645 memcpy(v->str, trimmed.str, len);
2646 }
2647 if C4_UNLIKELY(trimmed.len > v->len)
2648 return csubstr::npos;
2649 return static_cast<size_t>(trimmed.end() - buf.begin());
2650}
2651
2652
2653//-----------------------------------------------------------------------------
2654
2655/** @ingroup doc_to_chars
2656 * (1) overload for `char(&)[N]` and `const char(&)[N]` */
2657template<size_t N>
2658size_t to_chars(substr buf, const char (& C4_RESTRICT v)[N]) noexcept
2659{
2660 return to_chars(buf, csubstr{v, N-1});
2661}
2662
2663/** @ingroup doc_to_chars
2664 * (2) overload for `char*` and `const char*`. Must be zero-terminated!
2665 * @warning will call strlen()
2666 * @note this overload uses SFINAE to prevent it from overriding the array overload
2667 * @see For a more detailed explanation on why the plain pointer overloads cannot
2668 * coexist with the array overloads, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */
2669template<class CharPtr>
2670auto to_chars(substr buf, CharPtr v) noexcept
2671 -> typename std::enable_if<std::is_same<CharPtr, char*>::value
2672 ||
2673 std::is_same<CharPtr, const char*>::value, size_t>::type
2674{
2675 return v ? to_chars(buf, csubstr{v, strlen(v)}) : 0;
2676}
2677
2678
2679//-----------------------------------------------------------------------------
2680// nullptr implementation
2681
2682/** @ingroup doc_to_chars */
2683C4_ALWAYS_INLINE size_t to_chars(substr, std::nullptr_t) noexcept
2684{
2685 return 0;
2686}
2687
2688// from_chars() and from_chars_sub() must not exist for nullptr
2689
2690
2691/** @} */
2692
2693} // namespace c4
2694
2695// NOLINTEND(*-signed-bitwise)
2696
2697#if defined(_MSC_VER) && !defined(__clang__)
2698# pragma warning(pop)
2699#elif defined(__clang__)
2700# pragma clang diagnostic pop
2701#elif defined(__GNUC__)
2702# pragma GCC diagnostic pop
2703#endif
2704
2705#endif /* C4_CHARCONV_HPP_ */
#define C4_NO_UBSAN_IOVRFLW
Definition charconv.hpp:120
bool atod(csubstr str, double *v) noexcept
Convert a string to a double precision real number.
size_t atod_first(csubstr str, double *v) noexcept
Convert a string to a double precision real number.
size_t atof_first(csubstr str, float *v) noexcept
Convert a string to a single precision real number.
bool atof(csubstr str, float *v) noexcept
Convert a string to a single precision real number.
bool atoi(csubstr str, T *v) noexcept
Convert a trimmed string to a signed integral value.
size_t atoi_first(csubstr str, T *v)
Select the next range of characters in the string that can be parsed as a signed integral value,...
bool atou(csubstr str, T *v) noexcept
Convert a trimmed string to an unsigned integral value.
size_t atou_first(csubstr str, T *v)
Select the next range of characters in the string that can be parsed as an unsigned integral value,...
bool atox(csubstr s, uint8_t *v) noexcept
RealFormat_e
Definition charconv.hpp:186
@ FTOA_FLEX
print the real number in flexible format (like g)
Definition charconv.hpp:192
@ FTOA_SCIENT
print the real number in scientific format (like e)
Definition charconv.hpp:190
@ FTOA_FLOAT
print the real number in floating point format (like f)
Definition charconv.hpp:188
@ FTOA_HEXA
print the real number in hexadecimal format (like a)
Definition charconv.hpp:194
auto digits_dec(T v) noexcept -> typename std::enable_if< sizeof(T)==1u, unsigned >::type
decimal digits for 8 bit integers
Definition charconv.hpp:426
unsigned digits_oct(T v_) noexcept
return the number of digits required to encode an octal number.
Definition charconv.hpp:541
unsigned digits_hex(T v) noexcept
return the number of digits required to encode an hexadecimal number.
Definition charconv.hpp:523
unsigned digits_bin(T v) noexcept
return the number of digits required to encode a binary number.
Definition charconv.hpp:532
size_t dtoa(substr str, double v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept
Convert a double-precision real number to string.
size_t from_chars_first(csubstr buf, uint8_t *v) noexcept
bool from_chars(csubstr buf, uint8_t *v) noexcept
size_t ftoa(substr str, float v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept
Convert a single-precision real number to string.
size_t itoa(substr buf, T v) noexcept
convert an integral signed decimal to a string.
auto overflows(csubstr str) noexcept -> typename std::enable_if< std::is_unsigned< T >::value, bool >::type
Test if the following string would overflow when converted to associated integral types; this functio...
bool read_bin(csubstr s, I *v) noexcept
read a binary integer from a string.
Definition charconv.hpp:931
bool read_oct(csubstr s, I *v) noexcept
read an octal integer from a string.
Definition charconv.hpp:961
bool read_hex(csubstr s, I *v) noexcept
read an hexadecimal integer from a string.
Definition charconv.hpp:896
bool read_dec(csubstr s, I *v) noexcept
read a decimal integer from a string.
Definition charconv.hpp:868
size_t to_chars(ryml::substr buf, vec2< T > v)
bool from_chars(ryml::csubstr buf, vec2< T > *v)
basic_substring< char > substr
a mutable string view
Definition substr.hpp:2355
basic_substring< const char > csubstr
an immutable string view
Definition substr.hpp:2356
substr to_chars_sub(substr buf, T const &v) noexcept
call to_chars() and return a substr consisting of the written portion of the input buffer.
size_t utoa(substr buf, T v) noexcept
convert an integral unsigned decimal to a string.
void write_bin_unchecked(substr buf, T v, unsigned digits_v) noexcept
Definition charconv.hpp:673
void write_dec_unchecked(substr buf, T v, unsigned digits_v) noexcept
Definition charconv.hpp:608
void write_hex_unchecked(substr buf, T v, unsigned digits_v) noexcept
Definition charconv.hpp:641
void write_oct_unchecked(substr buf, T v, unsigned digits_v) noexcept
Definition charconv.hpp:657
size_t write_hex(substr buf, T v) noexcept
write an integer to a string in hexadecimal format.
Definition charconv.hpp:727
size_t write_dec(substr buf, T v) noexcept
write an integer to a string in decimal format.
Definition charconv.hpp:708
size_t write_bin(substr buf, T v) noexcept
write an integer to a string in binary format.
Definition charconv.hpp:765
size_t write_oct(substr buf, T v) noexcept
write an integer to a string in octal format.
Definition charconv.hpp:746
size_t xtoa(substr s, uint8_t v) noexcept
basic_substring first_uint_span() const
get the first span which can be interpreted as an unsigned integer
Definition substr.hpp:1277
basic_substring first_int_span() const
get the first span which can be interpreted as a signed integer
Definition substr.hpp:1289
size_t len
the length of the substring
Definition substr.hpp:218
iterator begin() noexcept
Definition substr.hpp:360
bool overlaps(ro_substr const that) const noexcept
true if there is overlap of at least one element between that and *this
Definition substr.hpp:493
iterator end() noexcept
Definition substr.hpp:361
basic_substring sub(size_t first) const noexcept
return [first,len[
Definition substr.hpp:502
C * str
a restricted pointer to the first character of the substring
Definition substr.hpp:216
read+write string views