format 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098
  1. // <format> Formatting -*- C++ -*-
  2. // Copyright The GNU Toolchain Authors.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file include/format
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_FORMAT
  24. #define _GLIBCXX_FORMAT 1
  25. #pragma GCC system_header
  26. #include <bits/requires_hosted.h> // for std::string
  27. #if __cplusplus >= 202002L
  28. #include <array>
  29. #include <charconv>
  30. #include <concepts>
  31. #include <limits>
  32. #include <locale>
  33. #include <optional>
  34. #include <span>
  35. #include <string_view>
  36. #include <string>
  37. #include <variant> // monostate (TODO: move to bits/utility.h?)
  38. #include <bits/ranges_base.h> // input_range, range_reference_t
  39. #include <bits/ranges_algobase.h> // ranges::copy
  40. #include <bits/stl_iterator.h> // back_insert_iterator
  41. #include <bits/stl_pair.h> // __is_pair
  42. #include <bits/utility.h> // tuple_size_v
  43. #include <ext/numeric_traits.h> // __int_traits
  44. #if !__has_builtin(__builtin_toupper)
  45. # include <cctype>
  46. #endif
  47. namespace std _GLIBCXX_VISIBILITY(default)
  48. {
  49. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  50. // 201907 Text Formatting, Integration of chrono, printf corner cases.
  51. // 202106 std::format improvements.
  52. // 202110 Fixing locale handling in chrono formatters, generator-like types.
  53. // 202207 Encodings in localized formatting of chrono, basic-format-string.
  54. #define __cpp_lib_format 202110L
  55. #define __cpp_lib_format_uchar 202311L
  56. #if __cplusplus > 202002L
  57. // 202207 P2286R8 Formatting Ranges
  58. // 202207 P2585R1 Improving default container formatting
  59. // TODO: #define __cpp_lib_format_ranges 202207L
  60. #endif
  61. // [format.context], class template basic_format_context
  62. template<typename _Out, typename _CharT> class basic_format_context;
  63. /// @cond undocumented
  64. namespace __format
  65. {
  66. // Type-erased character sink.
  67. template<typename _CharT> class _Sink;
  68. // Output iterator that writes to a type-erase character sink.
  69. template<typename _CharT>
  70. class _Sink_iter;
  71. } // namespace __format
  72. /// @endcond
  73. using format_context
  74. = basic_format_context<__format::_Sink_iter<char>, char>;
  75. using wformat_context
  76. = basic_format_context<__format::_Sink_iter<wchar_t>, wchar_t>;
  77. // [format.args], class template basic_format_args
  78. template<typename _Context> class basic_format_args;
  79. using format_args = basic_format_args<format_context>;
  80. using wformat_args = basic_format_args<wformat_context>;
  81. // [format.arguments], arguments
  82. // [format.arg], class template basic_format_arg
  83. template<typename _Context>
  84. class basic_format_arg;
  85. // [format.fmt.string], class template basic_format_string
  86. /** A compile-time checked format string for the specified argument types.
  87. *
  88. * @since C++23 but available as an extension in C++20.
  89. */
  90. template<typename _CharT, typename... _Args>
  91. struct basic_format_string
  92. {
  93. template<typename _Tp>
  94. requires convertible_to<const _Tp&, basic_string_view<_CharT>>
  95. consteval
  96. basic_format_string(const _Tp& __s);
  97. [[__gnu__::__always_inline__]]
  98. constexpr basic_string_view<_CharT>
  99. get() const noexcept
  100. { return _M_str; }
  101. private:
  102. basic_string_view<_CharT> _M_str;
  103. };
  104. template<typename... _Args>
  105. using format_string = basic_format_string<char, type_identity_t<_Args>...>;
  106. template<typename... _Args>
  107. using wformat_string
  108. = basic_format_string<wchar_t, type_identity_t<_Args>...>;
  109. // [format.formatter], formatter
  110. /// The primary template of std::formatter is disabled.
  111. template<typename _Tp, typename _CharT = char>
  112. struct formatter
  113. {
  114. formatter() = delete; // No std::formatter specialization for this type.
  115. formatter(const formatter&) = delete;
  116. formatter& operator=(const formatter&) = delete;
  117. };
  118. // [format.error], class format_error
  119. class format_error : public runtime_error
  120. {
  121. public:
  122. explicit format_error(const string& __what) : runtime_error(__what) { }
  123. explicit format_error(const char* __what) : runtime_error(__what) { }
  124. };
  125. /// @cond undocumented
  126. [[noreturn]]
  127. inline void
  128. __throw_format_error(const char* __what)
  129. { _GLIBCXX_THROW_OR_ABORT(format_error(__what)); }
  130. namespace __format
  131. {
  132. // XXX use named functions for each constexpr error?
  133. [[noreturn]]
  134. inline void
  135. __unmatched_left_brace_in_format_string()
  136. { __throw_format_error("format error: unmatched '{' in format string"); }
  137. [[noreturn]]
  138. inline void
  139. __unmatched_right_brace_in_format_string()
  140. { __throw_format_error("format error: unmatched '}' in format string"); }
  141. [[noreturn]]
  142. inline void
  143. __conflicting_indexing_in_format_string()
  144. { __throw_format_error("format error: conflicting indexing style in format string"); }
  145. [[noreturn]]
  146. inline void
  147. __invalid_arg_id_in_format_string()
  148. { __throw_format_error("format error: invalid arg-id in format string"); }
  149. [[noreturn]]
  150. inline void
  151. __failed_to_parse_format_spec()
  152. { __throw_format_error("format error: failed to parse format-spec"); }
  153. } // namespace __format
  154. /// @endcond
  155. // [format.parse.ctx], class template basic_format_parse_context
  156. template<typename _CharT> class basic_format_parse_context;
  157. using format_parse_context = basic_format_parse_context<char>;
  158. using wformat_parse_context = basic_format_parse_context<wchar_t>;
  159. template<typename _CharT>
  160. class basic_format_parse_context
  161. {
  162. public:
  163. using char_type = _CharT;
  164. using const_iterator = typename basic_string_view<_CharT>::const_iterator;
  165. using iterator = const_iterator;
  166. constexpr explicit
  167. basic_format_parse_context(basic_string_view<_CharT> __fmt,
  168. size_t __num_args = 0) noexcept
  169. : _M_begin(__fmt.begin()), _M_end(__fmt.end()), _M_num_args(__num_args)
  170. { }
  171. basic_format_parse_context(const basic_format_parse_context&) = delete;
  172. void operator=(const basic_format_parse_context&) = delete;
  173. constexpr const_iterator begin() const noexcept { return _M_begin; }
  174. constexpr const_iterator end() const noexcept { return _M_end; }
  175. constexpr void
  176. advance_to(const_iterator __it) noexcept
  177. { _M_begin = __it; }
  178. constexpr size_t
  179. next_arg_id()
  180. {
  181. if (_M_indexing == _Manual)
  182. __format::__conflicting_indexing_in_format_string();
  183. _M_indexing = _Auto;
  184. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  185. // 3825. Missing compile-time argument id check in next_arg_id
  186. if (std::is_constant_evaluated())
  187. if (_M_next_arg_id == _M_num_args)
  188. __format::__invalid_arg_id_in_format_string();
  189. return _M_next_arg_id++;
  190. }
  191. constexpr void
  192. check_arg_id(size_t __id)
  193. {
  194. if (_M_indexing == _Auto)
  195. __format::__conflicting_indexing_in_format_string();
  196. _M_indexing = _Manual;
  197. if (std::is_constant_evaluated())
  198. if (__id >= _M_num_args)
  199. __format::__invalid_arg_id_in_format_string();
  200. }
  201. private:
  202. iterator _M_begin;
  203. iterator _M_end;
  204. enum _Indexing { _Unknown, _Manual, _Auto };
  205. _Indexing _M_indexing = _Unknown;
  206. size_t _M_next_arg_id = 0;
  207. size_t _M_num_args;
  208. };
  209. /// @cond undocumented
  210. template<typename _Tp, template<typename...> class _Class>
  211. static constexpr bool __is_specialization_of = false;
  212. template<template<typename...> class _Class, typename... _Args>
  213. static constexpr bool __is_specialization_of<_Class<_Args...>, _Class>
  214. = true;
  215. namespace __format
  216. {
  217. // pre: first != last
  218. template<typename _CharT>
  219. constexpr pair<unsigned short, const _CharT*>
  220. __parse_integer(const _CharT* __first, const _CharT* __last)
  221. {
  222. if (__first == __last)
  223. __builtin_unreachable();
  224. if constexpr (is_same_v<_CharT, char>)
  225. {
  226. const auto __start = __first;
  227. unsigned short __val = 0;
  228. // N.B. std::from_chars is not constexpr in C++20.
  229. if (__detail::__from_chars_alnum<true>(__first, __last, __val, 10)
  230. && __first != __start) [[likely]]
  231. return {__val, __first};
  232. }
  233. else
  234. {
  235. constexpr int __n = 32;
  236. char __buf[__n]{};
  237. for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i)
  238. __buf[__i] = __first[__i];
  239. auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n);
  240. if (__ptr) [[likely]]
  241. return {__v, __first + (__ptr - __buf)};
  242. }
  243. return {0, nullptr};
  244. }
  245. template<typename _CharT>
  246. constexpr pair<unsigned short, const _CharT*>
  247. __parse_arg_id(const _CharT* __first, const _CharT* __last)
  248. {
  249. if (__first == __last)
  250. __builtin_unreachable();
  251. if (*__first == '0')
  252. return {0, __first + 1}; // No leading zeros allowed, so '0...' == 0
  253. if ('1' <= *__first && *__first <= '9')
  254. {
  255. const unsigned short __id = *__first - '0';
  256. const auto __next = __first + 1;
  257. // Optimize for most likely case of single digit arg-id.
  258. if (__next == __last || !('0' <= *__next && *__next <= '9'))
  259. return {__id, __next};
  260. else
  261. return __format::__parse_integer(__first, __last);
  262. }
  263. return {0, nullptr};
  264. }
  265. enum _Pres_type {
  266. _Pres_none = 0, // Default type (not valid for integer presentation types).
  267. // Presentation types for integral types (including bool and charT).
  268. _Pres_d = 1, _Pres_b, _Pres_B, _Pres_o, _Pres_x, _Pres_X, _Pres_c,
  269. // Presentation types for floating-point types.
  270. _Pres_a = 1, _Pres_A, _Pres_e, _Pres_E, _Pres_f, _Pres_F, _Pres_g, _Pres_G,
  271. _Pres_p = 0, _Pres_P, // For pointers.
  272. _Pres_s = 0, // For strings and bool.
  273. _Pres_esc = 0xf, // For strings and charT.
  274. };
  275. enum _Align {
  276. _Align_default,
  277. _Align_left,
  278. _Align_right,
  279. _Align_centre,
  280. };
  281. enum _Sign {
  282. _Sign_default,
  283. _Sign_plus,
  284. _Sign_minus, // XXX does this need to be distinct from _Sign_default?
  285. _Sign_space,
  286. };
  287. enum _WidthPrec {
  288. _WP_none, // No width/prec specified.
  289. _WP_value, // Fixed width/prec specified.
  290. _WP_from_arg // Use a formatting argument for width/prec.
  291. };
  292. template<typename _Context>
  293. size_t
  294. __int_from_arg(const basic_format_arg<_Context>& __arg);
  295. constexpr bool __is_digit(char __c)
  296. { return std::__detail::__from_chars_alnum_to_val(__c) < 10; }
  297. constexpr bool __is_xdigit(char __c)
  298. { return std::__detail::__from_chars_alnum_to_val(__c) < 16; }
  299. template<typename _CharT>
  300. struct _Spec
  301. {
  302. _Align _M_align : 2;
  303. _Sign _M_sign : 2;
  304. unsigned _M_alt : 1;
  305. unsigned _M_localized : 1;
  306. unsigned _M_zero_fill : 1;
  307. _WidthPrec _M_width_kind : 2;
  308. _WidthPrec _M_prec_kind : 2;
  309. _Pres_type _M_type : 4;
  310. unsigned short _M_width;
  311. unsigned short _M_prec;
  312. _CharT _M_fill = ' ';
  313. using iterator = typename basic_string_view<_CharT>::iterator;
  314. static constexpr _Align
  315. _S_align(_CharT __c) noexcept
  316. {
  317. switch (__c)
  318. {
  319. case '<': return _Align_left;
  320. case '>': return _Align_right;
  321. case '^': return _Align_centre;
  322. default: return _Align_default;
  323. }
  324. }
  325. // pre: __first != __last
  326. constexpr iterator
  327. _M_parse_fill_and_align(iterator __first, iterator __last) noexcept
  328. {
  329. if (*__first != '{')
  330. {
  331. // TODO: accept any UCS scalar value as fill character.
  332. // If narrow source encoding is UTF-8 then accept multibyte char.
  333. if (__last - __first >= 2)
  334. {
  335. if (_Align __align = _S_align(__first[1]))
  336. {
  337. _M_fill = *__first;
  338. _M_align = __align;
  339. return __first + 2;
  340. }
  341. }
  342. if (_Align __align = _S_align(__first[0]))
  343. {
  344. _M_fill = ' ';
  345. _M_align = __align;
  346. return __first + 1;
  347. }
  348. }
  349. return __first;
  350. }
  351. static constexpr _Sign
  352. _S_sign(_CharT __c) noexcept
  353. {
  354. switch (__c)
  355. {
  356. case '+': return _Sign_plus;
  357. case '-': return _Sign_minus;
  358. case ' ': return _Sign_space;
  359. default: return _Sign_default;
  360. }
  361. }
  362. // pre: __first != __last
  363. constexpr iterator
  364. _M_parse_sign(iterator __first, iterator) noexcept
  365. {
  366. if (_Sign __sign = _S_sign(*__first))
  367. {
  368. _M_sign = __sign;
  369. return __first + 1;
  370. }
  371. return __first;
  372. }
  373. // pre: *__first is valid
  374. constexpr iterator
  375. _M_parse_alternate_form(iterator __first, iterator) noexcept
  376. {
  377. if (*__first == '#')
  378. {
  379. _M_alt = true;
  380. ++__first;
  381. }
  382. return __first;
  383. }
  384. // pre: __first != __last
  385. constexpr iterator
  386. _M_parse_zero_fill(iterator __first, iterator /* __last */) noexcept
  387. {
  388. if (*__first == '0')
  389. {
  390. _M_zero_fill = true;
  391. ++__first;
  392. }
  393. return __first;
  394. }
  395. // pre: __first != __last
  396. static constexpr iterator
  397. _S_parse_width_or_precision(iterator __first, iterator __last,
  398. unsigned short& __val, bool& __arg_id,
  399. basic_format_parse_context<_CharT>& __pc)
  400. {
  401. if (__format::__is_digit(*__first))
  402. {
  403. auto [__v, __ptr] = __format::__parse_integer(__first, __last);
  404. if (!__ptr)
  405. __throw_format_error("format error: invalid width or precision "
  406. "in format-spec");
  407. __first = __ptr;
  408. __val = __v;
  409. }
  410. else if (*__first == '{')
  411. {
  412. __arg_id = true;
  413. ++__first;
  414. if (__first == __last)
  415. __format::__unmatched_left_brace_in_format_string();
  416. if (*__first == '}')
  417. __val = __pc.next_arg_id();
  418. else
  419. {
  420. auto [__v, __ptr] = __format::__parse_arg_id(__first, __last);
  421. if (__ptr == nullptr || __ptr == __last || *__ptr != '}')
  422. __format::__invalid_arg_id_in_format_string();
  423. __first = __ptr;
  424. __pc.check_arg_id(__v);
  425. __val = __v;
  426. }
  427. ++__first; // past the '}'
  428. }
  429. return __first;
  430. }
  431. // pre: __first != __last
  432. constexpr iterator
  433. _M_parse_width(iterator __first, iterator __last,
  434. basic_format_parse_context<_CharT>& __pc)
  435. {
  436. bool __arg_id = false;
  437. if (*__first == '0')
  438. __throw_format_error("format error: width must be non-zero in "
  439. "format string");
  440. auto __next = _S_parse_width_or_precision(__first, __last, _M_width,
  441. __arg_id, __pc);
  442. if (__next != __first)
  443. _M_width_kind = __arg_id ? _WP_from_arg : _WP_value;
  444. return __next;
  445. }
  446. // pre: __first != __last
  447. constexpr iterator
  448. _M_parse_precision(iterator __first, iterator __last,
  449. basic_format_parse_context<_CharT>& __pc)
  450. {
  451. if (__first[0] != '.')
  452. return __first;
  453. iterator __next = ++__first;
  454. bool __arg_id = false;
  455. if (__next != __last)
  456. __next = _S_parse_width_or_precision(__first, __last, _M_prec,
  457. __arg_id, __pc);
  458. if (__next == __first)
  459. __throw_format_error("format error: missing precision after '.' in "
  460. "format string");
  461. _M_prec_kind = __arg_id ? _WP_from_arg : _WP_value;
  462. return __next;
  463. }
  464. // pre: __first != __last
  465. constexpr iterator
  466. _M_parse_locale(iterator __first, iterator /* __last */) noexcept
  467. {
  468. if (*__first == 'L')
  469. {
  470. _M_localized = true;
  471. ++__first;
  472. }
  473. return __first;
  474. }
  475. template<typename _Context>
  476. size_t
  477. _M_get_width(_Context& __ctx) const
  478. {
  479. size_t __width = 0;
  480. if (_M_width_kind == _WP_value)
  481. __width = _M_width;
  482. else if (_M_width_kind == _WP_from_arg)
  483. __width = __format::__int_from_arg(__ctx.arg(_M_width));
  484. return __width;
  485. }
  486. template<typename _Context>
  487. size_t
  488. _M_get_precision(_Context& __ctx) const
  489. {
  490. size_t __prec = -1;
  491. if (_M_prec_kind == _WP_value)
  492. __prec = _M_prec;
  493. else if (_M_prec_kind == _WP_from_arg)
  494. __prec = __format::__int_from_arg(__ctx.arg(_M_prec));
  495. return __prec;
  496. }
  497. };
  498. template<typename _Int>
  499. inline char*
  500. __put_sign(_Int __i, _Sign __sign, char* __dest) noexcept
  501. {
  502. if (__i < 0)
  503. *__dest = '-';
  504. else if (__sign == _Sign_plus)
  505. *__dest = '+';
  506. else if (__sign == _Sign_space)
  507. *__dest = ' ';
  508. else
  509. ++__dest;
  510. return __dest;
  511. }
  512. // Write STR to OUT (and do so efficiently if OUT is a _Sink_iter).
  513. template<typename _Out, typename _CharT>
  514. requires output_iterator<_Out, const _CharT&>
  515. inline _Out
  516. __write(_Out __out, basic_string_view<_CharT> __str)
  517. {
  518. if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
  519. {
  520. if (__str.size())
  521. __out = __str;
  522. }
  523. else
  524. for (_CharT __c : __str)
  525. *__out++ = __c;
  526. return __out;
  527. }
  528. // Write STR to OUT with NFILL copies of FILL_CHAR specified by ALIGN.
  529. // pre: __align != _Align_default
  530. template<typename _Out, typename _CharT>
  531. _Out
  532. __write_padded(_Out __out, basic_string_view<_CharT> __str,
  533. _Align __align, size_t __nfill, _CharT __fill_char)
  534. {
  535. const size_t __buflen = 0x20;
  536. _CharT __padding_chars[__buflen];
  537. __padding_chars[0] = _CharT();
  538. basic_string_view<_CharT> __padding{__padding_chars, __buflen};
  539. auto __pad = [&__padding] (size_t __n, _Out& __o) {
  540. if (__n == 0)
  541. return;
  542. while (__n > __padding.size())
  543. {
  544. __o = __format::__write(std::move(__o), __padding);
  545. __n -= __padding.size();
  546. }
  547. if (__n != 0)
  548. __o = __format::__write(std::move(__o), __padding.substr(0, __n));
  549. };
  550. size_t __l, __r, __max;
  551. if (__align == _Align_centre)
  552. {
  553. __l = __nfill / 2;
  554. __r = __l + (__nfill & 1);
  555. __max = __r;
  556. }
  557. else if (__align == _Align_right)
  558. {
  559. __l = __nfill;
  560. __r = 0;
  561. __max = __l;
  562. }
  563. else
  564. {
  565. __l = 0;
  566. __r = __nfill;
  567. __max = __r;
  568. }
  569. if (__max < __buflen)
  570. __padding.remove_suffix(__buflen - __max);
  571. else
  572. __max = __buflen;
  573. char_traits<_CharT>::assign(__padding_chars, __max, __fill_char);
  574. __pad(__l, __out);
  575. __out = __format::__write(std::move(__out), __str);
  576. __pad(__r, __out);
  577. return __out;
  578. }
  579. // Write STR to OUT, with alignment and padding as determined by SPEC.
  580. // pre: __spec._M_align != _Align_default || __align != _Align_default
  581. template<typename _CharT, typename _Out>
  582. _Out
  583. __write_padded_as_spec(basic_string_view<type_identity_t<_CharT>> __str,
  584. size_t __estimated_width,
  585. basic_format_context<_Out, _CharT>& __fc,
  586. const _Spec<_CharT>& __spec,
  587. _Align __align = _Align_left)
  588. {
  589. size_t __width = __spec._M_get_width(__fc);
  590. if (__width <= __estimated_width)
  591. return __format::__write(__fc.out(), __str);
  592. const size_t __nfill = __width - __estimated_width;
  593. if (__spec._M_align)
  594. __align = __spec._M_align;
  595. return __format::__write_padded(__fc.out(), __str, __align, __nfill,
  596. __spec._M_fill);
  597. }
  598. // A lightweight optional<locale>.
  599. struct _Optional_locale
  600. {
  601. [[__gnu__::__always_inline__]]
  602. _Optional_locale() : _M_dummy(), _M_hasval(false) { }
  603. _Optional_locale(const locale& __loc) noexcept
  604. : _M_loc(__loc), _M_hasval(true)
  605. { }
  606. _Optional_locale(const _Optional_locale& __l) noexcept
  607. : _M_dummy(), _M_hasval(__l._M_hasval)
  608. {
  609. if (_M_hasval)
  610. std::construct_at(&_M_loc, __l._M_loc);
  611. }
  612. _Optional_locale&
  613. operator=(const _Optional_locale& __l) noexcept
  614. {
  615. if (_M_hasval)
  616. {
  617. if (__l._M_hasval)
  618. _M_loc = __l._M_loc;
  619. else
  620. {
  621. _M_loc.~locale();
  622. _M_hasval = false;
  623. }
  624. }
  625. else if (__l._M_hasval)
  626. {
  627. std::construct_at(&_M_loc, __l._M_loc);
  628. _M_hasval = true;
  629. }
  630. return *this;
  631. }
  632. ~_Optional_locale() { if (_M_hasval) _M_loc.~locale(); }
  633. _Optional_locale&
  634. operator=(locale&& __loc) noexcept
  635. {
  636. if (_M_hasval)
  637. _M_loc = std::move(__loc);
  638. else
  639. {
  640. std::construct_at(&_M_loc, std::move(__loc));
  641. _M_hasval = true;
  642. }
  643. return *this;
  644. }
  645. const locale&
  646. value() noexcept
  647. {
  648. if (!_M_hasval)
  649. {
  650. std::construct_at(&_M_loc);
  651. _M_hasval = true;
  652. }
  653. return _M_loc;
  654. }
  655. bool has_value() const noexcept { return _M_hasval; }
  656. union {
  657. char _M_dummy = '\0';
  658. std::locale _M_loc;
  659. };
  660. bool _M_hasval = false;
  661. };
  662. template<typename _CharT>
  663. concept __char = same_as<_CharT, char> || same_as<_CharT, wchar_t>;
  664. template<__char _CharT>
  665. struct __formatter_str
  666. {
  667. constexpr typename basic_format_parse_context<_CharT>::iterator
  668. parse(basic_format_parse_context<_CharT>& __pc)
  669. {
  670. auto __first = __pc.begin();
  671. const auto __last = __pc.end();
  672. _Spec<_CharT> __spec{};
  673. auto __finalize = [this, &__spec] {
  674. _M_spec = __spec;
  675. };
  676. auto __finished = [&] {
  677. if (__first == __last || *__first == '}')
  678. {
  679. __finalize();
  680. return true;
  681. }
  682. return false;
  683. };
  684. if (__finished())
  685. return __first;
  686. __first = __spec._M_parse_fill_and_align(__first, __last);
  687. if (__finished())
  688. return __first;
  689. __first = __spec._M_parse_width(__first, __last, __pc);
  690. if (__finished())
  691. return __first;
  692. __first = __spec._M_parse_precision(__first, __last, __pc);
  693. if (__finished())
  694. return __first;
  695. if (*__first == 's')
  696. ++__first;
  697. #if __cpp_lib_format_ranges
  698. else if (*__first == '?')
  699. {
  700. __spec._M_type = _Pres_esc;
  701. ++__first;
  702. }
  703. #endif
  704. if (__finished())
  705. return __first;
  706. __format::__failed_to_parse_format_spec();
  707. }
  708. template<typename _Out>
  709. _Out
  710. format(basic_string_view<_CharT> __s,
  711. basic_format_context<_Out, _CharT>& __fc) const
  712. {
  713. if (_M_spec._M_type == _Pres_esc)
  714. {
  715. // TODO: C++23 escaped string presentation
  716. }
  717. if (_M_spec._M_width_kind == _WP_none
  718. && _M_spec._M_prec_kind == _WP_none)
  719. return __format::__write(__fc.out(), __s);
  720. size_t __estimated_width = __s.size(); // TODO: Unicode-aware estim.
  721. if (_M_spec._M_prec_kind != _WP_none)
  722. {
  723. size_t __prec = _M_spec._M_get_precision(__fc);
  724. if (__estimated_width > __prec)
  725. {
  726. __s = __s.substr(0, __prec); // TODO: do not split code points
  727. __estimated_width = __prec;
  728. }
  729. }
  730. return __format::__write_padded_as_spec(__s, __estimated_width,
  731. __fc, _M_spec);
  732. }
  733. #if __cpp_lib_format_ranges
  734. constexpr void
  735. set_debug_format() noexcept
  736. { _M_spec._M_type = _Pres_esc; }
  737. #endif
  738. private:
  739. _Spec<_CharT> _M_spec{};
  740. };
  741. template<__char _CharT>
  742. struct __formatter_int
  743. {
  744. // If no presentation type is specified, meaning of "none" depends
  745. // whether we are formatting an integer or a char or a bool.
  746. static constexpr _Pres_type _AsInteger = _Pres_d;
  747. static constexpr _Pres_type _AsBool = _Pres_s;
  748. static constexpr _Pres_type _AsChar = _Pres_c;
  749. constexpr typename basic_format_parse_context<_CharT>::iterator
  750. _M_do_parse(basic_format_parse_context<_CharT>& __pc, _Pres_type __type)
  751. {
  752. _Spec<_CharT> __spec{};
  753. __spec._M_type = __type;
  754. const auto __last = __pc.end();
  755. auto __first = __pc.begin();
  756. auto __finalize = [this, &__spec] {
  757. _M_spec = __spec;
  758. };
  759. auto __finished = [&] {
  760. if (__first == __last || *__first == '}')
  761. {
  762. __finalize();
  763. return true;
  764. }
  765. return false;
  766. };
  767. if (__finished())
  768. return __first;
  769. __first = __spec._M_parse_fill_and_align(__first, __last);
  770. if (__finished())
  771. return __first;
  772. __first = __spec._M_parse_sign(__first, __last);
  773. if (__finished())
  774. return __first;
  775. __first = __spec._M_parse_alternate_form(__first, __last);
  776. if (__finished())
  777. return __first;
  778. __first = __spec._M_parse_zero_fill(__first, __last);
  779. if (__finished())
  780. return __first;
  781. __first = __spec._M_parse_width(__first, __last, __pc);
  782. if (__finished())
  783. return __first;
  784. __first = __spec._M_parse_locale(__first, __last);
  785. if (__finished())
  786. return __first;
  787. switch (*__first)
  788. {
  789. case 'b':
  790. __spec._M_type = _Pres_b;
  791. ++__first;
  792. break;
  793. case 'B':
  794. __spec._M_type = _Pres_B;
  795. ++__first;
  796. break;
  797. case 'c':
  798. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  799. // 3586. format should not print bool with 'c'
  800. if (__type != _AsBool)
  801. {
  802. __spec._M_type = _Pres_c;
  803. ++__first;
  804. }
  805. break;
  806. case 'd':
  807. __spec._M_type = _Pres_d;
  808. ++__first;
  809. break;
  810. case 'o':
  811. __spec._M_type = _Pres_o;
  812. ++__first;
  813. break;
  814. case 'x':
  815. __spec._M_type = _Pres_x;
  816. ++__first;
  817. break;
  818. case 'X':
  819. __spec._M_type = _Pres_X;
  820. ++__first;
  821. break;
  822. case 's':
  823. if (__type == _AsBool)
  824. {
  825. __spec._M_type = _Pres_s; // same value (and meaning) as "none"
  826. ++__first;
  827. }
  828. break;
  829. #if __cpp_lib_format_ranges
  830. case '?':
  831. if (__type == _AsChar)
  832. {
  833. __spec._M_type = _Pres_esc;
  834. ++__first;
  835. }
  836. #endif
  837. break;
  838. }
  839. if (__finished())
  840. return __first;
  841. __format::__failed_to_parse_format_spec();
  842. }
  843. template<typename _Tp>
  844. constexpr typename basic_format_parse_context<_CharT>::iterator
  845. _M_parse(basic_format_parse_context<_CharT>& __pc)
  846. {
  847. if constexpr (is_same_v<_Tp, bool>)
  848. {
  849. auto __end = _M_do_parse(__pc, _AsBool);
  850. if (_M_spec._M_type == _Pres_s)
  851. if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill)
  852. __throw_format_error("format error: format-spec contains "
  853. "invalid formatting options for "
  854. "'bool'");
  855. return __end;
  856. }
  857. else if constexpr (__char<_Tp>)
  858. {
  859. auto __end = _M_do_parse(__pc, _AsChar);
  860. if (_M_spec._M_type == _Pres_c || _M_spec._M_type == _Pres_esc)
  861. if (_M_spec._M_sign || _M_spec._M_alt || _M_spec._M_zero_fill
  862. /* XXX should be invalid? || _M_spec._M_localized */)
  863. __throw_format_error("format error: format-spec contains "
  864. "invalid formatting options for "
  865. "'charT'");
  866. return __end;
  867. }
  868. else
  869. return _M_do_parse(__pc, _AsInteger);
  870. }
  871. template<typename _Int, typename _Out>
  872. typename basic_format_context<_Out, _CharT>::iterator
  873. format(_Int __i, basic_format_context<_Out, _CharT>& __fc) const
  874. {
  875. if (_M_spec._M_type == _Pres_c)
  876. return _M_format_character(_S_to_character(__i), __fc);
  877. char __buf[sizeof(_Int) * __CHAR_BIT__ + 3];
  878. to_chars_result __res{};
  879. string_view __base_prefix;
  880. make_unsigned_t<_Int> __u;
  881. if (__i < 0)
  882. __u = -static_cast<make_unsigned_t<_Int>>(__i);
  883. else
  884. __u = __i;
  885. char* __start = __buf + 3;
  886. char* const __end = __buf + sizeof(__buf);
  887. char* const __start_digits = __start;
  888. switch (_M_spec._M_type)
  889. {
  890. case _Pres_b:
  891. case _Pres_B:
  892. __base_prefix = _M_spec._M_type == _Pres_b ? "0b" : "0B";
  893. __res = to_chars(__start, __end, __u, 2);
  894. break;
  895. #if 0
  896. case _Pres_c:
  897. return _M_format_character(_S_to_character(__i), __fc);
  898. #endif
  899. case _Pres_none:
  900. // Should not reach here with _Pres_none for bool or charT, so:
  901. [[fallthrough]];
  902. case _Pres_d:
  903. __res = to_chars(__start, __end, __u, 10);
  904. break;
  905. case _Pres_o:
  906. if (__i != 0)
  907. __base_prefix = "0";
  908. __res = to_chars(__start, __end, __u, 8);
  909. break;
  910. case _Pres_x:
  911. case _Pres_X:
  912. __base_prefix = _M_spec._M_type == _Pres_x ? "0x" : "0X";
  913. __res = to_chars(__start, __end, __u, 16);
  914. if (_M_spec._M_type == _Pres_X)
  915. for (auto __p = __start; __p != __res.ptr; ++__p)
  916. #if __has_builtin(__builtin_toupper)
  917. *__p = __builtin_toupper(*__p);
  918. #else
  919. *__p = std::toupper(*__p);
  920. #endif
  921. break;
  922. default:
  923. __builtin_unreachable();
  924. }
  925. if (_M_spec._M_alt && __base_prefix.size())
  926. {
  927. __start -= __base_prefix.size();
  928. __builtin_memcpy(__start, __base_prefix.data(),
  929. __base_prefix.size());
  930. }
  931. __start = __format::__put_sign(__i, _M_spec._M_sign, __start - 1);
  932. return _M_format_int(string_view(__start, __res.ptr - __start),
  933. __start_digits - __start, __fc);
  934. }
  935. template<typename _Out>
  936. typename basic_format_context<_Out, _CharT>::iterator
  937. format(bool __i, basic_format_context<_Out, _CharT>& __fc) const
  938. {
  939. if (_M_spec._M_type == _Pres_c)
  940. return _M_format_character(static_cast<unsigned char>(__i), __fc);
  941. if (_M_spec._M_type != _Pres_s)
  942. return format(static_cast<unsigned char>(__i), __fc);
  943. basic_string<_CharT> __s;
  944. size_t __est_width;
  945. if (_M_spec._M_localized) [[unlikely]]
  946. {
  947. auto& __np = std::use_facet<numpunct<_CharT>>(__fc.locale());
  948. __s = __i ? __np.truename() : __np.falsename();
  949. __est_width = __s.size(); // TODO Unicode-aware estimate
  950. }
  951. else
  952. {
  953. if constexpr (is_same_v<char, _CharT>)
  954. __s = __i ? "true" : "false";
  955. else
  956. __s = __i ? L"true" : L"false";
  957. __est_width = __s.size();
  958. }
  959. return __format::__write_padded_as_spec(__s, __est_width, __fc,
  960. _M_spec);
  961. }
  962. template<typename _Out>
  963. typename basic_format_context<_Out, _CharT>::iterator
  964. _M_format_character(_CharT __c,
  965. basic_format_context<_Out, _CharT>& __fc) const
  966. {
  967. return __format::__write_padded_as_spec({&__c, 1u}, 1, __fc, _M_spec);
  968. }
  969. template<typename _Int>
  970. static _CharT
  971. _S_to_character(_Int __i)
  972. {
  973. using _Traits = __gnu_cxx::__int_traits<_CharT>;
  974. if constexpr (is_signed_v<_Int> == is_signed_v<_CharT>)
  975. {
  976. if (_Traits::__min <= __i && __i <= _Traits::__max)
  977. return static_cast<_CharT>(__i);
  978. }
  979. else if constexpr (is_signed_v<_Int>)
  980. {
  981. if (__i >= 0 && make_unsigned_t<_Int>(__i) <= _Traits::__max)
  982. return static_cast<_CharT>(__i);
  983. }
  984. else if (__i <= make_unsigned_t<_CharT>(_Traits::__max))
  985. return static_cast<_CharT>(__i);
  986. __throw_format_error("format error: integer not representable as "
  987. "character");
  988. }
  989. template<typename _Out>
  990. typename basic_format_context<_Out, _CharT>::iterator
  991. _M_format_int(string_view __narrow_str, size_t __prefix_len,
  992. basic_format_context<_Out, _CharT>& __fc) const
  993. {
  994. size_t __width = _M_spec._M_get_width(__fc);
  995. _Optional_locale __loc;
  996. basic_string_view<_CharT> __str;
  997. if constexpr (is_same_v<char, _CharT>)
  998. __str = __narrow_str;
  999. else
  1000. {
  1001. __loc = __fc.locale();
  1002. auto& __ct = use_facet<ctype<_CharT>>(__loc.value());
  1003. size_t __n = __narrow_str.size();
  1004. auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
  1005. __ct.widen(__narrow_str.data(), __narrow_str.data() + __n, __p);
  1006. __str = {__p, __n};
  1007. }
  1008. if (_M_spec._M_localized)
  1009. {
  1010. if constexpr (is_same_v<char, _CharT>)
  1011. __loc = __fc.locale();
  1012. const auto& __l = __loc.value();
  1013. if (__l.name() != "C")
  1014. {
  1015. auto& __np = use_facet<numpunct<_CharT>>(__l);
  1016. string __grp = __np.grouping();
  1017. if (!__grp.empty())
  1018. {
  1019. size_t __n = __str.size() - __prefix_len;
  1020. auto __p = (_CharT*)__builtin_alloca(2 * __n
  1021. * sizeof(_CharT)
  1022. + __prefix_len);
  1023. auto __s = __str.data();
  1024. char_traits<_CharT>::copy(__p, __s, __prefix_len);
  1025. __s += __prefix_len;
  1026. auto __end = std::__add_grouping(__p + __prefix_len,
  1027. __np.thousands_sep(),
  1028. __grp.data(),
  1029. __grp.size(),
  1030. __s, __s + __n);
  1031. __str = {__p, size_t(__end - __p)};
  1032. }
  1033. }
  1034. }
  1035. if (__width <= __str.size())
  1036. return __format::__write(__fc.out(), __str);
  1037. _CharT __fill_char = _M_spec._M_fill;
  1038. _Align __align = _M_spec._M_align;
  1039. size_t __nfill = __width - __str.size();
  1040. auto __out = __fc.out();
  1041. if (__align == _Align_default)
  1042. {
  1043. __align = _Align_right;
  1044. if (_M_spec._M_zero_fill)
  1045. {
  1046. __fill_char = _CharT('0');
  1047. // Write sign and base prefix before zero filling.
  1048. if (__prefix_len != 0)
  1049. {
  1050. __out = __format::__write(std::move(__out),
  1051. __str.substr(0, __prefix_len));
  1052. __str.remove_prefix(__prefix_len);
  1053. }
  1054. }
  1055. else
  1056. __fill_char = _CharT(' ');
  1057. }
  1058. return __format::__write_padded(std::move(__out), __str,
  1059. __align, __nfill, __fill_char);
  1060. }
  1061. #if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
  1062. template<typename _Tp>
  1063. using make_unsigned_t
  1064. = typename __conditional_t<(sizeof(_Tp) <= sizeof(long long)),
  1065. std::make_unsigned<_Tp>,
  1066. type_identity<unsigned __int128>>::type;
  1067. // std::to_chars is not overloaded for int128 in strict mode.
  1068. template<typename _Int>
  1069. static to_chars_result
  1070. to_chars(char* __first, char* __last, _Int __value, int __base)
  1071. { return std::__to_chars_i<_Int>(__first, __last, __value, __base); }
  1072. #endif
  1073. _Spec<_CharT> _M_spec{};
  1074. };
  1075. // Decide how 128-bit floating-point types should be formatted (or not).
  1076. // When supported, the typedef __format::__float128_t is the type that
  1077. // format arguments should be converted to for storage in basic_format_arg.
  1078. // Define the macro _GLIBCXX_FORMAT_F128 to say they're supported.
  1079. // _GLIBCXX_FORMAT_F128=1 means __float128, _Float128 etc. will be formatted
  1080. // by converting them to long double (or __ieee128 for powerpc64le).
  1081. // _GLIBCXX_FORMAT_F128=2 means basic_format_arg needs to enable explicit
  1082. // support for _Float128, rather than formatting it as another type.
  1083. #undef _GLIBCXX_FORMAT_F128
  1084. #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  1085. // Format 128-bit floating-point types using __ieee128.
  1086. using __float128_t = __ieee128;
  1087. # define _GLIBCXX_FORMAT_F128 1
  1088. #ifdef __LONG_DOUBLE_IEEE128__
  1089. // These overloads exist in the library, but are not declared.
  1090. // Make them available as std::__format::to_chars.
  1091. to_chars_result
  1092. to_chars(char*, char*, __ibm128) noexcept
  1093. __asm("_ZSt8to_charsPcS_e");
  1094. to_chars_result
  1095. to_chars(char*, char*, __ibm128, chars_format) noexcept
  1096. __asm("_ZSt8to_charsPcS_eSt12chars_format");
  1097. to_chars_result
  1098. to_chars(char*, char*, __ibm128, chars_format, int) noexcept
  1099. __asm("_ZSt8to_charsPcS_eSt12chars_formati");
  1100. #elif __cplusplus == 202002L
  1101. to_chars_result
  1102. to_chars(char*, char*, __ieee128) noexcept
  1103. __asm("_ZSt8to_charsPcS_u9__ieee128");
  1104. to_chars_result
  1105. to_chars(char*, char*, __ieee128, chars_format) noexcept
  1106. __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_format");
  1107. to_chars_result
  1108. to_chars(char*, char*, __ieee128, chars_format, int) noexcept
  1109. __asm("_ZSt8to_charsPcS_u9__ieee128St12chars_formati");
  1110. #endif
  1111. #elif defined _GLIBCXX_LDOUBLE_IS_IEEE_BINARY128
  1112. // Format 128-bit floating-point types using long double.
  1113. using __float128_t = long double;
  1114. # define _GLIBCXX_FORMAT_F128 1
  1115. #elif __FLT128_DIG__ && defined(_GLIBCXX_HAVE_FLOAT128_MATH)
  1116. // Format 128-bit floating-point types using _Float128.
  1117. using __float128_t = _Float128;
  1118. # define _GLIBCXX_FORMAT_F128 2
  1119. # if __cplusplus == 202002L
  1120. // These overloads exist in the library, but are not declared for C++20.
  1121. // Make them available as std::__format::to_chars.
  1122. to_chars_result
  1123. to_chars(char*, char*, _Float128) noexcept
  1124. # if _GLIBCXX_INLINE_VERSION
  1125. __asm("_ZNSt3__88to_charsEPcS0_DF128_");
  1126. # else
  1127. __asm("_ZSt8to_charsPcS_DF128_");
  1128. # endif
  1129. to_chars_result
  1130. to_chars(char*, char*, _Float128, chars_format) noexcept
  1131. # if _GLIBCXX_INLINE_VERSION
  1132. __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatE");
  1133. # else
  1134. __asm("_ZSt8to_charsPcS_DF128_St12chars_format");
  1135. # endif
  1136. to_chars_result
  1137. to_chars(char*, char*, _Float128, chars_format, int) noexcept
  1138. # if _GLIBCXX_INLINE_VERSION
  1139. __asm("_ZNSt3__88to_charsEPcS0_DF128_NS_12chars_formatEi");
  1140. # else
  1141. __asm("_ZSt8to_charsPcS_DF128_St12chars_formati");
  1142. # endif
  1143. # endif
  1144. #endif
  1145. using std::to_chars;
  1146. // We can format a floating-point type iff it is usable with to_chars.
  1147. template<typename _Tp>
  1148. concept __formattable_float = requires (_Tp __t, char* __p)
  1149. { __format::to_chars(__p, __p, __t, chars_format::scientific, 6); };
  1150. template<__char _CharT>
  1151. struct __formatter_fp
  1152. {
  1153. constexpr typename basic_format_parse_context<_CharT>::iterator
  1154. parse(basic_format_parse_context<_CharT>& __pc)
  1155. {
  1156. _Spec<_CharT> __spec{};
  1157. const auto __last = __pc.end();
  1158. auto __first = __pc.begin();
  1159. auto __finalize = [this, &__spec] {
  1160. _M_spec = __spec;
  1161. };
  1162. auto __finished = [&] {
  1163. if (__first == __last || *__first == '}')
  1164. {
  1165. __finalize();
  1166. return true;
  1167. }
  1168. return false;
  1169. };
  1170. if (__finished())
  1171. return __first;
  1172. __first = __spec._M_parse_fill_and_align(__first, __last);
  1173. if (__finished())
  1174. return __first;
  1175. __first = __spec._M_parse_sign(__first, __last);
  1176. if (__finished())
  1177. return __first;
  1178. __first = __spec._M_parse_alternate_form(__first, __last);
  1179. if (__finished())
  1180. return __first;
  1181. __first = __spec._M_parse_zero_fill(__first, __last);
  1182. if (__finished())
  1183. return __first;
  1184. if (__first[0] != '.')
  1185. {
  1186. __first = __spec._M_parse_width(__first, __last, __pc);
  1187. if (__finished())
  1188. return __first;
  1189. }
  1190. __first = __spec._M_parse_precision(__first, __last, __pc);
  1191. if (__finished())
  1192. return __first;
  1193. __first = __spec._M_parse_locale(__first, __last);
  1194. if (__finished())
  1195. return __first;
  1196. switch (*__first)
  1197. {
  1198. case 'a':
  1199. __spec._M_type = _Pres_a;
  1200. ++__first;
  1201. break;
  1202. case 'A':
  1203. __spec._M_type = _Pres_A;
  1204. ++__first;
  1205. break;
  1206. case 'e':
  1207. __spec._M_type = _Pres_e;
  1208. ++__first;
  1209. break;
  1210. case 'E':
  1211. __spec._M_type = _Pres_E;
  1212. ++__first;
  1213. break;
  1214. case 'f':
  1215. __spec._M_type = _Pres_f;
  1216. ++__first;
  1217. break;
  1218. case 'F':
  1219. __spec._M_type = _Pres_F;
  1220. ++__first;
  1221. break;
  1222. case 'g':
  1223. __spec._M_type = _Pres_g;
  1224. ++__first;
  1225. break;
  1226. case 'G':
  1227. __spec._M_type = _Pres_G;
  1228. ++__first;
  1229. break;
  1230. }
  1231. if (__finished())
  1232. return __first;
  1233. __format::__failed_to_parse_format_spec();
  1234. }
  1235. template<typename _Fp, typename _Out>
  1236. typename basic_format_context<_Out, _CharT>::iterator
  1237. format(_Fp __v, basic_format_context<_Out, _CharT>& __fc) const
  1238. {
  1239. std::string __dynbuf;
  1240. char __buf[128];
  1241. to_chars_result __res{};
  1242. size_t __prec = 6;
  1243. bool __use_prec = _M_spec._M_prec_kind != _WP_none;
  1244. if (__use_prec)
  1245. __prec = _M_spec._M_get_precision(__fc);
  1246. char* __start = __buf + 1; // reserve space for sign
  1247. char* __end = __buf + sizeof(__buf);
  1248. chars_format __fmt{};
  1249. bool __upper = false;
  1250. bool __trailing_zeros = false;
  1251. char __expc = 'e';
  1252. switch (_M_spec._M_type)
  1253. {
  1254. case _Pres_A:
  1255. __upper = true;
  1256. __expc = 'P';
  1257. [[fallthrough]];
  1258. case _Pres_a:
  1259. if (_M_spec._M_type != _Pres_A)
  1260. __expc = 'p';
  1261. __fmt = chars_format::hex;
  1262. break;
  1263. case _Pres_E:
  1264. __upper = true;
  1265. __expc = 'E';
  1266. [[fallthrough]];
  1267. case _Pres_e:
  1268. __use_prec = true;
  1269. __fmt = chars_format::scientific;
  1270. break;
  1271. case _Pres_F:
  1272. __upper = true;
  1273. [[fallthrough]];
  1274. case _Pres_f:
  1275. __use_prec = true;
  1276. __fmt = chars_format::fixed;
  1277. break;
  1278. case _Pres_G:
  1279. __upper = true;
  1280. __expc = 'E';
  1281. [[fallthrough]];
  1282. case _Pres_g:
  1283. __trailing_zeros = true;
  1284. __use_prec = true;
  1285. __fmt = chars_format::general;
  1286. break;
  1287. case _Pres_none:
  1288. if (__use_prec)
  1289. __fmt = chars_format::general;
  1290. break;
  1291. default:
  1292. __builtin_unreachable();
  1293. }
  1294. // Write value into buffer using std::to_chars.
  1295. auto __to_chars = [&](char* __b, char* __e) {
  1296. if (__use_prec)
  1297. return __format::to_chars(__b, __e, __v, __fmt, __prec);
  1298. else if (__fmt != chars_format{})
  1299. return __format::to_chars(__b, __e, __v, __fmt);
  1300. else
  1301. return __format::to_chars(__b, __e, __v);
  1302. };
  1303. // First try using stack buffer.
  1304. __res = __to_chars(__start, __end);
  1305. if (__builtin_expect(__res.ec == errc::value_too_large, 0))
  1306. {
  1307. // If the buffer is too small it's probably because of a large
  1308. // precision, or a very large value in fixed format.
  1309. size_t __guess = 8 + __prec;
  1310. if (__fmt == chars_format::fixed) // +ddd.prec
  1311. {
  1312. if constexpr (is_same_v<_Fp, float> || is_same_v<_Fp, double>
  1313. || is_same_v<_Fp, long double>)
  1314. {
  1315. // The number of digits to the left of the decimal point
  1316. // is floor(log10(max(abs(__v),1)))+1
  1317. int __exp{};
  1318. if constexpr (is_same_v<_Fp, float>)
  1319. __builtin_frexpf(__v, &__exp);
  1320. else if constexpr (is_same_v<_Fp, double>)
  1321. __builtin_frexp(__v, &__exp);
  1322. else if constexpr (is_same_v<_Fp, long double>)
  1323. __builtin_frexpl(__v, &__exp);
  1324. if (__exp > 0)
  1325. __guess += 1U + __exp * 4004U / 13301U; // log10(2) approx.
  1326. }
  1327. else
  1328. __guess += numeric_limits<_Fp>::max_exponent10;
  1329. }
  1330. if (__guess <= sizeof(__buf)) [[unlikely]]
  1331. __guess = sizeof(__buf) * 2;
  1332. __dynbuf.reserve(__guess);
  1333. do
  1334. {
  1335. auto __overwrite = [&__to_chars, &__res] (char* __p, size_t __n)
  1336. {
  1337. __res = __to_chars(__p + 1, __p + __n - 1);
  1338. return __res.ec == errc{} ? __res.ptr - __p : 0;
  1339. };
  1340. _S_resize_and_overwrite(__dynbuf, __dynbuf.capacity() * 2,
  1341. __overwrite);
  1342. __start = __dynbuf.data() + 1; // reserve space for sign
  1343. __end = __dynbuf.data() + __dynbuf.size();
  1344. }
  1345. while (__builtin_expect(__res.ec == errc::value_too_large, 0));
  1346. }
  1347. // Use uppercase for 'A', 'E', and 'G' formats.
  1348. if (__upper)
  1349. {
  1350. for (char* __p = __start; __p != __res.ptr; ++__p)
  1351. *__p = std::toupper(*__p);
  1352. }
  1353. bool __have_sign = true;
  1354. // Add sign for non-negative values.
  1355. if (!__builtin_signbit(__v))
  1356. {
  1357. if (_M_spec._M_sign == _Sign_plus)
  1358. *--__start = '+';
  1359. else if (_M_spec._M_sign == _Sign_space)
  1360. *--__start = ' ';
  1361. else
  1362. __have_sign = false;
  1363. }
  1364. string_view __narrow_str(__start, __res.ptr - __start);
  1365. // Use alternate form. Ensure decimal point is always present,
  1366. // and add trailing zeros (up to precision) for g and G forms.
  1367. if (_M_spec._M_alt && __builtin_isfinite(__v))
  1368. {
  1369. string_view __s = __narrow_str;
  1370. size_t __sigfigs; // Number of significant figures.
  1371. size_t __z = 0; // Number of trailing zeros to add.
  1372. size_t __p; // Position of the exponent character (if any).
  1373. size_t __d = __s.find('.'); // Position of decimal point.
  1374. if (__d != __s.npos) // Found decimal point.
  1375. {
  1376. __p = __s.find(__expc, __d + 1);
  1377. if (__p == __s.npos)
  1378. __p = __s.size();
  1379. // If presentation type is g or G we might need to add zeros.
  1380. if (__trailing_zeros)
  1381. {
  1382. // Find number of digits after first significant figure.
  1383. if (__s[__have_sign] != '0')
  1384. // A string like "D.D" or "-D.DDD"
  1385. __sigfigs = __p - __have_sign - 1;
  1386. else
  1387. // A string like "0.D" or "-0.0DD".
  1388. // Safe to assume there is a non-zero digit, because
  1389. // otherwise there would be no decimal point.
  1390. __sigfigs = __p - __s.find_first_not_of('0', __d + 1);
  1391. }
  1392. }
  1393. else // No decimal point, we need to insert one.
  1394. {
  1395. __p = __s.find(__expc); // Find the exponent, if present.
  1396. if (__p == __s.npos)
  1397. __p = __s.size();
  1398. __d = __p; // Position where '.' should be inserted.
  1399. __sigfigs = __d - __have_sign;
  1400. }
  1401. if (__trailing_zeros && __prec != 0)
  1402. {
  1403. // For g and G presentation types std::to_chars produces
  1404. // no more than prec significant figures. Insert this many
  1405. // zeros so the result has exactly prec significant figures.
  1406. __z = __prec - __sigfigs;
  1407. }
  1408. if (size_t __extras = int(__d == __p) + __z) // How many to add.
  1409. {
  1410. if (__dynbuf.empty() && __extras <= size_t(__end - __res.ptr))
  1411. {
  1412. // The stack buffer is large enough for the result.
  1413. // Move exponent to make space for extra chars.
  1414. __builtin_memmove(__start + __p + __extras,
  1415. __start + __p,
  1416. __s.size() - __p);
  1417. if (__d == __p)
  1418. __start[__p++] = '.';
  1419. __builtin_memset(__start + __p, '0', __z);
  1420. __narrow_str = {__s.data(), __s.size() + __extras};
  1421. }
  1422. else // Need to switch to the dynamic buffer.
  1423. {
  1424. __dynbuf.reserve(__s.size() + __extras);
  1425. if (__dynbuf.empty())
  1426. {
  1427. __dynbuf = __s.substr(0, __p);
  1428. if (__d == __p)
  1429. __dynbuf += '.';
  1430. if (__z)
  1431. __dynbuf.append(__z, '0');
  1432. __dynbuf.append(__s.substr(__p));
  1433. }
  1434. else
  1435. {
  1436. __dynbuf.insert(__p, __extras, '0');
  1437. if (__d == __p)
  1438. __dynbuf[__p] = '.';
  1439. }
  1440. __narrow_str = __dynbuf;
  1441. }
  1442. }
  1443. }
  1444. // TODO move everything below to a new member function that
  1445. // doesn't depend on _Fp type.
  1446. _Optional_locale __loc;
  1447. basic_string<_CharT> __wstr;
  1448. basic_string_view<_CharT> __str;
  1449. if constexpr (is_same_v<_CharT, char>)
  1450. __str = __narrow_str;
  1451. else
  1452. {
  1453. __loc = __fc.locale();
  1454. auto& __ct = use_facet<ctype<_CharT>>(__loc.value());
  1455. const char* __data = __narrow_str.data();
  1456. auto __overwrite = [&__data, &__ct](_CharT* __p, size_t __n)
  1457. {
  1458. __ct.widen(__data, __data + __n, __p);
  1459. return __n;
  1460. };
  1461. _S_resize_and_overwrite(__wstr, __narrow_str.size(), __overwrite);
  1462. __str = __wstr;
  1463. }
  1464. if (_M_spec._M_localized && __builtin_isfinite(__v))
  1465. {
  1466. if constexpr (is_same_v<char, _CharT>)
  1467. __wstr = _M_localize(__str, __expc, __fc.locale());
  1468. else
  1469. __wstr = _M_localize(__str, __expc, __loc.value());
  1470. if (!__wstr.empty())
  1471. __str = __wstr;
  1472. }
  1473. size_t __width = _M_spec._M_get_width(__fc);
  1474. if (__width <= __str.size())
  1475. return __format::__write(__fc.out(), __str);
  1476. _CharT __fill_char = _M_spec._M_fill;
  1477. _Align __align = _M_spec._M_align;
  1478. size_t __nfill = __width - __str.size();
  1479. auto __out = __fc.out();
  1480. if (__align == _Align_default)
  1481. {
  1482. __align = _Align_right;
  1483. if (_M_spec._M_zero_fill && __builtin_isfinite(__v))
  1484. {
  1485. __fill_char = _CharT('0');
  1486. // Write sign before zero filling.
  1487. if (!__format::__is_xdigit(__narrow_str[0]))
  1488. {
  1489. *__out++ = __str[0];
  1490. __str.remove_prefix(1);
  1491. }
  1492. }
  1493. else
  1494. __fill_char = _CharT(' ');
  1495. }
  1496. return __format::__write_padded(std::move(__out), __str,
  1497. __align, __nfill, __fill_char);
  1498. }
  1499. // Locale-specific format.
  1500. basic_string<_CharT>
  1501. _M_localize(basic_string_view<_CharT> __str, char __expc,
  1502. const locale& __loc) const
  1503. {
  1504. basic_string<_CharT> __lstr;
  1505. if (__loc == locale::classic())
  1506. return __lstr; // Nothing to do.
  1507. const auto& __np = use_facet<numpunct<_CharT>>(__loc);
  1508. const _CharT __point = __np.decimal_point();
  1509. const string __grp = __np.grouping();
  1510. _CharT __dot, __exp;
  1511. if constexpr (is_same_v<_CharT, char>)
  1512. {
  1513. __dot = '.';
  1514. __exp = __expc;
  1515. }
  1516. else
  1517. {
  1518. const auto& __ct = use_facet<ctype<_CharT>>(__loc);
  1519. __dot = __ct.widen('.');
  1520. __exp = __ct.widen(__expc);
  1521. }
  1522. if (__grp.empty() && __point == __dot)
  1523. return __lstr; // Locale uses '.' and no grouping.
  1524. size_t __d = __str.find(__dot);
  1525. size_t __e = min(__d, __str.find(__exp));
  1526. if (__e == __str.npos)
  1527. __e = __str.size();
  1528. const size_t __r = __str.size() - __e;
  1529. auto __overwrite = [&](_CharT* __p, size_t) {
  1530. auto __end = std::__add_grouping(__p, __np.thousands_sep(),
  1531. __grp.data(), __grp.size(),
  1532. __str.data(), __str.data() + __e);
  1533. if (__r)
  1534. {
  1535. if (__d != __str.npos)
  1536. {
  1537. *__end = __point;
  1538. ++__end;
  1539. ++__e;
  1540. }
  1541. if (__r > 1)
  1542. __end += __str.copy(__end, __str.npos, __e);
  1543. }
  1544. return (__end - __p);
  1545. };
  1546. _S_resize_and_overwrite(__lstr, __e * 2 + __r, __overwrite);
  1547. return __lstr;
  1548. }
  1549. template<typename _Ch, typename _Func>
  1550. static void
  1551. _S_resize_and_overwrite(basic_string<_Ch>& __str, size_t __n, _Func __f)
  1552. {
  1553. #if __cpp_lib_string_resize_and_overwrite
  1554. __str.resize_and_overwrite(__n, __f);
  1555. #else
  1556. __str.resize(__n);
  1557. __str.resize(__f(__str.data(), __n));
  1558. #endif
  1559. }
  1560. _Spec<_CharT> _M_spec{};
  1561. };
  1562. } // namespace __format
  1563. /// @endcond
  1564. // Format a character.
  1565. template<__format::__char _CharT>
  1566. struct formatter<_CharT, _CharT>
  1567. {
  1568. formatter() = default;
  1569. constexpr typename basic_format_parse_context<_CharT>::iterator
  1570. parse(basic_format_parse_context<_CharT>& __pc)
  1571. {
  1572. return _M_f.template _M_parse<_CharT>(__pc);
  1573. }
  1574. template<typename _Out>
  1575. typename basic_format_context<_Out, _CharT>::iterator
  1576. format(_CharT __u, basic_format_context<_Out, _CharT>& __fc) const
  1577. {
  1578. if (_M_f._M_spec._M_type == __format::_Pres_none
  1579. || _M_f._M_spec._M_type == __format::_Pres_c)
  1580. return _M_f._M_format_character(__u, __fc);
  1581. else if (_M_f._M_spec._M_type == __format::_Pres_esc)
  1582. {
  1583. // TODO
  1584. return __fc.out();
  1585. }
  1586. else
  1587. return _M_f.format(static_cast<make_unsigned_t<_CharT>>(__u), __fc);
  1588. }
  1589. #if __cpp_lib_format_ranges
  1590. constexpr void
  1591. set_debug_format() noexcept
  1592. { _M_f._M_spec._M_type = __format::_Pres_esc; }
  1593. #endif
  1594. private:
  1595. __format::__formatter_int<_CharT> _M_f;
  1596. };
  1597. // Format a char value for wide character output.
  1598. template<>
  1599. struct formatter<char, wchar_t>
  1600. {
  1601. formatter() = default;
  1602. constexpr typename basic_format_parse_context<wchar_t>::iterator
  1603. parse(basic_format_parse_context<wchar_t>& __pc)
  1604. {
  1605. return _M_f._M_parse<char>(__pc);
  1606. }
  1607. template<typename _Out>
  1608. typename basic_format_context<_Out, wchar_t>::iterator
  1609. format(char __u, basic_format_context<_Out, wchar_t>& __fc) const
  1610. {
  1611. if (_M_f._M_spec._M_type == __format::_Pres_none
  1612. || _M_f._M_spec._M_type == __format::_Pres_c)
  1613. return _M_f._M_format_character(__u, __fc);
  1614. else if (_M_f._M_spec._M_type == __format::_Pres_esc)
  1615. {
  1616. // TODO
  1617. return __fc.out();
  1618. }
  1619. else
  1620. return _M_f.format(static_cast<unsigned char>(__u), __fc);
  1621. }
  1622. #if __cpp_lib_format_ranges
  1623. constexpr void
  1624. set_debug_format() noexcept
  1625. { _M_f._M_spec._M_type = __format::_Pres_esc; }
  1626. #endif
  1627. private:
  1628. __format::__formatter_int<wchar_t> _M_f;
  1629. };
  1630. /** Format a string.
  1631. * @{
  1632. */
  1633. template<__format::__char _CharT>
  1634. struct formatter<_CharT*, _CharT>
  1635. {
  1636. formatter() = default;
  1637. [[__gnu__::__always_inline__]]
  1638. constexpr typename basic_format_parse_context<_CharT>::iterator
  1639. parse(basic_format_parse_context<_CharT>& __pc)
  1640. { return _M_f.parse(__pc); }
  1641. template<typename _Out>
  1642. [[__gnu__::__nonnull__]]
  1643. typename basic_format_context<_Out, _CharT>::iterator
  1644. format(_CharT* __u, basic_format_context<_Out, _CharT>& __fc) const
  1645. { return _M_f.format(__u, __fc); }
  1646. #if __cpp_lib_format_ranges
  1647. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1648. #endif
  1649. private:
  1650. __format::__formatter_str<_CharT> _M_f;
  1651. };
  1652. template<__format::__char _CharT>
  1653. struct formatter<const _CharT*, _CharT>
  1654. {
  1655. formatter() = default;
  1656. [[__gnu__::__always_inline__]]
  1657. constexpr typename basic_format_parse_context<_CharT>::iterator
  1658. parse(basic_format_parse_context<_CharT>& __pc)
  1659. { return _M_f.parse(__pc); }
  1660. template<typename _Out>
  1661. [[__gnu__::__nonnull__]]
  1662. typename basic_format_context<_Out, _CharT>::iterator
  1663. format(const _CharT* __u,
  1664. basic_format_context<_Out, _CharT>& __fc) const
  1665. { return _M_f.format(__u, __fc); }
  1666. #if __cpp_lib_format_ranges
  1667. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1668. #endif
  1669. private:
  1670. __format::__formatter_str<_CharT> _M_f;
  1671. };
  1672. template<__format::__char _CharT, size_t _Nm>
  1673. struct formatter<_CharT[_Nm], _CharT>
  1674. {
  1675. formatter() = default;
  1676. [[__gnu__::__always_inline__]]
  1677. constexpr typename basic_format_parse_context<_CharT>::iterator
  1678. parse(basic_format_parse_context<_CharT>& __pc)
  1679. { return _M_f.parse(__pc); }
  1680. template<typename _Out>
  1681. typename basic_format_context<_Out, _CharT>::iterator
  1682. format(const _CharT (&__u)[_Nm],
  1683. basic_format_context<_Out, _CharT>& __fc) const
  1684. { return _M_f.format({__u, _Nm}, __fc); }
  1685. #if __cpp_lib_format_ranges
  1686. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1687. #endif
  1688. private:
  1689. __format::__formatter_str<_CharT> _M_f;
  1690. };
  1691. template<typename _Traits, typename _Alloc>
  1692. struct formatter<basic_string<char, _Traits, _Alloc>, char>
  1693. {
  1694. formatter() = default;
  1695. [[__gnu__::__always_inline__]]
  1696. constexpr typename basic_format_parse_context<char>::iterator
  1697. parse(basic_format_parse_context<char>& __pc)
  1698. { return _M_f.parse(__pc); }
  1699. template<typename _Out>
  1700. typename basic_format_context<_Out, char>::iterator
  1701. format(const basic_string<char, _Traits, _Alloc>& __u,
  1702. basic_format_context<_Out, char>& __fc) const
  1703. { return _M_f.format(__u, __fc); }
  1704. #if __cpp_lib_format_ranges
  1705. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1706. #endif
  1707. private:
  1708. __format::__formatter_str<char> _M_f;
  1709. };
  1710. template<typename _Traits, typename _Alloc>
  1711. struct formatter<basic_string<wchar_t, _Traits, _Alloc>, wchar_t>
  1712. {
  1713. formatter() = default;
  1714. [[__gnu__::__always_inline__]]
  1715. constexpr typename basic_format_parse_context<wchar_t>::iterator
  1716. parse(basic_format_parse_context<wchar_t>& __pc)
  1717. { return _M_f.parse(__pc); }
  1718. template<typename _Out>
  1719. typename basic_format_context<_Out, wchar_t>::iterator
  1720. format(const basic_string<wchar_t, _Traits, _Alloc>& __u,
  1721. basic_format_context<_Out, wchar_t>& __fc) const
  1722. { return _M_f.format(__u, __fc); }
  1723. #if __cpp_lib_format_ranges
  1724. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1725. #endif
  1726. private:
  1727. __format::__formatter_str<wchar_t> _M_f;
  1728. };
  1729. template<typename _Traits>
  1730. struct formatter<basic_string_view<char, _Traits>, char>
  1731. {
  1732. formatter() = default;
  1733. [[__gnu__::__always_inline__]]
  1734. constexpr typename basic_format_parse_context<char>::iterator
  1735. parse(basic_format_parse_context<char>& __pc)
  1736. { return _M_f.parse(__pc); }
  1737. template<typename _Out>
  1738. typename basic_format_context<_Out, char>::iterator
  1739. format(basic_string_view<char, _Traits> __u,
  1740. basic_format_context<_Out, char>& __fc) const
  1741. { return _M_f.format(__u, __fc); }
  1742. #if __cpp_lib_format_ranges
  1743. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1744. #endif
  1745. private:
  1746. __format::__formatter_str<char> _M_f;
  1747. };
  1748. template<typename _Traits>
  1749. struct formatter<basic_string_view<wchar_t, _Traits>, wchar_t>
  1750. {
  1751. formatter() = default;
  1752. [[__gnu__::__always_inline__]]
  1753. constexpr typename basic_format_parse_context<wchar_t>::iterator
  1754. parse(basic_format_parse_context<wchar_t>& __pc)
  1755. { return _M_f.parse(__pc); }
  1756. template<typename _Out>
  1757. typename basic_format_context<_Out, wchar_t>::iterator
  1758. format(basic_string_view<wchar_t, _Traits> __u,
  1759. basic_format_context<_Out, wchar_t>& __fc) const
  1760. { return _M_f.format(__u, __fc); }
  1761. #if __cpp_lib_format_ranges
  1762. constexpr void set_debug_format() noexcept { _M_f.set_debug_format(); }
  1763. #endif
  1764. private:
  1765. __format::__formatter_str<wchar_t> _M_f;
  1766. };
  1767. /// @}
  1768. /// Format an integer.
  1769. template<integral _Tp, __format::__char _CharT>
  1770. requires (!__is_one_of<_Tp, char, wchar_t, char16_t, char32_t>::value)
  1771. struct formatter<_Tp, _CharT>
  1772. {
  1773. formatter() = default;
  1774. [[__gnu__::__always_inline__]]
  1775. constexpr typename basic_format_parse_context<_CharT>::iterator
  1776. parse(basic_format_parse_context<_CharT>& __pc)
  1777. {
  1778. return _M_f.template _M_parse<_Tp>(__pc);
  1779. }
  1780. template<typename _Out>
  1781. typename basic_format_context<_Out, _CharT>::iterator
  1782. format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
  1783. { return _M_f.format(__u, __fc); }
  1784. private:
  1785. __format::__formatter_int<_CharT> _M_f;
  1786. };
  1787. #if defined __SIZEOF_INT128__ && defined __STRICT_ANSI__
  1788. template<typename _Tp, __format::__char _CharT>
  1789. requires (__is_one_of<_Tp, __int128, unsigned __int128>::value)
  1790. struct formatter<_Tp, _CharT>
  1791. {
  1792. formatter() = default;
  1793. [[__gnu__::__always_inline__]]
  1794. constexpr typename basic_format_parse_context<_CharT>::iterator
  1795. parse(basic_format_parse_context<_CharT>& __pc)
  1796. {
  1797. return _M_f.template _M_parse<_Tp>(__pc);
  1798. }
  1799. template<typename _Out>
  1800. typename basic_format_context<_Out, _CharT>::iterator
  1801. format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
  1802. { return _M_f.format(__u, __fc); }
  1803. private:
  1804. __format::__formatter_int<_CharT> _M_f;
  1805. };
  1806. #endif
  1807. /// Format a floating-point value.
  1808. template<__format::__formattable_float _Tp, __format::__char _CharT>
  1809. struct formatter<_Tp, _CharT>
  1810. {
  1811. formatter() = default;
  1812. [[__gnu__::__always_inline__]]
  1813. constexpr typename basic_format_parse_context<_CharT>::iterator
  1814. parse(basic_format_parse_context<_CharT>& __pc)
  1815. { return _M_f.parse(__pc); }
  1816. template<typename _Out>
  1817. typename basic_format_context<_Out, _CharT>::iterator
  1818. format(_Tp __u, basic_format_context<_Out, _CharT>& __fc) const
  1819. { return _M_f.format(__u, __fc); }
  1820. private:
  1821. __format::__formatter_fp<_CharT> _M_f;
  1822. };
  1823. /** Format a pointer.
  1824. * @{
  1825. */
  1826. template<__format::__char _CharT>
  1827. struct formatter<const void*, _CharT>
  1828. {
  1829. formatter() = default;
  1830. constexpr typename basic_format_parse_context<_CharT>::iterator
  1831. parse(basic_format_parse_context<_CharT>& __pc)
  1832. {
  1833. __format::_Spec<_CharT> __spec{};
  1834. const auto __last = __pc.end();
  1835. auto __first = __pc.begin();
  1836. auto __finalize = [this, &__spec] {
  1837. _M_spec = __spec;
  1838. };
  1839. auto __finished = [&] {
  1840. if (__first == __last || *__first == '}')
  1841. {
  1842. __finalize();
  1843. return true;
  1844. }
  1845. return false;
  1846. };
  1847. if (__finished())
  1848. return __first;
  1849. __first = __spec._M_parse_fill_and_align(__first, __last);
  1850. if (__finished())
  1851. return __first;
  1852. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1853. // P2510R3 Formatting pointers
  1854. #if __cplusplus > 202302L || ! defined __STRICT_ANSI__
  1855. #define _GLIBCXX_P2518R3 1
  1856. #else
  1857. #define _GLIBCXX_P2518R3 0
  1858. #endif
  1859. #if _GLIBCXX_P2518R3
  1860. __first = __spec._M_parse_zero_fill(__first, __last);
  1861. if (__finished())
  1862. return __first;
  1863. #endif
  1864. __first = __spec._M_parse_width(__first, __last, __pc);
  1865. if (__first != __last)
  1866. {
  1867. if (*__first == 'p')
  1868. ++__first;
  1869. #if _GLIBCXX_P2518R3
  1870. else if (*__first == 'P')
  1871. {
  1872. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1873. // P2510R3 Formatting pointers
  1874. __spec._M_type = __format::_Pres_P;
  1875. ++__first;
  1876. }
  1877. #endif
  1878. }
  1879. if (__finished())
  1880. return __first;
  1881. __format::__failed_to_parse_format_spec();
  1882. }
  1883. template<typename _Out>
  1884. typename basic_format_context<_Out, _CharT>::iterator
  1885. format(const void* __v, basic_format_context<_Out, _CharT>& __fc) const
  1886. {
  1887. auto __u = reinterpret_cast<__UINTPTR_TYPE__>(__v);
  1888. char __buf[2 + sizeof(__v) * 2];
  1889. auto [__ptr, __ec] = std::to_chars(__buf + 2, std::end(__buf),
  1890. __u, 16);
  1891. int __n = __ptr - __buf;
  1892. __buf[0] = '0';
  1893. __buf[1] = 'x';
  1894. #if _GLIBCXX_P2518R3
  1895. if (_M_spec._M_type == __format::_Pres_P)
  1896. {
  1897. __buf[1] = 'X';
  1898. for (auto __p = __buf + 2; __p != __ptr; ++__p)
  1899. #if __has_builtin(__builtin_toupper)
  1900. *__p = __builtin_toupper(*__p);
  1901. #else
  1902. *__p = std::toupper(*__p);
  1903. #endif
  1904. }
  1905. #endif
  1906. basic_string_view<_CharT> __str;
  1907. if constexpr (is_same_v<_CharT, char>)
  1908. __str = string_view(__buf, __n);
  1909. else
  1910. {
  1911. const std::locale& __loc = __fc.locale();
  1912. auto& __ct = use_facet<ctype<_CharT>>(__loc);
  1913. auto __p = (_CharT*)__builtin_alloca(__n * sizeof(_CharT));
  1914. __ct.widen(__buf, __buf + __n, __p);
  1915. __str = wstring_view(__p, __n);
  1916. }
  1917. #if _GLIBCXX_P2518R3
  1918. if (_M_spec._M_zero_fill)
  1919. {
  1920. size_t __width = _M_spec._M_get_width(__fc);
  1921. if (__width <= __str.size())
  1922. return __format::__write(__fc.out(), __str);
  1923. auto __out = __fc.out();
  1924. // Write "0x" or "0X" prefix before zero-filling.
  1925. __out = __format::__write(std::move(__out), __str.substr(0, 2));
  1926. __str.remove_prefix(2);
  1927. size_t __nfill = __width - __n;
  1928. return __format::__write_padded(std::move(__out), __str,
  1929. __format::_Align_right,
  1930. __nfill, _CharT('0'));
  1931. }
  1932. #endif
  1933. return __format::__write_padded_as_spec(__str, __n, __fc, _M_spec,
  1934. __format::_Align_right);
  1935. }
  1936. private:
  1937. __format::_Spec<_CharT> _M_spec{};
  1938. };
  1939. template<__format::__char _CharT>
  1940. struct formatter<void*, _CharT>
  1941. {
  1942. formatter() = default;
  1943. [[__gnu__::__always_inline__]]
  1944. constexpr typename basic_format_parse_context<_CharT>::iterator
  1945. parse(basic_format_parse_context<_CharT>& __pc)
  1946. { return _M_f.parse(__pc); }
  1947. template<typename _Out>
  1948. typename basic_format_context<_Out, _CharT>::iterator
  1949. format(void* __v, basic_format_context<_Out, _CharT>& __fc) const
  1950. { return _M_f.format(__v, __fc); }
  1951. private:
  1952. formatter<const void*, _CharT> _M_f;
  1953. };
  1954. template<__format::__char _CharT>
  1955. struct formatter<nullptr_t, _CharT>
  1956. {
  1957. formatter() = default;
  1958. [[__gnu__::__always_inline__]]
  1959. constexpr typename basic_format_parse_context<_CharT>::iterator
  1960. parse(basic_format_parse_context<_CharT>& __pc)
  1961. { return _M_f.parse(__pc); }
  1962. template<typename _Out>
  1963. typename basic_format_context<_Out, _CharT>::iterator
  1964. format(nullptr_t, basic_format_context<_Out, _CharT>& __fc) const
  1965. { return _M_f.format(nullptr, __fc); }
  1966. private:
  1967. formatter<const void*, _CharT> _M_f;
  1968. };
  1969. /// @}
  1970. /// @cond undocumented
  1971. namespace __format
  1972. {
  1973. template<typename _Tp, typename _Context,
  1974. typename _Formatter
  1975. = typename _Context::template formatter_type<remove_const_t<_Tp>>,
  1976. typename _ParseContext
  1977. = basic_format_parse_context<typename _Context::char_type>>
  1978. concept __parsable_with
  1979. = semiregular<_Formatter>
  1980. && requires (_Formatter __f, _ParseContext __pc)
  1981. {
  1982. { __f.parse(__pc) } -> same_as<typename _ParseContext::iterator>;
  1983. };
  1984. template<typename _Tp, typename _Context,
  1985. typename _Formatter
  1986. = typename _Context::template formatter_type<remove_const_t<_Tp>>,
  1987. typename _ParseContext
  1988. = basic_format_parse_context<typename _Context::char_type>>
  1989. concept __formattable_with
  1990. = semiregular<_Formatter>
  1991. && requires (const _Formatter __cf, _Tp&& __t, _Context __fc)
  1992. {
  1993. { __cf.format(__t, __fc) } -> same_as<typename _Context::iterator>;
  1994. };
  1995. // An unspecified output iterator type used in the `formattable` concept.
  1996. template<typename _CharT>
  1997. using _Iter_for = back_insert_iterator<basic_string<_CharT>>;
  1998. template<typename _Tp, typename _CharT,
  1999. typename _Context = basic_format_context<_Iter_for<_CharT>, _CharT>>
  2000. concept __formattable_impl
  2001. = __parsable_with<_Tp, _Context> && __formattable_with<_Tp, _Context>;
  2002. } // namespace __format
  2003. /// @endcond
  2004. #if __cplusplus > 202002L
  2005. // [format.formattable], concept formattable
  2006. template<typename _Tp, typename _CharT>
  2007. concept formattable
  2008. = __format::__formattable_impl<remove_reference_t<_Tp>, _CharT>;
  2009. #endif
  2010. #if __cpp_lib_format_ranges
  2011. /// @cond undocumented
  2012. namespace __format
  2013. {
  2014. template<typename _Rg, typename _CharT>
  2015. concept __const_formattable_range
  2016. = ranges::input_range<const _Rg>
  2017. && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
  2018. template<typename _Rg, typename _CharT>
  2019. using __maybe_const_range
  2020. = conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
  2021. } // namespace __format
  2022. /// @endcond
  2023. #endif // format_ranges
  2024. /// An iterator after the last character written, and the number of
  2025. /// characters that would have been written.
  2026. template<typename _Out>
  2027. struct format_to_n_result
  2028. {
  2029. _Out out;
  2030. iter_difference_t<_Out> size;
  2031. };
  2032. /// @cond undocumented
  2033. namespace __format
  2034. {
  2035. template<typename _CharT>
  2036. class _Sink_iter
  2037. {
  2038. _Sink<_CharT>* _M_sink = nullptr;
  2039. public:
  2040. using iterator_category = output_iterator_tag;
  2041. using value_type = void;
  2042. using difference_type = ptrdiff_t;
  2043. using pointer = void;
  2044. using reference = void;
  2045. _Sink_iter() = default;
  2046. _Sink_iter(const _Sink_iter&) = default;
  2047. _Sink_iter& operator=(const _Sink_iter&) = default;
  2048. [[__gnu__::__always_inline__]]
  2049. explicit constexpr
  2050. _Sink_iter(_Sink<_CharT>& __sink) : _M_sink(std::addressof(__sink)) { }
  2051. [[__gnu__::__always_inline__]]
  2052. constexpr _Sink_iter&
  2053. operator=(_CharT __c)
  2054. {
  2055. _M_sink->_M_write(__c);
  2056. return *this;
  2057. }
  2058. [[__gnu__::__always_inline__]]
  2059. constexpr _Sink_iter&
  2060. operator=(basic_string_view<_CharT> __s)
  2061. {
  2062. _M_sink->_M_write(__s);
  2063. return *this;
  2064. }
  2065. [[__gnu__::__always_inline__]]
  2066. constexpr _Sink_iter&
  2067. operator*() { return *this; }
  2068. [[__gnu__::__always_inline__]]
  2069. constexpr _Sink_iter&
  2070. operator++() { return *this; }
  2071. [[__gnu__::__always_inline__]]
  2072. constexpr _Sink_iter
  2073. operator++(int) { return *this; }
  2074. };
  2075. // Abstract base class for type-erased character sinks.
  2076. // All formatting and output is done via this type's iterator,
  2077. // to reduce the number of different template instantiations.
  2078. template<typename _CharT>
  2079. class _Sink
  2080. {
  2081. friend class _Sink_iter<_CharT>;
  2082. span<_CharT> _M_span;
  2083. typename span<_CharT>::iterator _M_next;
  2084. // Called when the span is full, to make more space available.
  2085. // Precondition: _M_next != _M_span.begin()
  2086. // Postcondition: _M_next != _M_span.end()
  2087. virtual void _M_overflow() = 0;
  2088. protected:
  2089. // Precondition: __span.size() != 0
  2090. [[__gnu__::__always_inline__]]
  2091. explicit constexpr
  2092. _Sink(span<_CharT> __span) noexcept
  2093. : _M_span(__span), _M_next(__span.begin())
  2094. { }
  2095. // The portion of the span that has been written to.
  2096. [[__gnu__::__always_inline__]]
  2097. span<_CharT>
  2098. _M_used() const noexcept
  2099. { return _M_span.first(_M_next - _M_span.begin()); }
  2100. // The portion of the span that has not been written to.
  2101. [[__gnu__::__always_inline__]]
  2102. constexpr span<_CharT>
  2103. _M_unused() const noexcept
  2104. { return _M_span.subspan(_M_next - _M_span.begin()); }
  2105. // Use the start of the span as the next write position.
  2106. [[__gnu__::__always_inline__]]
  2107. constexpr void
  2108. _M_rewind() noexcept
  2109. { _M_next = _M_span.begin(); }
  2110. // Replace the current output range.
  2111. void
  2112. _M_reset(span<_CharT> __s, size_t __pos = 0) noexcept
  2113. {
  2114. _M_span = __s;
  2115. _M_next = __s.begin() + __pos;
  2116. }
  2117. // Called by the iterator for *it++ = c
  2118. constexpr void
  2119. _M_write(_CharT __c)
  2120. {
  2121. *_M_next++ = __c;
  2122. if (_M_next - _M_span.begin() == std::ssize(_M_span)) [[unlikely]]
  2123. _M_overflow();
  2124. }
  2125. constexpr void
  2126. _M_write(basic_string_view<_CharT> __s)
  2127. {
  2128. span __to = _M_unused();
  2129. while (__to.size() <= __s.size())
  2130. {
  2131. __s.copy(__to.data(), __to.size());
  2132. _M_next += __to.size();
  2133. __s.remove_prefix(__to.size());
  2134. _M_overflow();
  2135. __to = _M_unused();
  2136. }
  2137. if (__s.size())
  2138. {
  2139. __s.copy(__to.data(), __s.size());
  2140. _M_next += __s.size();
  2141. }
  2142. }
  2143. public:
  2144. _Sink(const _Sink&) = delete;
  2145. _Sink& operator=(const _Sink&) = delete;
  2146. [[__gnu__::__always_inline__]]
  2147. constexpr _Sink_iter<_CharT>
  2148. out() noexcept
  2149. { return _Sink_iter<_CharT>(*this); }
  2150. };
  2151. // A sink with an internal buffer. This is used to implement concrete sinks.
  2152. template<typename _CharT>
  2153. class _Buf_sink : public _Sink<_CharT>
  2154. {
  2155. protected:
  2156. _CharT _M_buf[32 * sizeof(void*) / sizeof(_CharT)];
  2157. [[__gnu__::__always_inline__]]
  2158. constexpr
  2159. _Buf_sink() noexcept
  2160. : _Sink<_CharT>(_M_buf)
  2161. { }
  2162. };
  2163. // A sink that fills a sequence (e.g. std::string, std::vector, std::deque).
  2164. // Writes to a buffer then appends that to the sequence when it fills up.
  2165. template<typename _Seq>
  2166. class _Seq_sink final : public _Buf_sink<typename _Seq::value_type>
  2167. {
  2168. using _CharT = typename _Seq::value_type;
  2169. _Seq _M_seq;
  2170. // Transfer buffer contents to the sequence, so buffer can be refilled.
  2171. void
  2172. _M_overflow() override
  2173. {
  2174. auto __s = this->_M_used();
  2175. if (__s.empty())
  2176. return;
  2177. if constexpr (__is_specialization_of<_Seq, basic_string>)
  2178. _M_seq.append(__s.data(), __s.size());
  2179. else
  2180. _M_seq.insert(_M_seq.end(), __s.begin(), __s.end());
  2181. this->_M_rewind();
  2182. }
  2183. public:
  2184. // TODO: for SSO string, use SSO buffer as initial span, then switch
  2185. // to _M_buf if it overflows? Or even do that for all unused capacity?
  2186. [[__gnu__::__always_inline__]]
  2187. _Seq_sink() noexcept(is_nothrow_default_constructible_v<_Seq>)
  2188. { }
  2189. _Seq_sink(_Seq&& __s) noexcept(is_nothrow_move_constructible_v<_Seq>)
  2190. : _M_seq(std::move(__s))
  2191. { }
  2192. using _Sink<_CharT>::out;
  2193. _Seq
  2194. get() &&
  2195. {
  2196. if (this->_M_used().size() != 0)
  2197. _Seq_sink::_M_overflow();
  2198. return std::move(_M_seq);
  2199. }
  2200. };
  2201. template<typename _CharT, typename _Alloc = allocator<_CharT>>
  2202. using _Str_sink
  2203. = _Seq_sink<basic_string<_CharT, char_traits<_CharT>, _Alloc>>;
  2204. // template<typename _CharT, typename _Alloc = allocator<_CharT>>
  2205. // using _Vec_sink = _Seq_sink<vector<_CharT, _Alloc>>;
  2206. // A sink that writes to an output iterator.
  2207. // Writes to a fixed-size buffer and then flushes to the output iterator
  2208. // when the buffer fills up.
  2209. template<typename _CharT, typename _OutIter>
  2210. class _Iter_sink : public _Buf_sink<_CharT>
  2211. {
  2212. _OutIter _M_out;
  2213. iter_difference_t<_OutIter> _M_max;
  2214. protected:
  2215. size_t _M_count = 0;
  2216. void
  2217. _M_overflow() override
  2218. {
  2219. auto __s = this->_M_used();
  2220. if (_M_max < 0) // No maximum.
  2221. _M_out = ranges::copy(__s, std::move(_M_out)).out;
  2222. else if (_M_count < static_cast<size_t>(_M_max))
  2223. {
  2224. auto __max = _M_max - _M_count;
  2225. span<_CharT> __first;
  2226. if (__max < __s.size())
  2227. __first = __s.first(static_cast<size_t>(__max));
  2228. else
  2229. __first = __s;
  2230. _M_out = ranges::copy(__first, std::move(_M_out)).out;
  2231. }
  2232. this->_M_rewind();
  2233. _M_count += __s.size();
  2234. }
  2235. public:
  2236. [[__gnu__::__always_inline__]]
  2237. explicit
  2238. _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __max = -1)
  2239. : _M_out(std::move(__out)), _M_max(__max)
  2240. { }
  2241. using _Sink<_CharT>::out;
  2242. format_to_n_result<_OutIter>
  2243. _M_finish() &&
  2244. {
  2245. if (this->_M_used().size() != 0)
  2246. _Iter_sink::_M_overflow();
  2247. iter_difference_t<_OutIter> __count(_M_count);
  2248. return { std::move(_M_out), __count };
  2249. }
  2250. };
  2251. // Partial specialization for contiguous iterators.
  2252. // No buffer is used, characters are written straight to the iterator.
  2253. // We do not know the size of the output range, so the span size just grows
  2254. // as needed. The end of the span might be an invalid pointer outside the
  2255. // valid range, but we never actually call _M_span.end(). This class does
  2256. // not introduce any invalid pointer arithmetic or overflows that would not
  2257. // have happened anyway.
  2258. template<typename _CharT, contiguous_iterator _OutIter>
  2259. requires same_as<iter_value_t<_OutIter>, _CharT>
  2260. class _Iter_sink<_CharT, _OutIter> : public _Sink<_CharT>
  2261. {
  2262. _OutIter _M_first;
  2263. iter_difference_t<_OutIter> _M_max = -1;
  2264. protected:
  2265. size_t _M_count = 0;
  2266. private:
  2267. _CharT _M_buf[64]; // Write here after outputting _M_max characters.
  2268. protected:
  2269. void
  2270. _M_overflow() override
  2271. {
  2272. if (this->_M_unused().size() != 0)
  2273. return; // No need to switch to internal buffer yet.
  2274. auto __s = this->_M_used();
  2275. if (_M_max >= 0)
  2276. {
  2277. _M_count += __s.size();
  2278. // Span was already sized for the maximum character count,
  2279. // if it overflows then any further output must go to the
  2280. // internal buffer, to be discarded.
  2281. this->_M_reset(this->_M_buf);
  2282. }
  2283. else
  2284. {
  2285. // No maximum character count. Just extend the span to allow
  2286. // writing more characters to it.
  2287. this->_M_reset({__s.data(), __s.size() + 1024}, __s.size());
  2288. }
  2289. }
  2290. private:
  2291. static span<_CharT>
  2292. _S_make_span(_CharT* __ptr, iter_difference_t<_OutIter> __n,
  2293. span<_CharT> __buf) noexcept
  2294. {
  2295. if (__n == 0)
  2296. return __buf; // Only write to the internal buffer.
  2297. if (__n > 0)
  2298. {
  2299. if constexpr (!is_integral_v<iter_difference_t<_OutIter>>
  2300. || sizeof(__n) > sizeof(size_t))
  2301. {
  2302. // __int128 or __detail::__max_diff_type
  2303. auto __m = iter_difference_t<_OutIter>((size_t)-1);
  2304. if (__n > __m)
  2305. __n = __m;
  2306. }
  2307. return {__ptr, (size_t)__n};
  2308. }
  2309. #if __has_builtin(__builtin_dynamic_object_size)
  2310. if (size_t __bytes = __builtin_dynamic_object_size(__ptr, 2))
  2311. return {__ptr, __bytes / sizeof(_CharT)};
  2312. #endif
  2313. // Avoid forming a pointer to a different memory page.
  2314. const auto __off = reinterpret_cast<__UINTPTR_TYPE__>(__ptr) % 1024;
  2315. __n = (1024 - __off) / sizeof(_CharT);
  2316. if (__n > 0) [[likely]]
  2317. return {__ptr, static_cast<size_t>(__n)};
  2318. else // Misaligned/packed buffer of wchar_t?
  2319. return {__ptr, 1};
  2320. }
  2321. public:
  2322. explicit
  2323. _Iter_sink(_OutIter __out, iter_difference_t<_OutIter> __n = -1) noexcept
  2324. : _Sink<_CharT>(_S_make_span(std::to_address(__out), __n, _M_buf)),
  2325. _M_first(__out), _M_max(__n)
  2326. { }
  2327. format_to_n_result<_OutIter>
  2328. _M_finish() &&
  2329. {
  2330. auto __s = this->_M_used();
  2331. if (__s.data() == _M_buf)
  2332. {
  2333. // Switched to internal buffer, so must have written _M_max.
  2334. iter_difference_t<_OutIter> __count(_M_count + __s.size());
  2335. return { _M_first + _M_max, __count };
  2336. }
  2337. else // Not using internal buffer yet
  2338. {
  2339. iter_difference_t<_OutIter> __count(__s.size());
  2340. return { _M_first + __count, __count };
  2341. }
  2342. }
  2343. };
  2344. enum _Arg_t : unsigned char {
  2345. _Arg_none, _Arg_bool, _Arg_c, _Arg_i, _Arg_u, _Arg_ll, _Arg_ull,
  2346. _Arg_flt, _Arg_dbl, _Arg_ldbl, _Arg_str, _Arg_sv, _Arg_ptr, _Arg_handle,
  2347. _Arg_i128, _Arg_u128,
  2348. _Arg_bf16, _Arg_f16, _Arg_f32, _Arg_f64, // These are unused.
  2349. #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2350. _Arg_next_value_,
  2351. _Arg_f128 = _Arg_ldbl,
  2352. _Arg_ibm128 = _Arg_next_value_,
  2353. #else
  2354. _Arg_f128,
  2355. #endif
  2356. _Arg_max_
  2357. };
  2358. template<typename _Context>
  2359. struct _Arg_value
  2360. {
  2361. using _CharT = typename _Context::char_type;
  2362. struct _HandleBase
  2363. {
  2364. const void* _M_ptr;
  2365. void (*_M_func)();
  2366. };
  2367. union
  2368. {
  2369. monostate _M_none;
  2370. bool _M_bool;
  2371. _CharT _M_c;
  2372. int _M_i;
  2373. unsigned _M_u;
  2374. long long _M_ll;
  2375. unsigned long long _M_ull;
  2376. float _M_flt;
  2377. double _M_dbl;
  2378. #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT // No long double if it's ambiguous.
  2379. long double _M_ldbl;
  2380. #endif
  2381. const _CharT* _M_str;
  2382. basic_string_view<_CharT> _M_sv;
  2383. const void* _M_ptr;
  2384. _HandleBase _M_handle;
  2385. #ifdef __SIZEOF_INT128__
  2386. __int128 _M_i128;
  2387. unsigned __int128 _M_u128;
  2388. #endif
  2389. // TODO _Float16 etc.
  2390. #ifdef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2391. __ieee128 _M_f128;
  2392. __ibm128 _M_ibm128;
  2393. #elif _GLIBCXX_FORMAT_F128 == 2
  2394. __float128_t _M_f128;
  2395. #endif
  2396. };
  2397. [[__gnu__::__always_inline__]]
  2398. _Arg_value() : _M_none() { }
  2399. #if 0
  2400. template<typename _Tp>
  2401. _Arg_value(in_place_type_t<_Tp>, _Tp __val)
  2402. { _S_get<_Tp>() = __val; }
  2403. #endif
  2404. template<typename _Tp, typename _Self>
  2405. [[__gnu__::__always_inline__]]
  2406. static auto&
  2407. _S_get(_Self& __u) noexcept
  2408. {
  2409. if constexpr (is_same_v<_Tp, bool>)
  2410. return __u._M_bool;
  2411. else if constexpr (is_same_v<_Tp, _CharT>)
  2412. return __u._M_c;
  2413. else if constexpr (is_same_v<_Tp, int>)
  2414. return __u._M_i;
  2415. else if constexpr (is_same_v<_Tp, unsigned>)
  2416. return __u._M_u;
  2417. else if constexpr (is_same_v<_Tp, long long>)
  2418. return __u._M_ll;
  2419. else if constexpr (is_same_v<_Tp, unsigned long long>)
  2420. return __u._M_ull;
  2421. else if constexpr (is_same_v<_Tp, float>)
  2422. return __u._M_flt;
  2423. else if constexpr (is_same_v<_Tp, double>)
  2424. return __u._M_dbl;
  2425. #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2426. else if constexpr (is_same_v<_Tp, long double>)
  2427. return __u._M_ldbl;
  2428. #else
  2429. else if constexpr (is_same_v<_Tp, __ieee128>)
  2430. return __u._M_f128;
  2431. else if constexpr (is_same_v<_Tp, __ibm128>)
  2432. return __u._M_ibm128;
  2433. #endif
  2434. else if constexpr (is_same_v<_Tp, const _CharT*>)
  2435. return __u._M_str;
  2436. else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
  2437. return __u._M_sv;
  2438. else if constexpr (is_same_v<_Tp, const void*>)
  2439. return __u._M_ptr;
  2440. #ifdef __SIZEOF_INT128__
  2441. else if constexpr (is_same_v<_Tp, __int128>)
  2442. return __u._M_i128;
  2443. else if constexpr (is_same_v<_Tp, unsigned __int128>)
  2444. return __u._M_u128;
  2445. #endif
  2446. #if _GLIBCXX_FORMAT_F128 == 2
  2447. else if constexpr (is_same_v<_Tp, __float128_t>)
  2448. return __u._M_f128;
  2449. #endif
  2450. else if constexpr (derived_from<_Tp, _HandleBase>)
  2451. return static_cast<_Tp&>(__u._M_handle);
  2452. // Otherwise, ill-formed.
  2453. }
  2454. template<typename _Tp>
  2455. [[__gnu__::__always_inline__]]
  2456. auto&
  2457. _M_get() noexcept
  2458. { return _S_get<_Tp>(*this); }
  2459. template<typename _Tp>
  2460. [[__gnu__::__always_inline__]]
  2461. const auto&
  2462. _M_get() const noexcept
  2463. { return _S_get<_Tp>(*this); }
  2464. template<typename _Tp>
  2465. [[__gnu__::__always_inline__]]
  2466. void
  2467. _M_set(_Tp __v) noexcept
  2468. {
  2469. if constexpr (derived_from<_Tp, _HandleBase>)
  2470. std::construct_at(&_M_handle, __v);
  2471. else
  2472. _S_get<_Tp>(*this) = __v;
  2473. }
  2474. };
  2475. // [format.arg.store], class template format-arg-store
  2476. template<typename _Context, typename... _Args>
  2477. class _Arg_store;
  2478. } // namespace __format
  2479. /// @endcond
  2480. template<typename _Context>
  2481. class basic_format_arg
  2482. {
  2483. using _CharT = typename _Context::char_type;
  2484. template<typename _Tp>
  2485. static constexpr bool __formattable
  2486. = __format::__formattable_with<_Tp, _Context>;
  2487. public:
  2488. class handle : public __format::_Arg_value<_Context>::_HandleBase
  2489. {
  2490. using _Base = typename __format::_Arg_value<_Context>::_HandleBase;
  2491. // Format as const if possible, to reduce instantiations.
  2492. template<typename _Tp>
  2493. using __maybe_const_t
  2494. = __conditional_t<__formattable<const _Tp>, const _Tp, _Tp>;
  2495. template<typename _Tq>
  2496. static void
  2497. _S_format(basic_format_parse_context<_CharT>& __parse_ctx,
  2498. _Context& __format_ctx, const void* __ptr)
  2499. {
  2500. using _Td = remove_const_t<_Tq>;
  2501. typename _Context::template formatter_type<_Td> __f;
  2502. __parse_ctx.advance_to(__f.parse(__parse_ctx));
  2503. _Tq& __val = *const_cast<_Tq*>(static_cast<const _Td*>(__ptr));
  2504. __format_ctx.advance_to(__f.format(__val, __format_ctx));
  2505. }
  2506. template<typename _Tp>
  2507. explicit
  2508. handle(_Tp& __val) noexcept
  2509. {
  2510. this->_M_ptr = __builtin_addressof(__val);
  2511. auto __func = _S_format<__maybe_const_t<_Tp>>;
  2512. this->_M_func = reinterpret_cast<void(*)()>(__func);
  2513. }
  2514. friend class basic_format_arg<_Context>;
  2515. public:
  2516. handle(const handle&) = default;
  2517. handle& operator=(const handle&) = default;
  2518. [[__gnu__::__always_inline__]]
  2519. void
  2520. format(basic_format_parse_context<_CharT>& __pc, _Context& __fc) const
  2521. {
  2522. using _Func = void(*)(basic_format_parse_context<_CharT>&,
  2523. _Context&, const void*);
  2524. auto __f = reinterpret_cast<_Func>(this->_M_func);
  2525. __f(__pc, __fc, this->_M_ptr);
  2526. }
  2527. };
  2528. [[__gnu__::__always_inline__]]
  2529. basic_format_arg() noexcept : _M_type(__format::_Arg_none) { }
  2530. [[nodiscard,__gnu__::__always_inline__]]
  2531. explicit operator bool() const noexcept
  2532. { return _M_type != __format::_Arg_none; }
  2533. private:
  2534. template<typename _Ctx>
  2535. friend class basic_format_args;
  2536. template<typename _Ctx, typename... _Args>
  2537. friend class __format::_Arg_store;
  2538. static_assert(is_trivially_copyable_v<__format::_Arg_value<_Context>>);
  2539. __format::_Arg_value<_Context> _M_val;
  2540. __format::_Arg_t _M_type;
  2541. // Transform incoming argument type to the type stored in _Arg_value.
  2542. // e.g. short -> int, std::string -> std::string_view,
  2543. // char[3] -> const char*.
  2544. template<typename _Tp>
  2545. static consteval auto
  2546. _S_to_arg_type()
  2547. {
  2548. using _Td = remove_const_t<_Tp>;
  2549. if constexpr (is_same_v<_Td, bool>)
  2550. return type_identity<bool>();
  2551. else if constexpr (is_same_v<_Td, _CharT>)
  2552. return type_identity<_CharT>();
  2553. else if constexpr (is_same_v<_Td, char> && is_same_v<_CharT, wchar_t>)
  2554. return type_identity<_CharT>();
  2555. #ifdef __SIZEOF_INT128__ // Check before signed/unsigned integer
  2556. else if constexpr (is_same_v<_Td, __int128>)
  2557. return type_identity<__int128>();
  2558. else if constexpr (is_same_v<_Td, unsigned __int128>)
  2559. return type_identity<unsigned __int128>();
  2560. #endif
  2561. else if constexpr (__is_signed_integer<_Td>::value)
  2562. {
  2563. if constexpr (sizeof(_Td) <= sizeof(int))
  2564. return type_identity<int>();
  2565. else if constexpr (sizeof(_Td) <= sizeof(long long))
  2566. return type_identity<long long>();
  2567. }
  2568. else if constexpr (__is_unsigned_integer<_Td>::value)
  2569. {
  2570. if constexpr (sizeof(_Td) <= sizeof(unsigned))
  2571. return type_identity<unsigned>();
  2572. else if constexpr (sizeof(_Td) <= sizeof(unsigned long long))
  2573. return type_identity<unsigned long long>();
  2574. }
  2575. else if constexpr (is_same_v<_Td, float>)
  2576. return type_identity<float>();
  2577. else if constexpr (is_same_v<_Td, double>)
  2578. return type_identity<double>();
  2579. #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2580. else if constexpr (is_same_v<_Td, long double>)
  2581. return type_identity<long double>();
  2582. #else
  2583. else if constexpr (is_same_v<_Td, __ibm128>)
  2584. return type_identity<__ibm128>();
  2585. else if constexpr (is_same_v<_Td, __ieee128>)
  2586. return type_identity<__ieee128>();
  2587. #endif
  2588. // TODO bfloat16 and float16
  2589. #ifdef __FLT32_DIG__
  2590. else if constexpr (is_same_v<_Td, _Float32>)
  2591. # ifdef _GLIBCXX_FLOAT_IS_IEEE_BINARY32
  2592. return type_identity<float>();
  2593. # else
  2594. return type_identity<_Float32>();
  2595. # endif
  2596. #endif
  2597. #ifdef __FLT64_DIG__
  2598. else if constexpr (is_same_v<_Td, _Float64>)
  2599. # ifdef _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
  2600. return type_identity<double>();
  2601. # else
  2602. return type_identity<_Float64>();
  2603. # endif
  2604. #endif
  2605. #if _GLIBCXX_FORMAT_F128
  2606. # if __FLT128_DIG__
  2607. else if constexpr (is_same_v<_Td, _Float128>)
  2608. return type_identity<__format::__float128_t>();
  2609. # endif
  2610. # if __SIZEOF_FLOAT128__
  2611. else if constexpr (is_same_v<_Td, __float128>)
  2612. return type_identity<__format::__float128_t>();
  2613. # endif
  2614. #endif
  2615. else if constexpr (__is_specialization_of<_Td, basic_string_view>
  2616. || __is_specialization_of<_Td, basic_string>)
  2617. {
  2618. if constexpr (is_same_v<typename _Td::value_type, _CharT>)
  2619. return type_identity<basic_string_view<_CharT>>();
  2620. else
  2621. return type_identity<handle>();
  2622. }
  2623. else if constexpr (is_same_v<decay_t<_Td>, const _CharT*>)
  2624. return type_identity<const _CharT*>();
  2625. else if constexpr (is_same_v<decay_t<_Td>, _CharT*>)
  2626. return type_identity<const _CharT*>();
  2627. else if constexpr (is_void_v<remove_pointer_t<_Td>>)
  2628. return type_identity<const void*>();
  2629. else if constexpr (is_same_v<_Td, nullptr_t>)
  2630. return type_identity<const void*>();
  2631. else
  2632. return type_identity<handle>();
  2633. }
  2634. // Transform a formattable type to the appropriate storage type.
  2635. template<typename _Tp>
  2636. using _Normalize = typename decltype(_S_to_arg_type<_Tp>())::type;
  2637. // Get the _Arg_t value corresponding to a normalized type.
  2638. template<typename _Tp>
  2639. static consteval __format::_Arg_t
  2640. _S_to_enum()
  2641. {
  2642. using namespace __format;
  2643. if constexpr (is_same_v<_Tp, bool>)
  2644. return _Arg_bool;
  2645. else if constexpr (is_same_v<_Tp, _CharT>)
  2646. return _Arg_c;
  2647. else if constexpr (is_same_v<_Tp, int>)
  2648. return _Arg_i;
  2649. else if constexpr (is_same_v<_Tp, unsigned>)
  2650. return _Arg_u;
  2651. else if constexpr (is_same_v<_Tp, long long>)
  2652. return _Arg_ll;
  2653. else if constexpr (is_same_v<_Tp, unsigned long long>)
  2654. return _Arg_ull;
  2655. else if constexpr (is_same_v<_Tp, float>)
  2656. return _Arg_flt;
  2657. else if constexpr (is_same_v<_Tp, double>)
  2658. return _Arg_dbl;
  2659. #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2660. else if constexpr (is_same_v<_Tp, long double>)
  2661. return _Arg_ldbl;
  2662. #else
  2663. // Don't use _Arg_ldbl for this target, it's ambiguous.
  2664. else if constexpr (is_same_v<_Tp, __ibm128>)
  2665. return _Arg_ibm128;
  2666. else if constexpr (is_same_v<_Tp, __ieee128>)
  2667. return _Arg_f128;
  2668. #endif
  2669. else if constexpr (is_same_v<_Tp, const _CharT*>)
  2670. return _Arg_str;
  2671. else if constexpr (is_same_v<_Tp, basic_string_view<_CharT>>)
  2672. return _Arg_sv;
  2673. else if constexpr (is_same_v<_Tp, const void*>)
  2674. return _Arg_ptr;
  2675. #ifdef __SIZEOF_INT128__
  2676. else if constexpr (is_same_v<_Tp, __int128>)
  2677. return _Arg_i128;
  2678. else if constexpr (is_same_v<_Tp, unsigned __int128>)
  2679. return _Arg_u128;
  2680. #endif
  2681. // N.B. some of these types will never actually be used here,
  2682. // because they get normalized to a standard floating-point type.
  2683. #if defined __FLT32_DIG__ && ! _GLIBCXX_FLOAT_IS_IEEE_BINARY32
  2684. else if constexpr (is_same_v<_Tp, _Float32>)
  2685. return _Arg_f32;
  2686. #endif
  2687. #if defined __FLT64_DIG__ && ! _GLIBCXX_DOUBLE_IS_IEEE_BINARY64
  2688. else if constexpr (is_same_v<_Tp, _Float64>)
  2689. return _Arg_f64;
  2690. #endif
  2691. #if _GLIBCXX_FORMAT_F128 == 2
  2692. else if constexpr (is_same_v<_Tp, __format::__float128_t>)
  2693. return _Arg_f128;
  2694. #endif
  2695. else if constexpr (is_same_v<_Tp, handle>)
  2696. return _Arg_handle;
  2697. }
  2698. template<typename _Tp>
  2699. void
  2700. _M_set(_Tp __v) noexcept
  2701. {
  2702. _M_type = _S_to_enum<_Tp>();
  2703. _M_val._M_set(__v);
  2704. }
  2705. template<typename _Tp>
  2706. requires __format::__formattable_with<_Tp, _Context>
  2707. explicit
  2708. basic_format_arg(_Tp& __v) noexcept
  2709. {
  2710. using _Td = _Normalize<_Tp>;
  2711. if constexpr (is_same_v<_Td, basic_string_view<_CharT>>)
  2712. _M_set(_Td{__v.data(), __v.size()});
  2713. else if constexpr (is_same_v<remove_const_t<_Tp>, char>
  2714. && is_same_v<_CharT, wchar_t>)
  2715. _M_set(static_cast<_Td>(static_cast<unsigned char>(__v)));
  2716. else
  2717. _M_set(static_cast<_Td>(__v));
  2718. }
  2719. template<typename _Ctx, typename... _Argz>
  2720. friend auto
  2721. make_format_args(_Argz&...) noexcept;
  2722. template<typename _Visitor, typename _Ctx>
  2723. friend decltype(auto)
  2724. visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx>);
  2725. template<typename _Visitor>
  2726. decltype(auto)
  2727. _M_visit(_Visitor&& __vis, __format::_Arg_t __type)
  2728. {
  2729. using namespace __format;
  2730. switch (__type)
  2731. {
  2732. case _Arg_none:
  2733. return std::forward<_Visitor>(__vis)(_M_val._M_none);
  2734. case _Arg_bool:
  2735. return std::forward<_Visitor>(__vis)(_M_val._M_bool);
  2736. case _Arg_c:
  2737. return std::forward<_Visitor>(__vis)(_M_val._M_c);
  2738. case _Arg_i:
  2739. return std::forward<_Visitor>(__vis)(_M_val._M_i);
  2740. case _Arg_u:
  2741. return std::forward<_Visitor>(__vis)(_M_val._M_u);
  2742. case _Arg_ll:
  2743. return std::forward<_Visitor>(__vis)(_M_val._M_ll);
  2744. case _Arg_ull:
  2745. return std::forward<_Visitor>(__vis)(_M_val._M_ull);
  2746. #if __cpp_lib_to_chars // FIXME: need to be able to format these types!
  2747. case _Arg_flt:
  2748. return std::forward<_Visitor>(__vis)(_M_val._M_flt);
  2749. case _Arg_dbl:
  2750. return std::forward<_Visitor>(__vis)(_M_val._M_dbl);
  2751. #ifndef _GLIBCXX_LONG_DOUBLE_ALT128_COMPAT
  2752. case _Arg_ldbl:
  2753. return std::forward<_Visitor>(__vis)(_M_val._M_ldbl);
  2754. #else
  2755. case _Arg_f128:
  2756. return std::forward<_Visitor>(__vis)(_M_val._M_f128);
  2757. case _Arg_ibm128:
  2758. return std::forward<_Visitor>(__vis)(_M_val._M_ibm128);
  2759. #endif
  2760. #endif
  2761. case _Arg_str:
  2762. return std::forward<_Visitor>(__vis)(_M_val._M_str);
  2763. case _Arg_sv:
  2764. return std::forward<_Visitor>(__vis)(_M_val._M_sv);
  2765. case _Arg_ptr:
  2766. return std::forward<_Visitor>(__vis)(_M_val._M_ptr);
  2767. case _Arg_handle:
  2768. {
  2769. auto& __h = static_cast<handle&>(_M_val._M_handle);
  2770. return std::forward<_Visitor>(__vis)(__h);
  2771. }
  2772. #ifdef __SIZEOF_INT128__
  2773. case _Arg_i128:
  2774. return std::forward<_Visitor>(__vis)(_M_val._M_i128);
  2775. case _Arg_u128:
  2776. return std::forward<_Visitor>(__vis)(_M_val._M_u128);
  2777. #endif
  2778. #if _GLIBCXX_FORMAT_F128 == 2
  2779. case _Arg_f128:
  2780. return std::forward<_Visitor>(__vis)(_M_val._M_f128);
  2781. #endif
  2782. default:
  2783. // _Arg_f16 etc.
  2784. __builtin_unreachable();
  2785. }
  2786. }
  2787. };
  2788. template<typename _Visitor, typename _Context>
  2789. inline decltype(auto)
  2790. visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg)
  2791. {
  2792. return __arg._M_visit(std::forward<_Visitor>(__vis), __arg._M_type);
  2793. }
  2794. /// @cond undocumented
  2795. namespace __format
  2796. {
  2797. struct _WidthPrecVisitor
  2798. {
  2799. template<typename _Tp>
  2800. size_t
  2801. operator()(_Tp& __arg) const
  2802. {
  2803. if constexpr (is_same_v<_Tp, monostate>)
  2804. __format::__invalid_arg_id_in_format_string();
  2805. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  2806. // 3720. Restrict the valid types of arg-id for width and precision
  2807. // 3721. Allow an arg-id with a value of zero for width
  2808. else if constexpr (sizeof(_Tp) <= sizeof(long long))
  2809. {
  2810. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  2811. // 3720. Restrict the valid types of arg-id for width and precision
  2812. if constexpr (__is_unsigned_integer<_Tp>::value)
  2813. return __arg;
  2814. else if constexpr (__is_signed_integer<_Tp>::value)
  2815. if (__arg >= 0)
  2816. return __arg;
  2817. }
  2818. __throw_format_error("format error: argument used for width or "
  2819. "precision must be a non-negative integer");
  2820. }
  2821. };
  2822. template<typename _Context>
  2823. inline size_t
  2824. __int_from_arg(const basic_format_arg<_Context>& __arg)
  2825. { return std::visit_format_arg(_WidthPrecVisitor(), __arg); }
  2826. // Pack _Arg_t enum values into a single 60-bit integer.
  2827. template<int _Bits, size_t _Nm>
  2828. constexpr auto
  2829. __pack_arg_types(const array<_Arg_t, _Nm>& __types)
  2830. {
  2831. __UINT64_TYPE__ __packed_types = 0;
  2832. for (auto __i = __types.rbegin(); __i != __types.rend(); ++__i)
  2833. __packed_types = (__packed_types << _Bits) | *__i;
  2834. return __packed_types;
  2835. }
  2836. } // namespace __format
  2837. /// @endcond
  2838. template<typename _Context>
  2839. class basic_format_args
  2840. {
  2841. static constexpr int _S_packed_type_bits = 5; // _Arg_t values [0,20]
  2842. static constexpr int _S_packed_type_mask = 0b11111;
  2843. static constexpr int _S_max_packed_args = 12;
  2844. static_assert( __format::_Arg_max_ <= (1 << _S_packed_type_bits) );
  2845. template<typename... _Args>
  2846. using _Store = __format::_Arg_store<_Context, _Args...>;
  2847. template<typename _Ctx, typename... _Args>
  2848. friend class __format::_Arg_store;
  2849. using uint64_t = __UINT64_TYPE__;
  2850. using _Format_arg = basic_format_arg<_Context>;
  2851. using _Format_arg_val = __format::_Arg_value<_Context>;
  2852. // If args are packed then the number of args is in _M_packed_size and
  2853. // the packed types are in _M_unpacked_size, accessed via _M_type(i).
  2854. // If args are not packed then the number of args is in _M_unpacked_size
  2855. // and _M_packed_size is zero.
  2856. uint64_t _M_packed_size : 4;
  2857. uint64_t _M_unpacked_size : 60;
  2858. union {
  2859. const _Format_arg_val* _M_values; // Active when _M_packed_size != 0
  2860. const _Format_arg* _M_args; // Active when _M_packed_size == 0
  2861. };
  2862. size_t
  2863. _M_size() const noexcept
  2864. { return _M_packed_size ? _M_packed_size : _M_unpacked_size; }
  2865. typename __format::_Arg_t
  2866. _M_type(size_t __i) const noexcept
  2867. {
  2868. uint64_t __t = _M_unpacked_size >> (__i * _S_packed_type_bits);
  2869. return static_cast<__format::_Arg_t>(__t & _S_packed_type_mask);
  2870. }
  2871. template<typename _Ctx, typename... _Args>
  2872. friend auto
  2873. make_format_args(_Args&...) noexcept;
  2874. // An array of _Arg_t enums corresponding to _Args...
  2875. template<typename... _Args>
  2876. static consteval array<__format::_Arg_t, sizeof...(_Args)>
  2877. _S_types_to_pack()
  2878. { return {_Format_arg::template _S_to_enum<_Args>()...}; }
  2879. public:
  2880. basic_format_args() noexcept = default;
  2881. template<typename... _Args>
  2882. basic_format_args(const _Store<_Args...>& __store) noexcept;
  2883. [[nodiscard,__gnu__::__always_inline__]]
  2884. basic_format_arg<_Context>
  2885. get(size_t __i) const noexcept
  2886. {
  2887. basic_format_arg<_Context> __arg;
  2888. if (__i < _M_packed_size)
  2889. {
  2890. __arg._M_type = _M_type(__i);
  2891. __arg._M_val = _M_values[__i];
  2892. }
  2893. else if (_M_packed_size == 0 && __i < _M_unpacked_size)
  2894. __arg = _M_args[__i];
  2895. return __arg;
  2896. }
  2897. };
  2898. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  2899. // 3810. CTAD for std::basic_format_args
  2900. template<typename _Context, typename... _Args>
  2901. basic_format_args(__format::_Arg_store<_Context, _Args...>)
  2902. -> basic_format_args<_Context>;
  2903. template<typename _Context, typename... _Args>
  2904. auto
  2905. make_format_args(_Args&... __fmt_args) noexcept;
  2906. // An array of type-erased formatting arguments.
  2907. template<typename _Context, typename... _Args>
  2908. class __format::_Arg_store
  2909. {
  2910. friend std::basic_format_args<_Context>;
  2911. template<typename _Ctx, typename... _Argz>
  2912. friend auto std::
  2913. #if _GLIBCXX_INLINE_VERSION
  2914. __8:: // Needed for PR c++/59256
  2915. #endif
  2916. make_format_args(_Argz&...) noexcept;
  2917. // For a sufficiently small number of arguments we only store values.
  2918. // basic_format_args can get the types from the _Args pack.
  2919. static constexpr bool _S_values_only
  2920. = sizeof...(_Args) <= basic_format_args<_Context>::_S_max_packed_args;
  2921. using _Element_t
  2922. = __conditional_t<_S_values_only,
  2923. __format::_Arg_value<_Context>,
  2924. basic_format_arg<_Context>>;
  2925. _Element_t _M_args[sizeof...(_Args)];
  2926. template<typename _Tp>
  2927. static _Element_t
  2928. _S_make_elt(_Tp& __v)
  2929. {
  2930. basic_format_arg<_Context> __arg(__v);
  2931. if constexpr (_S_values_only)
  2932. return __arg._M_val;
  2933. else
  2934. return __arg;
  2935. }
  2936. template<typename... _Tp>
  2937. requires (sizeof...(_Tp) == sizeof...(_Args))
  2938. [[__gnu__::__always_inline__]]
  2939. _Arg_store(_Tp&... __a) noexcept
  2940. : _M_args{_S_make_elt(__a)...}
  2941. { }
  2942. };
  2943. template<typename _Context>
  2944. class __format::_Arg_store<_Context>
  2945. { };
  2946. template<typename _Context>
  2947. template<typename... _Args>
  2948. inline
  2949. basic_format_args<_Context>::
  2950. basic_format_args(const _Store<_Args...>& __store) noexcept
  2951. {
  2952. if constexpr (sizeof...(_Args) == 0)
  2953. {
  2954. _M_packed_size = 0;
  2955. _M_unpacked_size = 0;
  2956. _M_args = nullptr;
  2957. }
  2958. else if constexpr (sizeof...(_Args) <= _S_max_packed_args)
  2959. {
  2960. // The number of packed arguments:
  2961. _M_packed_size = sizeof...(_Args);
  2962. // The packed type enums:
  2963. _M_unpacked_size
  2964. = __format::__pack_arg_types<_S_packed_type_bits>(_S_types_to_pack<_Args...>());
  2965. // The _Arg_value objects.
  2966. _M_values = __store._M_args;
  2967. }
  2968. else
  2969. {
  2970. // No packed arguments:
  2971. _M_packed_size = 0;
  2972. // The number of unpacked arguments:
  2973. _M_unpacked_size = sizeof...(_Args);
  2974. // The basic_format_arg objects:
  2975. _M_args = __store._M_args;
  2976. }
  2977. }
  2978. /// Capture formatting arguments for use by `std::vformat`.
  2979. template<typename _Context = format_context, typename... _Args>
  2980. [[nodiscard,__gnu__::__always_inline__]]
  2981. inline auto
  2982. make_format_args(_Args&... __fmt_args) noexcept
  2983. {
  2984. using _Fmt_arg = basic_format_arg<_Context>;
  2985. using _Store = __format::_Arg_store<_Context, typename _Fmt_arg::template
  2986. _Normalize<_Args>...>;
  2987. return _Store(__fmt_args...);
  2988. }
  2989. /// Capture formatting arguments for use by `std::vformat` (for wide output).
  2990. template<typename... _Args>
  2991. [[nodiscard,__gnu__::__always_inline__]]
  2992. inline auto
  2993. make_wformat_args(_Args&... __args) noexcept
  2994. { return std::make_format_args<wformat_context>(__args...); }
  2995. /// @cond undocumented
  2996. namespace __format
  2997. {
  2998. template<typename _Out, typename _CharT, typename _Context>
  2999. _Out
  3000. __do_vformat_to(_Out, basic_string_view<_CharT>,
  3001. const basic_format_args<_Context>&,
  3002. const locale* = nullptr);
  3003. } // namespace __format
  3004. /// @endcond
  3005. /** Context for std::format and similar functions.
  3006. *
  3007. * A formatting context contains an output iterator and locale to use
  3008. * for the formatting operations. Most programs will never need to use
  3009. * this class template explicitly. For typical uses of `std::format` the
  3010. * library will use the specializations `std::format_context` (for `char`)
  3011. * and `std::wformat_context` (for `wchar_t`).
  3012. */
  3013. template<typename _Out, typename _CharT>
  3014. class basic_format_context
  3015. {
  3016. static_assert( output_iterator<_Out, const _CharT&> );
  3017. basic_format_args<basic_format_context> _M_args;
  3018. _Out _M_out;
  3019. __format::_Optional_locale _M_loc;
  3020. basic_format_context(basic_format_args<basic_format_context> __args,
  3021. _Out __out)
  3022. : _M_args(__args), _M_out(std::move(__out))
  3023. { }
  3024. basic_format_context(basic_format_args<basic_format_context> __args,
  3025. _Out __out, const std::locale& __loc)
  3026. : _M_args(__args), _M_out(std::move(__out)), _M_loc(__loc)
  3027. { }
  3028. template<typename _Out2, typename _CharT2, typename _Context2>
  3029. friend _Out2
  3030. __format::__do_vformat_to(_Out2, basic_string_view<_CharT2>,
  3031. const basic_format_args<_Context2>&,
  3032. const locale*);
  3033. public:
  3034. basic_format_context() = default;
  3035. ~basic_format_context() = default;
  3036. using iterator = _Out;
  3037. using char_type = _CharT;
  3038. template<typename _Tp>
  3039. using formatter_type = formatter<_Tp, _CharT>;
  3040. [[nodiscard]]
  3041. basic_format_arg<basic_format_context>
  3042. arg(size_t __id) const noexcept
  3043. { return _M_args.get(__id); }
  3044. [[nodiscard]]
  3045. std::locale locale() { return _M_loc.value(); }
  3046. [[nodiscard]]
  3047. iterator out() { return std::move(_M_out); }
  3048. void advance_to(iterator __it) { _M_out = std::move(__it); }
  3049. };
  3050. /// @cond undocumented
  3051. namespace __format
  3052. {
  3053. // Abstract base class defining an interface for scanning format strings.
  3054. // Scan the characters in a format string, dividing it up into strings of
  3055. // ordinary characters, escape sequences, and replacement fields.
  3056. // Call virtual functions for derived classes to parse format-specifiers
  3057. // or write formatted output.
  3058. template<typename _CharT>
  3059. struct _Scanner
  3060. {
  3061. using iterator = typename basic_format_parse_context<_CharT>::iterator;
  3062. basic_format_parse_context<_CharT> _M_pc;
  3063. constexpr explicit
  3064. _Scanner(basic_string_view<_CharT> __str, size_t __nargs = -1)
  3065. : _M_pc(__str, __nargs)
  3066. { }
  3067. constexpr iterator begin() const noexcept { return _M_pc.begin(); }
  3068. constexpr iterator end() const noexcept { return _M_pc.end(); }
  3069. constexpr void
  3070. _M_scan()
  3071. {
  3072. basic_string_view<_CharT> __fmt = _M_fmt_str();
  3073. if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
  3074. {
  3075. _M_pc.advance_to(begin() + 1);
  3076. _M_format_arg(_M_pc.next_arg_id());
  3077. return;
  3078. }
  3079. size_t __lbr = __fmt.find('{');
  3080. size_t __rbr = __fmt.find('}');
  3081. while (__fmt.size())
  3082. {
  3083. auto __cmp = __lbr <=> __rbr;
  3084. if (__cmp == 0)
  3085. {
  3086. _M_on_chars(end());
  3087. _M_pc.advance_to(end());
  3088. return;
  3089. }
  3090. else if (__cmp < 0)
  3091. {
  3092. if (__lbr + 1 == __fmt.size()
  3093. || (__rbr == __fmt.npos && __fmt[__lbr + 1] != '{'))
  3094. __format::__unmatched_left_brace_in_format_string();
  3095. const bool __is_escape = __fmt[__lbr + 1] == '{';
  3096. iterator __last = begin() + __lbr + int(__is_escape);
  3097. _M_on_chars(__last);
  3098. _M_pc.advance_to(__last + 1);
  3099. __fmt = _M_fmt_str();
  3100. if (__is_escape)
  3101. {
  3102. if (__rbr != __fmt.npos)
  3103. __rbr -= __lbr + 2;
  3104. __lbr = __fmt.find('{');
  3105. }
  3106. else
  3107. {
  3108. _M_on_replacement_field();
  3109. __fmt = _M_fmt_str();
  3110. __lbr = __fmt.find('{');
  3111. __rbr = __fmt.find('}');
  3112. }
  3113. }
  3114. else
  3115. {
  3116. if (++__rbr == __fmt.size() || __fmt[__rbr] != '}')
  3117. __format::__unmatched_right_brace_in_format_string();
  3118. iterator __last = begin() + __rbr;
  3119. _M_on_chars(__last);
  3120. _M_pc.advance_to(__last + 1);
  3121. __fmt = _M_fmt_str();
  3122. if (__lbr != __fmt.npos)
  3123. __lbr -= __rbr + 1;
  3124. __rbr = __fmt.find('}');
  3125. }
  3126. }
  3127. }
  3128. constexpr basic_string_view<_CharT>
  3129. _M_fmt_str() const noexcept
  3130. { return {begin(), end()}; }
  3131. constexpr virtual void _M_on_chars(iterator) { }
  3132. constexpr void _M_on_replacement_field()
  3133. {
  3134. auto __next = begin();
  3135. size_t __id;
  3136. if (*__next == '}')
  3137. __id = _M_pc.next_arg_id();
  3138. else if (*__next == ':')
  3139. {
  3140. __id = _M_pc.next_arg_id();
  3141. _M_pc.advance_to(++__next);
  3142. }
  3143. else
  3144. {
  3145. auto [__i, __ptr] = __format::__parse_arg_id(begin(), end());
  3146. if (!__ptr || !(*__ptr == '}' || *__ptr == ':'))
  3147. __format::__invalid_arg_id_in_format_string();
  3148. _M_pc.check_arg_id(__id = __i);
  3149. if (*__ptr == ':')
  3150. {
  3151. _M_pc.advance_to(++__ptr);
  3152. }
  3153. else
  3154. _M_pc.advance_to(__ptr);
  3155. }
  3156. _M_format_arg(__id);
  3157. if (begin() == end() || *begin() != '}')
  3158. __format::__unmatched_left_brace_in_format_string();
  3159. _M_pc.advance_to(begin() + 1); // Move past '}'
  3160. }
  3161. constexpr virtual void _M_format_arg(size_t __id) = 0;
  3162. };
  3163. // Process a format string and format the arguments in the context.
  3164. template<typename _Out, typename _CharT>
  3165. class _Formatting_scanner : public _Scanner<_CharT>
  3166. {
  3167. public:
  3168. _Formatting_scanner(basic_format_context<_Out, _CharT>& __fc,
  3169. basic_string_view<_CharT> __str)
  3170. : _Scanner<_CharT>(__str), _M_fc(__fc)
  3171. { }
  3172. private:
  3173. basic_format_context<_Out, _CharT>& _M_fc;
  3174. using iterator = typename _Scanner<_CharT>::iterator;
  3175. constexpr void
  3176. _M_on_chars(iterator __last) override
  3177. {
  3178. basic_string_view<_CharT> __str(this->begin(), __last);
  3179. _M_fc.advance_to(__format::__write(_M_fc.out(), __str));
  3180. }
  3181. constexpr void
  3182. _M_format_arg(size_t __id) override
  3183. {
  3184. using _Context = basic_format_context<_Out, _CharT>;
  3185. using handle = typename basic_format_arg<_Context>::handle;
  3186. std::visit_format_arg([this](auto& __arg) {
  3187. using _Type = remove_reference_t<decltype(__arg)>;
  3188. using _Formatter = typename _Context::template formatter_type<_Type>;
  3189. if constexpr (is_same_v<_Type, monostate>)
  3190. __format::__invalid_arg_id_in_format_string();
  3191. else if constexpr (is_same_v<_Type, handle>)
  3192. __arg.format(this->_M_pc, this->_M_fc);
  3193. else if constexpr (is_default_constructible_v<_Formatter>)
  3194. {
  3195. _Formatter __f;
  3196. this->_M_pc.advance_to(__f.parse(this->_M_pc));
  3197. this->_M_fc.advance_to(__f.format(__arg, this->_M_fc));
  3198. }
  3199. else
  3200. static_assert(__format::__formattable_with<_Type, _Context>);
  3201. }, _M_fc.arg(__id));
  3202. }
  3203. };
  3204. // Validate a format string for Args.
  3205. template<typename _CharT, typename... _Args>
  3206. class _Checking_scanner : public _Scanner<_CharT>
  3207. {
  3208. static_assert(
  3209. (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
  3210. "std::formatter must be specialized for each type being formatted");
  3211. public:
  3212. constexpr
  3213. _Checking_scanner(basic_string_view<_CharT> __str)
  3214. : _Scanner<_CharT>(__str, sizeof...(_Args))
  3215. { }
  3216. private:
  3217. constexpr void
  3218. _M_format_arg(size_t __id) override
  3219. {
  3220. if constexpr (sizeof...(_Args) != 0)
  3221. {
  3222. if (__id < sizeof...(_Args))
  3223. {
  3224. _M_parse_format_spec<_Args...>(__id);
  3225. return;
  3226. }
  3227. }
  3228. __builtin_unreachable();
  3229. }
  3230. template<typename _Tp, typename... _OtherArgs>
  3231. constexpr void
  3232. _M_parse_format_spec(size_t __id)
  3233. {
  3234. if (__id == 0)
  3235. {
  3236. formatter<_Tp, _CharT> __f;
  3237. this->_M_pc.advance_to(__f.parse(this->_M_pc));
  3238. }
  3239. else if constexpr (sizeof...(_OtherArgs) != 0)
  3240. _M_parse_format_spec<_OtherArgs...>(__id - 1);
  3241. else
  3242. __builtin_unreachable();
  3243. }
  3244. };
  3245. template<typename _Out, typename _CharT, typename _Context>
  3246. inline _Out
  3247. __do_vformat_to(_Out __out, basic_string_view<_CharT> __fmt,
  3248. const basic_format_args<_Context>& __args,
  3249. const locale* __loc)
  3250. {
  3251. _Iter_sink<_CharT, _Out> __sink(std::move(__out));
  3252. _Sink_iter<_CharT> __sink_out;
  3253. if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
  3254. __sink_out = __out; // Already a sink iterator, safe to use post-move.
  3255. else
  3256. __sink_out = __sink.out();
  3257. auto __ctx = __loc == nullptr
  3258. ? _Context(__args, __sink_out)
  3259. : _Context(__args, __sink_out, *__loc);
  3260. _Formatting_scanner<_Sink_iter<_CharT>, _CharT> __scanner(__ctx, __fmt);
  3261. __scanner._M_scan();
  3262. if constexpr (is_same_v<_Out, _Sink_iter<_CharT>>)
  3263. return __ctx.out();
  3264. else
  3265. return std::move(__sink)._M_finish().out;
  3266. }
  3267. } // namespace __format
  3268. /// @endcond
  3269. template<typename _CharT, typename... _Args>
  3270. template<typename _Tp>
  3271. requires convertible_to<const _Tp&, basic_string_view<_CharT>>
  3272. consteval
  3273. basic_format_string<_CharT, _Args...>::
  3274. basic_format_string(const _Tp& __s)
  3275. : _M_str(__s)
  3276. {
  3277. __format::_Checking_scanner<_CharT, remove_cvref_t<_Args>...>
  3278. __scanner(_M_str);
  3279. __scanner._M_scan();
  3280. }
  3281. // [format.functions], formatting functions
  3282. template<typename _Out> requires output_iterator<_Out, const char&>
  3283. [[__gnu__::__always_inline__]]
  3284. inline _Out
  3285. vformat_to(_Out __out, string_view __fmt, format_args __args)
  3286. { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
  3287. template<typename _Out> requires output_iterator<_Out, const wchar_t&>
  3288. [[__gnu__::__always_inline__]]
  3289. inline _Out
  3290. vformat_to(_Out __out, wstring_view __fmt, wformat_args __args)
  3291. { return __format::__do_vformat_to(std::move(__out), __fmt, __args); }
  3292. template<typename _Out> requires output_iterator<_Out, const char&>
  3293. [[__gnu__::__always_inline__]]
  3294. inline _Out
  3295. vformat_to(_Out __out, const locale& __loc, string_view __fmt,
  3296. format_args __args)
  3297. { return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc); }
  3298. template<typename _Out> requires output_iterator<_Out, const wchar_t&>
  3299. [[__gnu__::__always_inline__]]
  3300. inline _Out
  3301. vformat_to(_Out __out, const locale& __loc, wstring_view __fmt,
  3302. wformat_args __args)
  3303. { return __format::__do_vformat_to(std::move(__out), __fmt, __args, &__loc); }
  3304. [[nodiscard]]
  3305. inline string
  3306. vformat(string_view __fmt, format_args __args)
  3307. {
  3308. __format::_Str_sink<char> __buf;
  3309. std::vformat_to(__buf.out(), __fmt, __args);
  3310. return std::move(__buf).get();
  3311. }
  3312. [[nodiscard]]
  3313. inline wstring
  3314. vformat(wstring_view __fmt, wformat_args __args)
  3315. {
  3316. __format::_Str_sink<wchar_t> __buf;
  3317. std::vformat_to(__buf.out(), __fmt, __args);
  3318. return std::move(__buf).get();
  3319. }
  3320. [[nodiscard]]
  3321. inline string
  3322. vformat(const locale& __loc, string_view __fmt, format_args __args)
  3323. {
  3324. __format::_Str_sink<char> __buf;
  3325. std::vformat_to(__buf.out(), __loc, __fmt, __args);
  3326. return std::move(__buf).get();
  3327. }
  3328. [[nodiscard]]
  3329. inline wstring
  3330. vformat(const locale& __loc, wstring_view __fmt, wformat_args __args)
  3331. {
  3332. __format::_Str_sink<wchar_t> __buf;
  3333. std::vformat_to(__buf.out(), __loc, __fmt, __args);
  3334. return std::move(__buf).get();
  3335. }
  3336. template<typename... _Args>
  3337. [[nodiscard]]
  3338. inline string
  3339. format(format_string<_Args...> __fmt, _Args&&... __args)
  3340. { return std::vformat(__fmt.get(), std::make_format_args(__args...)); }
  3341. template<typename... _Args>
  3342. [[nodiscard]]
  3343. inline wstring
  3344. format(wformat_string<_Args...> __fmt, _Args&&... __args)
  3345. { return std::vformat(__fmt.get(), std::make_wformat_args(__args...)); }
  3346. template<typename... _Args>
  3347. [[nodiscard]]
  3348. inline string
  3349. format(const locale& __loc, format_string<_Args...> __fmt,
  3350. _Args&&... __args)
  3351. {
  3352. return std::vformat(__loc, __fmt.get(),
  3353. std::make_format_args(__args...));
  3354. }
  3355. template<typename... _Args>
  3356. [[nodiscard]]
  3357. inline wstring
  3358. format(const locale& __loc, wformat_string<_Args...> __fmt,
  3359. _Args&&... __args)
  3360. {
  3361. return std::vformat(__loc, __fmt.get(),
  3362. std::make_wformat_args(__args...));
  3363. }
  3364. template<typename _Out, typename... _Args>
  3365. requires output_iterator<_Out, const char&>
  3366. inline _Out
  3367. format_to(_Out __out, format_string<_Args...> __fmt, _Args&&... __args)
  3368. {
  3369. return std::vformat_to(std::move(__out), __fmt.get(),
  3370. std::make_format_args(__args...));
  3371. }
  3372. template<typename _Out, typename... _Args>
  3373. requires output_iterator<_Out, const wchar_t&>
  3374. inline _Out
  3375. format_to(_Out __out, wformat_string<_Args...> __fmt, _Args&&... __args)
  3376. {
  3377. return std::vformat_to(std::move(__out), __fmt.get(),
  3378. std::make_wformat_args(__args...));
  3379. }
  3380. template<typename _Out, typename... _Args>
  3381. requires output_iterator<_Out, const char&>
  3382. inline _Out
  3383. format_to(_Out __out, const locale& __loc, format_string<_Args...> __fmt,
  3384. _Args&&... __args)
  3385. {
  3386. return std::vformat_to(std::move(__out), __loc, __fmt.get(),
  3387. std::make_format_args(__args...));
  3388. }
  3389. template<typename _Out, typename... _Args>
  3390. requires output_iterator<_Out, const wchar_t&>
  3391. inline _Out
  3392. format_to(_Out __out, const locale& __loc, wformat_string<_Args...> __fmt,
  3393. _Args&&... __args)
  3394. {
  3395. return std::vformat_to(std::move(__out), __loc, __fmt.get(),
  3396. std::make_wformat_args(__args...));
  3397. }
  3398. template<typename _Out, typename... _Args>
  3399. requires output_iterator<_Out, const char&>
  3400. inline format_to_n_result<_Out>
  3401. format_to_n(_Out __out, iter_difference_t<_Out> __n,
  3402. format_string<_Args...> __fmt, _Args&&... __args)
  3403. {
  3404. __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
  3405. std::vformat_to(__sink.out(), __fmt.get(),
  3406. std::make_format_args(__args...));
  3407. return std::move(__sink)._M_finish();
  3408. }
  3409. template<typename _Out, typename... _Args>
  3410. requires output_iterator<_Out, const wchar_t&>
  3411. inline format_to_n_result<_Out>
  3412. format_to_n(_Out __out, iter_difference_t<_Out> __n,
  3413. wformat_string<_Args...> __fmt, _Args&&... __args)
  3414. {
  3415. __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
  3416. std::vformat_to(__sink.out(), __fmt.get(),
  3417. std::make_wformat_args(__args...));
  3418. return std::move(__sink)._M_finish();
  3419. }
  3420. template<typename _Out, typename... _Args>
  3421. requires output_iterator<_Out, const char&>
  3422. inline format_to_n_result<_Out>
  3423. format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
  3424. format_string<_Args...> __fmt, _Args&&... __args)
  3425. {
  3426. __format::_Iter_sink<char, _Out> __sink(std::move(__out), __n);
  3427. std::vformat_to(__sink.out(), __loc, __fmt.get(),
  3428. std::make_format_args(__args...));
  3429. return std::move(__sink)._M_finish();
  3430. }
  3431. template<typename _Out, typename... _Args>
  3432. requires output_iterator<_Out, const wchar_t&>
  3433. inline format_to_n_result<_Out>
  3434. format_to_n(_Out __out, iter_difference_t<_Out> __n, const locale& __loc,
  3435. wformat_string<_Args...> __fmt, _Args&&... __args)
  3436. {
  3437. __format::_Iter_sink<wchar_t, _Out> __sink(std::move(__out), __n);
  3438. std::vformat_to(__sink.out(), __loc, __fmt.get(),
  3439. std::make_wformat_args(__args...));
  3440. return std::move(__sink)._M_finish();
  3441. }
  3442. /// @cond undocumented
  3443. namespace __format
  3444. {
  3445. #if 1
  3446. template<typename _CharT>
  3447. class _Counting_sink final : public _Iter_sink<_CharT, _CharT*>
  3448. {
  3449. public:
  3450. _Counting_sink() : _Iter_sink<_CharT, _CharT*>(nullptr, 0) { }
  3451. [[__gnu__::__always_inline__]]
  3452. size_t
  3453. count() const
  3454. { return this->_M_count + this->_M_used().size(); }
  3455. };
  3456. #else
  3457. template<typename _CharT>
  3458. class _Counting_sink : public _Buf_sink<_CharT>
  3459. {
  3460. size_t _M_count = 0;
  3461. void
  3462. _M_overflow() override
  3463. {
  3464. if (!std::is_constant_evaluated())
  3465. _M_count += this->_M_used().size();
  3466. this->_M_rewind();
  3467. }
  3468. public:
  3469. _Counting_sink() = default;
  3470. [[__gnu__::__always_inline__]]
  3471. size_t
  3472. count() noexcept
  3473. {
  3474. _Counting_sink::_M_overflow();
  3475. return _M_count;
  3476. }
  3477. };
  3478. #endif
  3479. } // namespace __format
  3480. /// @endcond
  3481. template<typename... _Args>
  3482. [[nodiscard]]
  3483. inline size_t
  3484. formatted_size(format_string<_Args...> __fmt, _Args&&... __args)
  3485. {
  3486. __format::_Counting_sink<char> __buf;
  3487. std::vformat_to(__buf.out(), __fmt.get(),
  3488. std::make_format_args(__args...));
  3489. return __buf.count();
  3490. }
  3491. template<typename... _Args>
  3492. [[nodiscard]]
  3493. inline size_t
  3494. formatted_size(wformat_string<_Args...> __fmt, _Args&&... __args)
  3495. {
  3496. __format::_Counting_sink<wchar_t> __buf;
  3497. std::vformat_to(__buf.out(), __fmt.get(),
  3498. std::make_wformat_args(__args...));
  3499. return __buf.count();
  3500. }
  3501. template<typename... _Args>
  3502. [[nodiscard]]
  3503. inline size_t
  3504. formatted_size(const locale& __loc, format_string<_Args...> __fmt,
  3505. _Args&&... __args)
  3506. {
  3507. __format::_Counting_sink<char> __buf;
  3508. std::vformat_to(__buf.out(), __loc, __fmt.get(),
  3509. std::make_format_args(__args...));
  3510. return __buf.count();
  3511. }
  3512. template<typename... _Args>
  3513. [[nodiscard]]
  3514. inline size_t
  3515. formatted_size(const locale& __loc, wformat_string<_Args...> __fmt,
  3516. _Args&&... __args)
  3517. {
  3518. __format::_Counting_sink<wchar_t> __buf;
  3519. std::vformat_to(__buf.out(), __loc, __fmt.get(),
  3520. std::make_wformat_args(__args...));
  3521. return __buf.count();
  3522. }
  3523. #if __cpp_lib_format_ranges
  3524. // [format.range], formatting of ranges
  3525. // [format.range.fmtkind], variable template format_kind
  3526. enum class range_format {
  3527. disabled,
  3528. map,
  3529. set,
  3530. sequence,
  3531. string,
  3532. debug_string
  3533. };
  3534. /// @cond undocumented
  3535. template<typename _Rg>
  3536. constexpr auto format_kind = not defined(format_kind<_Rg>);
  3537. template<typename _Tp>
  3538. consteval range_format
  3539. __fmt_kind()
  3540. {
  3541. using _Ref = ranges::range_reference_t<_Tp>;
  3542. if constexpr (is_same_v<remove_cvref_t<_Ref>, _Tp>)
  3543. return range_format::disabled;
  3544. else if constexpr (requires { typename _Tp::key_type; })
  3545. {
  3546. if constexpr (requires { typename _Tp::mapped_type; })
  3547. {
  3548. using _Up = remove_cvref_t<_Ref>;
  3549. if constexpr (__is_pair<_Up>)
  3550. return range_format::map;
  3551. else if constexpr (__is_specialization_of<_Up, tuple>)
  3552. if constexpr (tuple_size_v<_Up> == 2)
  3553. return range_format::map;
  3554. }
  3555. return range_format::set;
  3556. }
  3557. else
  3558. return range_format::sequence;
  3559. }
  3560. /// @endcond
  3561. /// A constant determining how a range should be formatted.
  3562. template<ranges::input_range _Rg> requires same_as<_Rg, remove_cvref_t<_Rg>>
  3563. constexpr range_format format_kind<_Rg> = __fmt_kind<_Rg>();
  3564. // [format.range.formatter], class template range_formatter
  3565. template<typename _Tp, typename _CharT = char>
  3566. requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
  3567. class range_formatter; // TODO
  3568. /// @cond undocumented
  3569. namespace __format
  3570. {
  3571. // [format.range.fmtdef], class template range-default-formatter
  3572. template<range_format _Kind, ranges::input_range _Rg, typename _CharT>
  3573. struct __range_default_formatter; // TODO
  3574. } // namespace __format
  3575. /// @endcond
  3576. // [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr],
  3577. // specializations for maps, sets, and strings
  3578. template<ranges::input_range _Rg, typename _CharT>
  3579. requires (format_kind<_Rg> != range_format::disabled)
  3580. && formattable<ranges::range_reference_t<_Rg>, _CharT>
  3581. struct formatter<_Rg, _CharT>
  3582. : __format::__range_default_formatter<format_kind<_Rg>, _Rg, _CharT>
  3583. { };
  3584. #endif // C++23 formatting ranges
  3585. _GLIBCXX_END_NAMESPACE_VERSION
  3586. } // namespace std
  3587. #endif // C++20
  3588. #endif // _GLIBCXX_FORMAT