forked from biojppm/c4core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcharconv.hpp
More file actions
1522 lines (1372 loc) · 52.7 KB
/
Copy pathcharconv.hpp
File metadata and controls
1522 lines (1372 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef _C4_CHARCONV_HPP_
#define _C4_CHARCONV_HPP_
/** @file charconv.hpp Lightweight generic type-safe wrappers for
* converting individual values to/from strings.
*
* These are the main functions:
*
* @code{.cpp}
* // Convert the given value, writing into the string.
* // The resulting string will NOT be null-terminated.
* // Return the number of characters needed.
* // This function is safe to call when the string is too small -
* // no writes will occur beyond the string's last character.
* template<class T> size_t c4::to_chars(substr buf, T const& C4_RESTRICT val);
*
*
* // Convert the given value to a string using to_chars(), and
* // return the resulting string, up to and including the last
* // written character.
* template<class T> substr c4::to_chars_sub(substr buf, T const& C4_RESTRICT val);
*
*
* // Read a value from the string, which must be
* // trimmed to the value (ie, no leading/trailing whitespace).
* // return true if the conversion succeeded.
* template<class T> bool c4::from_chars(csubstr buf, T * C4_RESTRICT val);
*
*
* // Read the first valid sequence of characters from the string,
* // skipping leading whitespace, and convert it using from_chars().
* // Return the number of characters read for converting.
* template<class T> size_t c4::from_chars_first(csubstr buf, T * C4_RESTRICT val);
* @endcode
*/
#include "c4/language.hpp"
#include <inttypes.h>
#include <type_traits>
#include <climits>
#include <limits>
#include <utility>
#include "c4/config.hpp"
#include "c4/substr.hpp"
#include "c4/memory_util.hpp"
#include "c4/szconv.hpp"
#ifndef C4CORE_NO_FAST_FLOAT
C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wsign-conversion")
C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Warray-bounds")
C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wshift-count-overflow")
# include "c4/ext/fast_float.hpp"
C4_SUPPRESS_WARNING_GCC_POP
# define C4CORE_HAVE_FAST_FLOAT 1
# define C4CORE_HAVE_STD_FROMCHARS 0
# if (C4_CPP >= 17)
# if defined(_MSC_VER)
# if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019)
# include <charconv>
# define C4CORE_HAVE_STD_TOCHARS 1
# else
# define C4CORE_HAVE_STD_TOCHARS 0
# endif
# else // VS2017 and lower do not have these macros
# if __has_include(<charconv>) && __cpp_lib_to_chars
# define C4CORE_HAVE_STD_TOCHARS 1
# include <charconv>
# else
# define C4CORE_HAVE_STD_TOCHARS 0
# endif
# endif
# else
# define C4CORE_HAVE_STD_TOCHARS 0
# endif
#elif (C4_CPP >= 17)
# if defined(_MSC_VER)
# if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019)
# include <charconv>
# define C4CORE_HAVE_STD_TOCHARS 1
# define C4CORE_HAVE_STD_FROMCHARS 1
# else
# define C4CORE_HAVE_STD_TOCHARS 0
# define C4CORE_HAVE_STD_FROMCHARS 0
# endif
# else // VS2017 and lower do not have these macros
# if __has_include(<charconv>) && __cpp_lib_to_chars
# define C4CORE_HAVE_STD_TOCHARS 1
# define C4CORE_HAVE_STD_FROMCHARS 1
# include <charconv>
# else
# define C4CORE_HAVE_STD_TOCHARS 0
# define C4CORE_HAVE_STD_FROMCHARS 0
# endif
# endif
#else
# define C4CORE_HAVE_STD_TOCHARS 0
# define C4CORE_HAVE_STD_FROMCHARS 0
#endif
#if !C4CORE_HAVE_STD_FROMCHARS && !defined(C4CORE_HAVE_FAST_FLOAT)
#include <cstdio>
#endif
#ifdef _MSC_VER
# pragma warning(push)
# if C4_MSVC_VERSION != C4_MSVC_VERSION_2017
# pragma warning(disable: 4800) //'int': forcing value to bool 'true' or 'false' (performance warning)
# endif
# pragma warning(disable: 4996) // snprintf/scanf: this function or variable may be unsafe
#elif defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
# pragma clang diagnostic ignored "-Wformat-nonliteral"
# pragma clang diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wformat-nonliteral"
# pragma GCC diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision
# pragma GCC diagnostic ignored "-Wuseless-cast"
#endif
namespace c4 {
typedef enum : uint8_t {
/** print the real number in floating point format (like %f) */
FTOA_FLOAT = 0,
/** print the real number in scientific format (like %e) */
FTOA_SCIENT = 1,
/** print the real number in flexible format (like %g) */
FTOA_FLEX = 2,
/** print the real number in hexadecimal format (like %a) */
FTOA_HEXA = 3,
_FTOA_COUNT
} RealFormat_e;
inline C4_CONSTEXPR14 char to_c_fmt(RealFormat_e f)
{
constexpr const char fmt[] = {
'f', // FTOA_FLOAT
'e', // FTOA_SCIENT
'g', // FTOA_FLEX
'a', // FTOA_HEXA
};
C4_STATIC_ASSERT(C4_COUNTOF(fmt) == _FTOA_COUNT);
C4_ASSERT(f < _FTOA_COUNT);
return fmt[f];
}
#if C4CORE_HAVE_STD_TOCHARS
inline constexpr std::chars_format to_std_fmt(RealFormat_e f)
{
constexpr const std::chars_format fmt[] = {
std::chars_format::fixed, // FTOA_FLOAT
std::chars_format::scientific, // FTOA_SCIENT
std::chars_format::general, // FTOA_FLEX
std::chars_format::hex, // FTOA_HEXA
};
C4_STATIC_ASSERT(C4_COUNTOF(fmt) == _FTOA_COUNT);
C4_ASSERT(f < _FTOA_COUNT);
return fmt[f];
}
#endif // C4CORE_HAVE_STD_TOCHARS
/** in some platforms, int,unsigned int
* are not any of int8_t...int64_t and
* long,unsigned long are not any of uint8_t...uint64_t */
template<class T>
struct is_fixed_length
{
enum : bool {
/** true if T is one of the fixed length signed types */
value_i = (std::is_integral<T>::value
&& (std::is_same<T, int8_t>::value
|| std::is_same<T, int16_t>::value
|| std::is_same<T, int32_t>::value
|| std::is_same<T, int64_t>::value)),
/** true if T is one of the fixed length unsigned types */
value_u = (std::is_integral<T>::value
&& (std::is_same<T, uint8_t>::value
|| std::is_same<T, uint16_t>::value
|| std::is_same<T, uint32_t>::value
|| std::is_same<T, uint64_t>::value)),
/** true if T is one of the fixed length signed or unsigned types */
value = value_i || value_u
};
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifdef _MSC_VER
# pragma warning(push)
#elif defined(__clang__)
# pragma clang diagnostic push
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# if __GNUC__ >= 6
# pragma GCC diagnostic ignored "-Wnull-dereference"
# endif
#endif
// Helper macros, undefined below
#define _c4append(c) { if(C4_LIKELY(pos < buf.len)) { buf.str[pos++] = static_cast<char>(c); } else { ++pos; } }
#define _c4appendhex(i) { if(C4_LIKELY(pos < buf.len)) { buf.str[pos++] = hexchars[i]; } else { ++pos; } }
namespace detail {
template<class T>
C4_NO_INLINE size_t write_dec_neg(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(v < 0);
size_t pos = 0;
do {
_c4append('0' - v % T(10));
v /= T(10);
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
template<class T>
C4_NO_INLINE size_t write_hex_neg(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(v < 0);
constexpr const char hexchars[] = "0123456789abcdef";
size_t pos = 0;
do {
_c4appendhex(-(v % T(16)));
v /= 16;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
template<class T>
C4_NO_INLINE size_t write_oct_neg(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(v < 0);
size_t pos = 0;
do {
_c4append('0' - (v % T(8)));
v /= 8;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
template<class T>
C4_NO_INLINE size_t write_bin_neg(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(v < 0);
size_t pos = 0;
do {
_c4append('0' - (v % T(2)));
v /= 2;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
} // namespace detail
/** write an integer to a string in decimal format. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @return the number of characters required for the string,
* even if the string is not long enough for the result.
* No writes are done past the end of the string. */
template<class T>
size_t write_dec(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_ASSERT(v >= 0);
size_t pos = 0;
do {
_c4append('0' + (v % T(10)));
v /= T(10);
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
/** write an integer to a string in hexadecimal format. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @return the number of characters required for the string,
* even if the string is not long enough for the result.
* No writes are done past the end of the string. */
template<class T>
size_t write_hex(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_ASSERT(v >= 0);
constexpr const char hexchars[] = "0123456789abcdef";
size_t pos = 0;
do {
_c4appendhex(v & T(15));
v >>= 4;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
/** write an integer to a string in octal format. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note does not prefix with 0o
* @return the number of characters required for the string,
* even if the string is not long enough for the result.
* No writes are done past the end of the string. */
template<class T>
size_t write_oct(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_ASSERT(v >= 0);
size_t pos = 0;
do {
_c4append('0' + (v & T(7)));
v >>= 3;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
/** write an integer to a string in binary format. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note does not prefix with 0b
* @return the number of characters required for the string,
* even if the string is not long enough for the result.
* No writes are done past the end of the string. */
template<class T>
size_t write_bin(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_ASSERT(v >= 0);
size_t pos = 0;
do {
_c4append('0' + (v & T(1)));
v >>= 1;
} while(v);
buf.reverse_range(0, pos <= buf.len ? pos : buf.len);
return pos;
}
namespace detail {
template<class U> using NumberWriter = size_t (*)(substr, U);
template<class T>
size_t write_num_digits(NumberWriter<T> writer, substr buf, T v, size_t num_digits)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
size_t ret = writer(buf, v);
if(ret >= num_digits)
{
return ret;
}
else if(ret >= buf.len || num_digits > buf.len)
{
return num_digits;
}
C4_ASSERT(num_digits >= ret);
size_t delta = static_cast<size_t>(num_digits - ret);
memmove(buf.str + delta, buf.str, ret);
memset(buf.str, '0', delta);
return num_digits;
}
} // namespace detail
/** same as c4::write_dec(), but pad with zeroes on the left
* such that the resulting string is @p num_digits wide.
* If the given number is wider than num_digits, then the number prevails. */
template<class T>
size_t write_dec(substr buf, T val, size_t num_digits)
{
return detail::write_num_digits<T>(&write_dec<T>, buf, val, num_digits);
}
/** same as c4::write_hex(), but pad with zeroes on the left
* such that the resulting string is @p num_digits wide.
* If the given number is wider than num_digits, then the number prevails. */
template<class T>
size_t write_hex(substr buf, T val, size_t num_digits)
{
return detail::write_num_digits<T>(&write_hex<T>, buf, val, num_digits);
}
/** same as c4::write_bin(), but pad with zeroes on the left
* such that the resulting string is @p num_digits wide.
* If the given number is wider than num_digits, then the number prevails. */
template<class T>
size_t write_bin(substr buf, T val, size_t num_digits)
{
return detail::write_num_digits<T>(&write_bin<T>, buf, val, num_digits);
}
/** same as c4::write_oct(), but pad with zeroes on the left
* such that the resulting string is @p num_digits wide.
* If the given number is wider than num_digits, then the number prevails. */
template<class T>
size_t write_oct(substr buf, T val, size_t num_digits)
{
return detail::write_num_digits<T>(&write_oct<T>, buf, val, num_digits);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** read a decimal integer from a string. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note The string must be trimmed. Whitespace is not accepted.
* @return true if the conversion was successful */
template<class I>
C4_ALWAYS_INLINE bool read_dec(csubstr s, I *C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<I>::value);
*v = 0;
for(char c : s)
{
if(C4_UNLIKELY(c < '0' || c > '9'))
{
return false;
}
*v = (*v) * I(10) + (I(c) - I('0'));
}
return true;
}
/** read an hexadecimal integer from a string. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note does not accept leading 0x or 0X
* @note the string must be trimmed. Whitespace is not accepted.
* @return true if the conversion was successful */
template<class I>
C4_ALWAYS_INLINE bool read_hex(csubstr s, I *C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<I>::value);
*v = 0;
for(char c : s)
{
I cv;
if(c >= '0' && c <= '9')
{
cv = I(c) - I('0');
}
else if(c >= 'a' && c <= 'f')
{
cv = I(10) + (I(c) - I('a'));
}
else if(c >= 'A' && c <= 'F')
{
cv = I(10) + (I(c) - I('A'));
}
else
{
return false;
}
*v = (*v) * I(16) + cv;
}
return true;
}
/** read a binary integer from a string. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note does not accept leading 0b or 0B
* @note the string must be trimmed. Whitespace is not accepted.
* @return true if the conversion was successful */
template<class I>
C4_ALWAYS_INLINE bool read_bin(csubstr s, I *C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<I>::value);
*v = 0;
for(char c : s)
{
*v <<= 1;
if(c == '1')
{
*v |= 1;
}
else if(c == '0')
{
;
}
else
{
return false;
}
}
return true;
}
/** read an octal integer from a string. This is the
* lowest level (and the fastest) function to do this task.
* @note does not accept negative numbers
* @note does not accept leading 0o or 0O
* @note the string must be trimmed. Whitespace is not accepted.
* @return true if the conversion was successful */
template<class I>
C4_ALWAYS_INLINE bool read_oct(csubstr s, I *C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<I>::value);
*v = 0;
for(char c : s)
{
if(C4_UNLIKELY(c < '0' || c > '7'))
{
return false;
}
*v = (*v) * I(8) + (I(c) - I('0'));
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace detail {
template<class T>
C4_NO_INLINE size_t itoa_neg(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(v < 0);
if(buf.len > 0)
{
buf.str[0] = '-';
return size_t(1) + detail::write_dec_neg(buf.sub(1), v);
}
return size_t(1) + detail::write_dec_neg({}, v);
}
template<class T>
C4_NO_INLINE size_t itoa_neg(substr buf, T v, T radix)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
C4_ASSERT(v < 0);
size_t pos = 0;
_c4append('-');
switch(radix)
{
case 10: return pos + detail::write_dec_neg(pos < buf.len ? buf.sub(pos) : substr(), v);
case 16: _c4append('0'); _c4append('x'); return pos + detail::write_hex_neg(pos < buf.len ? buf.sub(pos) : substr(), v);
case 2 : _c4append('0'); _c4append('b'); return pos + detail::write_bin_neg(pos < buf.len ? buf.sub(pos) : substr(), v);
case 8 : _c4append('0'); _c4append('o'); return pos + detail::write_oct_neg(pos < buf.len ? buf.sub(pos) : substr(), v);
}
C4_UNREACHABLE();
return substr::npos;
}
template<class T>
C4_NO_INLINE size_t itoa_neg(substr buf, T v, T radix, size_t num_digits)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
C4_ASSERT(v < 0);
size_t pos = 0;
_c4append('-');
switch(radix)
{
case 10: return pos + detail::write_num_digits<T>(&detail::write_dec_neg<T>, pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 16: _c4append('0'); _c4append('x'); return pos + detail::write_num_digits<T>(&detail::write_hex_neg<T>, pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 2 : _c4append('0'); _c4append('b'); return pos + detail::write_num_digits<T>(&detail::write_bin_neg<T>, pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 8 : _c4append('0'); _c4append('o'); return pos + detail::write_num_digits<T>(&detail::write_oct_neg<T>, pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
}
C4_UNREACHABLE();
return csubstr::npos;
}
} // namespace detail
/** convert an integral signed decimal to a string.
* The resulting string is NOT zero-terminated.
* Writing stops at the buffer's end.
* @return the number of characters needed for the result, even if the buffer size is insufficient */
template<class T>
size_t itoa(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
if(v >= 0)
{
return write_dec(buf, v);
}
else if(C4_LIKELY(v != std::numeric_limits<T>::min()))
{
if(buf.len > 0)
{
buf.str[0] = '-';
return size_t(1) + write_dec(buf.sub(1), -v);
}
return size_t(1) + write_dec({}, -v);
}
// when T is the min value (eg i8: -128), negating it
// will overflow
return detail::itoa_neg(buf, v);
}
/** convert an integral signed integer to a string, using a specific
* radix. The radix must be 2, 8, 10 or 16.
*
* The resulting string is NOT zero-terminated.
* Writing stops at the buffer's end.
* @return the number of characters needed for the result, even if the buffer size is insufficient */
template<class T>
size_t itoa(substr buf, T v, T radix)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
// when T is the min value (eg i8: -128), negating it
// will overflow
if(C4_LIKELY(v != std::numeric_limits<T>::min()))
{
size_t pos = 0;
if(v < 0)
{
v = -v;
_c4append('-');
}
switch(radix)
{
case 10: return pos + write_dec(pos < buf.len ? buf.sub(pos) : substr(), v);
case 16: _c4append('0'); _c4append('x'); return pos + write_hex(pos < buf.len ? buf.sub(pos) : substr(), v);
case 2 : _c4append('0'); _c4append('b'); return pos + write_bin(pos < buf.len ? buf.sub(pos) : substr(), v);
case 8 : _c4append('0'); _c4append('o'); return pos + write_oct(pos < buf.len ? buf.sub(pos) : substr(), v);
}
}
// when T is the min value (eg i8: -128), negating it
// will overflow
return detail::itoa_neg<T>(buf, v, radix);
}
/** same as c4::itoa(), but pad with zeroes on the left such that the
* resulting string is @p num_digits wide. The @p radix must be 2,
* 8, 10 or 16. The resulting string is NOT zero-terminated. Writing
* stops at the buffer's end.
*
* @return the number of characters needed for the result, even if
* the buffer size is insufficient */
template<class T>
size_t itoa(substr buf, T v, T radix, size_t num_digits)
{
C4_STATIC_ASSERT(std::is_signed<T>::value);
C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16);
// when T is the min value (eg i8: -128), negating it
// will overflow
if(C4_LIKELY(v != std::numeric_limits<T>::min()))
{
size_t pos = 0;
if(v < 0)
{
v = -v;
_c4append('-');
}
switch(radix)
{
case 10: return pos + write_dec(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 16: _c4append('0'); _c4append('x'); return pos + write_hex(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 2 : _c4append('0'); _c4append('b'); return pos + write_bin(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 8 : _c4append('0'); _c4append('o'); return pos + write_oct(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
}
}
return detail::itoa_neg(buf, v, radix, num_digits);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** convert an integral unsigned decimal to a string.
* The resulting string is NOT zero-terminated.
* Writing stops at the buffer's end.
* @return the number of characters needed for the result, even if the buffer size is insufficient */
template<class T>
size_t utoa(substr buf, T v)
{
C4_STATIC_ASSERT(std::is_unsigned<T>::value);
return write_dec(buf, v);
}
/** convert an integral unsigned integer to a string, using a specific radix. The radix must be 2, 8, 10 or 16.
* The resulting string is NOT zero-terminated.
* Writing stops at the buffer's end.
* @return the number of characters needed for the result, even if the buffer size is insufficient */
template<class T>
size_t utoa(substr buf, T v, T radix)
{
C4_STATIC_ASSERT(std::is_unsigned<T>::value);
C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8);
size_t pos = 0;
switch(radix)
{
case 10: return pos + write_dec(pos < buf.len ? buf.sub(pos) : substr(), v);
case 16: _c4append('0'); _c4append('x'); return pos + write_hex(pos < buf.len ? buf.sub(pos) : substr(), v);
case 2 : _c4append('0'); _c4append('b'); return pos + write_bin(pos < buf.len ? buf.sub(pos) : substr(), v);
case 8 : _c4append('0'); _c4append('o'); return pos + write_oct(pos < buf.len ? buf.sub(pos) : substr(), v);
}
C4_UNREACHABLE();
return substr::npos;
}
/** same as c4::utoa(), but pad with zeroes on the left such that the
* resulting string is @p num_digits wide. The @p radix must be 2,
* 8, 10 or 16. The resulting string is NOT zero-terminated. Writing
* stops at the buffer's end.
*
* @return the number of characters needed for the result, even if
* the buffer size is insufficient */
template<class T>
size_t utoa(substr buf, T v, T radix, size_t num_digits)
{
C4_STATIC_ASSERT(std::is_unsigned<T>::value);
C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8);
size_t pos = 0;
switch(radix)
{
case 10: return pos + write_dec(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 16: _c4append('0'); _c4append('x'); return pos + write_hex(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 2 : _c4append('0'); _c4append('b'); return pos + write_bin(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
case 8 : _c4append('0'); _c4append('o'); return pos + write_oct(pos < buf.len ? buf.sub(pos) : substr(), v, num_digits);
}
C4_UNREACHABLE();
return substr::npos;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** Convert a trimmed string to a signed integral value. The string
* can be formatted as decimal, binary (prefix 0b or 0B), octal
* (prefix 0o or 0O) or hexadecimal (prefix 0x or 0X). Strings with
* leading zeroes are considered as decimal. Every character in the
* input string is read for the conversion; it must not contain any
* leading or trailing whitespace.
*
* @return true if the conversion was successful.
*
* @note overflow is not detected: the return status is true even if
* the conversion would return a value outside of the type's range, in
* which case the result will wrap around the type's range. This is similar to, just like the native.
*
* @see atoi_first() if the string is not trimmed to the value to read. */
template<class T>
bool atoi(csubstr str, T * C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
C4_STATIC_ASSERT(std::is_signed<T>::value);
if(C4_UNLIKELY(str.len == 0))
{
return false;
}
T sign = 1;
size_t start = 0;
if(str.str[0] == '-')
{
if(C4_UNLIKELY(str.len == 1))
{
return false;
}
++start;
sign = -1;
}
if(str.str[start] != '0')
{
if(C4_UNLIKELY( ! read_dec(str.sub(start), v)))
{
return false;
}
}
else
{
if(str.len == start+1)
{
*v = 0; // because the first character is 0
return true;
}
else
{
char pfx = str.str[start+1];
if(pfx == 'x' || pfx == 'X') // hexadecimal
{
if(C4_UNLIKELY(str.len <= start + 2))
{
return false;
}
if(C4_UNLIKELY( ! read_hex(str.sub(start + 2), v)))
{
return false;
}
}
else if(pfx == 'b' || pfx == 'B') // binary
{
if(C4_UNLIKELY(str.len <= start + 2))
{
return false;
}
if(C4_UNLIKELY( ! read_bin(str.sub(start + 2), v)))
{
return false;
}
}
else if(pfx == 'o' || pfx == 'O') // octal
{
if(C4_UNLIKELY(str.len <= start + 2))
{
return false;
}
if(C4_UNLIKELY( ! read_oct(str.sub(start + 2), v)))
{
return false;
}
}
else
{
// we know the first character is 0
auto fno = str.first_not_of('0', start + 1);
if(fno == csubstr::npos)
{
*v = 0;
return true;
}
if(C4_UNLIKELY( ! read_dec(str.sub(fno), v)))
{
return false;
}
}
}
}
*v *= sign;
return true;
}
/** Select the next range of characters in the string that can be parsed
* as a signed integral value, and convert it using atoi(). Leading
* whitespace (space, newline, tabs) is skipped.
* @return the number of characters read for conversion, or csubstr::npos if the conversion failed
* @see atoi() if the string is already trimmed to the value to read.
* @see csubstr::first_int_span() */
template<class T>
inline size_t atoi_first(csubstr str, T * C4_RESTRICT v)
{
csubstr trimmed = str.first_int_span();
if(trimmed.len == 0) return csubstr::npos;
if(atoi(trimmed, v)) return static_cast<size_t>(trimmed.end() - str.begin());
return csubstr::npos;
}
//-----------------------------------------------------------------------------
/** Convert a trimmed string to an unsigned integral value. The string can be
* formatted as decimal, binary (prefix 0b or 0B), octal (prefix 0o or 0O)
* or hexadecimal (prefix 0x or 0X). Every character in the input string is read
* for the conversion; it must not contain any leading or trailing whitespace.
*
* @return true if the conversion was successful.
*
* @note overflow is not detected: the return status is true even if
* the conversion would return a value outside of the type's range, in
* which case the result will wrap around the type's range.
*
* @note If the string has a minus character, the return status
* will be false.
*
* @see atou_first() if the string is not trimmed to the value to read. */
template<class T>
bool atou(csubstr str, T * C4_RESTRICT v)
{
C4_STATIC_ASSERT(std::is_integral<T>::value);
if(C4_UNLIKELY(str.len == 0 || str.front() == '-'))
{
return false;
}
if(str.str[0] != '0')
{
if(C4_UNLIKELY( ! read_dec(str, v)))
{
return false;
}
}
else
{
if(str.len == 1)
{
*v = 0; // we know the first character is 0
return true;
}
else
{
char pfx = str.str[1];
if(pfx == 'x' || pfx == 'X') // hexadecimal
{
if(C4_UNLIKELY(str.len <= 2))
{
return false;
}
return read_hex(str.sub(2), v);
}
else if(pfx == 'b' || pfx == 'B') // binary
{
if(C4_UNLIKELY(str.len <= 2))
{
return false;
}
return read_bin(str.sub(2), v);
}
else if(pfx == 'o' || pfx == 'O') // octal
{
if(C4_UNLIKELY(str.len <= 2))
{
return false;
}
return read_oct(str.sub(2), v);
}
else
{
// we know the first character is 0
auto fno = str.first_not_of('0');
if(fno == csubstr::npos)
{
*v = 0;
return true;
}
return read_dec(str.sub(fno), v);
}
}
}
return true;
}
/** Select the next range of characters in the string that can be parsed
* as an unsigned integral value, and convert it using atou(). Leading
* whitespace (space, newline, tabs) is skipped.
* @return the number of characters read for conversion, or csubstr::npos if the conversion faileds
* @see atou() if the string is already trimmed to the value to read.
* @see csubstr::first_uint_span() */
template<class T>
inline size_t atou_first(csubstr str, T *v)
{
csubstr trimmed = str.first_uint_span();
if(trimmed.len == 0) return csubstr::npos;
if(atou(trimmed, v)) return static_cast<size_t>(trimmed.end() - str.begin());
return csubstr::npos;
}
#ifdef _MSC_VER
# pragma warning(pop)
#elif defined(__clang__)
# pragma clang diagnostic pop
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
//-----------------------------------------------------------------------------
namespace detail {
/** @see http://www.exploringbinary.com/ for many good examples on float-str conversion */
template<size_t N>
void get_real_format_str(char (& C4_RESTRICT fmt)[N], int precision, RealFormat_e formatting, const char* length_modifier="")
{
int iret;
if(precision == -1)
{