format.h 161 KB

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