format.h 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419
  1. /*
  2. Formatting library for C++
  3. Copyright (c) 2012 - present, Victor Zverovich
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. --- Optional exception to the license ---
  21. As an exception, if, as a result of your compiling your source code, portions
  22. of this Software are embedded into a machine-executable object form of such
  23. source code, you may redistribute such embedded portions in such object form
  24. without including the above copyright and permission notices.
  25. */
  26. #ifndef FMT_FORMAT_H_
  27. #define FMT_FORMAT_H_
  28. #ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
  29. # define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
  30. # define FMT_REMOVE_TRANSITIVE_INCLUDES
  31. #endif
  32. #include "base.h"
  33. #ifndef FMT_MODULE
  34. # include <cmath> // std::signbit
  35. # include <cstdint> // uint32_t
  36. # include <cstring> // std::memcpy
  37. # include <initializer_list> // std::initializer_list
  38. # include <limits> // std::numeric_limits
  39. # if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI)
  40. // Workaround for pre gcc 5 libstdc++.
  41. # include <memory> // std::allocator_traits
  42. # endif
  43. # include <stdexcept> // std::runtime_error
  44. # include <string> // std::string
  45. # include <system_error> // std::system_error
  46. // Checking FMT_CPLUSPLUS for warning suppression in MSVC.
  47. # if FMT_HAS_INCLUDE(<bit>) && FMT_CPLUSPLUS > 201703L
  48. # include <bit> // std::bit_cast
  49. # endif
  50. // libc++ supports string_view in pre-c++17.
  51. # if FMT_HAS_INCLUDE(<string_view>) && \
  52. (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))
  53. # include <string_view>
  54. # define FMT_USE_STRING_VIEW
  55. # endif
  56. #endif // FMT_MODULE
  57. #if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L
  58. # define FMT_INLINE_VARIABLE inline
  59. #else
  60. # define FMT_INLINE_VARIABLE
  61. #endif
  62. #ifndef FMT_NO_UNIQUE_ADDRESS
  63. # if FMT_CPLUSPLUS >= 202002L
  64. # if FMT_HAS_CPP_ATTRIBUTE(no_unique_address)
  65. # define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]]
  66. // VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485).
  67. # elif (FMT_MSC_VERSION >= 1929) && !FMT_CLANG_VERSION
  68. # define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
  69. # endif
  70. # endif
  71. #endif
  72. #ifndef FMT_NO_UNIQUE_ADDRESS
  73. # define FMT_NO_UNIQUE_ADDRESS
  74. #endif
  75. // Visibility when compiled as a shared library/object.
  76. #if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
  77. # define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value)
  78. #else
  79. # define FMT_SO_VISIBILITY(value)
  80. #endif
  81. #ifdef __has_builtin
  82. # define FMT_HAS_BUILTIN(x) __has_builtin(x)
  83. #else
  84. # define FMT_HAS_BUILTIN(x) 0
  85. #endif
  86. #if FMT_GCC_VERSION || FMT_CLANG_VERSION
  87. # define FMT_NOINLINE __attribute__((noinline))
  88. #else
  89. # define FMT_NOINLINE
  90. #endif
  91. #ifndef FMT_THROW
  92. # if FMT_EXCEPTIONS
  93. # if FMT_MSC_VERSION || defined(__NVCC__)
  94. FMT_BEGIN_NAMESPACE
  95. namespace detail {
  96. template <typename Exception> inline void do_throw(const Exception& x) {
  97. // Silence unreachable code warnings in MSVC and NVCC because these
  98. // are nearly impossible to fix in a generic code.
  99. volatile bool b = true;
  100. if (b) throw x;
  101. }
  102. } // namespace detail
  103. FMT_END_NAMESPACE
  104. # define FMT_THROW(x) detail::do_throw(x)
  105. # else
  106. # define FMT_THROW(x) throw x
  107. # endif
  108. # else
  109. # define FMT_THROW(x) \
  110. ::fmt::detail::assert_fail(__FILE__, __LINE__, (x).what())
  111. # endif
  112. #endif
  113. #ifndef FMT_MAYBE_UNUSED
  114. # if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused)
  115. # define FMT_MAYBE_UNUSED [[maybe_unused]]
  116. # else
  117. # define FMT_MAYBE_UNUSED
  118. # endif
  119. #endif
  120. #ifndef FMT_USE_USER_DEFINED_LITERALS
  121. // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
  122. //
  123. // GCC before 4.9 requires a space in `operator"" _a` which is invalid in later
  124. // compiler versions.
  125. # if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 409 || \
  126. FMT_MSC_VERSION >= 1900) && \
  127. (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
  128. # define FMT_USE_USER_DEFINED_LITERALS 1
  129. # else
  130. # define FMT_USE_USER_DEFINED_LITERALS 0
  131. # endif
  132. #endif
  133. // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
  134. // integer formatter template instantiations to just one by only using the
  135. // largest integer type. This results in a reduction in binary size but will
  136. // cause a decrease in integer formatting performance.
  137. #if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
  138. # define FMT_REDUCE_INT_INSTANTIATIONS 0
  139. #endif
  140. // __builtin_clz is broken in clang with Microsoft CodeGen:
  141. // https://github.com/fmtlib/fmt/issues/519.
  142. #if !FMT_MSC_VERSION
  143. # if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
  144. # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
  145. # endif
  146. # if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
  147. # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
  148. # endif
  149. #endif
  150. // __builtin_ctz is broken in Intel Compiler Classic on Windows:
  151. // https://github.com/fmtlib/fmt/issues/2510.
  152. #ifndef __ICL
  153. # if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION || \
  154. defined(__NVCOMPILER)
  155. # define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
  156. # endif
  157. # if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || \
  158. FMT_ICC_VERSION || defined(__NVCOMPILER)
  159. # define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
  160. # endif
  161. #endif
  162. #if FMT_MSC_VERSION
  163. # include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128
  164. #endif
  165. // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
  166. // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
  167. // MSVC intrinsics if the clz and clzll builtins are not available.
  168. #if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) && \
  169. !defined(FMT_BUILTIN_CTZLL)
  170. FMT_BEGIN_NAMESPACE
  171. namespace detail {
  172. // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
  173. # if !defined(__clang__)
  174. # pragma intrinsic(_BitScanForward)
  175. # pragma intrinsic(_BitScanReverse)
  176. # if defined(_WIN64)
  177. # pragma intrinsic(_BitScanForward64)
  178. # pragma intrinsic(_BitScanReverse64)
  179. # endif
  180. # endif
  181. inline auto clz(uint32_t x) -> int {
  182. unsigned long r = 0;
  183. _BitScanReverse(&r, x);
  184. FMT_ASSERT(x != 0, "");
  185. // Static analysis complains about using uninitialized data
  186. // "r", but the only way that can happen is if "x" is 0,
  187. // which the callers guarantee to not happen.
  188. FMT_MSC_WARNING(suppress : 6102)
  189. return 31 ^ static_cast<int>(r);
  190. }
  191. # define FMT_BUILTIN_CLZ(n) detail::clz(n)
  192. inline auto clzll(uint64_t x) -> int {
  193. unsigned long r = 0;
  194. # ifdef _WIN64
  195. _BitScanReverse64(&r, x);
  196. # else
  197. // Scan the high 32 bits.
  198. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
  199. return 63 ^ static_cast<int>(r + 32);
  200. // Scan the low 32 bits.
  201. _BitScanReverse(&r, static_cast<uint32_t>(x));
  202. # endif
  203. FMT_ASSERT(x != 0, "");
  204. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  205. return 63 ^ static_cast<int>(r);
  206. }
  207. # define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
  208. inline auto ctz(uint32_t x) -> int {
  209. unsigned long r = 0;
  210. _BitScanForward(&r, x);
  211. FMT_ASSERT(x != 0, "");
  212. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  213. return static_cast<int>(r);
  214. }
  215. # define FMT_BUILTIN_CTZ(n) detail::ctz(n)
  216. inline auto ctzll(uint64_t x) -> int {
  217. unsigned long r = 0;
  218. FMT_ASSERT(x != 0, "");
  219. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  220. # ifdef _WIN64
  221. _BitScanForward64(&r, x);
  222. # else
  223. // Scan the low 32 bits.
  224. if (_BitScanForward(&r, static_cast<uint32_t>(x))) return static_cast<int>(r);
  225. // Scan the high 32 bits.
  226. _BitScanForward(&r, static_cast<uint32_t>(x >> 32));
  227. r += 32;
  228. # endif
  229. return static_cast<int>(r);
  230. }
  231. # define FMT_BUILTIN_CTZLL(n) detail::ctzll(n)
  232. } // namespace detail
  233. FMT_END_NAMESPACE
  234. #endif
  235. FMT_BEGIN_NAMESPACE
  236. template <typename Char, typename Traits, typename Allocator>
  237. struct is_contiguous<std::basic_string<Char, Traits, Allocator>>
  238. : std::true_type {};
  239. namespace detail {
  240. FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) {
  241. ignore_unused(condition);
  242. #ifdef FMT_FUZZ
  243. if (condition) throw std::runtime_error("fuzzing limit reached");
  244. #endif
  245. }
  246. #if defined(FMT_USE_STRING_VIEW)
  247. template <typename Char> using std_string_view = std::basic_string_view<Char>;
  248. #else
  249. template <typename T> struct std_string_view {};
  250. #endif
  251. // Implementation of std::bit_cast for pre-C++20.
  252. template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) == sizeof(From))>
  253. FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
  254. #ifdef __cpp_lib_bit_cast
  255. if (is_constant_evaluated()) return std::bit_cast<To>(from);
  256. #endif
  257. auto to = To();
  258. // The cast suppresses a bogus -Wclass-memaccess on GCC.
  259. std::memcpy(static_cast<void*>(&to), &from, sizeof(to));
  260. return to;
  261. }
  262. inline auto is_big_endian() -> bool {
  263. #ifdef _WIN32
  264. return false;
  265. #elif defined(__BIG_ENDIAN__)
  266. return true;
  267. #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
  268. return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
  269. #else
  270. struct bytes {
  271. char data[sizeof(int)];
  272. };
  273. return bit_cast<bytes>(1).data[0] == 0;
  274. #endif
  275. }
  276. class uint128_fallback {
  277. private:
  278. uint64_t lo_, hi_;
  279. public:
  280. constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {}
  281. constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {}
  282. constexpr auto high() const noexcept -> uint64_t { return hi_; }
  283. constexpr auto low() const noexcept -> uint64_t { return lo_; }
  284. template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
  285. constexpr explicit operator T() const {
  286. return static_cast<T>(lo_);
  287. }
  288. friend constexpr auto operator==(const uint128_fallback& lhs,
  289. const uint128_fallback& rhs) -> bool {
  290. return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_;
  291. }
  292. friend constexpr auto operator!=(const uint128_fallback& lhs,
  293. const uint128_fallback& rhs) -> bool {
  294. return !(lhs == rhs);
  295. }
  296. friend constexpr auto operator>(const uint128_fallback& lhs,
  297. const uint128_fallback& rhs) -> bool {
  298. return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_;
  299. }
  300. friend constexpr auto operator|(const uint128_fallback& lhs,
  301. const uint128_fallback& rhs)
  302. -> uint128_fallback {
  303. return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_};
  304. }
  305. friend constexpr auto operator&(const uint128_fallback& lhs,
  306. const uint128_fallback& rhs)
  307. -> uint128_fallback {
  308. return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_};
  309. }
  310. friend constexpr auto operator~(const uint128_fallback& n)
  311. -> uint128_fallback {
  312. return {~n.hi_, ~n.lo_};
  313. }
  314. friend auto operator+(const uint128_fallback& lhs,
  315. const uint128_fallback& rhs) -> uint128_fallback {
  316. auto result = uint128_fallback(lhs);
  317. result += rhs;
  318. return result;
  319. }
  320. friend auto operator*(const uint128_fallback& lhs, uint32_t rhs)
  321. -> uint128_fallback {
  322. FMT_ASSERT(lhs.hi_ == 0, "");
  323. uint64_t hi = (lhs.lo_ >> 32) * rhs;
  324. uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs;
  325. uint64_t new_lo = (hi << 32) + lo;
  326. return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo};
  327. }
  328. friend auto operator-(const uint128_fallback& lhs, uint64_t rhs)
  329. -> uint128_fallback {
  330. return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs};
  331. }
  332. FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback {
  333. if (shift == 64) return {0, hi_};
  334. if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64);
  335. return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)};
  336. }
  337. FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback {
  338. if (shift == 64) return {lo_, 0};
  339. if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64);
  340. return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)};
  341. }
  342. FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& {
  343. return *this = *this >> shift;
  344. }
  345. FMT_CONSTEXPR void operator+=(uint128_fallback n) {
  346. uint64_t new_lo = lo_ + n.lo_;
  347. uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0);
  348. FMT_ASSERT(new_hi >= hi_, "");
  349. lo_ = new_lo;
  350. hi_ = new_hi;
  351. }
  352. FMT_CONSTEXPR void operator&=(uint128_fallback n) {
  353. lo_ &= n.lo_;
  354. hi_ &= n.hi_;
  355. }
  356. FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& {
  357. if (is_constant_evaluated()) {
  358. lo_ += n;
  359. hi_ += (lo_ < n ? 1 : 0);
  360. return *this;
  361. }
  362. #if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__)
  363. unsigned long long carry;
  364. lo_ = __builtin_addcll(lo_, n, 0, &carry);
  365. hi_ += carry;
  366. #elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__)
  367. unsigned long long result;
  368. auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result);
  369. lo_ = result;
  370. hi_ += carry;
  371. #elif defined(_MSC_VER) && defined(_M_X64)
  372. auto carry = _addcarry_u64(0, lo_, n, &lo_);
  373. _addcarry_u64(carry, hi_, 0, &hi_);
  374. #else
  375. lo_ += n;
  376. hi_ += (lo_ < n ? 1 : 0);
  377. #endif
  378. return *this;
  379. }
  380. };
  381. using uint128_t = conditional_t<FMT_USE_INT128, uint128_opt, uint128_fallback>;
  382. #ifdef UINTPTR_MAX
  383. using uintptr_t = ::uintptr_t;
  384. #else
  385. using uintptr_t = uint128_t;
  386. #endif
  387. // Returns the largest possible value for type T. Same as
  388. // std::numeric_limits<T>::max() but shorter and not affected by the max macro.
  389. template <typename T> constexpr auto max_value() -> T {
  390. return (std::numeric_limits<T>::max)();
  391. }
  392. template <typename T> constexpr auto num_bits() -> int {
  393. return std::numeric_limits<T>::digits;
  394. }
  395. // std::numeric_limits<T>::digits may return 0 for 128-bit ints.
  396. template <> constexpr auto num_bits<int128_opt>() -> int { return 128; }
  397. template <> constexpr auto num_bits<uint128_opt>() -> int { return 128; }
  398. template <> constexpr auto num_bits<uint128_fallback>() -> int { return 128; }
  399. // A heterogeneous bit_cast used for converting 96-bit long double to uint128_t
  400. // and 128-bit pointers to uint128_fallback.
  401. template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) > sizeof(From))>
  402. inline auto bit_cast(const From& from) -> To {
  403. constexpr auto size = static_cast<int>(sizeof(From) / sizeof(unsigned));
  404. struct data_t {
  405. unsigned value[static_cast<unsigned>(size)];
  406. } data = bit_cast<data_t>(from);
  407. auto result = To();
  408. if (const_check(is_big_endian())) {
  409. for (int i = 0; i < size; ++i)
  410. result = (result << num_bits<unsigned>()) | data.value[i];
  411. } else {
  412. for (int i = size - 1; i >= 0; --i)
  413. result = (result << num_bits<unsigned>()) | data.value[i];
  414. }
  415. return result;
  416. }
  417. template <typename UInt>
  418. FMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int {
  419. int lz = 0;
  420. constexpr UInt msb_mask = static_cast<UInt>(1) << (num_bits<UInt>() - 1);
  421. for (; (n & msb_mask) == 0; n <<= 1) lz++;
  422. return lz;
  423. }
  424. FMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int {
  425. #ifdef FMT_BUILTIN_CLZ
  426. if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n);
  427. #endif
  428. return countl_zero_fallback(n);
  429. }
  430. FMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int {
  431. #ifdef FMT_BUILTIN_CLZLL
  432. if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n);
  433. #endif
  434. return countl_zero_fallback(n);
  435. }
  436. FMT_INLINE void assume(bool condition) {
  437. (void)condition;
  438. #if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION
  439. __builtin_assume(condition);
  440. #elif FMT_GCC_VERSION
  441. if (!condition) __builtin_unreachable();
  442. #endif
  443. }
  444. // An approximation of iterator_t for pre-C++20 systems.
  445. template <typename T>
  446. using iterator_t = decltype(std::begin(std::declval<T&>()));
  447. template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>()));
  448. // A workaround for std::string not having mutable data() until C++17.
  449. template <typename Char>
  450. inline auto get_data(std::basic_string<Char>& s) -> Char* {
  451. return &s[0];
  452. }
  453. template <typename Container>
  454. inline auto get_data(Container& c) -> typename Container::value_type* {
  455. return c.data();
  456. }
  457. // Attempts to reserve space for n extra characters in the output range.
  458. // Returns a pointer to the reserved range or a reference to it.
  459. template <typename OutputIt,
  460. FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
  461. is_contiguous<typename OutputIt::container>::value)>
  462. #if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION
  463. __attribute__((no_sanitize("undefined")))
  464. #endif
  465. inline auto
  466. reserve(OutputIt it, size_t n) -> typename OutputIt::value_type* {
  467. auto& c = get_container(it);
  468. size_t size = c.size();
  469. c.resize(size + n);
  470. return get_data(c) + size;
  471. }
  472. template <typename T>
  473. inline auto reserve(basic_appender<T> it, size_t n) -> basic_appender<T> {
  474. buffer<T>& buf = get_container(it);
  475. buf.try_reserve(buf.size() + n);
  476. return it;
  477. }
  478. template <typename Iterator>
  479. constexpr auto reserve(Iterator& it, size_t) -> Iterator& {
  480. return it;
  481. }
  482. template <typename OutputIt>
  483. using reserve_iterator =
  484. remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
  485. template <typename T, typename OutputIt>
  486. constexpr auto to_pointer(OutputIt, size_t) -> T* {
  487. return nullptr;
  488. }
  489. template <typename T> auto to_pointer(basic_appender<T> it, size_t n) -> T* {
  490. buffer<T>& buf = get_container(it);
  491. auto size = buf.size();
  492. if (buf.capacity() < size + n) return nullptr;
  493. buf.try_resize(size + n);
  494. return buf.data() + size;
  495. }
  496. template <typename OutputIt,
  497. FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
  498. is_contiguous<typename OutputIt::container>::value)>
  499. inline auto base_iterator(OutputIt it,
  500. typename OutputIt::container_type::value_type*)
  501. -> OutputIt {
  502. return it;
  503. }
  504. template <typename Iterator>
  505. constexpr auto base_iterator(Iterator, Iterator it) -> Iterator {
  506. return it;
  507. }
  508. // <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n
  509. // instead (#1998).
  510. template <typename OutputIt, typename Size, typename T>
  511. FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)
  512. -> OutputIt {
  513. for (Size i = 0; i < count; ++i) *out++ = value;
  514. return out;
  515. }
  516. template <typename T, typename Size>
  517. FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {
  518. if (is_constant_evaluated()) {
  519. return fill_n<T*, Size, T>(out, count, value);
  520. }
  521. std::memset(out, value, to_unsigned(count));
  522. return out + count;
  523. }
  524. template <typename OutChar, typename InputIt, typename OutputIt>
  525. FMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end,
  526. OutputIt out) -> OutputIt {
  527. return copy<OutChar>(begin, end, out);
  528. }
  529. // A public domain branchless UTF-8 decoder by Christopher Wellons:
  530. // https://github.com/skeeto/branchless-utf8
  531. /* Decode the next character, c, from s, reporting errors in e.
  532. *
  533. * Since this is a branchless decoder, four bytes will be read from the
  534. * buffer regardless of the actual length of the next character. This
  535. * means the buffer _must_ have at least three bytes of zero padding
  536. * following the end of the data stream.
  537. *
  538. * Errors are reported in e, which will be non-zero if the parsed
  539. * character was somehow invalid: invalid byte sequence, non-canonical
  540. * encoding, or a surrogate half.
  541. *
  542. * The function returns a pointer to the next character. When an error
  543. * occurs, this pointer will be a guess that depends on the particular
  544. * error, but it will always advance at least one byte.
  545. */
  546. FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
  547. -> const char* {
  548. constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
  549. constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
  550. constexpr const int shiftc[] = {0, 18, 12, 6, 0};
  551. constexpr const int shifte[] = {0, 6, 4, 2, 0};
  552. int len = "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4"
  553. [static_cast<unsigned char>(*s) >> 3];
  554. // Compute the pointer to the next character early so that the next
  555. // iteration can start working on the next character. Neither Clang
  556. // nor GCC figure out this reordering on their own.
  557. const char* next = s + len + !len;
  558. using uchar = unsigned char;
  559. // Assume a four-byte character and load four bytes. Unused bits are
  560. // shifted out.
  561. *c = uint32_t(uchar(s[0]) & masks[len]) << 18;
  562. *c |= uint32_t(uchar(s[1]) & 0x3f) << 12;
  563. *c |= uint32_t(uchar(s[2]) & 0x3f) << 6;
  564. *c |= uint32_t(uchar(s[3]) & 0x3f) << 0;
  565. *c >>= shiftc[len];
  566. // Accumulate the various error conditions.
  567. *e = (*c < mins[len]) << 6; // non-canonical encoding
  568. *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half?
  569. *e |= (*c > 0x10FFFF) << 8; // out of range?
  570. *e |= (uchar(s[1]) & 0xc0) >> 2;
  571. *e |= (uchar(s[2]) & 0xc0) >> 4;
  572. *e |= uchar(s[3]) >> 6;
  573. *e ^= 0x2a; // top two bits of each tail byte correct?
  574. *e >>= shifte[len];
  575. return next;
  576. }
  577. constexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t();
  578. // Invokes f(cp, sv) for every code point cp in s with sv being the string view
  579. // corresponding to the code point. cp is invalid_code_point on error.
  580. template <typename F>
  581. FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
  582. auto decode = [f](const char* buf_ptr, const char* ptr) {
  583. auto cp = uint32_t();
  584. auto error = 0;
  585. auto end = utf8_decode(buf_ptr, &cp, &error);
  586. bool result = f(error ? invalid_code_point : cp,
  587. string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr)));
  588. return result ? (error ? buf_ptr + 1 : end) : nullptr;
  589. };
  590. auto p = s.data();
  591. const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars.
  592. if (s.size() >= block_size) {
  593. for (auto end = p + s.size() - block_size + 1; p < end;) {
  594. p = decode(p, p);
  595. if (!p) return;
  596. }
  597. }
  598. if (auto num_chars_left = s.data() + s.size() - p) {
  599. char buf[2 * block_size - 1] = {};
  600. copy<char>(p, p + num_chars_left, buf);
  601. const char* buf_ptr = buf;
  602. do {
  603. auto end = decode(buf_ptr, p);
  604. if (!end) return;
  605. p += end - buf_ptr;
  606. buf_ptr = end;
  607. } while (buf_ptr - buf < num_chars_left);
  608. }
  609. }
  610. template <typename Char>
  611. inline auto compute_width(basic_string_view<Char> s) -> size_t {
  612. return s.size();
  613. }
  614. // Computes approximate display width of a UTF-8 string.
  615. FMT_CONSTEXPR inline auto compute_width(string_view s) -> size_t {
  616. size_t num_code_points = 0;
  617. // It is not a lambda for compatibility with C++14.
  618. struct count_code_points {
  619. size_t* count;
  620. FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool {
  621. *count += detail::to_unsigned(
  622. 1 +
  623. (cp >= 0x1100 &&
  624. (cp <= 0x115f || // Hangul Jamo init. consonants
  625. cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET
  626. cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET
  627. // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:
  628. (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
  629. (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables
  630. (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs
  631. (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms
  632. (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms
  633. (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms
  634. (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms
  635. (cp >= 0x20000 && cp <= 0x2fffd) || // CJK
  636. (cp >= 0x30000 && cp <= 0x3fffd) ||
  637. // Miscellaneous Symbols and Pictographs + Emoticons:
  638. (cp >= 0x1f300 && cp <= 0x1f64f) ||
  639. // Supplemental Symbols and Pictographs:
  640. (cp >= 0x1f900 && cp <= 0x1f9ff))));
  641. return true;
  642. }
  643. };
  644. // We could avoid branches by using utf8_decode directly.
  645. for_each_codepoint(s, count_code_points{&num_code_points});
  646. return num_code_points;
  647. }
  648. template <typename Char>
  649. inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
  650. size_t size = s.size();
  651. return n < size ? n : size;
  652. }
  653. // Calculates the index of the nth code point in a UTF-8 string.
  654. inline auto code_point_index(string_view s, size_t n) -> size_t {
  655. size_t result = s.size();
  656. const char* begin = s.begin();
  657. for_each_codepoint(s, [begin, &n, &result](uint32_t, string_view sv) {
  658. if (n != 0) {
  659. --n;
  660. return true;
  661. }
  662. result = to_unsigned(sv.begin() - begin);
  663. return false;
  664. });
  665. return result;
  666. }
  667. template <typename T> struct is_integral : std::is_integral<T> {};
  668. template <> struct is_integral<int128_opt> : std::true_type {};
  669. template <> struct is_integral<uint128_t> : std::true_type {};
  670. template <typename T>
  671. using is_signed =
  672. std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
  673. std::is_same<T, int128_opt>::value>;
  674. template <typename T>
  675. using is_integer =
  676. bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
  677. !std::is_same<T, char>::value &&
  678. !std::is_same<T, wchar_t>::value>;
  679. #ifndef FMT_USE_FLOAT
  680. # define FMT_USE_FLOAT 1
  681. #endif
  682. #ifndef FMT_USE_DOUBLE
  683. # define FMT_USE_DOUBLE 1
  684. #endif
  685. #ifndef FMT_USE_LONG_DOUBLE
  686. # define FMT_USE_LONG_DOUBLE 1
  687. #endif
  688. #if defined(FMT_USE_FLOAT128)
  689. // Use the provided definition.
  690. #elif FMT_CLANG_VERSION && FMT_HAS_INCLUDE(<quadmath.h>)
  691. # define FMT_USE_FLOAT128 1
  692. #elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \
  693. !defined(__STRICT_ANSI__)
  694. # define FMT_USE_FLOAT128 1
  695. #else
  696. # define FMT_USE_FLOAT128 0
  697. #endif
  698. #if FMT_USE_FLOAT128
  699. using float128 = __float128;
  700. #else
  701. using float128 = void;
  702. #endif
  703. template <typename T> using is_float128 = std::is_same<T, float128>;
  704. template <typename T>
  705. using is_floating_point =
  706. bool_constant<std::is_floating_point<T>::value || is_float128<T>::value>;
  707. template <typename T, bool = std::is_floating_point<T>::value>
  708. struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
  709. sizeof(T) <= sizeof(double)> {};
  710. template <typename T> struct is_fast_float<T, false> : std::false_type {};
  711. template <typename T>
  712. using is_double_double = bool_constant<std::numeric_limits<T>::digits == 106>;
  713. #ifndef FMT_USE_FULL_CACHE_DRAGONBOX
  714. # define FMT_USE_FULL_CACHE_DRAGONBOX 0
  715. #endif
  716. template <typename T, typename Enable = void>
  717. struct is_locale : std::false_type {};
  718. template <typename T>
  719. struct is_locale<T, void_t<decltype(T::classic())>> : std::true_type {};
  720. } // namespace detail
  721. FMT_BEGIN_EXPORT
  722. // The number of characters to store in the basic_memory_buffer object itself
  723. // to avoid dynamic memory allocation.
  724. enum { inline_buffer_size = 500 };
  725. /**
  726. * A dynamically growing memory buffer for trivially copyable/constructible
  727. * types with the first `SIZE` elements stored in the object itself. Most
  728. * commonly used via the `memory_buffer` alias for `char`.
  729. *
  730. * **Example**:
  731. *
  732. * auto out = fmt::memory_buffer();
  733. * fmt::format_to(std::back_inserter(out), "The answer is {}.", 42);
  734. *
  735. * This will append "The answer is 42." to `out`. The buffer content can be
  736. * converted to `std::string` with `to_string(out)`.
  737. */
  738. template <typename T, size_t SIZE = inline_buffer_size,
  739. typename Allocator = std::allocator<T>>
  740. class basic_memory_buffer : public detail::buffer<T> {
  741. private:
  742. T store_[SIZE];
  743. // Don't inherit from Allocator to avoid generating type_info for it.
  744. FMT_NO_UNIQUE_ADDRESS Allocator alloc_;
  745. // Deallocate memory allocated by the buffer.
  746. FMT_CONSTEXPR20 void deallocate() {
  747. T* data = this->data();
  748. if (data != store_) alloc_.deallocate(data, this->capacity());
  749. }
  750. static FMT_CONSTEXPR20 void grow(detail::buffer<T>& buf, size_t size) {
  751. detail::abort_fuzzing_if(size > 5000);
  752. auto& self = static_cast<basic_memory_buffer&>(buf);
  753. const size_t max_size =
  754. std::allocator_traits<Allocator>::max_size(self.alloc_);
  755. size_t old_capacity = buf.capacity();
  756. size_t new_capacity = old_capacity + old_capacity / 2;
  757. if (size > new_capacity)
  758. new_capacity = size;
  759. else if (new_capacity > max_size)
  760. new_capacity = size > max_size ? size : max_size;
  761. T* old_data = buf.data();
  762. T* new_data = self.alloc_.allocate(new_capacity);
  763. // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481).
  764. detail::assume(buf.size() <= new_capacity);
  765. // The following code doesn't throw, so the raw pointer above doesn't leak.
  766. memcpy(new_data, old_data, buf.size() * sizeof(T));
  767. self.set(new_data, new_capacity);
  768. // deallocate must not throw according to the standard, but even if it does,
  769. // the buffer already uses the new storage and will deallocate it in
  770. // destructor.
  771. if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity);
  772. }
  773. public:
  774. using value_type = T;
  775. using const_reference = const T&;
  776. FMT_CONSTEXPR20 explicit basic_memory_buffer(
  777. const Allocator& alloc = Allocator())
  778. : detail::buffer<T>(grow), alloc_(alloc) {
  779. this->set(store_, SIZE);
  780. if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T());
  781. }
  782. FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
  783. private:
  784. // Move data from other to this buffer.
  785. FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {
  786. alloc_ = std::move(other.alloc_);
  787. T* data = other.data();
  788. size_t size = other.size(), capacity = other.capacity();
  789. if (data == other.store_) {
  790. this->set(store_, capacity);
  791. detail::copy<T>(other.store_, other.store_ + size, store_);
  792. } else {
  793. this->set(data, capacity);
  794. // Set pointer to the inline array so that delete is not called
  795. // when deallocating.
  796. other.set(other.store_, 0);
  797. other.clear();
  798. }
  799. this->resize(size);
  800. }
  801. public:
  802. /// Constructs a `basic_memory_buffer` object moving the content of the other
  803. /// object to it.
  804. FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept
  805. : detail::buffer<T>(grow) {
  806. move(other);
  807. }
  808. /// Moves the content of the other `basic_memory_buffer` object to this one.
  809. auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& {
  810. FMT_ASSERT(this != &other, "");
  811. deallocate();
  812. move(other);
  813. return *this;
  814. }
  815. // Returns a copy of the allocator associated with this buffer.
  816. auto get_allocator() const -> Allocator { return alloc_; }
  817. /// Resizes the buffer to contain `count` elements. If T is a POD type new
  818. /// elements may not be initialized.
  819. FMT_CONSTEXPR20 void resize(size_t count) { this->try_resize(count); }
  820. /// Increases the buffer capacity to `new_capacity`.
  821. void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
  822. using detail::buffer<T>::append;
  823. template <typename ContiguousRange>
  824. void append(const ContiguousRange& range) {
  825. append(range.data(), range.data() + range.size());
  826. }
  827. };
  828. using memory_buffer = basic_memory_buffer<char>;
  829. template <typename T, size_t SIZE, typename Allocator>
  830. struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
  831. };
  832. FMT_END_EXPORT
  833. namespace detail {
  834. FMT_API auto write_console(int fd, string_view text) -> bool;
  835. FMT_API void print(std::FILE*, string_view);
  836. } // namespace detail
  837. FMT_BEGIN_EXPORT
  838. // Suppress a misleading warning in older versions of clang.
  839. #if FMT_CLANG_VERSION
  840. # pragma clang diagnostic ignored "-Wweak-vtables"
  841. #endif
  842. /// An error reported from a formatting function.
  843. class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error {
  844. public:
  845. using std::runtime_error::runtime_error;
  846. };
  847. namespace detail_exported {
  848. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  849. template <typename Char, size_t N> struct fixed_string {
  850. constexpr fixed_string(const Char (&str)[N]) {
  851. detail::copy<Char, const Char*, Char*>(static_cast<const Char*>(str),
  852. str + N, data);
  853. }
  854. Char data[N] = {};
  855. };
  856. #endif
  857. // Converts a compile-time string to basic_string_view.
  858. template <typename Char, size_t N>
  859. constexpr auto compile_string_to_view(const Char (&s)[N])
  860. -> basic_string_view<Char> {
  861. // Remove trailing NUL character if needed. Won't be present if this is used
  862. // with a raw character array (i.e. not defined as a string).
  863. return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};
  864. }
  865. template <typename Char>
  866. constexpr auto compile_string_to_view(basic_string_view<Char> s)
  867. -> basic_string_view<Char> {
  868. return s;
  869. }
  870. } // namespace detail_exported
  871. // A generic formatting context with custom output iterator and character
  872. // (code unit) support. Char is the format string code unit type which can be
  873. // different from OutputIt::value_type.
  874. template <typename OutputIt, typename Char> class generic_context {
  875. private:
  876. OutputIt out_;
  877. basic_format_args<generic_context> args_;
  878. detail::locale_ref loc_;
  879. public:
  880. using char_type = Char;
  881. using iterator = OutputIt;
  882. using parse_context_type = basic_format_parse_context<Char>;
  883. template <typename T> using formatter_type = formatter<T, Char>;
  884. constexpr generic_context(OutputIt out,
  885. basic_format_args<generic_context> ctx_args,
  886. detail::locale_ref loc = {})
  887. : out_(out), args_(ctx_args), loc_(loc) {}
  888. generic_context(generic_context&&) = default;
  889. generic_context(const generic_context&) = delete;
  890. void operator=(const generic_context&) = delete;
  891. constexpr auto arg(int id) const -> basic_format_arg<generic_context> {
  892. return args_.get(id);
  893. }
  894. auto arg(basic_string_view<Char> name) -> basic_format_arg<generic_context> {
  895. return args_.get(name);
  896. }
  897. FMT_CONSTEXPR auto arg_id(basic_string_view<Char> name) -> int {
  898. return args_.get_id(name);
  899. }
  900. auto args() const -> const basic_format_args<generic_context>& {
  901. return args_;
  902. }
  903. FMT_CONSTEXPR auto out() -> iterator { return out_; }
  904. void advance_to(iterator it) {
  905. if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
  906. }
  907. FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
  908. };
  909. class loc_value {
  910. private:
  911. basic_format_arg<format_context> value_;
  912. public:
  913. template <typename T, FMT_ENABLE_IF(!detail::is_float128<T>::value)>
  914. loc_value(T value) : value_(detail::make_arg<format_context>(value)) {}
  915. template <typename T, FMT_ENABLE_IF(detail::is_float128<T>::value)>
  916. loc_value(T) {}
  917. template <typename Visitor> auto visit(Visitor&& vis) -> decltype(vis(0)) {
  918. return value_.visit(vis);
  919. }
  920. };
  921. // A locale facet that formats values in UTF-8.
  922. // It is parameterized on the locale to avoid the heavy <locale> include.
  923. template <typename Locale> class format_facet : public Locale::facet {
  924. private:
  925. std::string separator_;
  926. std::string grouping_;
  927. std::string decimal_point_;
  928. protected:
  929. virtual auto do_put(appender out, loc_value val,
  930. const format_specs& specs) const -> bool;
  931. public:
  932. static FMT_API typename Locale::id id;
  933. explicit format_facet(Locale& loc);
  934. explicit format_facet(string_view sep = "",
  935. std::initializer_list<unsigned char> g = {3},
  936. std::string decimal_point = ".")
  937. : separator_(sep.data(), sep.size()),
  938. grouping_(g.begin(), g.end()),
  939. decimal_point_(decimal_point) {}
  940. auto put(appender out, loc_value val, const format_specs& specs) const
  941. -> bool {
  942. return do_put(out, val, specs);
  943. }
  944. };
  945. FMT_END_EXPORT
  946. namespace detail {
  947. // Returns true if value is negative, false otherwise.
  948. // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
  949. template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
  950. constexpr auto is_negative(T value) -> bool {
  951. return value < 0;
  952. }
  953. template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
  954. constexpr auto is_negative(T) -> bool {
  955. return false;
  956. }
  957. template <typename T>
  958. FMT_CONSTEXPR auto is_supported_floating_point(T) -> bool {
  959. if (std::is_same<T, float>()) return FMT_USE_FLOAT;
  960. if (std::is_same<T, double>()) return FMT_USE_DOUBLE;
  961. if (std::is_same<T, long double>()) return FMT_USE_LONG_DOUBLE;
  962. return true;
  963. }
  964. // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
  965. // represent all values of an integral type T.
  966. template <typename T>
  967. using uint32_or_64_or_128_t =
  968. conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
  969. uint32_t,
  970. conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
  971. template <typename T>
  972. using uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;
  973. #define FMT_POWERS_OF_10(factor) \
  974. factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \
  975. (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \
  976. (factor) * 100000000, (factor) * 1000000000
  977. // Converts value in the range [0, 100) to a string.
  978. constexpr auto digits2(size_t value) -> const char* {
  979. // GCC generates slightly better code when value is pointer-size.
  980. return &"0001020304050607080910111213141516171819"
  981. "2021222324252627282930313233343536373839"
  982. "4041424344454647484950515253545556575859"
  983. "6061626364656667686970717273747576777879"
  984. "8081828384858687888990919293949596979899"[value * 2];
  985. }
  986. // Sign is a template parameter to workaround a bug in gcc 4.8.
  987. template <typename Char, typename Sign> constexpr auto sign(Sign s) -> Char {
  988. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604
  989. static_assert(std::is_same<Sign, sign_t>::value, "");
  990. #endif
  991. return static_cast<Char>("\0-+ "[s]);
  992. }
  993. template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
  994. int count = 1;
  995. for (;;) {
  996. // Integer division is slow so do it for a group of four digits instead
  997. // of for every digit. The idea comes from the talk by Alexandrescu
  998. // "Three Optimization Tips for C++". See speed-test for a comparison.
  999. if (n < 10) return count;
  1000. if (n < 100) return count + 1;
  1001. if (n < 1000) return count + 2;
  1002. if (n < 10000) return count + 3;
  1003. n /= 10000u;
  1004. count += 4;
  1005. }
  1006. }
  1007. #if FMT_USE_INT128
  1008. FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int {
  1009. return count_digits_fallback(n);
  1010. }
  1011. #endif
  1012. #ifdef FMT_BUILTIN_CLZLL
  1013. // It is a separate function rather than a part of count_digits to workaround
  1014. // the lack of static constexpr in constexpr functions.
  1015. inline auto do_count_digits(uint64_t n) -> int {
  1016. // This has comparable performance to the version by Kendall Willets
  1017. // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)
  1018. // but uses smaller tables.
  1019. // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
  1020. static constexpr uint8_t bsr2log10[] = {
  1021. 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
  1022. 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
  1023. 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
  1024. 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
  1025. auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];
  1026. static constexpr const uint64_t zero_or_powers_of_10[] = {
  1027. 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),
  1028. 10000000000000000000ULL};
  1029. return t - (n < zero_or_powers_of_10[t]);
  1030. }
  1031. #endif
  1032. // Returns the number of decimal digits in n. Leading zeros are not counted
  1033. // except for n == 0 in which case count_digits returns 1.
  1034. FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
  1035. #ifdef FMT_BUILTIN_CLZLL
  1036. if (!is_constant_evaluated()) return do_count_digits(n);
  1037. #endif
  1038. return count_digits_fallback(n);
  1039. }
  1040. // Counts the number of digits in n. BITS = log2(radix).
  1041. template <int BITS, typename UInt>
  1042. FMT_CONSTEXPR auto count_digits(UInt n) -> int {
  1043. #ifdef FMT_BUILTIN_CLZ
  1044. if (!is_constant_evaluated() && num_bits<UInt>() == 32)
  1045. return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
  1046. #endif
  1047. // Lambda avoids unreachable code warnings from NVHPC.
  1048. return [](UInt m) {
  1049. int num_digits = 0;
  1050. do {
  1051. ++num_digits;
  1052. } while ((m >>= BITS) != 0);
  1053. return num_digits;
  1054. }(n);
  1055. }
  1056. #ifdef FMT_BUILTIN_CLZ
  1057. // It is a separate function rather than a part of count_digits to workaround
  1058. // the lack of static constexpr in constexpr functions.
  1059. FMT_INLINE auto do_count_digits(uint32_t n) -> int {
  1060. // An optimization by Kendall Willets from https://bit.ly/3uOIQrB.
  1061. // This increments the upper 32 bits (log10(T) - 1) when >= T is added.
  1062. # define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T)
  1063. static constexpr uint64_t table[] = {
  1064. FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8
  1065. FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64
  1066. FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512
  1067. FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096
  1068. FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k
  1069. FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k
  1070. FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k
  1071. FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M
  1072. FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M
  1073. FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M
  1074. FMT_INC(1000000000), FMT_INC(1000000000) // 4B
  1075. };
  1076. auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];
  1077. return static_cast<int>((n + inc) >> 32);
  1078. }
  1079. #endif
  1080. // Optional version of count_digits for better performance on 32-bit platforms.
  1081. FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
  1082. #ifdef FMT_BUILTIN_CLZ
  1083. if (!is_constant_evaluated()) {
  1084. return do_count_digits(n);
  1085. }
  1086. #endif
  1087. return count_digits_fallback(n);
  1088. }
  1089. template <typename Int> constexpr auto digits10() noexcept -> int {
  1090. return std::numeric_limits<Int>::digits10;
  1091. }
  1092. template <> constexpr auto digits10<int128_opt>() noexcept -> int { return 38; }
  1093. template <> constexpr auto digits10<uint128_t>() noexcept -> int { return 38; }
  1094. template <typename Char> struct thousands_sep_result {
  1095. std::string grouping;
  1096. Char thousands_sep;
  1097. };
  1098. template <typename Char>
  1099. FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;
  1100. template <typename Char>
  1101. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {
  1102. auto result = thousands_sep_impl<char>(loc);
  1103. return {result.grouping, Char(result.thousands_sep)};
  1104. }
  1105. template <>
  1106. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {
  1107. return thousands_sep_impl<wchar_t>(loc);
  1108. }
  1109. template <typename Char>
  1110. FMT_API auto decimal_point_impl(locale_ref loc) -> Char;
  1111. template <typename Char> inline auto decimal_point(locale_ref loc) -> Char {
  1112. return Char(decimal_point_impl<char>(loc));
  1113. }
  1114. template <> inline auto decimal_point(locale_ref loc) -> wchar_t {
  1115. return decimal_point_impl<wchar_t>(loc);
  1116. }
  1117. // Compares two characters for equality.
  1118. template <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {
  1119. return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);
  1120. }
  1121. inline auto equal2(const char* lhs, const char* rhs) -> bool {
  1122. return memcmp(lhs, rhs, 2) == 0;
  1123. }
  1124. // Copies two characters from src to dst.
  1125. template <typename Char>
  1126. FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) {
  1127. if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) {
  1128. memcpy(dst, src, 2);
  1129. return;
  1130. }
  1131. *dst++ = static_cast<Char>(*src++);
  1132. *dst = static_cast<Char>(*src);
  1133. }
  1134. template <typename Iterator> struct format_decimal_result {
  1135. Iterator begin;
  1136. Iterator end;
  1137. };
  1138. // Formats a decimal unsigned integer value writing into out pointing to a
  1139. // buffer of specified size. The caller must ensure that the buffer is large
  1140. // enough.
  1141. template <typename Char, typename UInt>
  1142. FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
  1143. -> format_decimal_result<Char*> {
  1144. FMT_ASSERT(size >= count_digits(value), "invalid digit count");
  1145. out += size;
  1146. Char* end = out;
  1147. while (value >= 100) {
  1148. // Integer division is slow so do it for a group of two digits instead
  1149. // of for every digit. The idea comes from the talk by Alexandrescu
  1150. // "Three Optimization Tips for C++". See speed-test for a comparison.
  1151. out -= 2;
  1152. copy2(out, digits2(static_cast<size_t>(value % 100)));
  1153. value /= 100;
  1154. }
  1155. if (value < 10) {
  1156. *--out = static_cast<Char>('0' + value);
  1157. return {out, end};
  1158. }
  1159. out -= 2;
  1160. copy2(out, digits2(static_cast<size_t>(value)));
  1161. return {out, end};
  1162. }
  1163. template <typename Char, typename UInt, typename Iterator,
  1164. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
  1165. FMT_CONSTEXPR inline auto format_decimal(Iterator out, UInt value, int size)
  1166. -> format_decimal_result<Iterator> {
  1167. // Buffer is large enough to hold all digits (digits10 + 1).
  1168. Char buffer[digits10<UInt>() + 1] = {};
  1169. auto end = format_decimal(buffer, value, size).end;
  1170. return {out, detail::copy_noinline<Char>(buffer, end, out)};
  1171. }
  1172. template <unsigned BASE_BITS, typename Char, typename UInt>
  1173. FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits,
  1174. bool upper = false) -> Char* {
  1175. buffer += num_digits;
  1176. Char* end = buffer;
  1177. do {
  1178. const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
  1179. unsigned digit = static_cast<unsigned>(value & ((1 << BASE_BITS) - 1));
  1180. *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
  1181. : digits[digit]);
  1182. } while ((value >>= BASE_BITS) != 0);
  1183. return end;
  1184. }
  1185. template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
  1186. FMT_CONSTEXPR inline auto format_uint(It out, UInt value, int num_digits,
  1187. bool upper = false) -> It {
  1188. if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
  1189. format_uint<BASE_BITS>(ptr, value, num_digits, upper);
  1190. return out;
  1191. }
  1192. // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
  1193. char buffer[num_bits<UInt>() / BASE_BITS + 1] = {};
  1194. format_uint<BASE_BITS>(buffer, value, num_digits, upper);
  1195. return detail::copy_noinline<Char>(buffer, buffer + num_digits, out);
  1196. }
  1197. // A converter from UTF-8 to UTF-16.
  1198. class utf8_to_utf16 {
  1199. private:
  1200. basic_memory_buffer<wchar_t> buffer_;
  1201. public:
  1202. FMT_API explicit utf8_to_utf16(string_view s);
  1203. operator basic_string_view<wchar_t>() const { return {&buffer_[0], size()}; }
  1204. auto size() const -> size_t { return buffer_.size() - 1; }
  1205. auto c_str() const -> const wchar_t* { return &buffer_[0]; }
  1206. auto str() const -> std::wstring { return {&buffer_[0], size()}; }
  1207. };
  1208. enum class to_utf8_error_policy { abort, replace };
  1209. // A converter from UTF-16/UTF-32 (host endian) to UTF-8.
  1210. template <typename WChar, typename Buffer = memory_buffer> class to_utf8 {
  1211. private:
  1212. Buffer buffer_;
  1213. public:
  1214. to_utf8() {}
  1215. explicit to_utf8(basic_string_view<WChar> s,
  1216. to_utf8_error_policy policy = to_utf8_error_policy::abort) {
  1217. static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4,
  1218. "Expect utf16 or utf32");
  1219. if (!convert(s, policy))
  1220. FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? "invalid utf16"
  1221. : "invalid utf32"));
  1222. }
  1223. operator string_view() const { return string_view(&buffer_[0], size()); }
  1224. auto size() const -> size_t { return buffer_.size() - 1; }
  1225. auto c_str() const -> const char* { return &buffer_[0]; }
  1226. auto str() const -> std::string { return std::string(&buffer_[0], size()); }
  1227. // Performs conversion returning a bool instead of throwing exception on
  1228. // conversion error. This method may still throw in case of memory allocation
  1229. // error.
  1230. auto convert(basic_string_view<WChar> s,
  1231. to_utf8_error_policy policy = to_utf8_error_policy::abort)
  1232. -> bool {
  1233. if (!convert(buffer_, s, policy)) return false;
  1234. buffer_.push_back(0);
  1235. return true;
  1236. }
  1237. static auto convert(Buffer& buf, basic_string_view<WChar> s,
  1238. to_utf8_error_policy policy = to_utf8_error_policy::abort)
  1239. -> bool {
  1240. for (auto p = s.begin(); p != s.end(); ++p) {
  1241. uint32_t c = static_cast<uint32_t>(*p);
  1242. if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) {
  1243. // Handle a surrogate pair.
  1244. ++p;
  1245. if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) {
  1246. if (policy == to_utf8_error_policy::abort) return false;
  1247. buf.append(string_view("\xEF\xBF\xBD"));
  1248. --p;
  1249. } else {
  1250. c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;
  1251. }
  1252. } else if (c < 0x80) {
  1253. buf.push_back(static_cast<char>(c));
  1254. } else if (c < 0x800) {
  1255. buf.push_back(static_cast<char>(0xc0 | (c >> 6)));
  1256. buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
  1257. } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {
  1258. buf.push_back(static_cast<char>(0xe0 | (c >> 12)));
  1259. buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
  1260. buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
  1261. } else if (c >= 0x10000 && c <= 0x10ffff) {
  1262. buf.push_back(static_cast<char>(0xf0 | (c >> 18)));
  1263. buf.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));
  1264. buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
  1265. buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
  1266. } else {
  1267. return false;
  1268. }
  1269. }
  1270. return true;
  1271. }
  1272. };
  1273. // Computes 128-bit result of multiplication of two 64-bit unsigned integers.
  1274. inline auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback {
  1275. #if FMT_USE_INT128
  1276. auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
  1277. return {static_cast<uint64_t>(p >> 64), static_cast<uint64_t>(p)};
  1278. #elif defined(_MSC_VER) && defined(_M_X64)
  1279. auto hi = uint64_t();
  1280. auto lo = _umul128(x, y, &hi);
  1281. return {hi, lo};
  1282. #else
  1283. const uint64_t mask = static_cast<uint64_t>(max_value<uint32_t>());
  1284. uint64_t a = x >> 32;
  1285. uint64_t b = x & mask;
  1286. uint64_t c = y >> 32;
  1287. uint64_t d = y & mask;
  1288. uint64_t ac = a * c;
  1289. uint64_t bc = b * c;
  1290. uint64_t ad = a * d;
  1291. uint64_t bd = b * d;
  1292. uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask);
  1293. return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32),
  1294. (intermediate << 32) + (bd & mask)};
  1295. #endif
  1296. }
  1297. namespace dragonbox {
  1298. // Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from
  1299. // https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1.
  1300. inline auto floor_log10_pow2(int e) noexcept -> int {
  1301. FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent");
  1302. static_assert((-1 >> 1) == -1, "right shift is not arithmetic");
  1303. return (e * 315653) >> 20;
  1304. }
  1305. inline auto floor_log2_pow10(int e) noexcept -> int {
  1306. FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent");
  1307. return (e * 1741647) >> 19;
  1308. }
  1309. // Computes upper 64 bits of multiplication of two 64-bit unsigned integers.
  1310. inline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t {
  1311. #if FMT_USE_INT128
  1312. auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
  1313. return static_cast<uint64_t>(p >> 64);
  1314. #elif defined(_MSC_VER) && defined(_M_X64)
  1315. return __umulh(x, y);
  1316. #else
  1317. return umul128(x, y).high();
  1318. #endif
  1319. }
  1320. // Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a
  1321. // 128-bit unsigned integer.
  1322. inline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept
  1323. -> uint128_fallback {
  1324. uint128_fallback r = umul128(x, y.high());
  1325. r += umul128_upper64(x, y.low());
  1326. return r;
  1327. }
  1328. FMT_API auto get_cached_power(int k) noexcept -> uint128_fallback;
  1329. // Type-specific information that Dragonbox uses.
  1330. template <typename T, typename Enable = void> struct float_info;
  1331. template <> struct float_info<float> {
  1332. using carrier_uint = uint32_t;
  1333. static const int exponent_bits = 8;
  1334. static const int kappa = 1;
  1335. static const int big_divisor = 100;
  1336. static const int small_divisor = 10;
  1337. static const int min_k = -31;
  1338. static const int max_k = 46;
  1339. static const int shorter_interval_tie_lower_threshold = -35;
  1340. static const int shorter_interval_tie_upper_threshold = -35;
  1341. };
  1342. template <> struct float_info<double> {
  1343. using carrier_uint = uint64_t;
  1344. static const int exponent_bits = 11;
  1345. static const int kappa = 2;
  1346. static const int big_divisor = 1000;
  1347. static const int small_divisor = 100;
  1348. static const int min_k = -292;
  1349. static const int max_k = 341;
  1350. static const int shorter_interval_tie_lower_threshold = -77;
  1351. static const int shorter_interval_tie_upper_threshold = -77;
  1352. };
  1353. // An 80- or 128-bit floating point number.
  1354. template <typename T>
  1355. struct float_info<T, enable_if_t<std::numeric_limits<T>::digits == 64 ||
  1356. std::numeric_limits<T>::digits == 113 ||
  1357. is_float128<T>::value>> {
  1358. using carrier_uint = detail::uint128_t;
  1359. static const int exponent_bits = 15;
  1360. };
  1361. // A double-double floating point number.
  1362. template <typename T>
  1363. struct float_info<T, enable_if_t<is_double_double<T>::value>> {
  1364. using carrier_uint = detail::uint128_t;
  1365. };
  1366. template <typename T> struct decimal_fp {
  1367. using significand_type = typename float_info<T>::carrier_uint;
  1368. significand_type significand;
  1369. int exponent;
  1370. };
  1371. template <typename T> FMT_API auto to_decimal(T x) noexcept -> decimal_fp<T>;
  1372. } // namespace dragonbox
  1373. // Returns true iff Float has the implicit bit which is not stored.
  1374. template <typename Float> constexpr auto has_implicit_bit() -> bool {
  1375. // An 80-bit FP number has a 64-bit significand an no implicit bit.
  1376. return std::numeric_limits<Float>::digits != 64;
  1377. }
  1378. // Returns the number of significand bits stored in Float. The implicit bit is
  1379. // not counted since it is not stored.
  1380. template <typename Float> constexpr auto num_significand_bits() -> int {
  1381. // std::numeric_limits may not support __float128.
  1382. return is_float128<Float>() ? 112
  1383. : (std::numeric_limits<Float>::digits -
  1384. (has_implicit_bit<Float>() ? 1 : 0));
  1385. }
  1386. template <typename Float>
  1387. constexpr auto exponent_mask() ->
  1388. typename dragonbox::float_info<Float>::carrier_uint {
  1389. using float_uint = typename dragonbox::float_info<Float>::carrier_uint;
  1390. return ((float_uint(1) << dragonbox::float_info<Float>::exponent_bits) - 1)
  1391. << num_significand_bits<Float>();
  1392. }
  1393. template <typename Float> constexpr auto exponent_bias() -> int {
  1394. // std::numeric_limits may not support __float128.
  1395. return is_float128<Float>() ? 16383
  1396. : std::numeric_limits<Float>::max_exponent - 1;
  1397. }
  1398. // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
  1399. template <typename Char, typename It>
  1400. FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It {
  1401. FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
  1402. if (exp < 0) {
  1403. *it++ = static_cast<Char>('-');
  1404. exp = -exp;
  1405. } else {
  1406. *it++ = static_cast<Char>('+');
  1407. }
  1408. if (exp >= 100) {
  1409. const char* top = digits2(to_unsigned(exp / 100));
  1410. if (exp >= 1000) *it++ = static_cast<Char>(top[0]);
  1411. *it++ = static_cast<Char>(top[1]);
  1412. exp %= 100;
  1413. }
  1414. const char* d = digits2(to_unsigned(exp));
  1415. *it++ = static_cast<Char>(d[0]);
  1416. *it++ = static_cast<Char>(d[1]);
  1417. return it;
  1418. }
  1419. // A floating-point number f * pow(2, e) where F is an unsigned type.
  1420. template <typename F> struct basic_fp {
  1421. F f;
  1422. int e;
  1423. static constexpr const int num_significand_bits =
  1424. static_cast<int>(sizeof(F) * num_bits<unsigned char>());
  1425. constexpr basic_fp() : f(0), e(0) {}
  1426. constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
  1427. // Constructs fp from an IEEE754 floating-point number.
  1428. template <typename Float> FMT_CONSTEXPR basic_fp(Float n) { assign(n); }
  1429. // Assigns n to this and return true iff predecessor is closer than successor.
  1430. template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
  1431. FMT_CONSTEXPR auto assign(Float n) -> bool {
  1432. static_assert(std::numeric_limits<Float>::digits <= 113, "unsupported FP");
  1433. // Assume Float is in the format [sign][exponent][significand].
  1434. using carrier_uint = typename dragonbox::float_info<Float>::carrier_uint;
  1435. const auto num_float_significand_bits =
  1436. detail::num_significand_bits<Float>();
  1437. const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
  1438. const auto significand_mask = implicit_bit - 1;
  1439. auto u = bit_cast<carrier_uint>(n);
  1440. f = static_cast<F>(u & significand_mask);
  1441. auto biased_e = static_cast<int>((u & exponent_mask<Float>()) >>
  1442. num_float_significand_bits);
  1443. // The predecessor is closer if n is a normalized power of 2 (f == 0)
  1444. // other than the smallest normalized number (biased_e > 1).
  1445. auto is_predecessor_closer = f == 0 && biased_e > 1;
  1446. if (biased_e == 0)
  1447. biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
  1448. else if (has_implicit_bit<Float>())
  1449. f += static_cast<F>(implicit_bit);
  1450. e = biased_e - exponent_bias<Float>() - num_float_significand_bits;
  1451. if (!has_implicit_bit<Float>()) ++e;
  1452. return is_predecessor_closer;
  1453. }
  1454. template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
  1455. FMT_CONSTEXPR auto assign(Float n) -> bool {
  1456. static_assert(std::numeric_limits<double>::is_iec559, "unsupported FP");
  1457. return assign(static_cast<double>(n));
  1458. }
  1459. };
  1460. using fp = basic_fp<unsigned long long>;
  1461. // Normalizes the value converted from double and multiplied by (1 << SHIFT).
  1462. template <int SHIFT = 0, typename F>
  1463. FMT_CONSTEXPR auto normalize(basic_fp<F> value) -> basic_fp<F> {
  1464. // Handle subnormals.
  1465. const auto implicit_bit = F(1) << num_significand_bits<double>();
  1466. const auto shifted_implicit_bit = implicit_bit << SHIFT;
  1467. while ((value.f & shifted_implicit_bit) == 0) {
  1468. value.f <<= 1;
  1469. --value.e;
  1470. }
  1471. // Subtract 1 to account for hidden bit.
  1472. const auto offset = basic_fp<F>::num_significand_bits -
  1473. num_significand_bits<double>() - SHIFT - 1;
  1474. value.f <<= offset;
  1475. value.e -= offset;
  1476. return value;
  1477. }
  1478. // Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
  1479. FMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t {
  1480. #if FMT_USE_INT128
  1481. auto product = static_cast<__uint128_t>(lhs) * rhs;
  1482. auto f = static_cast<uint64_t>(product >> 64);
  1483. return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
  1484. #else
  1485. // Multiply 32-bit parts of significands.
  1486. uint64_t mask = (1ULL << 32) - 1;
  1487. uint64_t a = lhs >> 32, b = lhs & mask;
  1488. uint64_t c = rhs >> 32, d = rhs & mask;
  1489. uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
  1490. // Compute mid 64-bit of result and round.
  1491. uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
  1492. return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
  1493. #endif
  1494. }
  1495. FMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp {
  1496. return {multiply(x.f, y.f), x.e + y.e + 64};
  1497. }
  1498. template <typename T, bool doublish = num_bits<T>() == num_bits<double>()>
  1499. using convert_float_result =
  1500. conditional_t<std::is_same<T, float>::value || doublish, double, T>;
  1501. template <typename T>
  1502. constexpr auto convert_float(T value) -> convert_float_result<T> {
  1503. return static_cast<convert_float_result<T>>(value);
  1504. }
  1505. template <typename Char, typename OutputIt>
  1506. FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n, const fill_t& fill)
  1507. -> OutputIt {
  1508. auto fill_size = fill.size();
  1509. if (fill_size == 1) return detail::fill_n(it, n, fill.template get<Char>());
  1510. if (const Char* data = fill.template data<Char>()) {
  1511. for (size_t i = 0; i < n; ++i) it = copy<Char>(data, data + fill_size, it);
  1512. }
  1513. return it;
  1514. }
  1515. // Writes the output of f, padded according to format specifications in specs.
  1516. // size: output size in code units.
  1517. // width: output display width in (terminal) column positions.
  1518. template <typename Char, align::type align = align::left, typename OutputIt,
  1519. typename F>
  1520. FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs,
  1521. size_t size, size_t width, F&& f) -> OutputIt {
  1522. static_assert(align == align::left || align == align::right, "");
  1523. unsigned spec_width = to_unsigned(specs.width);
  1524. size_t padding = spec_width > width ? spec_width - width : 0;
  1525. // Shifts are encoded as string literals because static constexpr is not
  1526. // supported in constexpr functions.
  1527. auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01";
  1528. size_t left_padding = padding >> shifts[specs.align];
  1529. size_t right_padding = padding - left_padding;
  1530. auto it = reserve(out, size + padding * specs.fill.size());
  1531. if (left_padding != 0) it = fill<Char>(it, left_padding, specs.fill);
  1532. it = f(it);
  1533. if (right_padding != 0) it = fill<Char>(it, right_padding, specs.fill);
  1534. return base_iterator(out, it);
  1535. }
  1536. template <typename Char, align::type align = align::left, typename OutputIt,
  1537. typename F>
  1538. constexpr auto write_padded(OutputIt out, const format_specs& specs,
  1539. size_t size, F&& f) -> OutputIt {
  1540. return write_padded<Char, align>(out, specs, size, size, f);
  1541. }
  1542. template <typename Char, align::type align = align::left, typename OutputIt>
  1543. FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,
  1544. const format_specs& specs = {}) -> OutputIt {
  1545. return write_padded<Char, align>(
  1546. out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {
  1547. const char* data = bytes.data();
  1548. return copy<Char>(data, data + bytes.size(), it);
  1549. });
  1550. }
  1551. template <typename Char, typename OutputIt, typename UIntPtr>
  1552. auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs)
  1553. -> OutputIt {
  1554. int num_digits = count_digits<4>(value);
  1555. auto size = to_unsigned(num_digits) + size_t(2);
  1556. auto write = [=](reserve_iterator<OutputIt> it) {
  1557. *it++ = static_cast<Char>('0');
  1558. *it++ = static_cast<Char>('x');
  1559. return format_uint<4, Char>(it, value, num_digits);
  1560. };
  1561. return specs ? write_padded<Char, align::right>(out, *specs, size, write)
  1562. : base_iterator(out, write(reserve(out, size)));
  1563. }
  1564. // Returns true iff the code point cp is printable.
  1565. FMT_API auto is_printable(uint32_t cp) -> bool;
  1566. inline auto needs_escape(uint32_t cp) -> bool {
  1567. return cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\' ||
  1568. !is_printable(cp);
  1569. }
  1570. template <typename Char> struct find_escape_result {
  1571. const Char* begin;
  1572. const Char* end;
  1573. uint32_t cp;
  1574. };
  1575. template <typename Char>
  1576. auto find_escape(const Char* begin, const Char* end)
  1577. -> find_escape_result<Char> {
  1578. for (; begin != end; ++begin) {
  1579. uint32_t cp = static_cast<unsigned_char<Char>>(*begin);
  1580. if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue;
  1581. if (needs_escape(cp)) return {begin, begin + 1, cp};
  1582. }
  1583. return {begin, nullptr, 0};
  1584. }
  1585. inline auto find_escape(const char* begin, const char* end)
  1586. -> find_escape_result<char> {
  1587. if (!use_utf8()) return find_escape<char>(begin, end);
  1588. auto result = find_escape_result<char>{end, nullptr, 0};
  1589. for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
  1590. [&](uint32_t cp, string_view sv) {
  1591. if (needs_escape(cp)) {
  1592. result = {sv.begin(), sv.end(), cp};
  1593. return false;
  1594. }
  1595. return true;
  1596. });
  1597. return result;
  1598. }
  1599. #define FMT_STRING_IMPL(s, base, explicit) \
  1600. [] { \
  1601. /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
  1602. /* Use a macro-like name to avoid shadowing warnings. */ \
  1603. struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \
  1604. using char_type FMT_MAYBE_UNUSED = fmt::remove_cvref_t<decltype(s[0])>; \
  1605. FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \
  1606. operator fmt::basic_string_view<char_type>() const { \
  1607. return fmt::detail_exported::compile_string_to_view<char_type>(s); \
  1608. } \
  1609. }; \
  1610. return FMT_COMPILE_STRING(); \
  1611. }()
  1612. /**
  1613. * Constructs a compile-time format string from a string literal `s`.
  1614. *
  1615. * **Example**:
  1616. *
  1617. * // A compile-time error because 'd' is an invalid specifier for strings.
  1618. * std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
  1619. */
  1620. #define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string, )
  1621. template <size_t width, typename Char, typename OutputIt>
  1622. auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt {
  1623. *out++ = static_cast<Char>('\\');
  1624. *out++ = static_cast<Char>(prefix);
  1625. Char buf[width];
  1626. fill_n(buf, width, static_cast<Char>('0'));
  1627. format_uint<4>(buf, cp, width);
  1628. return copy<Char>(buf, buf + width, out);
  1629. }
  1630. template <typename OutputIt, typename Char>
  1631. auto write_escaped_cp(OutputIt out, const find_escape_result<Char>& escape)
  1632. -> OutputIt {
  1633. auto c = static_cast<Char>(escape.cp);
  1634. switch (escape.cp) {
  1635. case '\n':
  1636. *out++ = static_cast<Char>('\\');
  1637. c = static_cast<Char>('n');
  1638. break;
  1639. case '\r':
  1640. *out++ = static_cast<Char>('\\');
  1641. c = static_cast<Char>('r');
  1642. break;
  1643. case '\t':
  1644. *out++ = static_cast<Char>('\\');
  1645. c = static_cast<Char>('t');
  1646. break;
  1647. case '"':
  1648. FMT_FALLTHROUGH;
  1649. case '\'':
  1650. FMT_FALLTHROUGH;
  1651. case '\\':
  1652. *out++ = static_cast<Char>('\\');
  1653. break;
  1654. default:
  1655. if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp);
  1656. if (escape.cp < 0x10000)
  1657. return write_codepoint<4, Char>(out, 'u', escape.cp);
  1658. if (escape.cp < 0x110000)
  1659. return write_codepoint<8, Char>(out, 'U', escape.cp);
  1660. for (Char escape_char : basic_string_view<Char>(
  1661. escape.begin, to_unsigned(escape.end - escape.begin))) {
  1662. out = write_codepoint<2, Char>(out, 'x',
  1663. static_cast<uint32_t>(escape_char) & 0xFF);
  1664. }
  1665. return out;
  1666. }
  1667. *out++ = c;
  1668. return out;
  1669. }
  1670. template <typename Char, typename OutputIt>
  1671. auto write_escaped_string(OutputIt out, basic_string_view<Char> str)
  1672. -> OutputIt {
  1673. *out++ = static_cast<Char>('"');
  1674. auto begin = str.begin(), end = str.end();
  1675. do {
  1676. auto escape = find_escape(begin, end);
  1677. out = copy<Char>(begin, escape.begin, out);
  1678. begin = escape.end;
  1679. if (!begin) break;
  1680. out = write_escaped_cp<OutputIt, Char>(out, escape);
  1681. } while (begin != end);
  1682. *out++ = static_cast<Char>('"');
  1683. return out;
  1684. }
  1685. template <typename Char, typename OutputIt>
  1686. auto write_escaped_char(OutputIt out, Char v) -> OutputIt {
  1687. Char v_array[1] = {v};
  1688. *out++ = static_cast<Char>('\'');
  1689. if ((needs_escape(static_cast<uint32_t>(v)) && v != static_cast<Char>('"')) ||
  1690. v == static_cast<Char>('\'')) {
  1691. out = write_escaped_cp(out,
  1692. find_escape_result<Char>{v_array, v_array + 1,
  1693. static_cast<uint32_t>(v)});
  1694. } else {
  1695. *out++ = v;
  1696. }
  1697. *out++ = static_cast<Char>('\'');
  1698. return out;
  1699. }
  1700. template <typename Char, typename OutputIt>
  1701. FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
  1702. const format_specs& specs) -> OutputIt {
  1703. bool is_debug = specs.type == presentation_type::debug;
  1704. return write_padded<Char>(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
  1705. if (is_debug) return write_escaped_char(it, value);
  1706. *it++ = value;
  1707. return it;
  1708. });
  1709. }
  1710. template <typename Char, typename OutputIt>
  1711. FMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs,
  1712. locale_ref loc = {}) -> OutputIt {
  1713. // char is formatted as unsigned char for consistency across platforms.
  1714. using unsigned_type =
  1715. conditional_t<std::is_same<Char, char>::value, unsigned char, unsigned>;
  1716. return check_char_specs(specs)
  1717. ? write_char<Char>(out, value, specs)
  1718. : write<Char>(out, static_cast<unsigned_type>(value), specs, loc);
  1719. }
  1720. // Data for write_int that doesn't depend on output iterator type. It is used to
  1721. // avoid template code bloat.
  1722. template <typename Char> struct write_int_data {
  1723. size_t size;
  1724. size_t padding;
  1725. FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix,
  1726. const format_specs& specs)
  1727. : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {
  1728. if (specs.align == align::numeric) {
  1729. auto width = to_unsigned(specs.width);
  1730. if (width > size) {
  1731. padding = width - size;
  1732. size = width;
  1733. }
  1734. } else if (specs.precision > num_digits) {
  1735. size = (prefix >> 24) + to_unsigned(specs.precision);
  1736. padding = to_unsigned(specs.precision - num_digits);
  1737. }
  1738. }
  1739. };
  1740. // Writes an integer in the format
  1741. // <left-padding><prefix><numeric-padding><digits><right-padding>
  1742. // where <digits> are written by write_digits(it).
  1743. // prefix contains chars in three lower bytes and the size in the fourth byte.
  1744. template <typename Char, typename OutputIt, typename W>
  1745. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits,
  1746. unsigned prefix,
  1747. const format_specs& specs,
  1748. W write_digits) -> OutputIt {
  1749. // Slightly faster check for specs.width == 0 && specs.precision == -1.
  1750. if ((specs.width | (specs.precision + 1)) == 0) {
  1751. auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));
  1752. if (prefix != 0) {
  1753. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1754. *it++ = static_cast<Char>(p & 0xff);
  1755. }
  1756. return base_iterator(out, write_digits(it));
  1757. }
  1758. auto data = write_int_data<Char>(num_digits, prefix, specs);
  1759. return write_padded<Char, align::right>(
  1760. out, specs, data.size, [=](reserve_iterator<OutputIt> it) {
  1761. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1762. *it++ = static_cast<Char>(p & 0xff);
  1763. it = detail::fill_n(it, data.padding, static_cast<Char>('0'));
  1764. return write_digits(it);
  1765. });
  1766. }
  1767. template <typename Char> class digit_grouping {
  1768. private:
  1769. std::string grouping_;
  1770. std::basic_string<Char> thousands_sep_;
  1771. struct next_state {
  1772. std::string::const_iterator group;
  1773. int pos;
  1774. };
  1775. auto initial_state() const -> next_state { return {grouping_.begin(), 0}; }
  1776. // Returns the next digit group separator position.
  1777. auto next(next_state& state) const -> int {
  1778. if (thousands_sep_.empty()) return max_value<int>();
  1779. if (state.group == grouping_.end()) return state.pos += grouping_.back();
  1780. if (*state.group <= 0 || *state.group == max_value<char>())
  1781. return max_value<int>();
  1782. state.pos += *state.group++;
  1783. return state.pos;
  1784. }
  1785. public:
  1786. explicit digit_grouping(locale_ref loc, bool localized = true) {
  1787. if (!localized) return;
  1788. auto sep = thousands_sep<Char>(loc);
  1789. grouping_ = sep.grouping;
  1790. if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep);
  1791. }
  1792. digit_grouping(std::string grouping, std::basic_string<Char> sep)
  1793. : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {}
  1794. auto has_separator() const -> bool { return !thousands_sep_.empty(); }
  1795. auto count_separators(int num_digits) const -> int {
  1796. int count = 0;
  1797. auto state = initial_state();
  1798. while (num_digits > next(state)) ++count;
  1799. return count;
  1800. }
  1801. // Applies grouping to digits and write the output to out.
  1802. template <typename Out, typename C>
  1803. auto apply(Out out, basic_string_view<C> digits) const -> Out {
  1804. auto num_digits = static_cast<int>(digits.size());
  1805. auto separators = basic_memory_buffer<int>();
  1806. separators.push_back(0);
  1807. auto state = initial_state();
  1808. while (int i = next(state)) {
  1809. if (i >= num_digits) break;
  1810. separators.push_back(i);
  1811. }
  1812. for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);
  1813. i < num_digits; ++i) {
  1814. if (num_digits - i == separators[sep_index]) {
  1815. out = copy<Char>(thousands_sep_.data(),
  1816. thousands_sep_.data() + thousands_sep_.size(), out);
  1817. --sep_index;
  1818. }
  1819. *out++ = static_cast<Char>(digits[to_unsigned(i)]);
  1820. }
  1821. return out;
  1822. }
  1823. };
  1824. FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {
  1825. prefix |= prefix != 0 ? value << 8 : value;
  1826. prefix += (1u + (value > 0xff ? 1 : 0)) << 24;
  1827. }
  1828. // Writes a decimal integer with digit grouping.
  1829. template <typename OutputIt, typename UInt, typename Char>
  1830. auto write_int(OutputIt out, UInt value, unsigned prefix,
  1831. const format_specs& specs, const digit_grouping<Char>& grouping)
  1832. -> OutputIt {
  1833. static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, "");
  1834. int num_digits = 0;
  1835. auto buffer = memory_buffer();
  1836. switch (specs.type) {
  1837. default:
  1838. FMT_ASSERT(false, "");
  1839. FMT_FALLTHROUGH;
  1840. case presentation_type::none:
  1841. case presentation_type::dec:
  1842. num_digits = count_digits(value);
  1843. format_decimal<char>(appender(buffer), value, num_digits);
  1844. break;
  1845. case presentation_type::hex:
  1846. if (specs.alt)
  1847. prefix_append(prefix, unsigned(specs.upper ? 'X' : 'x') << 8 | '0');
  1848. num_digits = count_digits<4>(value);
  1849. format_uint<4, char>(appender(buffer), value, num_digits, specs.upper);
  1850. break;
  1851. case presentation_type::oct:
  1852. num_digits = count_digits<3>(value);
  1853. // Octal prefix '0' is counted as a digit, so only add it if precision
  1854. // is not greater than the number of digits.
  1855. if (specs.alt && specs.precision <= num_digits && value != 0)
  1856. prefix_append(prefix, '0');
  1857. format_uint<3, char>(appender(buffer), value, num_digits);
  1858. break;
  1859. case presentation_type::bin:
  1860. if (specs.alt)
  1861. prefix_append(prefix, unsigned(specs.upper ? 'B' : 'b') << 8 | '0');
  1862. num_digits = count_digits<1>(value);
  1863. format_uint<1, char>(appender(buffer), value, num_digits);
  1864. break;
  1865. case presentation_type::chr:
  1866. return write_char<Char>(out, static_cast<Char>(value), specs);
  1867. }
  1868. unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) +
  1869. to_unsigned(grouping.count_separators(num_digits));
  1870. return write_padded<Char, align::right>(
  1871. out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
  1872. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1873. *it++ = static_cast<Char>(p & 0xff);
  1874. return grouping.apply(it, string_view(buffer.data(), buffer.size()));
  1875. });
  1876. }
  1877. // Writes a localized value.
  1878. FMT_API auto write_loc(appender out, loc_value value, const format_specs& specs,
  1879. locale_ref loc) -> bool;
  1880. template <typename OutputIt>
  1881. inline auto write_loc(OutputIt, loc_value, const format_specs&, locale_ref)
  1882. -> bool {
  1883. return false;
  1884. }
  1885. template <typename UInt> struct write_int_arg {
  1886. UInt abs_value;
  1887. unsigned prefix;
  1888. };
  1889. template <typename T>
  1890. FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign)
  1891. -> write_int_arg<uint32_or_64_or_128_t<T>> {
  1892. auto prefix = 0u;
  1893. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  1894. if (is_negative(value)) {
  1895. prefix = 0x01000000 | '-';
  1896. abs_value = 0 - abs_value;
  1897. } else {
  1898. constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+',
  1899. 0x1000000u | ' '};
  1900. prefix = prefixes[sign];
  1901. }
  1902. return {abs_value, prefix};
  1903. }
  1904. template <typename Char = char> struct loc_writer {
  1905. basic_appender<Char> out;
  1906. const format_specs& specs;
  1907. std::basic_string<Char> sep;
  1908. std::string grouping;
  1909. std::basic_string<Char> decimal_point;
  1910. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  1911. auto operator()(T value) -> bool {
  1912. auto arg = make_write_int_arg(value, specs.sign);
  1913. write_int(out, static_cast<uint64_or_128_t<T>>(arg.abs_value), arg.prefix,
  1914. specs, digit_grouping<Char>(grouping, sep));
  1915. return true;
  1916. }
  1917. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  1918. auto operator()(T) -> bool {
  1919. return false;
  1920. }
  1921. };
  1922. template <typename Char, typename OutputIt, typename T>
  1923. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,
  1924. const format_specs& specs, locale_ref)
  1925. -> OutputIt {
  1926. static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, "");
  1927. auto abs_value = arg.abs_value;
  1928. auto prefix = arg.prefix;
  1929. switch (specs.type) {
  1930. default:
  1931. FMT_ASSERT(false, "");
  1932. FMT_FALLTHROUGH;
  1933. case presentation_type::none:
  1934. case presentation_type::dec: {
  1935. int num_digits = count_digits(abs_value);
  1936. return write_int<Char>(
  1937. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1938. return format_decimal<Char>(it, abs_value, num_digits).end;
  1939. });
  1940. }
  1941. case presentation_type::hex: {
  1942. if (specs.alt)
  1943. prefix_append(prefix, unsigned(specs.upper ? 'X' : 'x') << 8 | '0');
  1944. int num_digits = count_digits<4>(abs_value);
  1945. return write_int<Char>(
  1946. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1947. return format_uint<4, Char>(it, abs_value, num_digits, specs.upper);
  1948. });
  1949. }
  1950. case presentation_type::oct: {
  1951. int num_digits = count_digits<3>(abs_value);
  1952. // Octal prefix '0' is counted as a digit, so only add it if precision
  1953. // is not greater than the number of digits.
  1954. if (specs.alt && specs.precision <= num_digits && abs_value != 0)
  1955. prefix_append(prefix, '0');
  1956. return write_int<Char>(
  1957. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1958. return format_uint<3, Char>(it, abs_value, num_digits);
  1959. });
  1960. }
  1961. case presentation_type::bin: {
  1962. if (specs.alt)
  1963. prefix_append(prefix, unsigned(specs.upper ? 'B' : 'b') << 8 | '0');
  1964. int num_digits = count_digits<1>(abs_value);
  1965. return write_int<Char>(
  1966. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1967. return format_uint<1, Char>(it, abs_value, num_digits);
  1968. });
  1969. }
  1970. case presentation_type::chr:
  1971. return write_char<Char>(out, static_cast<Char>(abs_value), specs);
  1972. }
  1973. }
  1974. template <typename Char, typename OutputIt, typename T>
  1975. FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out,
  1976. write_int_arg<T> arg,
  1977. const format_specs& specs,
  1978. locale_ref loc) -> OutputIt {
  1979. return write_int<Char>(out, arg, specs, loc);
  1980. }
  1981. template <typename Char, typename T,
  1982. FMT_ENABLE_IF(is_integral<T>::value &&
  1983. !std::is_same<T, bool>::value &&
  1984. !std::is_same<T, Char>::value)>
  1985. FMT_CONSTEXPR FMT_INLINE auto write(basic_appender<Char> out, T value,
  1986. const format_specs& specs, locale_ref loc)
  1987. -> basic_appender<Char> {
  1988. if (specs.localized && write_loc(out, value, specs, loc)) return out;
  1989. return write_int_noinline<Char>(out, make_write_int_arg(value, specs.sign),
  1990. specs, loc);
  1991. }
  1992. // An inlined version of write used in format string compilation.
  1993. template <typename Char, typename OutputIt, typename T,
  1994. FMT_ENABLE_IF(is_integral<T>::value &&
  1995. !std::is_same<T, bool>::value &&
  1996. !std::is_same<T, Char>::value &&
  1997. !std::is_same<OutputIt, basic_appender<Char>>::value)>
  1998. FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
  1999. const format_specs& specs, locale_ref loc)
  2000. -> OutputIt {
  2001. if (specs.localized && write_loc(out, value, specs, loc)) return out;
  2002. return write_int<Char>(out, make_write_int_arg(value, specs.sign), specs,
  2003. loc);
  2004. }
  2005. // An output iterator that counts the number of objects written to it and
  2006. // discards them.
  2007. class counting_iterator {
  2008. private:
  2009. size_t count_;
  2010. public:
  2011. using iterator_category = std::output_iterator_tag;
  2012. using difference_type = std::ptrdiff_t;
  2013. using pointer = void;
  2014. using reference = void;
  2015. FMT_UNCHECKED_ITERATOR(counting_iterator);
  2016. struct value_type {
  2017. template <typename T> FMT_CONSTEXPR void operator=(const T&) {}
  2018. };
  2019. FMT_CONSTEXPR counting_iterator() : count_(0) {}
  2020. FMT_CONSTEXPR auto count() const -> size_t { return count_; }
  2021. FMT_CONSTEXPR auto operator++() -> counting_iterator& {
  2022. ++count_;
  2023. return *this;
  2024. }
  2025. FMT_CONSTEXPR auto operator++(int) -> counting_iterator {
  2026. auto it = *this;
  2027. ++*this;
  2028. return it;
  2029. }
  2030. FMT_CONSTEXPR friend auto operator+(counting_iterator it, difference_type n)
  2031. -> counting_iterator {
  2032. it.count_ += static_cast<size_t>(n);
  2033. return it;
  2034. }
  2035. FMT_CONSTEXPR auto operator*() const -> value_type { return {}; }
  2036. };
  2037. template <typename Char, typename OutputIt>
  2038. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
  2039. const format_specs& specs) -> OutputIt {
  2040. auto data = s.data();
  2041. auto size = s.size();
  2042. if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
  2043. size = code_point_index(s, to_unsigned(specs.precision));
  2044. bool is_debug = specs.type == presentation_type::debug;
  2045. size_t width = 0;
  2046. if (is_debug) size = write_escaped_string(counting_iterator{}, s).count();
  2047. if (specs.width != 0) {
  2048. if (is_debug)
  2049. width = size;
  2050. else
  2051. width = compute_width(basic_string_view<Char>(data, size));
  2052. }
  2053. return write_padded<Char>(out, specs, size, width,
  2054. [=](reserve_iterator<OutputIt> it) {
  2055. if (is_debug) return write_escaped_string(it, s);
  2056. return copy<Char>(data, data + size, it);
  2057. });
  2058. }
  2059. template <typename Char, typename OutputIt>
  2060. FMT_CONSTEXPR auto write(OutputIt out,
  2061. basic_string_view<type_identity_t<Char>> s,
  2062. const format_specs& specs, locale_ref) -> OutputIt {
  2063. return write<Char>(out, s, specs);
  2064. }
  2065. template <typename Char, typename OutputIt>
  2066. FMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs,
  2067. locale_ref) -> OutputIt {
  2068. if (specs.type == presentation_type::pointer)
  2069. return write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
  2070. if (!s) report_error("string pointer is null");
  2071. return write<Char>(out, basic_string_view<Char>(s), specs, {});
  2072. }
  2073. template <typename Char, typename OutputIt, typename T,
  2074. FMT_ENABLE_IF(is_integral<T>::value &&
  2075. !std::is_same<T, bool>::value &&
  2076. !std::is_same<T, Char>::value)>
  2077. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  2078. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  2079. bool negative = is_negative(value);
  2080. // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
  2081. if (negative) abs_value = ~abs_value + 1;
  2082. int num_digits = count_digits(abs_value);
  2083. auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
  2084. auto it = reserve(out, size);
  2085. if (auto ptr = to_pointer<Char>(it, size)) {
  2086. if (negative) *ptr++ = static_cast<Char>('-');
  2087. format_decimal<Char>(ptr, abs_value, num_digits);
  2088. return out;
  2089. }
  2090. if (negative) *it++ = static_cast<Char>('-');
  2091. it = format_decimal<Char>(it, abs_value, num_digits).end;
  2092. return base_iterator(out, it);
  2093. }
  2094. // DEPRECATED!
  2095. template <typename Char>
  2096. FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
  2097. format_specs& specs) -> const Char* {
  2098. FMT_ASSERT(begin != end, "");
  2099. auto align = align::none;
  2100. auto p = begin + code_point_length(begin);
  2101. if (end - p <= 0) p = begin;
  2102. for (;;) {
  2103. switch (to_ascii(*p)) {
  2104. case '<':
  2105. align = align::left;
  2106. break;
  2107. case '>':
  2108. align = align::right;
  2109. break;
  2110. case '^':
  2111. align = align::center;
  2112. break;
  2113. }
  2114. if (align != align::none) {
  2115. if (p != begin) {
  2116. auto c = *begin;
  2117. if (c == '}') return begin;
  2118. if (c == '{') {
  2119. report_error("invalid fill character '{'");
  2120. return begin;
  2121. }
  2122. specs.fill = basic_string_view<Char>(begin, to_unsigned(p - begin));
  2123. begin = p + 1;
  2124. } else {
  2125. ++begin;
  2126. }
  2127. break;
  2128. } else if (p == begin) {
  2129. break;
  2130. }
  2131. p = begin;
  2132. }
  2133. specs.align = align;
  2134. return begin;
  2135. }
  2136. // A floating-point presentation format.
  2137. enum class float_format : unsigned char {
  2138. general, // General: exponent notation or fixed point based on magnitude.
  2139. exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3.
  2140. fixed // Fixed point with the default precision of 6, e.g. 0.0012.
  2141. };
  2142. struct float_specs {
  2143. int precision;
  2144. float_format format : 8;
  2145. sign_t sign : 8;
  2146. bool locale : 1;
  2147. bool binary32 : 1;
  2148. bool showpoint : 1;
  2149. };
  2150. // DEPRECATED!
  2151. FMT_CONSTEXPR inline auto parse_float_type_spec(const format_specs& specs)
  2152. -> float_specs {
  2153. auto result = float_specs();
  2154. result.showpoint = specs.alt;
  2155. result.locale = specs.localized;
  2156. switch (specs.type) {
  2157. default:
  2158. FMT_FALLTHROUGH;
  2159. case presentation_type::none:
  2160. result.format = float_format::general;
  2161. break;
  2162. case presentation_type::exp:
  2163. result.format = float_format::exp;
  2164. result.showpoint |= specs.precision != 0;
  2165. break;
  2166. case presentation_type::fixed:
  2167. result.format = float_format::fixed;
  2168. result.showpoint |= specs.precision != 0;
  2169. break;
  2170. case presentation_type::general:
  2171. result.format = float_format::general;
  2172. break;
  2173. }
  2174. return result;
  2175. }
  2176. template <typename Char, typename OutputIt>
  2177. FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan,
  2178. format_specs specs, sign_t sign)
  2179. -> OutputIt {
  2180. auto str =
  2181. isnan ? (specs.upper ? "NAN" : "nan") : (specs.upper ? "INF" : "inf");
  2182. constexpr size_t str_size = 3;
  2183. auto size = str_size + (sign ? 1 : 0);
  2184. // Replace '0'-padding with space for non-finite values.
  2185. const bool is_zero_fill =
  2186. specs.fill.size() == 1 && specs.fill.template get<Char>() == '0';
  2187. if (is_zero_fill) specs.fill = ' ';
  2188. return write_padded<Char>(out, specs, size,
  2189. [=](reserve_iterator<OutputIt> it) {
  2190. if (sign) *it++ = detail::sign<Char>(sign);
  2191. return copy<Char>(str, str + str_size, it);
  2192. });
  2193. }
  2194. // A decimal floating-point number significand * pow(10, exp).
  2195. struct big_decimal_fp {
  2196. const char* significand;
  2197. int significand_size;
  2198. int exponent;
  2199. };
  2200. constexpr auto get_significand_size(const big_decimal_fp& f) -> int {
  2201. return f.significand_size;
  2202. }
  2203. template <typename T>
  2204. inline auto get_significand_size(const dragonbox::decimal_fp<T>& f) -> int {
  2205. return count_digits(f.significand);
  2206. }
  2207. template <typename Char, typename OutputIt>
  2208. constexpr auto write_significand(OutputIt out, const char* significand,
  2209. int significand_size) -> OutputIt {
  2210. return copy<Char>(significand, significand + significand_size, out);
  2211. }
  2212. template <typename Char, typename OutputIt, typename UInt>
  2213. inline auto write_significand(OutputIt out, UInt significand,
  2214. int significand_size) -> OutputIt {
  2215. return format_decimal<Char>(out, significand, significand_size).end;
  2216. }
  2217. template <typename Char, typename OutputIt, typename T, typename Grouping>
  2218. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  2219. int significand_size, int exponent,
  2220. const Grouping& grouping) -> OutputIt {
  2221. if (!grouping.has_separator()) {
  2222. out = write_significand<Char>(out, significand, significand_size);
  2223. return detail::fill_n(out, exponent, static_cast<Char>('0'));
  2224. }
  2225. auto buffer = memory_buffer();
  2226. write_significand<char>(appender(buffer), significand, significand_size);
  2227. detail::fill_n(appender(buffer), exponent, '0');
  2228. return grouping.apply(out, string_view(buffer.data(), buffer.size()));
  2229. }
  2230. template <typename Char, typename UInt,
  2231. FMT_ENABLE_IF(std::is_integral<UInt>::value)>
  2232. inline auto write_significand(Char* out, UInt significand, int significand_size,
  2233. int integral_size, Char decimal_point) -> Char* {
  2234. if (!decimal_point)
  2235. return format_decimal(out, significand, significand_size).end;
  2236. out += significand_size + 1;
  2237. Char* end = out;
  2238. int floating_size = significand_size - integral_size;
  2239. for (int i = floating_size / 2; i > 0; --i) {
  2240. out -= 2;
  2241. copy2(out, digits2(static_cast<std::size_t>(significand % 100)));
  2242. significand /= 100;
  2243. }
  2244. if (floating_size % 2 != 0) {
  2245. *--out = static_cast<Char>('0' + significand % 10);
  2246. significand /= 10;
  2247. }
  2248. *--out = decimal_point;
  2249. format_decimal(out - integral_size, significand, integral_size);
  2250. return end;
  2251. }
  2252. template <typename OutputIt, typename UInt, typename Char,
  2253. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
  2254. inline auto write_significand(OutputIt out, UInt significand,
  2255. int significand_size, int integral_size,
  2256. Char decimal_point) -> OutputIt {
  2257. // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
  2258. Char buffer[digits10<UInt>() + 2];
  2259. auto end = write_significand(buffer, significand, significand_size,
  2260. integral_size, decimal_point);
  2261. return detail::copy_noinline<Char>(buffer, end, out);
  2262. }
  2263. template <typename OutputIt, typename Char>
  2264. FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,
  2265. int significand_size, int integral_size,
  2266. Char decimal_point) -> OutputIt {
  2267. out = detail::copy_noinline<Char>(significand, significand + integral_size,
  2268. out);
  2269. if (!decimal_point) return out;
  2270. *out++ = decimal_point;
  2271. return detail::copy_noinline<Char>(significand + integral_size,
  2272. significand + significand_size, out);
  2273. }
  2274. template <typename OutputIt, typename Char, typename T, typename Grouping>
  2275. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  2276. int significand_size, int integral_size,
  2277. Char decimal_point,
  2278. const Grouping& grouping) -> OutputIt {
  2279. if (!grouping.has_separator()) {
  2280. return write_significand(out, significand, significand_size, integral_size,
  2281. decimal_point);
  2282. }
  2283. auto buffer = basic_memory_buffer<Char>();
  2284. write_significand(basic_appender<Char>(buffer), significand, significand_size,
  2285. integral_size, decimal_point);
  2286. grouping.apply(
  2287. out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));
  2288. return detail::copy_noinline<Char>(buffer.data() + integral_size,
  2289. buffer.end(), out);
  2290. }
  2291. template <typename Char, typename OutputIt, typename DecimalFP,
  2292. typename Grouping = digit_grouping<Char>>
  2293. FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f,
  2294. const format_specs& specs,
  2295. float_specs fspecs, locale_ref loc)
  2296. -> OutputIt {
  2297. auto significand = f.significand;
  2298. int significand_size = get_significand_size(f);
  2299. const Char zero = static_cast<Char>('0');
  2300. auto sign = fspecs.sign;
  2301. size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
  2302. using iterator = reserve_iterator<OutputIt>;
  2303. Char decimal_point =
  2304. fspecs.locale ? detail::decimal_point<Char>(loc) : static_cast<Char>('.');
  2305. int output_exp = f.exponent + significand_size - 1;
  2306. auto use_exp_format = [=]() {
  2307. if (fspecs.format == float_format::exp) return true;
  2308. if (fspecs.format != float_format::general) return false;
  2309. // Use the fixed notation if the exponent is in [exp_lower, exp_upper),
  2310. // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
  2311. const int exp_lower = -4, exp_upper = 16;
  2312. return output_exp < exp_lower ||
  2313. output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper);
  2314. };
  2315. if (use_exp_format()) {
  2316. int num_zeros = 0;
  2317. if (fspecs.showpoint) {
  2318. num_zeros = fspecs.precision - significand_size;
  2319. if (num_zeros < 0) num_zeros = 0;
  2320. size += to_unsigned(num_zeros);
  2321. } else if (significand_size == 1) {
  2322. decimal_point = Char();
  2323. }
  2324. auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp;
  2325. int exp_digits = 2;
  2326. if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3;
  2327. size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits);
  2328. char exp_char = specs.upper ? 'E' : 'e';
  2329. auto write = [=](iterator it) {
  2330. if (sign) *it++ = detail::sign<Char>(sign);
  2331. // Insert a decimal point after the first digit and add an exponent.
  2332. it = write_significand(it, significand, significand_size, 1,
  2333. decimal_point);
  2334. if (num_zeros > 0) it = detail::fill_n(it, num_zeros, zero);
  2335. *it++ = static_cast<Char>(exp_char);
  2336. return write_exponent<Char>(output_exp, it);
  2337. };
  2338. return specs.width > 0
  2339. ? write_padded<Char, align::right>(out, specs, size, write)
  2340. : base_iterator(out, write(reserve(out, size)));
  2341. }
  2342. int exp = f.exponent + significand_size;
  2343. if (f.exponent >= 0) {
  2344. // 1234e5 -> 123400000[.0+]
  2345. size += to_unsigned(f.exponent);
  2346. int num_zeros = fspecs.precision - exp;
  2347. abort_fuzzing_if(num_zeros > 5000);
  2348. if (fspecs.showpoint) {
  2349. ++size;
  2350. if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 0;
  2351. if (num_zeros > 0) size += to_unsigned(num_zeros);
  2352. }
  2353. auto grouping = Grouping(loc, fspecs.locale);
  2354. size += to_unsigned(grouping.count_separators(exp));
  2355. return write_padded<Char, align::right>(out, specs, size, [&](iterator it) {
  2356. if (sign) *it++ = detail::sign<Char>(sign);
  2357. it = write_significand<Char>(it, significand, significand_size,
  2358. f.exponent, grouping);
  2359. if (!fspecs.showpoint) return it;
  2360. *it++ = decimal_point;
  2361. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  2362. });
  2363. } else if (exp > 0) {
  2364. // 1234e-2 -> 12.34[0+]
  2365. int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0;
  2366. size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0);
  2367. auto grouping = Grouping(loc, fspecs.locale);
  2368. size += to_unsigned(grouping.count_separators(exp));
  2369. return write_padded<Char, align::right>(out, specs, size, [&](iterator it) {
  2370. if (sign) *it++ = detail::sign<Char>(sign);
  2371. it = write_significand(it, significand, significand_size, exp,
  2372. decimal_point, grouping);
  2373. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  2374. });
  2375. }
  2376. // 1234e-6 -> 0.001234
  2377. int num_zeros = -exp;
  2378. if (significand_size == 0 && fspecs.precision >= 0 &&
  2379. fspecs.precision < num_zeros) {
  2380. num_zeros = fspecs.precision;
  2381. }
  2382. bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint;
  2383. size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros);
  2384. return write_padded<Char, align::right>(out, specs, size, [&](iterator it) {
  2385. if (sign) *it++ = detail::sign<Char>(sign);
  2386. *it++ = zero;
  2387. if (!pointy) return it;
  2388. *it++ = decimal_point;
  2389. it = detail::fill_n(it, num_zeros, zero);
  2390. return write_significand<Char>(it, significand, significand_size);
  2391. });
  2392. }
  2393. template <typename Char> class fallback_digit_grouping {
  2394. public:
  2395. constexpr fallback_digit_grouping(locale_ref, bool) {}
  2396. constexpr auto has_separator() const -> bool { return false; }
  2397. constexpr auto count_separators(int) const -> int { return 0; }
  2398. template <typename Out, typename C>
  2399. constexpr auto apply(Out out, basic_string_view<C>) const -> Out {
  2400. return out;
  2401. }
  2402. };
  2403. template <typename Char, typename OutputIt, typename DecimalFP>
  2404. FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,
  2405. const format_specs& specs, float_specs fspecs,
  2406. locale_ref loc) -> OutputIt {
  2407. if (is_constant_evaluated()) {
  2408. return do_write_float<Char, OutputIt, DecimalFP,
  2409. fallback_digit_grouping<Char>>(out, f, specs, fspecs,
  2410. loc);
  2411. } else {
  2412. return do_write_float<Char>(out, f, specs, fspecs, loc);
  2413. }
  2414. }
  2415. template <typename T> constexpr auto isnan(T value) -> bool {
  2416. return value != value; // std::isnan doesn't support __float128.
  2417. }
  2418. template <typename T, typename Enable = void>
  2419. struct has_isfinite : std::false_type {};
  2420. template <typename T>
  2421. struct has_isfinite<T, enable_if_t<sizeof(std::isfinite(T())) != 0>>
  2422. : std::true_type {};
  2423. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value&&
  2424. has_isfinite<T>::value)>
  2425. FMT_CONSTEXPR20 auto isfinite(T value) -> bool {
  2426. constexpr T inf = T(std::numeric_limits<double>::infinity());
  2427. if (is_constant_evaluated())
  2428. return !detail::isnan(value) && value < inf && value > -inf;
  2429. return std::isfinite(value);
  2430. }
  2431. template <typename T, FMT_ENABLE_IF(!has_isfinite<T>::value)>
  2432. FMT_CONSTEXPR auto isfinite(T value) -> bool {
  2433. T inf = T(std::numeric_limits<double>::infinity());
  2434. // std::isfinite doesn't support __float128.
  2435. return !detail::isnan(value) && value < inf && value > -inf;
  2436. }
  2437. template <typename T, FMT_ENABLE_IF(is_floating_point<T>::value)>
  2438. FMT_INLINE FMT_CONSTEXPR bool signbit(T value) {
  2439. if (is_constant_evaluated()) {
  2440. #ifdef __cpp_if_constexpr
  2441. if constexpr (std::numeric_limits<double>::is_iec559) {
  2442. auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
  2443. return (bits >> (num_bits<uint64_t>() - 1)) != 0;
  2444. }
  2445. #endif
  2446. }
  2447. return std::signbit(static_cast<double>(value));
  2448. }
  2449. inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) {
  2450. // Adjust fixed precision by exponent because it is relative to decimal
  2451. // point.
  2452. if (exp10 > 0 && precision > max_value<int>() - exp10)
  2453. FMT_THROW(format_error("number is too big"));
  2454. precision += exp10;
  2455. }
  2456. class bigint {
  2457. private:
  2458. // A bigint is stored as an array of bigits (big digits), with bigit at index
  2459. // 0 being the least significant one.
  2460. using bigit = uint32_t;
  2461. using double_bigit = uint64_t;
  2462. enum { bigits_capacity = 32 };
  2463. basic_memory_buffer<bigit, bigits_capacity> bigits_;
  2464. int exp_;
  2465. FMT_CONSTEXPR20 auto operator[](int index) const -> bigit {
  2466. return bigits_[to_unsigned(index)];
  2467. }
  2468. FMT_CONSTEXPR20 auto operator[](int index) -> bigit& {
  2469. return bigits_[to_unsigned(index)];
  2470. }
  2471. static constexpr const int bigit_bits = num_bits<bigit>();
  2472. friend struct formatter<bigint>;
  2473. FMT_CONSTEXPR20 void subtract_bigits(int index, bigit other, bigit& borrow) {
  2474. auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
  2475. (*this)[index] = static_cast<bigit>(result);
  2476. borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
  2477. }
  2478. FMT_CONSTEXPR20 void remove_leading_zeros() {
  2479. int num_bigits = static_cast<int>(bigits_.size()) - 1;
  2480. while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
  2481. bigits_.resize(to_unsigned(num_bigits + 1));
  2482. }
  2483. // Computes *this -= other assuming aligned bigints and *this >= other.
  2484. FMT_CONSTEXPR20 void subtract_aligned(const bigint& other) {
  2485. FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
  2486. FMT_ASSERT(compare(*this, other) >= 0, "");
  2487. bigit borrow = 0;
  2488. int i = other.exp_ - exp_;
  2489. for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
  2490. subtract_bigits(i, other.bigits_[j], borrow);
  2491. while (borrow > 0) subtract_bigits(i, 0, borrow);
  2492. remove_leading_zeros();
  2493. }
  2494. FMT_CONSTEXPR20 void multiply(uint32_t value) {
  2495. const double_bigit wide_value = value;
  2496. bigit carry = 0;
  2497. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2498. double_bigit result = bigits_[i] * wide_value + carry;
  2499. bigits_[i] = static_cast<bigit>(result);
  2500. carry = static_cast<bigit>(result >> bigit_bits);
  2501. }
  2502. if (carry != 0) bigits_.push_back(carry);
  2503. }
  2504. template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
  2505. std::is_same<UInt, uint128_t>::value)>
  2506. FMT_CONSTEXPR20 void multiply(UInt value) {
  2507. using half_uint =
  2508. conditional_t<std::is_same<UInt, uint128_t>::value, uint64_t, uint32_t>;
  2509. const int shift = num_bits<half_uint>() - bigit_bits;
  2510. const UInt lower = static_cast<half_uint>(value);
  2511. const UInt upper = value >> num_bits<half_uint>();
  2512. UInt carry = 0;
  2513. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2514. UInt result = lower * bigits_[i] + static_cast<bigit>(carry);
  2515. carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) +
  2516. (carry >> bigit_bits);
  2517. bigits_[i] = static_cast<bigit>(result);
  2518. }
  2519. while (carry != 0) {
  2520. bigits_.push_back(static_cast<bigit>(carry));
  2521. carry >>= bigit_bits;
  2522. }
  2523. }
  2524. template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
  2525. std::is_same<UInt, uint128_t>::value)>
  2526. FMT_CONSTEXPR20 void assign(UInt n) {
  2527. size_t num_bigits = 0;
  2528. do {
  2529. bigits_[num_bigits++] = static_cast<bigit>(n);
  2530. n >>= bigit_bits;
  2531. } while (n != 0);
  2532. bigits_.resize(num_bigits);
  2533. exp_ = 0;
  2534. }
  2535. public:
  2536. FMT_CONSTEXPR20 bigint() : exp_(0) {}
  2537. explicit bigint(uint64_t n) { assign(n); }
  2538. bigint(const bigint&) = delete;
  2539. void operator=(const bigint&) = delete;
  2540. FMT_CONSTEXPR20 void assign(const bigint& other) {
  2541. auto size = other.bigits_.size();
  2542. bigits_.resize(size);
  2543. auto data = other.bigits_.data();
  2544. copy<bigit>(data, data + size, bigits_.data());
  2545. exp_ = other.exp_;
  2546. }
  2547. template <typename Int> FMT_CONSTEXPR20 void operator=(Int n) {
  2548. FMT_ASSERT(n > 0, "");
  2549. assign(uint64_or_128_t<Int>(n));
  2550. }
  2551. FMT_CONSTEXPR20 auto num_bigits() const -> int {
  2552. return static_cast<int>(bigits_.size()) + exp_;
  2553. }
  2554. FMT_NOINLINE FMT_CONSTEXPR20 auto operator<<=(int shift) -> bigint& {
  2555. FMT_ASSERT(shift >= 0, "");
  2556. exp_ += shift / bigit_bits;
  2557. shift %= bigit_bits;
  2558. if (shift == 0) return *this;
  2559. bigit carry = 0;
  2560. for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
  2561. bigit c = bigits_[i] >> (bigit_bits - shift);
  2562. bigits_[i] = (bigits_[i] << shift) + carry;
  2563. carry = c;
  2564. }
  2565. if (carry != 0) bigits_.push_back(carry);
  2566. return *this;
  2567. }
  2568. template <typename Int>
  2569. FMT_CONSTEXPR20 auto operator*=(Int value) -> bigint& {
  2570. FMT_ASSERT(value > 0, "");
  2571. multiply(uint32_or_64_or_128_t<Int>(value));
  2572. return *this;
  2573. }
  2574. friend FMT_CONSTEXPR20 auto compare(const bigint& lhs, const bigint& rhs)
  2575. -> int {
  2576. int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
  2577. if (num_lhs_bigits != num_rhs_bigits)
  2578. return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
  2579. int i = static_cast<int>(lhs.bigits_.size()) - 1;
  2580. int j = static_cast<int>(rhs.bigits_.size()) - 1;
  2581. int end = i - j;
  2582. if (end < 0) end = 0;
  2583. for (; i >= end; --i, --j) {
  2584. bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
  2585. if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
  2586. }
  2587. if (i != j) return i > j ? 1 : -1;
  2588. return 0;
  2589. }
  2590. // Returns compare(lhs1 + lhs2, rhs).
  2591. friend FMT_CONSTEXPR20 auto add_compare(const bigint& lhs1,
  2592. const bigint& lhs2, const bigint& rhs)
  2593. -> int {
  2594. auto minimum = [](int a, int b) { return a < b ? a : b; };
  2595. auto maximum = [](int a, int b) { return a > b ? a : b; };
  2596. int max_lhs_bigits = maximum(lhs1.num_bigits(), lhs2.num_bigits());
  2597. int num_rhs_bigits = rhs.num_bigits();
  2598. if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
  2599. if (max_lhs_bigits > num_rhs_bigits) return 1;
  2600. auto get_bigit = [](const bigint& n, int i) -> bigit {
  2601. return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
  2602. };
  2603. double_bigit borrow = 0;
  2604. int min_exp = minimum(minimum(lhs1.exp_, lhs2.exp_), rhs.exp_);
  2605. for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
  2606. double_bigit sum =
  2607. static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
  2608. bigit rhs_bigit = get_bigit(rhs, i);
  2609. if (sum > rhs_bigit + borrow) return 1;
  2610. borrow = rhs_bigit + borrow - sum;
  2611. if (borrow > 1) return -1;
  2612. borrow <<= bigit_bits;
  2613. }
  2614. return borrow != 0 ? -1 : 0;
  2615. }
  2616. // Assigns pow(10, exp) to this bigint.
  2617. FMT_CONSTEXPR20 void assign_pow10(int exp) {
  2618. FMT_ASSERT(exp >= 0, "");
  2619. if (exp == 0) return *this = 1;
  2620. // Find the top bit.
  2621. int bitmask = 1;
  2622. while (exp >= bitmask) bitmask <<= 1;
  2623. bitmask >>= 1;
  2624. // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
  2625. // repeated squaring and multiplication.
  2626. *this = 5;
  2627. bitmask >>= 1;
  2628. while (bitmask != 0) {
  2629. square();
  2630. if ((exp & bitmask) != 0) *this *= 5;
  2631. bitmask >>= 1;
  2632. }
  2633. *this <<= exp; // Multiply by pow(2, exp) by shifting.
  2634. }
  2635. FMT_CONSTEXPR20 void square() {
  2636. int num_bigits = static_cast<int>(bigits_.size());
  2637. int num_result_bigits = 2 * num_bigits;
  2638. basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
  2639. bigits_.resize(to_unsigned(num_result_bigits));
  2640. auto sum = uint128_t();
  2641. for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
  2642. // Compute bigit at position bigit_index of the result by adding
  2643. // cross-product terms n[i] * n[j] such that i + j == bigit_index.
  2644. for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
  2645. // Most terms are multiplied twice which can be optimized in the future.
  2646. sum += static_cast<double_bigit>(n[i]) * n[j];
  2647. }
  2648. (*this)[bigit_index] = static_cast<bigit>(sum);
  2649. sum >>= num_bits<bigit>(); // Compute the carry.
  2650. }
  2651. // Do the same for the top half.
  2652. for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
  2653. ++bigit_index) {
  2654. for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
  2655. sum += static_cast<double_bigit>(n[i++]) * n[j--];
  2656. (*this)[bigit_index] = static_cast<bigit>(sum);
  2657. sum >>= num_bits<bigit>();
  2658. }
  2659. remove_leading_zeros();
  2660. exp_ *= 2;
  2661. }
  2662. // If this bigint has a bigger exponent than other, adds trailing zero to make
  2663. // exponents equal. This simplifies some operations such as subtraction.
  2664. FMT_CONSTEXPR20 void align(const bigint& other) {
  2665. int exp_difference = exp_ - other.exp_;
  2666. if (exp_difference <= 0) return;
  2667. int num_bigits = static_cast<int>(bigits_.size());
  2668. bigits_.resize(to_unsigned(num_bigits + exp_difference));
  2669. for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
  2670. bigits_[j] = bigits_[i];
  2671. memset(bigits_.data(), 0, to_unsigned(exp_difference) * sizeof(bigit));
  2672. exp_ -= exp_difference;
  2673. }
  2674. // Divides this bignum by divisor, assigning the remainder to this and
  2675. // returning the quotient.
  2676. FMT_CONSTEXPR20 auto divmod_assign(const bigint& divisor) -> int {
  2677. FMT_ASSERT(this != &divisor, "");
  2678. if (compare(*this, divisor) < 0) return 0;
  2679. FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
  2680. align(divisor);
  2681. int quotient = 0;
  2682. do {
  2683. subtract_aligned(divisor);
  2684. ++quotient;
  2685. } while (compare(*this, divisor) >= 0);
  2686. return quotient;
  2687. }
  2688. };
  2689. // format_dragon flags.
  2690. enum dragon {
  2691. predecessor_closer = 1,
  2692. fixup = 2, // Run fixup to correct exp10 which can be off by one.
  2693. fixed = 4,
  2694. };
  2695. // Formats a floating-point number using a variation of the Fixed-Precision
  2696. // Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
  2697. // https://fmt.dev/papers/p372-steele.pdf.
  2698. FMT_CONSTEXPR20 inline void format_dragon(basic_fp<uint128_t> value,
  2699. unsigned flags, int num_digits,
  2700. buffer<char>& buf, int& exp10) {
  2701. bigint numerator; // 2 * R in (FPP)^2.
  2702. bigint denominator; // 2 * S in (FPP)^2.
  2703. // lower and upper are differences between value and corresponding boundaries.
  2704. bigint lower; // (M^- in (FPP)^2).
  2705. bigint upper_store; // upper's value if different from lower.
  2706. bigint* upper = nullptr; // (M^+ in (FPP)^2).
  2707. // Shift numerator and denominator by an extra bit or two (if lower boundary
  2708. // is closer) to make lower and upper integers. This eliminates multiplication
  2709. // by 2 during later computations.
  2710. bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0;
  2711. int shift = is_predecessor_closer ? 2 : 1;
  2712. if (value.e >= 0) {
  2713. numerator = value.f;
  2714. numerator <<= value.e + shift;
  2715. lower = 1;
  2716. lower <<= value.e;
  2717. if (is_predecessor_closer) {
  2718. upper_store = 1;
  2719. upper_store <<= value.e + 1;
  2720. upper = &upper_store;
  2721. }
  2722. denominator.assign_pow10(exp10);
  2723. denominator <<= shift;
  2724. } else if (exp10 < 0) {
  2725. numerator.assign_pow10(-exp10);
  2726. lower.assign(numerator);
  2727. if (is_predecessor_closer) {
  2728. upper_store.assign(numerator);
  2729. upper_store <<= 1;
  2730. upper = &upper_store;
  2731. }
  2732. numerator *= value.f;
  2733. numerator <<= shift;
  2734. denominator = 1;
  2735. denominator <<= shift - value.e;
  2736. } else {
  2737. numerator = value.f;
  2738. numerator <<= shift;
  2739. denominator.assign_pow10(exp10);
  2740. denominator <<= shift - value.e;
  2741. lower = 1;
  2742. if (is_predecessor_closer) {
  2743. upper_store = 1ULL << 1;
  2744. upper = &upper_store;
  2745. }
  2746. }
  2747. int even = static_cast<int>((value.f & 1) == 0);
  2748. if (!upper) upper = &lower;
  2749. bool shortest = num_digits < 0;
  2750. if ((flags & dragon::fixup) != 0) {
  2751. if (add_compare(numerator, *upper, denominator) + even <= 0) {
  2752. --exp10;
  2753. numerator *= 10;
  2754. if (num_digits < 0) {
  2755. lower *= 10;
  2756. if (upper != &lower) *upper *= 10;
  2757. }
  2758. }
  2759. if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1);
  2760. }
  2761. // Invariant: value == (numerator / denominator) * pow(10, exp10).
  2762. if (shortest) {
  2763. // Generate the shortest representation.
  2764. num_digits = 0;
  2765. char* data = buf.data();
  2766. for (;;) {
  2767. int digit = numerator.divmod_assign(denominator);
  2768. bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower.
  2769. // numerator + upper >[=] pow10:
  2770. bool high = add_compare(numerator, *upper, denominator) + even > 0;
  2771. data[num_digits++] = static_cast<char>('0' + digit);
  2772. if (low || high) {
  2773. if (!low) {
  2774. ++data[num_digits - 1];
  2775. } else if (high) {
  2776. int result = add_compare(numerator, numerator, denominator);
  2777. // Round half to even.
  2778. if (result > 0 || (result == 0 && (digit % 2) != 0))
  2779. ++data[num_digits - 1];
  2780. }
  2781. buf.try_resize(to_unsigned(num_digits));
  2782. exp10 -= num_digits - 1;
  2783. return;
  2784. }
  2785. numerator *= 10;
  2786. lower *= 10;
  2787. if (upper != &lower) *upper *= 10;
  2788. }
  2789. }
  2790. // Generate the given number of digits.
  2791. exp10 -= num_digits - 1;
  2792. if (num_digits <= 0) {
  2793. auto digit = '0';
  2794. if (num_digits == 0) {
  2795. denominator *= 10;
  2796. digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
  2797. }
  2798. buf.push_back(digit);
  2799. return;
  2800. }
  2801. buf.try_resize(to_unsigned(num_digits));
  2802. for (int i = 0; i < num_digits - 1; ++i) {
  2803. int digit = numerator.divmod_assign(denominator);
  2804. buf[i] = static_cast<char>('0' + digit);
  2805. numerator *= 10;
  2806. }
  2807. int digit = numerator.divmod_assign(denominator);
  2808. auto result = add_compare(numerator, numerator, denominator);
  2809. if (result > 0 || (result == 0 && (digit % 2) != 0)) {
  2810. if (digit == 9) {
  2811. const auto overflow = '0' + 10;
  2812. buf[num_digits - 1] = overflow;
  2813. // Propagate the carry.
  2814. for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
  2815. buf[i] = '0';
  2816. ++buf[i - 1];
  2817. }
  2818. if (buf[0] == overflow) {
  2819. buf[0] = '1';
  2820. if ((flags & dragon::fixed) != 0)
  2821. buf.push_back('0');
  2822. else
  2823. ++exp10;
  2824. }
  2825. return;
  2826. }
  2827. ++digit;
  2828. }
  2829. buf[num_digits - 1] = static_cast<char>('0' + digit);
  2830. }
  2831. // Formats a floating-point number using the hexfloat format.
  2832. template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
  2833. FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,
  2834. buffer<char>& buf) {
  2835. // float is passed as double to reduce the number of instantiations and to
  2836. // simplify implementation.
  2837. static_assert(!std::is_same<Float, float>::value, "");
  2838. using info = dragonbox::float_info<Float>;
  2839. // Assume Float is in the format [sign][exponent][significand].
  2840. using carrier_uint = typename info::carrier_uint;
  2841. constexpr auto num_float_significand_bits =
  2842. detail::num_significand_bits<Float>();
  2843. basic_fp<carrier_uint> f(value);
  2844. f.e += num_float_significand_bits;
  2845. if (!has_implicit_bit<Float>()) --f.e;
  2846. constexpr auto num_fraction_bits =
  2847. num_float_significand_bits + (has_implicit_bit<Float>() ? 1 : 0);
  2848. constexpr auto num_xdigits = (num_fraction_bits + 3) / 4;
  2849. constexpr auto leading_shift = ((num_xdigits - 1) * 4);
  2850. const auto leading_mask = carrier_uint(0xF) << leading_shift;
  2851. const auto leading_xdigit =
  2852. static_cast<uint32_t>((f.f & leading_mask) >> leading_shift);
  2853. if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1);
  2854. int print_xdigits = num_xdigits - 1;
  2855. if (specs.precision >= 0 && print_xdigits > specs.precision) {
  2856. const int shift = ((print_xdigits - specs.precision - 1) * 4);
  2857. const auto mask = carrier_uint(0xF) << shift;
  2858. const auto v = static_cast<uint32_t>((f.f & mask) >> shift);
  2859. if (v >= 8) {
  2860. const auto inc = carrier_uint(1) << (shift + 4);
  2861. f.f += inc;
  2862. f.f &= ~(inc - 1);
  2863. }
  2864. // Check long double overflow
  2865. if (!has_implicit_bit<Float>()) {
  2866. const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
  2867. if ((f.f & implicit_bit) == implicit_bit) {
  2868. f.f >>= 4;
  2869. f.e += 4;
  2870. }
  2871. }
  2872. print_xdigits = specs.precision;
  2873. }
  2874. char xdigits[num_bits<carrier_uint>() / 4];
  2875. detail::fill_n(xdigits, sizeof(xdigits), '0');
  2876. format_uint<4>(xdigits, f.f, num_xdigits, specs.upper);
  2877. // Remove zero tail
  2878. while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits;
  2879. buf.push_back('0');
  2880. buf.push_back(specs.upper ? 'X' : 'x');
  2881. buf.push_back(xdigits[0]);
  2882. if (specs.alt || print_xdigits > 0 || print_xdigits < specs.precision)
  2883. buf.push_back('.');
  2884. buf.append(xdigits + 1, xdigits + 1 + print_xdigits);
  2885. for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0');
  2886. buf.push_back(specs.upper ? 'P' : 'p');
  2887. uint32_t abs_e;
  2888. if (f.e < 0) {
  2889. buf.push_back('-');
  2890. abs_e = static_cast<uint32_t>(-f.e);
  2891. } else {
  2892. buf.push_back('+');
  2893. abs_e = static_cast<uint32_t>(f.e);
  2894. }
  2895. format_decimal<char>(appender(buf), abs_e, detail::count_digits(abs_e));
  2896. }
  2897. template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
  2898. FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,
  2899. buffer<char>& buf) {
  2900. format_hexfloat(static_cast<double>(value), specs, buf);
  2901. }
  2902. constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t {
  2903. // For checking rounding thresholds.
  2904. // The kth entry is chosen to be the smallest integer such that the
  2905. // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k.
  2906. // It is equal to ceil(2^31 + 2^32/10^(k + 1)).
  2907. // These are stored in a string literal because we cannot have static arrays
  2908. // in constexpr functions and non-static ones are poorly optimized.
  2909. return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7"
  2910. U"\x800001ae\x8000002b"[index];
  2911. }
  2912. template <typename Float>
  2913. FMT_CONSTEXPR20 auto format_float(Float value, int precision, float_specs specs,
  2914. buffer<char>& buf) -> int {
  2915. // float is passed as double to reduce the number of instantiations.
  2916. static_assert(!std::is_same<Float, float>::value, "");
  2917. FMT_ASSERT(value >= 0, "value is negative");
  2918. auto converted_value = convert_float(value);
  2919. const bool fixed = specs.format == float_format::fixed;
  2920. if (value <= 0) { // <= instead of == to silence a warning.
  2921. if (precision <= 0 || !fixed) {
  2922. buf.push_back('0');
  2923. return 0;
  2924. }
  2925. buf.try_resize(to_unsigned(precision));
  2926. fill_n(buf.data(), precision, '0');
  2927. return -precision;
  2928. }
  2929. int exp = 0;
  2930. bool use_dragon = true;
  2931. unsigned dragon_flags = 0;
  2932. if (!is_fast_float<Float>() || is_constant_evaluated()) {
  2933. const auto inv_log2_10 = 0.3010299956639812; // 1 / log2(10)
  2934. using info = dragonbox::float_info<decltype(converted_value)>;
  2935. const auto f = basic_fp<typename info::carrier_uint>(converted_value);
  2936. // Compute exp, an approximate power of 10, such that
  2937. // 10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1).
  2938. // This is based on log10(value) == log2(value) / log2(10) and approximation
  2939. // of log2(value) by e + num_fraction_bits idea from double-conversion.
  2940. auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10;
  2941. exp = static_cast<int>(e);
  2942. if (e > exp) ++exp; // Compute ceil.
  2943. dragon_flags = dragon::fixup;
  2944. } else if (precision < 0) {
  2945. // Use Dragonbox for the shortest format.
  2946. if (specs.binary32) {
  2947. auto dec = dragonbox::to_decimal(static_cast<float>(value));
  2948. write<char>(appender(buf), dec.significand);
  2949. return dec.exponent;
  2950. }
  2951. auto dec = dragonbox::to_decimal(static_cast<double>(value));
  2952. write<char>(appender(buf), dec.significand);
  2953. return dec.exponent;
  2954. } else {
  2955. // Extract significand bits and exponent bits.
  2956. using info = dragonbox::float_info<double>;
  2957. auto br = bit_cast<uint64_t>(static_cast<double>(value));
  2958. const uint64_t significand_mask =
  2959. (static_cast<uint64_t>(1) << num_significand_bits<double>()) - 1;
  2960. uint64_t significand = (br & significand_mask);
  2961. int exponent = static_cast<int>((br & exponent_mask<double>()) >>
  2962. num_significand_bits<double>());
  2963. if (exponent != 0) { // Check if normal.
  2964. exponent -= exponent_bias<double>() + num_significand_bits<double>();
  2965. significand |=
  2966. (static_cast<uint64_t>(1) << num_significand_bits<double>());
  2967. significand <<= 1;
  2968. } else {
  2969. // Normalize subnormal inputs.
  2970. FMT_ASSERT(significand != 0, "zeros should not appear here");
  2971. int shift = countl_zero(significand);
  2972. FMT_ASSERT(shift >= num_bits<uint64_t>() - num_significand_bits<double>(),
  2973. "");
  2974. shift -= (num_bits<uint64_t>() - num_significand_bits<double>() - 2);
  2975. exponent = (std::numeric_limits<double>::min_exponent -
  2976. num_significand_bits<double>()) -
  2977. shift;
  2978. significand <<= shift;
  2979. }
  2980. // Compute the first several nonzero decimal significand digits.
  2981. // We call the number we get the first segment.
  2982. const int k = info::kappa - dragonbox::floor_log10_pow2(exponent);
  2983. exp = -k;
  2984. const int beta = exponent + dragonbox::floor_log2_pow10(k);
  2985. uint64_t first_segment;
  2986. bool has_more_segments;
  2987. int digits_in_the_first_segment;
  2988. {
  2989. const auto r = dragonbox::umul192_upper128(
  2990. significand << beta, dragonbox::get_cached_power(k));
  2991. first_segment = r.high();
  2992. has_more_segments = r.low() != 0;
  2993. // The first segment can have 18 ~ 19 digits.
  2994. if (first_segment >= 1000000000000000000ULL) {
  2995. digits_in_the_first_segment = 19;
  2996. } else {
  2997. // When it is of 18-digits, we align it to 19-digits by adding a bogus
  2998. // zero at the end.
  2999. digits_in_the_first_segment = 18;
  3000. first_segment *= 10;
  3001. }
  3002. }
  3003. // Compute the actual number of decimal digits to print.
  3004. if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment);
  3005. // Use Dragon4 only when there might be not enough digits in the first
  3006. // segment.
  3007. if (digits_in_the_first_segment > precision) {
  3008. use_dragon = false;
  3009. if (precision <= 0) {
  3010. exp += digits_in_the_first_segment;
  3011. if (precision < 0) {
  3012. // Nothing to do, since all we have are just leading zeros.
  3013. buf.try_resize(0);
  3014. } else {
  3015. // We may need to round-up.
  3016. buf.try_resize(1);
  3017. if ((first_segment | static_cast<uint64_t>(has_more_segments)) >
  3018. 5000000000000000000ULL) {
  3019. buf[0] = '1';
  3020. } else {
  3021. buf[0] = '0';
  3022. }
  3023. }
  3024. } // precision <= 0
  3025. else {
  3026. exp += digits_in_the_first_segment - precision;
  3027. // When precision > 0, we divide the first segment into three
  3028. // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits
  3029. // in 32-bits which usually allows faster calculation than in
  3030. // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize
  3031. // division-by-constant for large 64-bit divisors, we do it here
  3032. // manually. The magic number 7922816251426433760 below is equal to
  3033. // ceil(2^(64+32) / 10^10).
  3034. const uint32_t first_subsegment = static_cast<uint32_t>(
  3035. dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >>
  3036. 32);
  3037. const uint64_t second_third_subsegments =
  3038. first_segment - first_subsegment * 10000000000ULL;
  3039. uint64_t prod;
  3040. uint32_t digits;
  3041. bool should_round_up;
  3042. int number_of_digits_to_print = precision > 9 ? 9 : precision;
  3043. // Print a 9-digits subsegment, either the first or the second.
  3044. auto print_subsegment = [&](uint32_t subsegment, char* buffer) {
  3045. int number_of_digits_printed = 0;
  3046. // If we want to print an odd number of digits from the subsegment,
  3047. if ((number_of_digits_to_print & 1) != 0) {
  3048. // Convert to 64-bit fixed-point fractional form with 1-digit
  3049. // integer part. The magic number 720575941 is a good enough
  3050. // approximation of 2^(32 + 24) / 10^8; see
  3051. // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case
  3052. // for details.
  3053. prod = ((subsegment * static_cast<uint64_t>(720575941)) >> 24) + 1;
  3054. digits = static_cast<uint32_t>(prod >> 32);
  3055. *buffer = static_cast<char>('0' + digits);
  3056. number_of_digits_printed++;
  3057. }
  3058. // If we want to print an even number of digits from the
  3059. // first_subsegment,
  3060. else {
  3061. // Convert to 64-bit fixed-point fractional form with 2-digits
  3062. // integer part. The magic number 450359963 is a good enough
  3063. // approximation of 2^(32 + 20) / 10^7; see
  3064. // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case
  3065. // for details.
  3066. prod = ((subsegment * static_cast<uint64_t>(450359963)) >> 20) + 1;
  3067. digits = static_cast<uint32_t>(prod >> 32);
  3068. copy2(buffer, digits2(digits));
  3069. number_of_digits_printed += 2;
  3070. }
  3071. // Print all digit pairs.
  3072. while (number_of_digits_printed < number_of_digits_to_print) {
  3073. prod = static_cast<uint32_t>(prod) * static_cast<uint64_t>(100);
  3074. digits = static_cast<uint32_t>(prod >> 32);
  3075. copy2(buffer + number_of_digits_printed, digits2(digits));
  3076. number_of_digits_printed += 2;
  3077. }
  3078. };
  3079. // Print first subsegment.
  3080. print_subsegment(first_subsegment, buf.data());
  3081. // Perform rounding if the first subsegment is the last subsegment to
  3082. // print.
  3083. if (precision <= 9) {
  3084. // Rounding inside the subsegment.
  3085. // We round-up if:
  3086. // - either the fractional part is strictly larger than 1/2, or
  3087. // - the fractional part is exactly 1/2 and the last digit is odd.
  3088. // We rely on the following observations:
  3089. // - If fractional_part >= threshold, then the fractional part is
  3090. // strictly larger than 1/2.
  3091. // - If the MSB of fractional_part is set, then the fractional part
  3092. // must be at least 1/2.
  3093. // - When the MSB of fractional_part is set, either
  3094. // second_third_subsegments being nonzero or has_more_segments
  3095. // being true means there are further digits not printed, so the
  3096. // fractional part is strictly larger than 1/2.
  3097. if (precision < 9) {
  3098. uint32_t fractional_part = static_cast<uint32_t>(prod);
  3099. should_round_up =
  3100. fractional_part >= fractional_part_rounding_thresholds(
  3101. 8 - number_of_digits_to_print) ||
  3102. ((fractional_part >> 31) &
  3103. ((digits & 1) | (second_third_subsegments != 0) |
  3104. has_more_segments)) != 0;
  3105. }
  3106. // Rounding at the subsegment boundary.
  3107. // In this case, the fractional part is at least 1/2 if and only if
  3108. // second_third_subsegments >= 5000000000ULL, and is strictly larger
  3109. // than 1/2 if we further have either second_third_subsegments >
  3110. // 5000000000ULL or has_more_segments == true.
  3111. else {
  3112. should_round_up = second_third_subsegments > 5000000000ULL ||
  3113. (second_third_subsegments == 5000000000ULL &&
  3114. ((digits & 1) != 0 || has_more_segments));
  3115. }
  3116. }
  3117. // Otherwise, print the second subsegment.
  3118. else {
  3119. // Compilers are not aware of how to leverage the maximum value of
  3120. // second_third_subsegments to find out a better magic number which
  3121. // allows us to eliminate an additional shift. 1844674407370955162 =
  3122. // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))).
  3123. const uint32_t second_subsegment =
  3124. static_cast<uint32_t>(dragonbox::umul128_upper64(
  3125. second_third_subsegments, 1844674407370955162ULL));
  3126. const uint32_t third_subsegment =
  3127. static_cast<uint32_t>(second_third_subsegments) -
  3128. second_subsegment * 10;
  3129. number_of_digits_to_print = precision - 9;
  3130. print_subsegment(second_subsegment, buf.data() + 9);
  3131. // Rounding inside the subsegment.
  3132. if (precision < 18) {
  3133. // The condition third_subsegment != 0 implies that the segment was
  3134. // of 19 digits, so in this case the third segment should be
  3135. // consisting of a genuine digit from the input.
  3136. uint32_t fractional_part = static_cast<uint32_t>(prod);
  3137. should_round_up =
  3138. fractional_part >= fractional_part_rounding_thresholds(
  3139. 8 - number_of_digits_to_print) ||
  3140. ((fractional_part >> 31) &
  3141. ((digits & 1) | (third_subsegment != 0) |
  3142. has_more_segments)) != 0;
  3143. }
  3144. // Rounding at the subsegment boundary.
  3145. else {
  3146. // In this case, the segment must be of 19 digits, thus
  3147. // the third subsegment should be consisting of a genuine digit from
  3148. // the input.
  3149. should_round_up = third_subsegment > 5 ||
  3150. (third_subsegment == 5 &&
  3151. ((digits & 1) != 0 || has_more_segments));
  3152. }
  3153. }
  3154. // Round-up if necessary.
  3155. if (should_round_up) {
  3156. ++buf[precision - 1];
  3157. for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) {
  3158. buf[i] = '0';
  3159. ++buf[i - 1];
  3160. }
  3161. if (buf[0] > '9') {
  3162. buf[0] = '1';
  3163. if (fixed)
  3164. buf[precision++] = '0';
  3165. else
  3166. ++exp;
  3167. }
  3168. }
  3169. buf.try_resize(to_unsigned(precision));
  3170. }
  3171. } // if (digits_in_the_first_segment > precision)
  3172. else {
  3173. // Adjust the exponent for its use in Dragon4.
  3174. exp += digits_in_the_first_segment - 1;
  3175. }
  3176. }
  3177. if (use_dragon) {
  3178. auto f = basic_fp<uint128_t>();
  3179. bool is_predecessor_closer = specs.binary32
  3180. ? f.assign(static_cast<float>(value))
  3181. : f.assign(converted_value);
  3182. if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer;
  3183. if (fixed) dragon_flags |= dragon::fixed;
  3184. // Limit precision to the maximum possible number of significant digits in
  3185. // an IEEE754 double because we don't need to generate zeros.
  3186. const int max_double_digits = 767;
  3187. if (precision > max_double_digits) precision = max_double_digits;
  3188. format_dragon(f, dragon_flags, precision, buf, exp);
  3189. }
  3190. if (!fixed && !specs.showpoint) {
  3191. // Remove trailing zeros.
  3192. auto num_digits = buf.size();
  3193. while (num_digits > 0 && buf[num_digits - 1] == '0') {
  3194. --num_digits;
  3195. ++exp;
  3196. }
  3197. buf.try_resize(num_digits);
  3198. }
  3199. return exp;
  3200. }
  3201. template <typename Char, typename OutputIt, typename T>
  3202. FMT_CONSTEXPR20 auto write_float(OutputIt out, T value, format_specs specs,
  3203. locale_ref loc) -> OutputIt {
  3204. sign_t sign = specs.sign;
  3205. if (detail::signbit(value)) { // value < 0 is false for NaN so use signbit.
  3206. sign = sign::minus;
  3207. value = -value;
  3208. } else if (sign == sign::minus) {
  3209. sign = sign::none;
  3210. }
  3211. if (!detail::isfinite(value))
  3212. return write_nonfinite<Char>(out, detail::isnan(value), specs, sign);
  3213. if (specs.align == align::numeric && sign) {
  3214. auto it = reserve(out, 1);
  3215. *it++ = detail::sign<Char>(sign);
  3216. out = base_iterator(out, it);
  3217. sign = sign::none;
  3218. if (specs.width != 0) --specs.width;
  3219. }
  3220. memory_buffer buffer;
  3221. if (specs.type == presentation_type::hexfloat) {
  3222. if (sign) buffer.push_back(detail::sign<char>(sign));
  3223. format_hexfloat(convert_float(value), specs, buffer);
  3224. return write_bytes<Char, align::right>(out, {buffer.data(), buffer.size()},
  3225. specs);
  3226. }
  3227. int precision = specs.precision >= 0 || specs.type == presentation_type::none
  3228. ? specs.precision
  3229. : 6;
  3230. if (specs.type == presentation_type::exp) {
  3231. if (precision == max_value<int>())
  3232. report_error("number is too big");
  3233. else
  3234. ++precision;
  3235. } else if (specs.type != presentation_type::fixed && precision == 0) {
  3236. precision = 1;
  3237. }
  3238. float_specs fspecs = parse_float_type_spec(specs);
  3239. fspecs.sign = sign;
  3240. if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
  3241. int exp = format_float(convert_float(value), precision, fspecs, buffer);
  3242. fspecs.precision = precision;
  3243. auto f = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
  3244. return write_float<Char>(out, f, specs, fspecs, loc);
  3245. }
  3246. template <typename Char, typename OutputIt, typename T,
  3247. FMT_ENABLE_IF(is_floating_point<T>::value)>
  3248. FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs,
  3249. locale_ref loc = {}) -> OutputIt {
  3250. if (const_check(!is_supported_floating_point(value))) return out;
  3251. return specs.localized && write_loc(out, value, specs, loc)
  3252. ? out
  3253. : write_float<Char>(out, value, specs, loc);
  3254. }
  3255. template <typename Char, typename OutputIt, typename T,
  3256. FMT_ENABLE_IF(is_fast_float<T>::value)>
  3257. FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
  3258. if (is_constant_evaluated()) return write<Char>(out, value, format_specs());
  3259. if (const_check(!is_supported_floating_point(value))) return out;
  3260. auto sign = sign_t::none;
  3261. if (detail::signbit(value)) {
  3262. sign = sign::minus;
  3263. value = -value;
  3264. }
  3265. constexpr auto specs = format_specs();
  3266. using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
  3267. using floaty_uint = typename dragonbox::float_info<floaty>::carrier_uint;
  3268. floaty_uint mask = exponent_mask<floaty>();
  3269. if ((bit_cast<floaty_uint>(value) & mask) == mask)
  3270. return write_nonfinite<Char>(out, std::isnan(value), specs, sign);
  3271. auto fspecs = float_specs();
  3272. fspecs.sign = sign;
  3273. auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
  3274. return write_float<Char>(out, dec, specs, fspecs, {});
  3275. }
  3276. template <typename Char, typename OutputIt, typename T,
  3277. FMT_ENABLE_IF(is_floating_point<T>::value &&
  3278. !is_fast_float<T>::value)>
  3279. inline auto write(OutputIt out, T value) -> OutputIt {
  3280. return write<Char>(out, value, format_specs());
  3281. }
  3282. template <typename Char, typename OutputIt>
  3283. auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {})
  3284. -> OutputIt {
  3285. FMT_ASSERT(false, "");
  3286. return out;
  3287. }
  3288. template <typename Char, typename OutputIt>
  3289. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)
  3290. -> OutputIt {
  3291. auto it = reserve(out, value.size());
  3292. it = copy_noinline<Char>(value.begin(), value.end(), it);
  3293. return base_iterator(out, it);
  3294. }
  3295. template <typename Char, typename OutputIt, typename T,
  3296. FMT_ENABLE_IF(has_to_string_view<T>::value)>
  3297. constexpr auto write(OutputIt out, const T& value) -> OutputIt {
  3298. return write<Char>(out, to_string_view(value));
  3299. }
  3300. // FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
  3301. template <
  3302. typename Char, typename OutputIt, typename T,
  3303. bool check =
  3304. std::is_enum<T>::value && !std::is_same<T, Char>::value &&
  3305. mapped_type_constant<T, basic_format_context<OutputIt, Char>>::value !=
  3306. type::custom_type,
  3307. FMT_ENABLE_IF(check)>
  3308. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  3309. return write<Char>(out, static_cast<underlying_t<T>>(value));
  3310. }
  3311. template <typename Char, typename OutputIt, typename T,
  3312. FMT_ENABLE_IF(std::is_same<T, bool>::value)>
  3313. FMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {},
  3314. locale_ref = {}) -> OutputIt {
  3315. return specs.type != presentation_type::none &&
  3316. specs.type != presentation_type::string
  3317. ? write<Char>(out, value ? 1 : 0, specs, {})
  3318. : write_bytes<Char>(out, value ? "true" : "false", specs);
  3319. }
  3320. template <typename Char, typename OutputIt>
  3321. FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {
  3322. auto it = reserve(out, 1);
  3323. *it++ = value;
  3324. return base_iterator(out, it);
  3325. }
  3326. template <typename Char, typename OutputIt>
  3327. FMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt {
  3328. if (value) return write(out, basic_string_view<Char>(value));
  3329. report_error("string pointer is null");
  3330. return out;
  3331. }
  3332. template <typename Char, typename OutputIt, typename T,
  3333. FMT_ENABLE_IF(std::is_same<T, void>::value)>
  3334. auto write(OutputIt out, const T* value, const format_specs& specs = {},
  3335. locale_ref = {}) -> OutputIt {
  3336. return write_ptr<Char>(out, bit_cast<uintptr_t>(value), &specs);
  3337. }
  3338. // A write overload that handles implicit conversions.
  3339. template <typename Char, typename OutputIt, typename T,
  3340. typename Context = basic_format_context<OutputIt, Char>>
  3341. FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t<
  3342. std::is_class<T>::value && !has_to_string_view<T>::value &&
  3343. !is_floating_point<T>::value && !std::is_same<T, Char>::value &&
  3344. !std::is_same<T, remove_cvref_t<decltype(arg_mapper<Context>().map(
  3345. value))>>::value,
  3346. OutputIt> {
  3347. return write<Char>(out, arg_mapper<Context>().map(value));
  3348. }
  3349. template <typename Char, typename OutputIt, typename T,
  3350. typename Context = basic_format_context<OutputIt, Char>>
  3351. FMT_CONSTEXPR auto write(OutputIt out, const T& value)
  3352. -> enable_if_t<mapped_type_constant<T, Context>::value ==
  3353. type::custom_type &&
  3354. !std::is_fundamental<T>::value,
  3355. OutputIt> {
  3356. auto formatter = typename Context::template formatter_type<T>();
  3357. auto parse_ctx = typename Context::parse_context_type({});
  3358. formatter.parse(parse_ctx);
  3359. auto ctx = Context(out, {}, {});
  3360. return formatter.format(value, ctx);
  3361. }
  3362. // An argument visitor that formats the argument and writes it via the output
  3363. // iterator. It's a class and not a generic lambda for compatibility with C++11.
  3364. template <typename Char> struct default_arg_formatter {
  3365. using iterator = basic_appender<Char>;
  3366. using context = buffered_context<Char>;
  3367. iterator out;
  3368. basic_format_args<context> args;
  3369. locale_ref loc;
  3370. template <typename T> auto operator()(T value) -> iterator {
  3371. return write<Char>(out, value);
  3372. }
  3373. auto operator()(typename basic_format_arg<context>::handle h) -> iterator {
  3374. basic_format_parse_context<Char> parse_ctx({});
  3375. context format_ctx(out, args, loc);
  3376. h.format(parse_ctx, format_ctx);
  3377. return format_ctx.out();
  3378. }
  3379. };
  3380. template <typename Char> struct arg_formatter {
  3381. using iterator = basic_appender<Char>;
  3382. using context = buffered_context<Char>;
  3383. iterator out;
  3384. const format_specs& specs;
  3385. locale_ref locale;
  3386. template <typename T>
  3387. FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator {
  3388. return detail::write<Char>(out, value, specs, locale);
  3389. }
  3390. auto operator()(typename basic_format_arg<context>::handle) -> iterator {
  3391. // User-defined types are handled separately because they require access
  3392. // to the parse context.
  3393. return out;
  3394. }
  3395. };
  3396. struct width_checker {
  3397. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  3398. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  3399. if (is_negative(value)) report_error("negative width");
  3400. return static_cast<unsigned long long>(value);
  3401. }
  3402. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  3403. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  3404. report_error("width is not integer");
  3405. return 0;
  3406. }
  3407. };
  3408. struct precision_checker {
  3409. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  3410. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  3411. if (is_negative(value)) report_error("negative precision");
  3412. return static_cast<unsigned long long>(value);
  3413. }
  3414. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  3415. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  3416. report_error("precision is not integer");
  3417. return 0;
  3418. }
  3419. };
  3420. template <typename Handler, typename FormatArg>
  3421. FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg) -> int {
  3422. unsigned long long value = arg.visit(Handler());
  3423. if (value > to_unsigned(max_value<int>())) report_error("number is too big");
  3424. return static_cast<int>(value);
  3425. }
  3426. template <typename Context, typename ID>
  3427. FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) -> decltype(ctx.arg(id)) {
  3428. auto arg = ctx.arg(id);
  3429. if (!arg) report_error("argument not found");
  3430. return arg;
  3431. }
  3432. template <typename Handler, typename Context>
  3433. FMT_CONSTEXPR void handle_dynamic_spec(int& value,
  3434. arg_ref<typename Context::char_type> ref,
  3435. Context& ctx) {
  3436. switch (ref.kind) {
  3437. case arg_id_kind::none:
  3438. break;
  3439. case arg_id_kind::index:
  3440. value = detail::get_dynamic_spec<Handler>(get_arg(ctx, ref.val.index));
  3441. break;
  3442. case arg_id_kind::name:
  3443. value = detail::get_dynamic_spec<Handler>(get_arg(ctx, ref.val.name));
  3444. break;
  3445. }
  3446. }
  3447. #if FMT_USE_USER_DEFINED_LITERALS
  3448. # if FMT_USE_NONTYPE_TEMPLATE_ARGS
  3449. template <typename T, typename Char, size_t N,
  3450. fmt::detail_exported::fixed_string<Char, N> Str>
  3451. struct statically_named_arg : view {
  3452. static constexpr auto name = Str.data;
  3453. const T& value;
  3454. statically_named_arg(const T& v) : value(v) {}
  3455. };
  3456. template <typename T, typename Char, size_t N,
  3457. fmt::detail_exported::fixed_string<Char, N> Str>
  3458. struct is_named_arg<statically_named_arg<T, Char, N, Str>> : std::true_type {};
  3459. template <typename T, typename Char, size_t N,
  3460. fmt::detail_exported::fixed_string<Char, N> Str>
  3461. struct is_statically_named_arg<statically_named_arg<T, Char, N, Str>>
  3462. : std::true_type {};
  3463. template <typename Char, size_t N,
  3464. fmt::detail_exported::fixed_string<Char, N> Str>
  3465. struct udl_arg {
  3466. template <typename T> auto operator=(T&& value) const {
  3467. return statically_named_arg<T, Char, N, Str>(std::forward<T>(value));
  3468. }
  3469. };
  3470. # else
  3471. template <typename Char> struct udl_arg {
  3472. const Char* str;
  3473. template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {
  3474. return {str, std::forward<T>(value)};
  3475. }
  3476. };
  3477. # endif
  3478. #endif // FMT_USE_USER_DEFINED_LITERALS
  3479. template <typename Locale, typename Char>
  3480. auto vformat(const Locale& loc, basic_string_view<Char> fmt,
  3481. typename detail::vformat_args<Char>::type args)
  3482. -> std::basic_string<Char> {
  3483. auto buf = basic_memory_buffer<Char>();
  3484. detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
  3485. return {buf.data(), buf.size()};
  3486. }
  3487. using format_func = void (*)(detail::buffer<char>&, int, const char*);
  3488. FMT_API void format_error_code(buffer<char>& out, int error_code,
  3489. string_view message) noexcept;
  3490. using fmt::report_error;
  3491. FMT_API void report_error(format_func func, int error_code,
  3492. const char* message) noexcept;
  3493. } // namespace detail
  3494. FMT_BEGIN_EXPORT
  3495. FMT_API auto vsystem_error(int error_code, string_view format_str,
  3496. format_args args) -> std::system_error;
  3497. /**
  3498. * Constructs `std::system_error` with a message formatted with
  3499. * `fmt::format(fmt, args...)`.
  3500. * `error_code` is a system error code as given by `errno`.
  3501. *
  3502. * **Example**:
  3503. *
  3504. * // This throws std::system_error with the description
  3505. * // cannot open file 'madeup': No such file or directory
  3506. * // or similar (system message may vary).
  3507. * const char* filename = "madeup";
  3508. * std::FILE* file = std::fopen(filename, "r");
  3509. * if (!file)
  3510. * throw fmt::system_error(errno, "cannot open file '{}'", filename);
  3511. */
  3512. template <typename... T>
  3513. auto system_error(int error_code, format_string<T...> fmt, T&&... args)
  3514. -> std::system_error {
  3515. return vsystem_error(error_code, fmt, fmt::make_format_args(args...));
  3516. }
  3517. /**
  3518. * Formats an error message for an error returned by an operating system or a
  3519. * language runtime, for example a file opening error, and writes it to `out`.
  3520. * The format is the same as the one used by `std::system_error(ec, message)`
  3521. * where `ec` is `std::error_code(error_code, std::generic_category())`.
  3522. * It is implementation-defined but normally looks like:
  3523. *
  3524. * <message>: <system-message>
  3525. *
  3526. * where `<message>` is the passed message and `<system-message>` is the system
  3527. * message corresponding to the error code.
  3528. * `error_code` is a system error code as given by `errno`.
  3529. */
  3530. FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
  3531. const char* message) noexcept;
  3532. // Reports a system error without throwing an exception.
  3533. // Can be used to report errors from destructors.
  3534. FMT_API void report_system_error(int error_code, const char* message) noexcept;
  3535. /// A fast integer formatter.
  3536. class format_int {
  3537. private:
  3538. // Buffer should be large enough to hold all digits (digits10 + 1),
  3539. // a sign and a null character.
  3540. enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
  3541. mutable char buffer_[buffer_size];
  3542. char* str_;
  3543. template <typename UInt>
  3544. FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* {
  3545. auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
  3546. return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
  3547. }
  3548. template <typename Int>
  3549. FMT_CONSTEXPR20 auto format_signed(Int value) -> char* {
  3550. auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
  3551. bool negative = value < 0;
  3552. if (negative) abs_value = 0 - abs_value;
  3553. auto begin = format_unsigned(abs_value);
  3554. if (negative) *--begin = '-';
  3555. return begin;
  3556. }
  3557. public:
  3558. explicit FMT_CONSTEXPR20 format_int(int value) : str_(format_signed(value)) {}
  3559. explicit FMT_CONSTEXPR20 format_int(long value)
  3560. : str_(format_signed(value)) {}
  3561. explicit FMT_CONSTEXPR20 format_int(long long value)
  3562. : str_(format_signed(value)) {}
  3563. explicit FMT_CONSTEXPR20 format_int(unsigned value)
  3564. : str_(format_unsigned(value)) {}
  3565. explicit FMT_CONSTEXPR20 format_int(unsigned long value)
  3566. : str_(format_unsigned(value)) {}
  3567. explicit FMT_CONSTEXPR20 format_int(unsigned long long value)
  3568. : str_(format_unsigned(value)) {}
  3569. /// Returns the number of characters written to the output buffer.
  3570. FMT_CONSTEXPR20 auto size() const -> size_t {
  3571. return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
  3572. }
  3573. /// Returns a pointer to the output buffer content. No terminating null
  3574. /// character is appended.
  3575. FMT_CONSTEXPR20 auto data() const -> const char* { return str_; }
  3576. /// Returns a pointer to the output buffer content with terminating null
  3577. /// character appended.
  3578. FMT_CONSTEXPR20 auto c_str() const -> const char* {
  3579. buffer_[buffer_size - 1] = '\0';
  3580. return str_;
  3581. }
  3582. /// Returns the content of the output buffer as an `std::string`.
  3583. auto str() const -> std::string { return std::string(str_, size()); }
  3584. };
  3585. template <typename T, typename Char>
  3586. struct formatter<T, Char, enable_if_t<detail::has_format_as<T>::value>>
  3587. : formatter<detail::format_as_t<T>, Char> {
  3588. template <typename FormatContext>
  3589. auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) {
  3590. using base = formatter<detail::format_as_t<T>, Char>;
  3591. auto&& val = format_as(value); // Make an lvalue reference for format.
  3592. return base::format(val, ctx);
  3593. }
  3594. };
  3595. #define FMT_FORMAT_AS(Type, Base) \
  3596. template <typename Char> \
  3597. struct formatter<Type, Char> : formatter<Base, Char> {}
  3598. FMT_FORMAT_AS(signed char, int);
  3599. FMT_FORMAT_AS(unsigned char, unsigned);
  3600. FMT_FORMAT_AS(short, int);
  3601. FMT_FORMAT_AS(unsigned short, unsigned);
  3602. FMT_FORMAT_AS(long, detail::long_type);
  3603. FMT_FORMAT_AS(unsigned long, detail::ulong_type);
  3604. FMT_FORMAT_AS(Char*, const Char*);
  3605. FMT_FORMAT_AS(std::nullptr_t, const void*);
  3606. FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
  3607. FMT_FORMAT_AS(void*, const void*);
  3608. template <typename Char, typename Traits, typename Allocator>
  3609. class formatter<std::basic_string<Char, Traits, Allocator>, Char>
  3610. : public formatter<basic_string_view<Char>, Char> {};
  3611. template <typename Char, size_t N>
  3612. struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {};
  3613. /**
  3614. * Converts `p` to `const void*` for pointer formatting.
  3615. *
  3616. * **Example**:
  3617. *
  3618. * auto s = fmt::format("{}", fmt::ptr(p));
  3619. */
  3620. template <typename T> auto ptr(T p) -> const void* {
  3621. static_assert(std::is_pointer<T>::value, "");
  3622. return detail::bit_cast<const void*>(p);
  3623. }
  3624. /**
  3625. * Converts `e` to the underlying type.
  3626. *
  3627. * **Example**:
  3628. *
  3629. * enum class color { red, green, blue };
  3630. * auto s = fmt::format("{}", fmt::underlying(color::red));
  3631. */
  3632. template <typename Enum>
  3633. constexpr auto underlying(Enum e) noexcept -> underlying_t<Enum> {
  3634. return static_cast<underlying_t<Enum>>(e);
  3635. }
  3636. namespace enums {
  3637. template <typename Enum, FMT_ENABLE_IF(std::is_enum<Enum>::value)>
  3638. constexpr auto format_as(Enum e) noexcept -> underlying_t<Enum> {
  3639. return static_cast<underlying_t<Enum>>(e);
  3640. }
  3641. } // namespace enums
  3642. class bytes {
  3643. private:
  3644. string_view data_;
  3645. friend struct formatter<bytes>;
  3646. public:
  3647. explicit bytes(string_view data) : data_(data) {}
  3648. };
  3649. template <> struct formatter<bytes> {
  3650. private:
  3651. detail::dynamic_format_specs<> specs_;
  3652. public:
  3653. template <typename ParseContext>
  3654. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* {
  3655. return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,
  3656. detail::type::string_type);
  3657. }
  3658. template <typename FormatContext>
  3659. auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) {
  3660. auto specs = specs_;
  3661. detail::handle_dynamic_spec<detail::width_checker>(specs.width,
  3662. specs.width_ref, ctx);
  3663. detail::handle_dynamic_spec<detail::precision_checker>(
  3664. specs.precision, specs.precision_ref, ctx);
  3665. return detail::write_bytes<char>(ctx.out(), b.data_, specs);
  3666. }
  3667. };
  3668. // group_digits_view is not derived from view because it copies the argument.
  3669. template <typename T> struct group_digits_view {
  3670. T value;
  3671. };
  3672. /**
  3673. * Returns a view that formats an integer value using ',' as a
  3674. * locale-independent thousands separator.
  3675. *
  3676. * **Example**:
  3677. *
  3678. * fmt::print("{}", fmt::group_digits(12345));
  3679. * // Output: "12,345"
  3680. */
  3681. template <typename T> auto group_digits(T value) -> group_digits_view<T> {
  3682. return {value};
  3683. }
  3684. template <typename T> struct formatter<group_digits_view<T>> : formatter<T> {
  3685. private:
  3686. detail::dynamic_format_specs<> specs_;
  3687. public:
  3688. template <typename ParseContext>
  3689. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> const char* {
  3690. return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,
  3691. detail::type::int_type);
  3692. }
  3693. template <typename FormatContext>
  3694. auto format(group_digits_view<T> t, FormatContext& ctx) const
  3695. -> decltype(ctx.out()) {
  3696. auto specs = specs_;
  3697. detail::handle_dynamic_spec<detail::width_checker>(specs.width,
  3698. specs.width_ref, ctx);
  3699. detail::handle_dynamic_spec<detail::precision_checker>(
  3700. specs.precision, specs.precision_ref, ctx);
  3701. auto arg = detail::make_write_int_arg(t.value, specs.sign);
  3702. return detail::write_int(
  3703. ctx.out(), static_cast<detail::uint64_or_128_t<T>>(arg.abs_value),
  3704. arg.prefix, specs, detail::digit_grouping<char>("\3", ","));
  3705. }
  3706. };
  3707. template <typename T, typename Char> struct nested_view {
  3708. const formatter<T, Char>* fmt;
  3709. const T* value;
  3710. };
  3711. template <typename T, typename Char>
  3712. struct formatter<nested_view<T, Char>, Char> {
  3713. template <typename ParseContext>
  3714. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  3715. return ctx.begin();
  3716. }
  3717. template <typename FormatContext>
  3718. auto format(nested_view<T, Char> view, FormatContext& ctx) const
  3719. -> decltype(ctx.out()) {
  3720. return view.fmt->format(*view.value, ctx);
  3721. }
  3722. };
  3723. template <typename T, typename Char = char> struct nested_formatter {
  3724. private:
  3725. int width_;
  3726. detail::fill_t fill_;
  3727. align_t align_ : 4;
  3728. formatter<T, Char> formatter_;
  3729. public:
  3730. constexpr nested_formatter() : width_(0), align_(align_t::none) {}
  3731. FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
  3732. -> decltype(ctx.begin()) {
  3733. auto specs = detail::dynamic_format_specs<Char>();
  3734. auto it = parse_format_specs(ctx.begin(), ctx.end(), specs, ctx,
  3735. detail::type::none_type);
  3736. width_ = specs.width;
  3737. fill_ = specs.fill;
  3738. align_ = specs.align;
  3739. ctx.advance_to(it);
  3740. return formatter_.parse(ctx);
  3741. }
  3742. template <typename FormatContext, typename F>
  3743. auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) {
  3744. if (width_ == 0) return write(ctx.out());
  3745. auto buf = basic_memory_buffer<Char>();
  3746. write(basic_appender<Char>(buf));
  3747. auto specs = format_specs();
  3748. specs.width = width_;
  3749. specs.fill = fill_;
  3750. specs.align = align_;
  3751. return detail::write<Char>(
  3752. ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
  3753. }
  3754. auto nested(const T& value) const -> nested_view<T, Char> {
  3755. return nested_view<T, Char>{&formatter_, &value};
  3756. }
  3757. };
  3758. /**
  3759. * Converts `value` to `std::string` using the default format for type `T`.
  3760. *
  3761. * **Example**:
  3762. *
  3763. * std::string answer = fmt::to_string(42);
  3764. */
  3765. template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&
  3766. !detail::has_format_as<T>::value)>
  3767. inline auto to_string(const T& value) -> std::string {
  3768. auto buffer = memory_buffer();
  3769. detail::write<char>(appender(buffer), value);
  3770. return {buffer.data(), buffer.size()};
  3771. }
  3772. template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
  3773. FMT_NODISCARD inline auto to_string(T value) -> std::string {
  3774. // The buffer should be large enough to store the number including the sign
  3775. // or "false" for bool.
  3776. constexpr int max_size = detail::digits10<T>() + 2;
  3777. char buffer[max_size > 5 ? static_cast<unsigned>(max_size) : 5];
  3778. char* begin = buffer;
  3779. return std::string(begin, detail::write<char>(begin, value));
  3780. }
  3781. template <typename Char, size_t SIZE>
  3782. FMT_NODISCARD auto to_string(const basic_memory_buffer<Char, SIZE>& buf)
  3783. -> std::basic_string<Char> {
  3784. auto size = buf.size();
  3785. detail::assume(size < std::basic_string<Char>().max_size());
  3786. return std::basic_string<Char>(buf.data(), size);
  3787. }
  3788. template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&
  3789. detail::has_format_as<T>::value)>
  3790. inline auto to_string(const T& value) -> std::string {
  3791. return to_string(format_as(value));
  3792. }
  3793. FMT_END_EXPORT
  3794. namespace detail {
  3795. template <typename Char>
  3796. void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
  3797. typename vformat_args<Char>::type args, locale_ref loc) {
  3798. auto out = basic_appender<Char>(buf);
  3799. if (fmt.size() == 2 && equal2(fmt.data(), "{}")) {
  3800. auto arg = args.get(0);
  3801. if (!arg) report_error("argument not found");
  3802. arg.visit(default_arg_formatter<Char>{out, args, loc});
  3803. return;
  3804. }
  3805. struct format_handler {
  3806. basic_format_parse_context<Char> parse_context;
  3807. buffered_context<Char> context;
  3808. format_handler(basic_appender<Char> p_out, basic_string_view<Char> str,
  3809. basic_format_args<buffered_context<Char>> p_args,
  3810. locale_ref p_loc)
  3811. : parse_context(str), context(p_out, p_args, p_loc) {}
  3812. void on_text(const Char* begin, const Char* end) {
  3813. auto text = basic_string_view<Char>(begin, to_unsigned(end - begin));
  3814. context.advance_to(write<Char>(context.out(), text));
  3815. }
  3816. FMT_CONSTEXPR auto on_arg_id() -> int {
  3817. return parse_context.next_arg_id();
  3818. }
  3819. FMT_CONSTEXPR auto on_arg_id(int id) -> int {
  3820. parse_context.check_arg_id(id);
  3821. return id;
  3822. }
  3823. FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
  3824. parse_context.check_arg_id(id);
  3825. int arg_id = context.arg_id(id);
  3826. if (arg_id < 0) report_error("argument not found");
  3827. return arg_id;
  3828. }
  3829. FMT_INLINE void on_replacement_field(int id, const Char*) {
  3830. auto arg = get_arg(context, id);
  3831. context.advance_to(arg.visit(default_arg_formatter<Char>{
  3832. context.out(), context.args(), context.locale()}));
  3833. }
  3834. auto on_format_specs(int id, const Char* begin, const Char* end)
  3835. -> const Char* {
  3836. auto arg = get_arg(context, id);
  3837. // Not using a visitor for custom types gives better codegen.
  3838. if (arg.format_custom(begin, parse_context, context))
  3839. return parse_context.begin();
  3840. auto specs = detail::dynamic_format_specs<Char>();
  3841. begin = parse_format_specs(begin, end, specs, parse_context, arg.type());
  3842. detail::handle_dynamic_spec<detail::width_checker>(
  3843. specs.width, specs.width_ref, context);
  3844. detail::handle_dynamic_spec<detail::precision_checker>(
  3845. specs.precision, specs.precision_ref, context);
  3846. if (begin == end || *begin != '}')
  3847. report_error("missing '}' in format string");
  3848. context.advance_to(arg.visit(
  3849. arg_formatter<Char>{context.out(), specs, context.locale()}));
  3850. return begin;
  3851. }
  3852. FMT_NORETURN void on_error(const char* message) { report_error(message); }
  3853. };
  3854. detail::parse_format_string<false>(fmt, format_handler(out, fmt, args, loc));
  3855. }
  3856. FMT_BEGIN_EXPORT
  3857. #ifndef FMT_HEADER_ONLY
  3858. extern template FMT_API void vformat_to(buffer<char>&, string_view,
  3859. typename vformat_args<>::type,
  3860. locale_ref);
  3861. extern template FMT_API auto thousands_sep_impl<char>(locale_ref)
  3862. -> thousands_sep_result<char>;
  3863. extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
  3864. -> thousands_sep_result<wchar_t>;
  3865. extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
  3866. extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
  3867. #endif // FMT_HEADER_ONLY
  3868. FMT_END_EXPORT
  3869. template <typename T, typename Char, type TYPE>
  3870. template <typename FormatContext>
  3871. FMT_CONSTEXPR FMT_INLINE auto native_formatter<T, Char, TYPE>::format(
  3872. const T& val, FormatContext& ctx) const -> decltype(ctx.out()) {
  3873. if (specs_.width_ref.kind == arg_id_kind::none &&
  3874. specs_.precision_ref.kind == arg_id_kind::none) {
  3875. return write<Char>(ctx.out(), val, specs_, ctx.locale());
  3876. }
  3877. auto specs = specs_;
  3878. handle_dynamic_spec<width_checker>(specs.width, specs.width_ref, ctx);
  3879. handle_dynamic_spec<precision_checker>(specs.precision, specs.precision_ref,
  3880. ctx);
  3881. return write<Char>(ctx.out(), val, specs, ctx.locale());
  3882. }
  3883. } // namespace detail
  3884. FMT_BEGIN_EXPORT
  3885. template <typename Char>
  3886. struct formatter<detail::float128, Char>
  3887. : detail::native_formatter<detail::float128, Char,
  3888. detail::type::float_type> {};
  3889. #if FMT_USE_USER_DEFINED_LITERALS
  3890. inline namespace literals {
  3891. /**
  3892. * User-defined literal equivalent of `fmt::arg`.
  3893. *
  3894. * **Example**:
  3895. *
  3896. * using namespace fmt::literals;
  3897. * fmt::print("The answer is {answer}.", "answer"_a=42);
  3898. */
  3899. # if FMT_USE_NONTYPE_TEMPLATE_ARGS
  3900. template <detail_exported::fixed_string Str> constexpr auto operator""_a() {
  3901. using char_t = remove_cvref_t<decltype(Str.data[0])>;
  3902. return detail::udl_arg<char_t, sizeof(Str.data) / sizeof(char_t), Str>();
  3903. }
  3904. # else
  3905. constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg<char> {
  3906. return {s};
  3907. }
  3908. # endif
  3909. } // namespace literals
  3910. #endif // FMT_USE_USER_DEFINED_LITERALS
  3911. FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
  3912. /**
  3913. * Formats `args` according to specifications in `fmt` and returns the result
  3914. * as a string.
  3915. *
  3916. * **Example**:
  3917. *
  3918. * #include <fmt/format.h>
  3919. * std::string message = fmt::format("The answer is {}.", 42);
  3920. */
  3921. template <typename... T>
  3922. FMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)
  3923. -> std::string {
  3924. return vformat(fmt, fmt::make_format_args(args...));
  3925. }
  3926. template <typename Locale, FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  3927. inline auto vformat(const Locale& loc, string_view fmt, format_args args)
  3928. -> std::string {
  3929. return detail::vformat(loc, fmt, args);
  3930. }
  3931. template <typename Locale, typename... T,
  3932. FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  3933. inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
  3934. -> std::string {
  3935. return fmt::vformat(loc, string_view(fmt), fmt::make_format_args(args...));
  3936. }
  3937. template <typename OutputIt, typename Locale,
  3938. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  3939. detail::is_locale<Locale>::value)>
  3940. auto vformat_to(OutputIt out, const Locale& loc, string_view fmt,
  3941. format_args args) -> OutputIt {
  3942. using detail::get_buffer;
  3943. auto&& buf = get_buffer<char>(out);
  3944. detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
  3945. return detail::get_iterator(buf, out);
  3946. }
  3947. template <typename OutputIt, typename Locale, typename... T,
  3948. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  3949. detail::is_locale<Locale>::value)>
  3950. FMT_INLINE auto format_to(OutputIt out, const Locale& loc,
  3951. format_string<T...> fmt, T&&... args) -> OutputIt {
  3952. return vformat_to(out, loc, fmt, fmt::make_format_args(args...));
  3953. }
  3954. template <typename Locale, typename... T,
  3955. FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  3956. FMT_NODISCARD FMT_INLINE auto formatted_size(const Locale& loc,
  3957. format_string<T...> fmt,
  3958. T&&... args) -> size_t {
  3959. auto buf = detail::counting_buffer<>();
  3960. detail::vformat_to<char>(buf, fmt, fmt::make_format_args(args...),
  3961. detail::locale_ref(loc));
  3962. return buf.count();
  3963. }
  3964. FMT_END_EXPORT
  3965. FMT_END_NAMESPACE
  3966. #ifdef FMT_HEADER_ONLY
  3967. # define FMT_FUNC inline
  3968. # include "format-inl.h"
  3969. #else
  3970. # define FMT_FUNC
  3971. #endif
  3972. // Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES.
  3973. #ifdef FMT_REMOVE_TRANSITIVE_INCLUDES
  3974. # undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
  3975. #endif
  3976. #endif // FMT_FORMAT_H_