-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathformat
3008 lines (2545 loc) · 113 KB
/
format
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
// format standard header
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// NOTE:
// The contents of this header are derived in part from libfmt under the following license:
// Copyright (c) 2012 - present, Victor Zverovich
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// --- Optional exception to the license ---
//
// As an exception, if, as a result of your compiling your source code, portions
// of this Software are embedded into a machine-executable object form of such
// source code, you may redistribute such embedded portions in such object form
// without including the above copyright and permission notices.
#pragma once
#ifndef _FORMAT_
#define _FORMAT_
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR
#ifndef __cpp_lib_format
#pragma message("The contents of <format> are available only in c++latest mode with concepts support;")
#pragma message("see https://github.com/microsoft/STL/issues/1814 for details.")
#else // ^^^ !defined(__cpp_lib_format) / defined(__cpp_lib_format) vvv
#include <charconv>
#include <concepts>
#include <cstdint>
#include <exception>
#include <iterator>
#include <locale>
#include <stdexcept>
#include <string>
#include <string_view>
#include <xfilesystem_abi.h>
#include <xutility>
#pragma pack(push, _CRT_PACKING)
#pragma warning(push, _STL_WARNING_LEVEL)
#pragma warning(disable : _STL_DISABLED_WARNINGS)
_STL_DISABLE_CLANG_WARNINGS
#pragma push_macro("new")
#undef new
extern "C" _NODISCARD __std_win_error __stdcall __std_get_cvt(__std_code_page _Codepage, _Cvtvec* _Pcvt) noexcept;
_STD_BEGIN
template <class, class>
class vector;
class format_error : public runtime_error {
using runtime_error::runtime_error;
};
enum class _Fmt_align : uint8_t { _None, _Left, _Right, _Center };
enum class _Fmt_sign : uint8_t { _None, _Plus, _Minus, _Space };
enum class _Basic_format_arg_type : uint8_t {
_None,
_Int_type,
_UInt_type,
_Long_long_type,
_ULong_long_type,
_Bool_type,
_Char_type,
_Float_type,
_Double_type,
_Long_double_type,
_Pointer_type,
_CString_type,
_String_type,
_Custom_type,
};
static_assert(static_cast<int>(_Basic_format_arg_type::_Custom_type) < 16, "must fit in 4-bit bitfield");
_NODISCARD constexpr bool _Is_integral_fmt_type(_Basic_format_arg_type _Ty) {
return _Ty > _Basic_format_arg_type::_None && _Ty <= _Basic_format_arg_type::_ULong_long_type;
}
_NODISCARD constexpr bool _Is_arithmetic_fmt_type(_Basic_format_arg_type _Ty) {
return _Ty > _Basic_format_arg_type::_None && _Ty <= _Basic_format_arg_type::_Long_double_type;
}
struct _Auto_id_tag {};
// clang-format off
template <class _Ty, class _CharT>
concept _Parse_arg_id_callbacks = requires(_Ty _At) {
{ _At._On_auto_id() } -> same_as<void>;
{ _At._On_manual_id(size_t{}) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Parse_replacement_field_callbacks = requires(_Ty _At, const _CharT* _First, const _CharT* _Last) {
{ _At._Parse_context };
{ _At._On_text(_First, _Last) } -> same_as<void>;
{ _At._On_replacement_field(size_t{}, static_cast<const _CharT*>(nullptr)) } -> same_as<void>;
{ _At._On_format_specs(size_t{}, _First, _Last) } -> same_as<const _CharT*>;
};
template <class _Ty, class _CharT>
concept _Parse_align_callbacks = requires(_Ty _At, basic_string_view<_CharT> _Sv, _Fmt_align _Aln) {
{ _At._On_fill(_Sv) } -> same_as<void>;
{ _At._On_align(_Aln) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Parse_width_callbacks = requires(_Ty _At) {
{ _At._On_width(int{}) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Parse_precision_callbacks = requires(_Ty _At) {
{ _At._On_precision(int{}) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Width_adapter_callbacks = requires(_Ty _At) {
{ _At._On_dynamic_width(_Auto_id_tag{}) } -> same_as<void>;
{ _At._On_dynamic_width(size_t{}) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Precision_adapter_callbacks = requires(_Ty _At) {
{ _At._On_dynamic_precision(_Auto_id_tag{}) } -> same_as<void>;
{ _At._On_dynamic_precision(size_t{}) } -> same_as<void>;
};
template <class _Ty, class _CharT>
concept _Parse_spec_callbacks = _Parse_align_callbacks<_Ty, _CharT>
&& _Parse_width_callbacks<_Ty, _CharT>
&& _Parse_precision_callbacks<_Ty, _CharT>
&& _Width_adapter_callbacks<_Ty, _CharT>
&& _Precision_adapter_callbacks<_Ty, _CharT>
&& requires(_Ty _At, basic_string_view<_CharT> _Sv, _Fmt_align _Aln, _Fmt_sign _Sgn) {
{ _At._On_sign(_Sgn) } -> same_as<void>;
{ _At._On_hash() } -> same_as<void>;
{ _At._On_zero() } -> same_as<void>;
{ _At._On_localized() } -> same_as<void>;
{ _At._On_type(_CharT{}) } -> same_as<void>;
};
// clang-format on
template <class _Ty, class _CharT>
concept _CharT_or_bool = same_as<_Ty, _CharT> || same_as<_Ty, bool>;
template <class _CharT>
concept _Format_supported_charT = _Is_any_of_v<_CharT, char, wchar_t>;
template <class _Ty, class _CharT = char>
struct formatter;
inline void _You_see_this_error_because_arg_id_is_out_of_range() noexcept {}
template <class _CharT>
class basic_format_parse_context {
public:
using char_type = _CharT;
using const_iterator = typename basic_string_view<_CharT>::const_iterator;
using iterator = const_iterator;
constexpr explicit basic_format_parse_context(
const basic_string_view<_CharT> _Fmt, const size_t _Num_args_ = 0) noexcept
: _Format_string(_Fmt), _Num_args(_Num_args_) {}
basic_format_parse_context(const basic_format_parse_context&) = delete;
basic_format_parse_context& operator=(const basic_format_parse_context&) = delete;
_NODISCARD constexpr const_iterator begin() const noexcept {
return _Format_string.begin();
}
_NODISCARD constexpr const_iterator end() const noexcept {
return _Format_string.end();
}
_NODISCARD constexpr const _CharT* _Unchecked_begin() const noexcept {
return _Format_string._Unchecked_begin();
}
_NODISCARD constexpr const _CharT* _Unchecked_end() const noexcept {
return _Format_string._Unchecked_end();
}
constexpr void advance_to(const const_iterator _It) {
_Adl_verify_range(_It, _Format_string.end());
_Adl_verify_range(_Format_string.begin(), _It);
const auto _Diff = static_cast<size_t>(_It._Unwrapped() - _Format_string._Unchecked_begin());
_Format_string.remove_prefix(_Diff);
}
// While the standard presents an exposition-only enum value for
// the indexing mode (manual, automatic, or unknown) we use _Next_arg_id to indicate it.
// _Next_arg_id > 0 means automatic
// _Next_arg_id == 0 means unknown
// _Next_arg_id < 0 means manual
_NODISCARD constexpr size_t next_arg_id() {
if (_Next_arg_id < 0) {
_THROW(format_error("Can not switch from manual to automatic indexing"));
}
return static_cast<size_t>(_Next_arg_id++);
}
constexpr void check_arg_id(const size_t _Id) {
if (_STD is_constant_evaluated()) {
if (_Id >= _Num_args) {
_You_see_this_error_because_arg_id_is_out_of_range();
}
}
if (_Next_arg_id > 0) {
_THROW(format_error("Can not switch from automatic to manual indexing"));
}
_Next_arg_id = -1;
}
private:
basic_string_view<_CharT> _Format_string;
size_t _Num_args;
// The standard says this is size_t, however we use ptrdiff_t to save some space
// by not having to store the indexing mode. Above is a more detailed explanation
// of how this works.
ptrdiff_t _Next_arg_id = 0;
};
using format_parse_context = basic_format_parse_context<char>;
using wformat_parse_context = basic_format_parse_context<wchar_t>;
template <class _Context>
class basic_format_arg {
public:
using _CharType = typename _Context::char_type;
class handle {
private:
const void* _Ptr;
void(__cdecl* _Format)(basic_format_parse_context<_CharType>& _Parse_ctx, _Context& _Format_ctx, const void*);
friend basic_format_arg;
public:
template <class _Ty>
explicit handle(const _Ty& _Val) noexcept
: _Ptr(_STD addressof(_Val)),
_Format([](basic_format_parse_context<_CharType>& _Parse_ctx, _Context& _Format_ctx, const void* _Ptr) {
typename _Context::template formatter_type<_Ty> _Formatter;
_Parse_ctx.advance_to(_Formatter.parse(_Parse_ctx));
_Format_ctx.advance_to(_Formatter.format(*static_cast<const _Ty*>(_Ptr), _Format_ctx));
}) {}
void format(basic_format_parse_context<_CharType>& _Parse_ctx, _Context& _Format_ctx) const {
_Format(_Parse_ctx, _Format_ctx, _Ptr);
}
};
// TRANSITION, LLVM-49072
basic_format_arg() noexcept : _Active_state(_Basic_format_arg_type::_None), _No_state() {}
explicit basic_format_arg(const int _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Int_type), _Int_state(_Val) {}
explicit basic_format_arg(const unsigned int _Val) noexcept
: _Active_state(_Basic_format_arg_type::_UInt_type), _UInt_state(_Val) {}
explicit basic_format_arg(const long long _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Long_long_type), _Long_long_state(_Val) {}
explicit basic_format_arg(const unsigned long long _Val) noexcept
: _Active_state(_Basic_format_arg_type::_ULong_long_type), _ULong_long_state(_Val) {}
explicit basic_format_arg(const bool _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Bool_type), _Bool_state(_Val) {}
explicit basic_format_arg(const _CharType _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Char_type), _Char_state(_Val) {}
explicit basic_format_arg(const float _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Float_type), _Float_state(_Val) {}
explicit basic_format_arg(const double _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Double_type), _Double_state(_Val) {}
explicit basic_format_arg(const long double _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Long_double_type), _Long_double_state(_Val) {}
explicit basic_format_arg(const void* _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Pointer_type), _Pointer_state(_Val) {}
explicit basic_format_arg(const _CharType* _Val) noexcept
: _Active_state(_Basic_format_arg_type::_CString_type), _CString_state(_Val) {}
explicit basic_format_arg(const basic_string_view<_CharType> _Val) noexcept
: _Active_state(_Basic_format_arg_type::_String_type), _String_state(_Val) {}
explicit basic_format_arg(const handle _Val) noexcept
: _Active_state(_Basic_format_arg_type::_Custom_type), _Custom_state(_Val) {}
explicit operator bool() const noexcept {
return _Active_state != _Basic_format_arg_type::_None;
}
_Basic_format_arg_type _Active_state = _Basic_format_arg_type::_None;
union {
monostate _No_state = monostate{};
int _Int_state;
unsigned int _UInt_state;
long long _Long_long_state;
unsigned long long _ULong_long_state;
bool _Bool_state;
_CharType _Char_state;
float _Float_state;
double _Double_state;
long double _Long_double_state;
const void* _Pointer_state;
const _CharType* _CString_state;
basic_string_view<_CharType> _String_state;
handle _Custom_state;
};
};
template <class _Visitor, class _Context>
decltype(auto) visit_format_arg(_Visitor&& _Vis, basic_format_arg<_Context> _Arg) {
switch (_Arg._Active_state) {
case _Basic_format_arg_type::_None:
return _STD forward<_Visitor>(_Vis)(_Arg._No_state);
case _Basic_format_arg_type::_Int_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Int_state);
case _Basic_format_arg_type::_UInt_type:
return _STD forward<_Visitor>(_Vis)(_Arg._UInt_state);
case _Basic_format_arg_type::_Long_long_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Long_long_state);
case _Basic_format_arg_type::_ULong_long_type:
return _STD forward<_Visitor>(_Vis)(_Arg._ULong_long_state);
case _Basic_format_arg_type::_Bool_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Bool_state);
case _Basic_format_arg_type::_Char_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Char_state);
case _Basic_format_arg_type::_Float_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Float_state);
case _Basic_format_arg_type::_Double_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Double_state);
case _Basic_format_arg_type::_Long_double_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Long_double_state);
case _Basic_format_arg_type::_Pointer_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Pointer_state);
case _Basic_format_arg_type::_CString_type:
return _STD forward<_Visitor>(_Vis)(_Arg._CString_state);
case _Basic_format_arg_type::_String_type:
return _STD forward<_Visitor>(_Vis)(_Arg._String_state);
case _Basic_format_arg_type::_Custom_type:
return _STD forward<_Visitor>(_Vis)(_Arg._Custom_state);
default:
_STL_VERIFY(false, "basic_format_arg is in impossible state");
return _STD forward<_Visitor>(_Vis)(0);
}
}
// we need to implement this ourselves because from_chars does not work with wide characters and isn't constexpr
template <class _CharT>
_NODISCARD constexpr const _CharT* _Parse_nonnegative_integer(
const _CharT* _First, const _CharT* _Last, unsigned int& _Value) {
_STL_INTERNAL_CHECK(_First != _Last && '0' <= *_First && *_First <= '9');
constexpr auto _Max_int = static_cast<unsigned int>((numeric_limits<int>::max) ());
constexpr auto _Big_int = _Max_int / 10u;
_Value = 0;
do {
if (_Value > _Big_int) {
_Value = _Max_int + 1;
break;
}
_Value = _Value * 10 + static_cast<unsigned int>(*_First - '0');
++_First;
} while (_First != _Last && '0' <= *_First && *_First <= '9');
if (_Value > _Max_int) {
_THROW(format_error("Number is too big"));
}
return _First;
}
template <class _CharT>
_NODISCARD constexpr const _CharT* _Parse_nonnegative_integer(const _CharT* _First, const _CharT* _Last, int& _Value) {
unsigned int _Val_unsigned = 0;
_First = _Parse_nonnegative_integer(_First, _Last, _Val_unsigned);
// Never invalid because _Parse_nonnegative_integer throws an error for values that don't fit in signed integers
_Value = static_cast<int>(_Val_unsigned);
return _First;
}
template <class _CharT, _Parse_arg_id_callbacks<_CharT> _Callbacks_type>
_NODISCARD constexpr const _CharT* _Parse_arg_id(
const _CharT* _First, const _CharT* _Last, _Callbacks_type&& _Callbacks) {
_STL_INTERNAL_CHECK(_First != _Last);
_CharT _Ch = *_First;
// No id provided, format string is using automatic indexing.
if (_Ch == '}' || _Ch == ':') {
_Callbacks._On_auto_id();
return _First;
}
if (_Ch >= '0' && _Ch <= '9') {
unsigned int _Index = 0;
// arg_id is not allowed to have any leading zeros, but is allowed to be
// equal to zero (but not '00'). So if _Ch is zero we skip the parsing, leave
// _Index set to zero and let the validity checks below ensure that the arg_id
// wasn't something like "00", or "023".
if (_Ch == '0') {
++_First;
} else {
_First = _Parse_nonnegative_integer(_First, _Last, _Index);
}
// The format string shouldn't end right after the index number.
// The only things permitted after the index are the end of the replacement field ('}')
// or the beginning of the format spec (':').
if (_First == _Last || (*_First != '}' && *_First != ':')) {
_THROW(format_error("Invalid format string."));
}
_Callbacks._On_manual_id(_Index);
return _First;
}
// This is where we would parse named arg ids if std::format were to support them.
_THROW(format_error("Invalid format string."));
}
_NODISCARD constexpr bool _Is_execution_charset_utf8() {
#pragma warning(push)
#pragma warning(disable : 4309) // 'initializing' : truncation of constant value
#pragma warning(disable : 4566) // character represented by universal-character-name '\u4E00' cannot be represented in
// the current code page
#pragma warning(disable : 6201) // Index '2' is out of valid index range '0' to '1' for possibly stack allocated buffer
// '_Test_char'
#pragma warning(disable : 6239) // (<non-zero constant> && <expression>) always evaluates to the result of <expression>.
// Did you intend to use the bitwise-and operator?
constexpr char _Test_char[] = "\u4e00";
return sizeof(_Test_char) == 4 && _Test_char[0] == '\xe4' && _Test_char[1] == '\xb8' && _Test_char[2] == '\x80';
#pragma warning(pop)
}
inline constexpr char16_t _Width_estimate_low_intervals[] = { // Per N4885 [format.string.std]/11
0x1100u, 0x1160u, 0x2329u, 0x232Bu, 0x2E80u, 0x303Fu, 0x3040u, 0xA4D0u, 0xAC00u, 0xD7A4u, 0xF900u, 0xFB00u, 0xFE10u,
0xFE1Au, 0xFE30u, 0xFE70u, 0xFF00u, 0xFF61u, 0xFFE0u, 0xFFE7u};
inline constexpr char32_t _Width_estimate_high_intervals[] = { // Per N4885 [format.string.std]/11
0x1F300u, 0x1F650u, 0x1F900u, 0x1FA00u, 0x20000u, 0x2FFFEu, 0x30000u, 0x3FFFEu};
template <auto& _Bounds>
_NODISCARD constexpr int _Unicode_width_estimate(const char32_t _Ch) noexcept {
// Computes the width estimation for Unicode characters from N4885 [format.string.std]/11
int _Result = 1;
for (const auto& _Bound : _Bounds) {
if (_Ch < _Bound) {
return _Result;
}
_Result ^= 0b11u; // Flip between 1 and 2 on each iteration
}
return 1;
}
template <class _CharT, bool _Statically_Utf8 = _Is_execution_charset_utf8()>
class _Fmt_codec;
template <bool _Statically_Utf8>
class _Fmt_codec_base {};
template <>
class _Fmt_codec_base<false> {
protected:
_Cvtvec _Cvt;
_NODISCARD int _Double_byte_encoding_code_units_in_next_character(
const char* const _First, const char* const _Last) const {
// Returns a count of the number of code units that compose the first encoded character in [_First, _Last),
// or -1 if [_First, _Last) doesn't contain an entire encoded character or *_First is not a valid lead byte.
wchar_t _Wide;
mbstate_t _St{};
const auto _Len = static_cast<size_t>(_Last - _First);
const int _Result = _Mbrtowc(&_Wide, _First, _Len, &_St, &_Cvt);
if (_Result > 0) {
return _Result;
} else if (_Result < 0) { // invalid or incomplete encoded character
return -1;
} else { // next code unit is '\0'
return 1;
}
}
_Fmt_codec_base() {
#ifndef _FORMAT_CODEPAGE
#define _FORMAT_CODEPAGE __std_code_page::_Acp
#endif // _FORMAT_CODEPAGE
[[maybe_unused]] const __std_win_error _Result = __std_get_cvt(_FORMAT_CODEPAGE, &_Cvt);
_STL_INTERNAL_CHECK(_Result == __std_win_error::_Success);
#undef _FORMAT_CODEPAGE
}
};
template <bool _Statically_Utf8>
class _Fmt_codec<char, _Statically_Utf8> : private _Fmt_codec_base<_Statically_Utf8> {
private:
_NODISCARD static constexpr int _Utf8_code_units_in_next_character(
const char* const _First, const char* const _Last) noexcept {
// Returns a count of the number of UTF-8 code units that compose the first encoded character in [_First,
// _Last), or -1 if [_First, _Last) doesn't contain an entire encoded character or *_First is not a valid lead
// byte.
const auto _Ch = static_cast<unsigned char>(*_First);
if (_Ch < 0b1000'0000u) {
return 1;
}
const auto _Len = static_cast<size_t>(_Last - _First);
if (_Ch < 0b1110'0000u) {
// check for non-lead byte or partial 2-byte encoded character
return (_Ch >= 0b1100'0000u && _Len >= 2) ? 2 : -1;
}
if (_Ch < 0b1111'0000u) {
// check for partial 3-byte encoded character
return (_Len >= 3) ? 3 : -1;
}
// check for partial 4-byte encoded character
return (_Len >= 4) ? 4 : -1;
}
_NODISCARD static int _Estimate_utf8_character_width(const char* const _Ptr, const int _Units) noexcept {
// Return an estimate for the width of the character composed of _Units code units,
// whose first code unit is denoted by _Ptr.
auto _Ch = static_cast<char32_t>(*_Ptr);
switch (_Units) {
default:
case 1:
case 2:
return 1;
case 3:
_Ch &= 0b1111u;
break;
case 4:
_Ch &= 0b111u;
break;
}
for (int _Idx = 1; _Idx < _Units; ++_Idx) {
_Ch = _Ch << 6 | (_Ptr[_Idx] & 0b11'1111u);
}
if (_Units == 3) {
return _Unicode_width_estimate<_Width_estimate_low_intervals>(_Ch);
}
return _Unicode_width_estimate<_Width_estimate_high_intervals>(_Ch);
}
public:
_NODISCARD int _Units_in_next_character(const char* const _First, const char* const _Last) const noexcept {
// Returns a count of the number of code units that compose the first encoded character in
// [_First, _Last), or -1 if [_First, _Last) doesn't contain an entire encoded character or
// *_First is not a valid lead byte.
_STL_INTERNAL_CHECK(_First < _Last);
if constexpr (_Statically_Utf8) {
return _Utf8_code_units_in_next_character(_First, _Last);
} else {
switch (this->_Cvt._Mbcurmax) {
default:
_STL_INTERNAL_CHECK(!"Bad number of encoding units for this code page");
[[fallthrough]];
case 1:
return 1; // all characters have only one code unit
case 2:
return this->_Double_byte_encoding_code_units_in_next_character(_First, _Last);
case 4: // Assume UTF-8 (as does _Mbrtowc)
return _Utf8_code_units_in_next_character(_First, _Last);
}
}
}
_NODISCARD const char* _Find_encoded(const char* _First, const char* const _Last, const char _Val) const {
// Returns the first occurrence of _Val as an encoded character (and not, for example, as a
// continuation byte) in [_First, _Last).
if constexpr (_Statically_Utf8) {
return _Find_unchecked(_First, _Last, _Val);
} else {
if (this->_Cvt._Mbcurmax == 1 || this->_Cvt._Mbcurmax == 4) {
// As above and in _Mbrtowc, assume 4-byte encodings are UTF-8
return _Find_unchecked(_First, _Last, _Val);
}
while (_First != _Last && *_First != _Val) {
const int _Units = _Units_in_next_character(_First, _Last);
if (_Units < 0) {
_THROW(format_error("Invalid encoded character in format string."));
}
_First += _Units;
}
return _First;
}
}
_NODISCARD int _Estimate_width(const char* const _Ptr, const int _Units) const {
// Return an estimate for the width of the character composed of _Units code units,
// whose first code unit is denoted by _Ptr.
if constexpr (_Statically_Utf8) {
return _Estimate_utf8_character_width(_Ptr, _Units);
} else {
if (this->_Cvt._Mbcurmax != 4) {
// not a Unicode encoding; estimate width == number of code units
return _Units;
}
// assume UTF-8
return _Estimate_utf8_character_width(_Ptr, _Units);
}
}
};
template <bool _Statically_Utf8>
class _Fmt_codec<wchar_t, _Statically_Utf8> {
public:
_NODISCARD int _Units_in_next_character(const wchar_t* _First, const wchar_t* const _Last) const noexcept {
// Returns a count of the number of code units that compose the first encoded character in
// [_First, _Last), or -1 if [_First, _Last) doesn't contain an entire encoded character or
// *_First is an unpaired surrogate.
_STL_INTERNAL_CHECK(_First < _Last);
if (*_First < 0xD800u || *_First >= 0xE000u) {
return 1;
}
if (*_First >= 0xDC00u) { // unpaired low surrogate
return -1;
}
if (++_First == _Last || *_First < 0xDC00u || *_First >= 0xE000u) { // unpaired high surrogate
return -1;
}
return 2; // surrogate pair
}
_NODISCARD const wchar_t* _Find_encoded(
const wchar_t* const _First, const wchar_t* const _Last, const wchar_t _Val) const {
return _Find_unchecked(_First, _Last, _Val);
}
_NODISCARD int _Estimate_width(const wchar_t* const _Ptr, const int _Units) const {
// Return an estimate for the width of the character composed of _Units code units,
// whose first code unit is denoted by _Ptr.
auto _Ch = static_cast<char32_t>(*_Ptr);
if (_Units == 1) {
return _Unicode_width_estimate<_Width_estimate_low_intervals>(_Ch);
}
// surrogate pair
_Ch = (_Ch - 0xD800u) << 10;
_Ch += static_cast<char32_t>(_Ptr[1]) - 0xDC00u;
_Ch += 0x10000u;
return _Unicode_width_estimate<_Width_estimate_high_intervals>(_Ch);
}
};
template <class _CharT, _Parse_align_callbacks<_CharT> _Callbacks_type>
_NODISCARD const _CharT* _Parse_align(const _CharT* _First, const _CharT* _Last, _Callbacks_type&& _Callbacks) {
// align and fill
_STL_INTERNAL_CHECK(_First != _Last && *_First != '}');
auto _Parsed_align = _Fmt_align::_None;
const int _Units = _Fmt_codec<_CharT>{}._Units_in_next_character(_First, _Last);
if (_Units < 0) { // invalid fill character encoding
_THROW(format_error("Invalid format string."));
}
auto _Align_pt = _First + _Units;
if (_Align_pt == _Last) {
_Align_pt = _First;
}
for (;;) {
switch (*_Align_pt) {
case '<':
_Parsed_align = _Fmt_align::_Left;
break;
case '>':
_Parsed_align = _Fmt_align::_Right;
break;
case '^':
_Parsed_align = _Fmt_align::_Center;
break;
}
if (_Parsed_align != _Fmt_align::_None) {
if (_Align_pt != _First) {
if (*_First == '{') {
_THROW(format_error("invalid fill character '{'"));
}
_Callbacks._On_fill({_First, static_cast<size_t>(_Align_pt - _First)});
_First = _Align_pt + 1;
} else {
++_First;
}
_Callbacks._On_align(_Parsed_align);
break;
} else if (_Align_pt == _First) {
break;
}
_Align_pt = _First;
}
return _First;
}
// Adapts a type modeling _Width_adapter_callbacks to model _Parse_arg_id_callbacks.
// Used in _Parse_width so that _Parse_arg_id can be used to parse dynamic widths.
template <class _CharT, _Width_adapter_callbacks<_CharT> _Callbacks_type>
struct _Width_adapter {
_Callbacks_type& _Callbacks;
constexpr explicit _Width_adapter(_Callbacks_type& _Handler) : _Callbacks(_Handler) {}
constexpr void _On_auto_id() {
_Callbacks._On_dynamic_width(_Auto_id_tag{});
}
constexpr void _On_manual_id(const size_t _Id) {
_Callbacks._On_dynamic_width(_Id);
}
};
// Adapts a type modeling _Precision_adapter_callbacks to model _Parse_arg_id_callbacks.
// Used in _Parse_precision so that _Parse_arg_id can be used to parse dynamic precisions.
template <class _CharT, _Precision_adapter_callbacks<_CharT> _Callbacks_type>
struct _Precision_adapter {
_Callbacks_type& _Callbacks;
constexpr explicit _Precision_adapter(_Callbacks_type& _Handler) : _Callbacks(_Handler) {}
constexpr void _On_auto_id() {
_Callbacks._On_dynamic_precision(_Auto_id_tag{});
}
constexpr void _On_manual_id(const size_t _Id) {
_Callbacks._On_dynamic_precision(_Id);
}
};
// _Parse_arg_id expects a handler when it finds an argument id, however
// _Parse_replacement_field actually needs to know the value of that argument ID to pass on
// to _Handler._On_replacement_field or _Handler._On_format_specs. This _Parse_arg_id wrapper
// stores the value of the arg id for later use, so _Parse_replacement_field has access to it.
template <class _CharT>
struct _Id_adapter {
basic_format_parse_context<_CharT>& _Parse_context;
size_t _Arg_id = static_cast<size_t>(-1);
constexpr void _On_auto_id() {
_Arg_id = _Parse_context.next_arg_id();
_STL_INTERNAL_CHECK(_Arg_id != static_cast<size_t>(-1));
}
constexpr void _On_manual_id(const size_t _Id) {
_Parse_context.check_arg_id(_Id);
_Arg_id = _Id;
_STL_INTERNAL_CHECK(_Arg_id != static_cast<size_t>(-1));
}
};
template <class _CharT, _Parse_width_callbacks<_CharT> _Callbacks_type>
_NODISCARD constexpr const _CharT* _Parse_width(
const _CharT* _First, const _CharT* _Last, _Callbacks_type&& _Callbacks) {
_STL_INTERNAL_CHECK(_First != _Last);
if ('1' <= *_First && *_First <= '9') {
int _Value = 0;
_First = _Parse_nonnegative_integer(_First, _Last, _Value);
_Callbacks._On_width(_Value);
} else if (*_First == '{') {
++_First;
if (_First != _Last) {
_First = _Parse_arg_id(_First, _Last, _Width_adapter<_CharT, _Callbacks_type>{_Callbacks});
}
if (_First == _Last || *_First != '}') {
_THROW(format_error("Invalid format string."));
}
++_First;
}
return _First;
}
template <class _CharT, _Parse_precision_callbacks<_CharT> _Callbacks_type>
_NODISCARD constexpr const _CharT* _Parse_precision(
const _CharT* _First, const _CharT* _Last, _Callbacks_type&& _Callbacks) {
++_First;
_CharT _Ch = '\0';
if (_First != _Last) {
_Ch = *_First;
}
if ('0' <= _Ch && _Ch <= '9') {
int _Precision = 0;
_First = _Parse_nonnegative_integer(_First, _Last, _Precision);
_Callbacks._On_precision(_Precision);
} else if (_Ch == '{') {
++_First;
if (_First != _Last) {
_First = _Parse_arg_id(_First, _Last, _Precision_adapter<_CharT, _Callbacks_type>{_Callbacks});
}
if (_First == _Last || *_First != '}') {
_THROW(format_error("Invalid format string."));
}
++_First;
} else {
_THROW(format_error("Missing precision specifier."));
}
return _First;
}
template <class _CharT, _Parse_spec_callbacks<_CharT> _Callbacks_type>
_NODISCARD constexpr const _CharT* _Parse_format_specs(
const _CharT* _First, const _CharT* _Last, _Callbacks_type&& _Callbacks) {
if (_First == _Last || *_First == '}') {
return _First;
}
_First = _Parse_align(_First, _Last, _Callbacks);
if (_First == _Last) {
return _First;
}
switch (*_First) {
case '+':
_Callbacks._On_sign(_Fmt_sign::_Plus);
++_First;
break;
case '-':
_Callbacks._On_sign(_Fmt_sign::_Minus);
++_First;
break;
case ' ':
_Callbacks._On_sign(_Fmt_sign::_Space);
++_First;
break;
default:
break;
}
if (_First == _Last) {
return _First;
}
if (*_First == '#') {
_Callbacks._On_hash();
if (++_First == _Last) {
return _First;
}
}
if (*_First == '0') {
_Callbacks._On_zero();
if (++_First == _Last) {
return _First;
}
}
_First = _Parse_width(_First, _Last, _Callbacks);
if (_First == _Last) {
return _First;
}
if (*_First == '.') {
_First = _Parse_precision(_First, _Last, _Callbacks);
if (_First == _Last) {
return _First;
}
}
if (*_First == 'L') {
_Callbacks._On_localized();
if (++_First == _Last) {
return _First;
}
}
// If there's anything remaining we assume it's a type.
if (*_First != '}') {
_Callbacks._On_type(*_First);
++_First;
}
return _First;
}
template <class _CharT, _Parse_replacement_field_callbacks<_CharT> _HandlerT>
_NODISCARD constexpr const _CharT* _Parse_replacement_field(
const _CharT* _First, const _CharT* _Last, _HandlerT&& _Handler) {
++_First;
if (_First == _Last) {
_THROW(format_error("Invalid format string."));
}
if (*_First == '}') {
// string was "{}", and we have a replacement field
_Handler._On_replacement_field(_Handler._Parse_context.next_arg_id(), _First);
} else if (*_First == '{') {
// string was "{{", so we have a literal "{" to print
_Handler._On_text(_First, _First + 1);
} else {
_Id_adapter<_CharT> _Adapter{_Handler._Parse_context};
_First = _Parse_arg_id(_First, _Last, _Adapter);
_CharT _Ch = _CharT{};
if (_First != _Last) {
_Ch = *_First;
}
if (_Ch == '}') {
_Handler._On_replacement_field(_Adapter._Arg_id, _First);
} else if (_Ch == ':') {
_First = _Handler._On_format_specs(_Adapter._Arg_id, _First + 1, _Last);
if (_First == _Last || *_First != '}') {
_THROW(format_error("Unknown format specifier."));
}
} else {
_THROW(format_error("Missing '}' in format string."));
}
}
return _First + 1;
}
template <class _CharT, _Parse_replacement_field_callbacks<_CharT> _HandlerT>
void _Parse_format_string(basic_string_view<_CharT> _Format_str, _HandlerT&& _Handler) {
auto _First = _Format_str.data();
auto _Last = _First + _Format_str.size();
const _Fmt_codec<_CharT> _Codec;
while (_First != _Last) {
const _CharT* _OpeningCurl = _First;
if (*_First != '{') {
_OpeningCurl = _Codec._Find_encoded(_First, _Last, _CharT{'{'});
for (;;) {
const _CharT* _ClosingCurl = _Codec._Find_encoded(_First, _OpeningCurl, _CharT{'}'});
// In this case there are neither closing nor opening curls in [_First, _OpeningCurl)
// Write the whole thing out.
if (_ClosingCurl == _OpeningCurl) {
_Handler._On_text(_First, _OpeningCurl);
break;
}
// We know _ClosingCurl isn't past the end because
// the above condition was not met.
++_ClosingCurl;
if (_ClosingCurl == _OpeningCurl || *_ClosingCurl != '}') {
_THROW(format_error("Unmatched '}' in format string."));
}
// We found two closing curls, so output only one of them
_Handler._On_text(_First, _ClosingCurl);
// skip over the second closing curl
_First = _ClosingCurl + 1;
}
// We are done, there were no replacement fields.
if (_OpeningCurl == _Last) {
return;
}
}
// Parse the replacement field starting at _OpeningCurl and ending sometime before _Last.
_First = _Parse_replacement_field(_OpeningCurl, _Last, _Handler);
}
}
template <class _CharT>
struct _Basic_format_specs {
int _Width = 0;
int _Precision = -1;
char _Type = '\0';
_Fmt_align _Alignment = _Fmt_align::_None;
_Fmt_sign _Sgn = _Fmt_sign::_None;
bool _Alt = false;
bool _Localized = false;
bool _Leading_zero = false;
uint8_t _Fill_length = 1;
// At most one codepoint (so one char32_t or four utf-8 char8_t).