format.h 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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 <limits> // std::numeric_limits
  31. #include <memory> // std::uninitialized_copy
  32. #include <stdexcept> // std::runtime_error
  33. #include <system_error> // std::system_error
  34. #include <utility> // std::swap
  35. #ifdef __cpp_lib_bit_cast
  36. # include <bit> // std::bitcast
  37. #endif
  38. #include "core.h"
  39. #if FMT_GCC_VERSION
  40. # define FMT_GCC_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
  41. #else
  42. # define FMT_GCC_VISIBILITY_HIDDEN
  43. #endif
  44. #ifdef __NVCC__
  45. # define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
  46. #else
  47. # define FMT_CUDA_VERSION 0
  48. #endif
  49. #ifdef __has_builtin
  50. # define FMT_HAS_BUILTIN(x) __has_builtin(x)
  51. #else
  52. # define FMT_HAS_BUILTIN(x) 0
  53. #endif
  54. #if FMT_GCC_VERSION || FMT_CLANG_VERSION
  55. # define FMT_NOINLINE __attribute__((noinline))
  56. #else
  57. # define FMT_NOINLINE
  58. #endif
  59. #if FMT_MSC_VER
  60. # define FMT_MSC_DEFAULT = default
  61. #else
  62. # define FMT_MSC_DEFAULT
  63. #endif
  64. #ifndef FMT_THROW
  65. # if FMT_EXCEPTIONS
  66. # if FMT_MSC_VER || FMT_NVCC
  67. FMT_BEGIN_NAMESPACE
  68. namespace detail {
  69. template <typename Exception> inline void do_throw(const Exception& x) {
  70. // Silence unreachable code warnings in MSVC and NVCC because these
  71. // are nearly impossible to fix in a generic code.
  72. volatile bool b = true;
  73. if (b) throw x;
  74. }
  75. } // namespace detail
  76. FMT_END_NAMESPACE
  77. # define FMT_THROW(x) detail::do_throw(x)
  78. # else
  79. # define FMT_THROW(x) throw x
  80. # endif
  81. # else
  82. # define FMT_THROW(x) \
  83. do { \
  84. FMT_ASSERT(false, (x).what()); \
  85. } while (false)
  86. # endif
  87. #endif
  88. #if FMT_EXCEPTIONS
  89. # define FMT_TRY try
  90. # define FMT_CATCH(x) catch (x)
  91. #else
  92. # define FMT_TRY if (true)
  93. # define FMT_CATCH(x) if (false)
  94. #endif
  95. #ifndef FMT_MAYBE_UNUSED
  96. # if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused)
  97. # define FMT_MAYBE_UNUSED [[maybe_unused]]
  98. # else
  99. # define FMT_MAYBE_UNUSED
  100. # endif
  101. #endif
  102. // Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
  103. #if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
  104. # define FMT_DEPRECATED_ALIAS
  105. #else
  106. # define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
  107. #endif
  108. #ifndef FMT_USE_USER_DEFINED_LITERALS
  109. // EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
  110. # if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
  111. FMT_MSC_VER >= 1900) && \
  112. (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
  113. # define FMT_USE_USER_DEFINED_LITERALS 1
  114. # else
  115. # define FMT_USE_USER_DEFINED_LITERALS 0
  116. # endif
  117. #endif
  118. // Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
  119. // integer formatter template instantiations to just one by only using the
  120. // largest integer type. This results in a reduction in binary size but will
  121. // cause a decrease in integer formatting performance.
  122. #if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
  123. # define FMT_REDUCE_INT_INSTANTIATIONS 0
  124. #endif
  125. // __builtin_clz is broken in clang with Microsoft CodeGen:
  126. // https://github.com/fmtlib/fmt/issues/519.
  127. #if !FMT_MSC_VER
  128. # if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
  129. # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
  130. # endif
  131. # if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
  132. # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
  133. # endif
  134. #endif
  135. // __builtin_ctz is broken in Intel Compiler Classic on Windows:
  136. // https://github.com/fmtlib/fmt/issues/2510.
  137. #ifndef __ICL
  138. # if FMT_HAS_BUILTIN(__builtin_ctz) || FMT_GCC_VERSION || FMT_ICC_VERSION
  139. # define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
  140. # endif
  141. # if FMT_HAS_BUILTIN(__builtin_ctzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
  142. # define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
  143. # endif
  144. #endif
  145. #if FMT_MSC_VER
  146. # include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128
  147. #endif
  148. // Some compilers masquerade as both MSVC and GCC-likes or otherwise support
  149. // __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
  150. // MSVC intrinsics if the clz and clzll builtins are not available.
  151. #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(FMT_BUILTIN_CTZLL)
  152. FMT_BEGIN_NAMESPACE
  153. namespace detail {
  154. // Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
  155. # if !defined(__clang__)
  156. # pragma intrinsic(_BitScanForward)
  157. # pragma intrinsic(_BitScanReverse)
  158. # if defined(_WIN64)
  159. # pragma intrinsic(_BitScanForward64)
  160. # pragma intrinsic(_BitScanReverse64)
  161. # endif
  162. # endif
  163. inline auto clz(uint32_t x) -> int {
  164. unsigned long r = 0;
  165. _BitScanReverse(&r, x);
  166. FMT_ASSERT(x != 0, "");
  167. // Static analysis complains about using uninitialized data
  168. // "r", but the only way that can happen is if "x" is 0,
  169. // which the callers guarantee to not happen.
  170. FMT_MSC_WARNING(suppress : 6102)
  171. return 31 ^ static_cast<int>(r);
  172. }
  173. # define FMT_BUILTIN_CLZ(n) detail::clz(n)
  174. inline auto clzll(uint64_t x) -> int {
  175. unsigned long r = 0;
  176. # ifdef _WIN64
  177. _BitScanReverse64(&r, x);
  178. # else
  179. // Scan the high 32 bits.
  180. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 ^ (r + 32);
  181. // Scan the low 32 bits.
  182. _BitScanReverse(&r, static_cast<uint32_t>(x));
  183. # endif
  184. FMT_ASSERT(x != 0, "");
  185. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  186. return 63 ^ static_cast<int>(r);
  187. }
  188. # define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
  189. inline auto ctz(uint32_t x) -> int {
  190. unsigned long r = 0;
  191. _BitScanForward(&r, x);
  192. FMT_ASSERT(x != 0, "");
  193. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  194. return static_cast<int>(r);
  195. }
  196. # define FMT_BUILTIN_CTZ(n) detail::ctz(n)
  197. inline auto ctzll(uint64_t x) -> int {
  198. unsigned long r = 0;
  199. FMT_ASSERT(x != 0, "");
  200. FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning.
  201. # ifdef _WIN64
  202. _BitScanForward64(&r, x);
  203. # else
  204. // Scan the low 32 bits.
  205. if (_BitScanForward(&r, static_cast<uint32_t>(x))) return static_cast<int>(r);
  206. // Scan the high 32 bits.
  207. _BitScanForward(&r, static_cast<uint32_t>(x >> 32));
  208. r += 32;
  209. # endif
  210. return static_cast<int>(r);
  211. }
  212. # define FMT_BUILTIN_CTZLL(n) detail::ctzll(n)
  213. } // namespace detail
  214. FMT_END_NAMESPACE
  215. #endif
  216. #ifdef FMT_HEADER_ONLY
  217. # define FMT_HEADER_ONLY_CONSTEXPR20 FMT_CONSTEXPR20
  218. #else
  219. # define FMT_HEADER_ONLY_CONSTEXPR20
  220. #endif
  221. FMT_BEGIN_NAMESPACE
  222. namespace detail {
  223. template <typename Streambuf> class formatbuf : public Streambuf {
  224. private:
  225. using char_type = typename Streambuf::char_type;
  226. using streamsize = decltype(std::declval<Streambuf>().sputn(nullptr, 0));
  227. using int_type = typename Streambuf::int_type;
  228. using traits_type = typename Streambuf::traits_type;
  229. buffer<char_type>& buffer_;
  230. public:
  231. explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}
  232. protected:
  233. // The put area is always empty. This makes the implementation simpler and has
  234. // the advantage that the streambuf and the buffer are always in sync and
  235. // sputc never writes into uninitialized memory. A disadvantage is that each
  236. // call to sputc always results in a (virtual) call to overflow. There is no
  237. // disadvantage here for sputn since this always results in a call to xsputn.
  238. auto overflow(int_type ch) -> int_type override {
  239. if (!traits_type::eq_int_type(ch, traits_type::eof()))
  240. buffer_.push_back(static_cast<char_type>(ch));
  241. return ch;
  242. }
  243. auto xsputn(const char_type* s, streamsize count) -> streamsize override {
  244. buffer_.append(s, s + count);
  245. return count;
  246. }
  247. };
  248. // Implementation of std::bit_cast for pre-C++20.
  249. template <typename To, typename From>
  250. FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
  251. static_assert(sizeof(To) == sizeof(From), "size mismatch");
  252. #ifdef __cpp_lib_bit_cast
  253. if (is_constant_evaluated()) return std::bit_cast<To>(from);
  254. #endif
  255. auto to = To();
  256. std::memcpy(&to, &from, sizeof(to));
  257. return to;
  258. }
  259. inline auto is_big_endian() -> bool {
  260. #ifdef _WIN32
  261. return false;
  262. #elif defined(__BIG_ENDIAN__)
  263. return true;
  264. #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
  265. return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
  266. #else
  267. struct bytes {
  268. char data[sizeof(int)];
  269. };
  270. return bit_cast<bytes>(1).data[0] == 0;
  271. #endif
  272. }
  273. // A fallback implementation of uintptr_t for systems that lack it.
  274. struct fallback_uintptr {
  275. unsigned char value[sizeof(void*)];
  276. fallback_uintptr() = default;
  277. explicit fallback_uintptr(const void* p) {
  278. *this = bit_cast<fallback_uintptr>(p);
  279. if (const_check(is_big_endian())) {
  280. for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j)
  281. std::swap(value[i], value[j]);
  282. }
  283. }
  284. };
  285. #ifdef UINTPTR_MAX
  286. using uintptr_t = ::uintptr_t;
  287. inline auto to_uintptr(const void* p) -> uintptr_t {
  288. return bit_cast<uintptr_t>(p);
  289. }
  290. #else
  291. using uintptr_t = fallback_uintptr;
  292. inline auto to_uintptr(const void* p) -> fallback_uintptr {
  293. return fallback_uintptr(p);
  294. }
  295. #endif
  296. // Returns the largest possible value for type T. Same as
  297. // std::numeric_limits<T>::max() but shorter and not affected by the max macro.
  298. template <typename T> constexpr auto max_value() -> T {
  299. return (std::numeric_limits<T>::max)();
  300. }
  301. template <typename T> constexpr auto num_bits() -> int {
  302. return std::numeric_limits<T>::digits;
  303. }
  304. // std::numeric_limits<T>::digits may return 0 for 128-bit ints.
  305. template <> constexpr auto num_bits<int128_t>() -> int { return 128; }
  306. template <> constexpr auto num_bits<uint128_t>() -> int { return 128; }
  307. template <> constexpr auto num_bits<fallback_uintptr>() -> int {
  308. return static_cast<int>(sizeof(void*) *
  309. std::numeric_limits<unsigned char>::digits);
  310. }
  311. FMT_INLINE void assume(bool condition) {
  312. (void)condition;
  313. #if FMT_HAS_BUILTIN(__builtin_assume)
  314. __builtin_assume(condition);
  315. #endif
  316. }
  317. // An approximation of iterator_t for pre-C++20 systems.
  318. template <typename T>
  319. using iterator_t = decltype(std::begin(std::declval<T&>()));
  320. template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>()));
  321. // A workaround for std::string not having mutable data() until C++17.
  322. template <typename Char>
  323. inline auto get_data(std::basic_string<Char>& s) -> Char* {
  324. return &s[0];
  325. }
  326. template <typename Container>
  327. inline auto get_data(Container& c) -> typename Container::value_type* {
  328. return c.data();
  329. }
  330. #if defined(_SECURE_SCL) && _SECURE_SCL
  331. // Make a checked iterator to avoid MSVC warnings.
  332. template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
  333. template <typename T>
  334. constexpr auto make_checked(T* p, size_t size) -> checked_ptr<T> {
  335. return {p, size};
  336. }
  337. #else
  338. template <typename T> using checked_ptr = T*;
  339. template <typename T> constexpr auto make_checked(T* p, size_t) -> T* {
  340. return p;
  341. }
  342. #endif
  343. // Attempts to reserve space for n extra characters in the output range.
  344. // Returns a pointer to the reserved range or a reference to it.
  345. template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
  346. #if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION
  347. __attribute__((no_sanitize("undefined")))
  348. #endif
  349. inline auto
  350. reserve(std::back_insert_iterator<Container> it, size_t n)
  351. -> checked_ptr<typename Container::value_type> {
  352. Container& c = get_container(it);
  353. size_t size = c.size();
  354. c.resize(size + n);
  355. return make_checked(get_data(c) + size, n);
  356. }
  357. template <typename T>
  358. inline auto reserve(buffer_appender<T> it, size_t n) -> buffer_appender<T> {
  359. buffer<T>& buf = get_container(it);
  360. buf.try_reserve(buf.size() + n);
  361. return it;
  362. }
  363. template <typename Iterator>
  364. constexpr auto reserve(Iterator& it, size_t) -> Iterator& {
  365. return it;
  366. }
  367. template <typename OutputIt>
  368. using reserve_iterator =
  369. remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
  370. template <typename T, typename OutputIt>
  371. constexpr auto to_pointer(OutputIt, size_t) -> T* {
  372. return nullptr;
  373. }
  374. template <typename T> auto to_pointer(buffer_appender<T> it, size_t n) -> T* {
  375. buffer<T>& buf = get_container(it);
  376. auto size = buf.size();
  377. if (buf.capacity() < size + n) return nullptr;
  378. buf.try_resize(size + n);
  379. return buf.data() + size;
  380. }
  381. template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
  382. inline auto base_iterator(std::back_insert_iterator<Container>& it,
  383. checked_ptr<typename Container::value_type>)
  384. -> std::back_insert_iterator<Container> {
  385. return it;
  386. }
  387. template <typename Iterator>
  388. constexpr auto base_iterator(Iterator, Iterator it) -> Iterator {
  389. return it;
  390. }
  391. // <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n
  392. // instead (#1998).
  393. template <typename OutputIt, typename Size, typename T>
  394. FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)
  395. -> OutputIt {
  396. for (Size i = 0; i < count; ++i) *out++ = value;
  397. return out;
  398. }
  399. template <typename T, typename Size>
  400. FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {
  401. if (is_constant_evaluated()) {
  402. return fill_n<T*, Size, T>(out, count, value);
  403. }
  404. std::memset(out, value, to_unsigned(count));
  405. return out + count;
  406. }
  407. #ifdef __cpp_char8_t
  408. using char8_type = char8_t;
  409. #else
  410. enum char8_type : unsigned char {};
  411. #endif
  412. template <typename OutChar, typename InputIt, typename OutputIt>
  413. FMT_CONSTEXPR FMT_NOINLINE auto copy_str_noinline(InputIt begin, InputIt end,
  414. OutputIt out) -> OutputIt {
  415. return copy_str<OutChar>(begin, end, out);
  416. }
  417. // A public domain branchless UTF-8 decoder by Christopher Wellons:
  418. // https://github.com/skeeto/branchless-utf8
  419. /* Decode the next character, c, from s, reporting errors in e.
  420. *
  421. * Since this is a branchless decoder, four bytes will be read from the
  422. * buffer regardless of the actual length of the next character. This
  423. * means the buffer _must_ have at least three bytes of zero padding
  424. * following the end of the data stream.
  425. *
  426. * Errors are reported in e, which will be non-zero if the parsed
  427. * character was somehow invalid: invalid byte sequence, non-canonical
  428. * encoding, or a surrogate half.
  429. *
  430. * The function returns a pointer to the next character. When an error
  431. * occurs, this pointer will be a guess that depends on the particular
  432. * error, but it will always advance at least one byte.
  433. */
  434. FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
  435. -> const char* {
  436. constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
  437. constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
  438. constexpr const int shiftc[] = {0, 18, 12, 6, 0};
  439. constexpr const int shifte[] = {0, 6, 4, 2, 0};
  440. int len = code_point_length(s);
  441. const char* next = s + len;
  442. // Assume a four-byte character and load four bytes. Unused bits are
  443. // shifted out.
  444. *c = uint32_t(s[0] & masks[len]) << 18;
  445. *c |= uint32_t(s[1] & 0x3f) << 12;
  446. *c |= uint32_t(s[2] & 0x3f) << 6;
  447. *c |= uint32_t(s[3] & 0x3f) << 0;
  448. *c >>= shiftc[len];
  449. // Accumulate the various error conditions.
  450. using uchar = unsigned char;
  451. *e = (*c < mins[len]) << 6; // non-canonical encoding
  452. *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half?
  453. *e |= (*c > 0x10FFFF) << 8; // out of range?
  454. *e |= (uchar(s[1]) & 0xc0) >> 2;
  455. *e |= (uchar(s[2]) & 0xc0) >> 4;
  456. *e |= uchar(s[3]) >> 6;
  457. *e ^= 0x2a; // top two bits of each tail byte correct?
  458. *e >>= shifte[len];
  459. return next;
  460. }
  461. constexpr uint32_t invalid_code_point = ~uint32_t();
  462. // Invokes f(cp, sv) for every code point cp in s with sv being the string view
  463. // corresponding to the code point. cp is invalid_code_point on error.
  464. template <typename F>
  465. FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
  466. auto decode = [f](const char* buf_ptr, const char* ptr) {
  467. auto cp = uint32_t();
  468. auto error = 0;
  469. auto end = utf8_decode(buf_ptr, &cp, &error);
  470. bool result = f(error ? invalid_code_point : cp,
  471. string_view(ptr, to_unsigned(end - buf_ptr)));
  472. return result ? end : nullptr;
  473. };
  474. auto p = s.data();
  475. const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars.
  476. if (s.size() >= block_size) {
  477. for (auto end = p + s.size() - block_size + 1; p < end;) {
  478. p = decode(p, p);
  479. if (!p) return;
  480. }
  481. }
  482. if (auto num_chars_left = s.data() + s.size() - p) {
  483. char buf[2 * block_size - 1] = {};
  484. copy_str<char>(p, p + num_chars_left, buf);
  485. const char* buf_ptr = buf;
  486. do {
  487. auto end = decode(buf_ptr, p);
  488. if (!end) return;
  489. p += end - buf_ptr;
  490. buf_ptr = end;
  491. } while (buf_ptr - buf < num_chars_left);
  492. }
  493. }
  494. template <typename Char>
  495. inline auto compute_width(basic_string_view<Char> s) -> size_t {
  496. return s.size();
  497. }
  498. // Computes approximate display width of a UTF-8 string.
  499. FMT_CONSTEXPR inline size_t compute_width(string_view s) {
  500. size_t num_code_points = 0;
  501. // It is not a lambda for compatibility with C++14.
  502. struct count_code_points {
  503. size_t* count;
  504. FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool {
  505. *count += detail::to_unsigned(
  506. 1 +
  507. (cp >= 0x1100 &&
  508. (cp <= 0x115f || // Hangul Jamo init. consonants
  509. cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET
  510. cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET
  511. // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:
  512. (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
  513. (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables
  514. (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs
  515. (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms
  516. (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms
  517. (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms
  518. (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms
  519. (cp >= 0x20000 && cp <= 0x2fffd) || // CJK
  520. (cp >= 0x30000 && cp <= 0x3fffd) ||
  521. // Miscellaneous Symbols and Pictographs + Emoticons:
  522. (cp >= 0x1f300 && cp <= 0x1f64f) ||
  523. // Supplemental Symbols and Pictographs:
  524. (cp >= 0x1f900 && cp <= 0x1f9ff))));
  525. return true;
  526. }
  527. };
  528. for_each_codepoint(s, count_code_points{&num_code_points});
  529. return num_code_points;
  530. }
  531. inline auto compute_width(basic_string_view<char8_type> s) -> size_t {
  532. return compute_width(basic_string_view<char>(
  533. reinterpret_cast<const char*>(s.data()), s.size()));
  534. }
  535. template <typename Char>
  536. inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
  537. size_t size = s.size();
  538. return n < size ? n : size;
  539. }
  540. // Calculates the index of the nth code point in a UTF-8 string.
  541. inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
  542. -> size_t {
  543. const char8_type* data = s.data();
  544. size_t num_code_points = 0;
  545. for (size_t i = 0, size = s.size(); i != size; ++i) {
  546. if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) return i;
  547. }
  548. return s.size();
  549. }
  550. template <typename T, bool = std::is_floating_point<T>::value>
  551. struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
  552. sizeof(T) <= sizeof(double)> {};
  553. template <typename T> struct is_fast_float<T, false> : std::false_type {};
  554. #ifndef FMT_USE_FULL_CACHE_DRAGONBOX
  555. # define FMT_USE_FULL_CACHE_DRAGONBOX 0
  556. #endif
  557. template <typename T>
  558. template <typename U>
  559. void buffer<T>::append(const U* begin, const U* end) {
  560. while (begin != end) {
  561. auto count = to_unsigned(end - begin);
  562. try_reserve(size_ + count);
  563. auto free_cap = capacity_ - size_;
  564. if (free_cap < count) count = free_cap;
  565. std::uninitialized_copy_n(begin, count, make_checked(ptr_ + size_, count));
  566. size_ += count;
  567. begin += count;
  568. }
  569. }
  570. template <typename T, typename Enable = void>
  571. struct is_locale : std::false_type {};
  572. template <typename T>
  573. struct is_locale<T, void_t<decltype(T::classic())>> : std::true_type {};
  574. } // namespace detail
  575. FMT_MODULE_EXPORT_BEGIN
  576. // The number of characters to store in the basic_memory_buffer object itself
  577. // to avoid dynamic memory allocation.
  578. enum { inline_buffer_size = 500 };
  579. /**
  580. \rst
  581. A dynamically growing memory buffer for trivially copyable/constructible types
  582. with the first ``SIZE`` elements stored in the object itself.
  583. You can use the ``memory_buffer`` type alias for ``char`` instead.
  584. **Example**::
  585. auto out = fmt::memory_buffer();
  586. format_to(std::back_inserter(out), "The answer is {}.", 42);
  587. This will append the following output to the ``out`` object:
  588. .. code-block:: none
  589. The answer is 42.
  590. The output can be converted to an ``std::string`` with ``to_string(out)``.
  591. \endrst
  592. */
  593. template <typename T, size_t SIZE = inline_buffer_size,
  594. typename Allocator = std::allocator<T>>
  595. class basic_memory_buffer final : public detail::buffer<T> {
  596. private:
  597. T store_[SIZE];
  598. // Don't inherit from Allocator avoid generating type_info for it.
  599. Allocator alloc_;
  600. // Deallocate memory allocated by the buffer.
  601. FMT_CONSTEXPR20 void deallocate() {
  602. T* data = this->data();
  603. if (data != store_) alloc_.deallocate(data, this->capacity());
  604. }
  605. protected:
  606. FMT_CONSTEXPR20 void grow(size_t size) override;
  607. public:
  608. using value_type = T;
  609. using const_reference = const T&;
  610. FMT_CONSTEXPR20 explicit basic_memory_buffer(
  611. const Allocator& alloc = Allocator())
  612. : alloc_(alloc) {
  613. this->set(store_, SIZE);
  614. if (detail::is_constant_evaluated()) {
  615. detail::fill_n(store_, SIZE, T{});
  616. }
  617. }
  618. FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
  619. private:
  620. // Move data from other to this buffer.
  621. FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {
  622. alloc_ = std::move(other.alloc_);
  623. T* data = other.data();
  624. size_t size = other.size(), capacity = other.capacity();
  625. if (data == other.store_) {
  626. this->set(store_, capacity);
  627. if (detail::is_constant_evaluated()) {
  628. detail::copy_str<T>(other.store_, other.store_ + size,
  629. detail::make_checked(store_, capacity));
  630. } else {
  631. std::uninitialized_copy(other.store_, other.store_ + size,
  632. detail::make_checked(store_, capacity));
  633. }
  634. } else {
  635. this->set(data, capacity);
  636. // Set pointer to the inline array so that delete is not called
  637. // when deallocating.
  638. other.set(other.store_, 0);
  639. }
  640. this->resize(size);
  641. }
  642. public:
  643. /**
  644. \rst
  645. Constructs a :class:`fmt::basic_memory_buffer` object moving the content
  646. of the other object to it.
  647. \endrst
  648. */
  649. FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other)
  650. FMT_NOEXCEPT {
  651. move(other);
  652. }
  653. /**
  654. \rst
  655. Moves the content of the other ``basic_memory_buffer`` object to this one.
  656. \endrst
  657. */
  658. auto operator=(basic_memory_buffer&& other) FMT_NOEXCEPT
  659. -> basic_memory_buffer& {
  660. FMT_ASSERT(this != &other, "");
  661. deallocate();
  662. move(other);
  663. return *this;
  664. }
  665. // Returns a copy of the allocator associated with this buffer.
  666. auto get_allocator() const -> Allocator { return alloc_; }
  667. /**
  668. Resizes the buffer to contain *count* elements. If T is a POD type new
  669. elements may not be initialized.
  670. */
  671. FMT_CONSTEXPR20 void resize(size_t count) { this->try_resize(count); }
  672. /** Increases the buffer capacity to *new_capacity*. */
  673. void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
  674. // Directly append data into the buffer
  675. using detail::buffer<T>::append;
  676. template <typename ContiguousRange>
  677. void append(const ContiguousRange& range) {
  678. append(range.data(), range.data() + range.size());
  679. }
  680. };
  681. template <typename T, size_t SIZE, typename Allocator>
  682. FMT_CONSTEXPR20 void basic_memory_buffer<T, SIZE, Allocator>::grow(
  683. size_t size) {
  684. #ifdef FMT_FUZZ
  685. if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much");
  686. #endif
  687. const size_t max_size = std::allocator_traits<Allocator>::max_size(alloc_);
  688. size_t old_capacity = this->capacity();
  689. size_t new_capacity = old_capacity + old_capacity / 2;
  690. if (size > new_capacity)
  691. new_capacity = size;
  692. else if (new_capacity > max_size)
  693. new_capacity = size > max_size ? size : max_size;
  694. T* old_data = this->data();
  695. T* new_data =
  696. std::allocator_traits<Allocator>::allocate(alloc_, new_capacity);
  697. // The following code doesn't throw, so the raw pointer above doesn't leak.
  698. std::uninitialized_copy(old_data, old_data + this->size(),
  699. detail::make_checked(new_data, new_capacity));
  700. this->set(new_data, new_capacity);
  701. // deallocate must not throw according to the standard, but even if it does,
  702. // the buffer already uses the new storage and will deallocate it in
  703. // destructor.
  704. if (old_data != store_) alloc_.deallocate(old_data, old_capacity);
  705. }
  706. using memory_buffer = basic_memory_buffer<char>;
  707. template <typename T, size_t SIZE, typename Allocator>
  708. struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
  709. };
  710. namespace detail {
  711. FMT_API void print(std::FILE*, string_view);
  712. }
  713. /** A formatting error such as invalid format string. */
  714. FMT_CLASS_API
  715. class FMT_API format_error : public std::runtime_error {
  716. public:
  717. explicit format_error(const char* message) : std::runtime_error(message) {}
  718. explicit format_error(const std::string& message)
  719. : std::runtime_error(message) {}
  720. format_error(const format_error&) = default;
  721. format_error& operator=(const format_error&) = default;
  722. format_error(format_error&&) = default;
  723. format_error& operator=(format_error&&) = default;
  724. ~format_error() FMT_NOEXCEPT override FMT_MSC_DEFAULT;
  725. };
  726. /**
  727. \rst
  728. Constructs a `~fmt::format_arg_store` object that contains references
  729. to arguments and can be implicitly converted to `~fmt::format_args`.
  730. If ``fmt`` is a compile-time string then `make_args_checked` checks
  731. its validity at compile time.
  732. \endrst
  733. */
  734. template <typename... Args, typename S, typename Char = char_t<S>>
  735. FMT_INLINE auto make_args_checked(const S& fmt,
  736. const remove_reference_t<Args>&... args)
  737. -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
  738. static_assert(
  739. detail::count<(
  740. std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
  741. std::is_reference<Args>::value)...>() == 0,
  742. "passing views as lvalues is disallowed");
  743. detail::check_format_string<Args...>(fmt);
  744. return {args...};
  745. }
  746. // compile-time support
  747. namespace detail_exported {
  748. #if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
  749. template <typename Char, size_t N> struct fixed_string {
  750. constexpr fixed_string(const Char (&str)[N]) {
  751. detail::copy_str<Char, const Char*, Char*>(static_cast<const Char*>(str),
  752. str + N, data);
  753. }
  754. Char data[N]{};
  755. };
  756. #endif
  757. // Converts a compile-time string to basic_string_view.
  758. template <typename Char, size_t N>
  759. constexpr auto compile_string_to_view(const Char (&s)[N])
  760. -> basic_string_view<Char> {
  761. // Remove trailing NUL character if needed. Won't be present if this is used
  762. // with a raw character array (i.e. not defined as a string).
  763. return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};
  764. }
  765. template <typename Char>
  766. constexpr auto compile_string_to_view(detail::std_string_view<Char> s)
  767. -> basic_string_view<Char> {
  768. return {s.data(), s.size()};
  769. }
  770. } // namespace detail_exported
  771. FMT_BEGIN_DETAIL_NAMESPACE
  772. template <typename T> struct is_integral : std::is_integral<T> {};
  773. template <> struct is_integral<int128_t> : std::true_type {};
  774. template <> struct is_integral<uint128_t> : std::true_type {};
  775. template <typename T>
  776. using is_signed =
  777. std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
  778. std::is_same<T, int128_t>::value>;
  779. // Returns true if value is negative, false otherwise.
  780. // Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
  781. template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
  782. FMT_CONSTEXPR auto is_negative(T value) -> bool {
  783. return value < 0;
  784. }
  785. template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
  786. FMT_CONSTEXPR auto is_negative(T) -> bool {
  787. return false;
  788. }
  789. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  790. FMT_CONSTEXPR auto is_supported_floating_point(T) -> uint16_t {
  791. return (std::is_same<T, float>::value && FMT_USE_FLOAT) ||
  792. (std::is_same<T, double>::value && FMT_USE_DOUBLE) ||
  793. (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE);
  794. }
  795. // Smallest of uint32_t, uint64_t, uint128_t that is large enough to
  796. // represent all values of an integral type T.
  797. template <typename T>
  798. using uint32_or_64_or_128_t =
  799. conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
  800. uint32_t,
  801. conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
  802. template <typename T>
  803. using uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;
  804. #define FMT_POWERS_OF_10(factor) \
  805. factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \
  806. (factor)*1000000, (factor)*10000000, (factor)*100000000, \
  807. (factor)*1000000000
  808. // Converts value in the range [0, 100) to a string.
  809. constexpr const char* digits2(size_t value) {
  810. // GCC generates slightly better code when value is pointer-size.
  811. return &"0001020304050607080910111213141516171819"
  812. "2021222324252627282930313233343536373839"
  813. "4041424344454647484950515253545556575859"
  814. "6061626364656667686970717273747576777879"
  815. "8081828384858687888990919293949596979899"[value * 2];
  816. }
  817. // Sign is a template parameter to workaround a bug in gcc 4.8.
  818. template <typename Char, typename Sign> constexpr Char sign(Sign s) {
  819. #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 604
  820. static_assert(std::is_same<Sign, sign_t>::value, "");
  821. #endif
  822. return static_cast<Char>("\0-+ "[s]);
  823. }
  824. template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
  825. int count = 1;
  826. for (;;) {
  827. // Integer division is slow so do it for a group of four digits instead
  828. // of for every digit. The idea comes from the talk by Alexandrescu
  829. // "Three Optimization Tips for C++". See speed-test for a comparison.
  830. if (n < 10) return count;
  831. if (n < 100) return count + 1;
  832. if (n < 1000) return count + 2;
  833. if (n < 10000) return count + 3;
  834. n /= 10000u;
  835. count += 4;
  836. }
  837. }
  838. #if FMT_USE_INT128
  839. FMT_CONSTEXPR inline auto count_digits(uint128_t n) -> int {
  840. return count_digits_fallback(n);
  841. }
  842. #endif
  843. #ifdef FMT_BUILTIN_CLZLL
  844. // It is a separate function rather than a part of count_digits to workaround
  845. // the lack of static constexpr in constexpr functions.
  846. inline auto do_count_digits(uint64_t n) -> int {
  847. // This has comparable performance to the version by Kendall Willets
  848. // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)
  849. // but uses smaller tables.
  850. // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
  851. static constexpr uint8_t bsr2log10[] = {
  852. 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
  853. 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
  854. 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
  855. 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
  856. auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];
  857. static constexpr const uint64_t zero_or_powers_of_10[] = {
  858. 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),
  859. 10000000000000000000ULL};
  860. return t - (n < zero_or_powers_of_10[t]);
  861. }
  862. #endif
  863. // Returns the number of decimal digits in n. Leading zeros are not counted
  864. // except for n == 0 in which case count_digits returns 1.
  865. FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
  866. #ifdef FMT_BUILTIN_CLZLL
  867. if (!is_constant_evaluated()) {
  868. return do_count_digits(n);
  869. }
  870. #endif
  871. return count_digits_fallback(n);
  872. }
  873. // Counts the number of digits in n. BITS = log2(radix).
  874. template <int BITS, typename UInt>
  875. FMT_CONSTEXPR auto count_digits(UInt n) -> int {
  876. #ifdef FMT_BUILTIN_CLZ
  877. if (num_bits<UInt>() == 32)
  878. return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
  879. #endif
  880. // Lambda avoids unreachable code warnings from NVHPC.
  881. return [](UInt m) {
  882. int num_digits = 0;
  883. do {
  884. ++num_digits;
  885. } while ((m >>= BITS) != 0);
  886. return num_digits;
  887. }(n);
  888. }
  889. template <> auto count_digits<4>(detail::fallback_uintptr n) -> int;
  890. #ifdef FMT_BUILTIN_CLZ
  891. // It is a separate function rather than a part of count_digits to workaround
  892. // the lack of static constexpr in constexpr functions.
  893. FMT_INLINE auto do_count_digits(uint32_t n) -> int {
  894. // An optimization by Kendall Willets from https://bit.ly/3uOIQrB.
  895. // This increments the upper 32 bits (log10(T) - 1) when >= T is added.
  896. # define FMT_INC(T) (((sizeof(# T) - 1ull) << 32) - T)
  897. static constexpr uint64_t table[] = {
  898. FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8
  899. FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64
  900. FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512
  901. FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096
  902. FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k
  903. FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k
  904. FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k
  905. FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M
  906. FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M
  907. FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M
  908. FMT_INC(1000000000), FMT_INC(1000000000) // 4B
  909. };
  910. auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];
  911. return static_cast<int>((n + inc) >> 32);
  912. }
  913. #endif
  914. // Optional version of count_digits for better performance on 32-bit platforms.
  915. FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
  916. #ifdef FMT_BUILTIN_CLZ
  917. if (!is_constant_evaluated()) {
  918. return do_count_digits(n);
  919. }
  920. #endif
  921. return count_digits_fallback(n);
  922. }
  923. template <typename Int> constexpr auto digits10() FMT_NOEXCEPT -> int {
  924. return std::numeric_limits<Int>::digits10;
  925. }
  926. template <> constexpr auto digits10<int128_t>() FMT_NOEXCEPT -> int {
  927. return 38;
  928. }
  929. template <> constexpr auto digits10<uint128_t>() FMT_NOEXCEPT -> int {
  930. return 38;
  931. }
  932. template <typename Char> struct thousands_sep_result {
  933. std::string grouping;
  934. Char thousands_sep;
  935. };
  936. template <typename Char>
  937. FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;
  938. template <typename Char>
  939. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {
  940. auto result = thousands_sep_impl<char>(loc);
  941. return {result.grouping, Char(result.thousands_sep)};
  942. }
  943. template <>
  944. inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {
  945. return thousands_sep_impl<wchar_t>(loc);
  946. }
  947. template <typename Char>
  948. FMT_API auto decimal_point_impl(locale_ref loc) -> Char;
  949. template <typename Char> inline auto decimal_point(locale_ref loc) -> Char {
  950. return Char(decimal_point_impl<char>(loc));
  951. }
  952. template <> inline auto decimal_point(locale_ref loc) -> wchar_t {
  953. return decimal_point_impl<wchar_t>(loc);
  954. }
  955. // Compares two characters for equality.
  956. template <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {
  957. return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);
  958. }
  959. inline auto equal2(const char* lhs, const char* rhs) -> bool {
  960. return memcmp(lhs, rhs, 2) == 0;
  961. }
  962. // Copies two characters from src to dst.
  963. template <typename Char>
  964. FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) {
  965. if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) {
  966. memcpy(dst, src, 2);
  967. return;
  968. }
  969. *dst++ = static_cast<Char>(*src++);
  970. *dst = static_cast<Char>(*src);
  971. }
  972. template <typename Iterator> struct format_decimal_result {
  973. Iterator begin;
  974. Iterator end;
  975. };
  976. // Formats a decimal unsigned integer value writing into out pointing to a
  977. // buffer of specified size. The caller must ensure that the buffer is large
  978. // enough.
  979. template <typename Char, typename UInt>
  980. FMT_CONSTEXPR20 auto format_decimal(Char* out, UInt value, int size)
  981. -> format_decimal_result<Char*> {
  982. FMT_ASSERT(size >= count_digits(value), "invalid digit count");
  983. out += size;
  984. Char* end = out;
  985. while (value >= 100) {
  986. // Integer division is slow so do it for a group of two digits instead
  987. // of for every digit. The idea comes from the talk by Alexandrescu
  988. // "Three Optimization Tips for C++". See speed-test for a comparison.
  989. out -= 2;
  990. copy2(out, digits2(static_cast<size_t>(value % 100)));
  991. value /= 100;
  992. }
  993. if (value < 10) {
  994. *--out = static_cast<Char>('0' + value);
  995. return {out, end};
  996. }
  997. out -= 2;
  998. copy2(out, digits2(static_cast<size_t>(value)));
  999. return {out, end};
  1000. }
  1001. template <typename Char, typename UInt, typename Iterator,
  1002. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
  1003. inline auto format_decimal(Iterator out, UInt value, int size)
  1004. -> format_decimal_result<Iterator> {
  1005. // Buffer is large enough to hold all digits (digits10 + 1).
  1006. Char buffer[digits10<UInt>() + 1];
  1007. auto end = format_decimal(buffer, value, size).end;
  1008. return {out, detail::copy_str_noinline<Char>(buffer, end, out)};
  1009. }
  1010. template <unsigned BASE_BITS, typename Char, typename UInt>
  1011. FMT_CONSTEXPR auto format_uint(Char* buffer, UInt value, int num_digits,
  1012. bool upper = false) -> Char* {
  1013. buffer += num_digits;
  1014. Char* end = buffer;
  1015. do {
  1016. const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
  1017. unsigned digit = (value & ((1 << BASE_BITS) - 1));
  1018. *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
  1019. : digits[digit]);
  1020. } while ((value >>= BASE_BITS) != 0);
  1021. return end;
  1022. }
  1023. template <unsigned BASE_BITS, typename Char>
  1024. auto format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits,
  1025. bool = false) -> Char* {
  1026. auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
  1027. int start = (num_digits + char_digits - 1) / char_digits - 1;
  1028. if (int start_digits = num_digits % char_digits) {
  1029. unsigned value = n.value[start--];
  1030. buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
  1031. }
  1032. for (; start >= 0; --start) {
  1033. unsigned value = n.value[start];
  1034. buffer += char_digits;
  1035. auto p = buffer;
  1036. for (int i = 0; i < char_digits; ++i) {
  1037. unsigned digit = (value & ((1 << BASE_BITS) - 1));
  1038. *--p = static_cast<Char>("0123456789abcdef"[digit]);
  1039. value >>= BASE_BITS;
  1040. }
  1041. }
  1042. return buffer;
  1043. }
  1044. template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
  1045. inline auto format_uint(It out, UInt value, int num_digits, bool upper = false)
  1046. -> It {
  1047. if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
  1048. format_uint<BASE_BITS>(ptr, value, num_digits, upper);
  1049. return out;
  1050. }
  1051. // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
  1052. char buffer[num_bits<UInt>() / BASE_BITS + 1];
  1053. format_uint<BASE_BITS>(buffer, value, num_digits, upper);
  1054. return detail::copy_str_noinline<Char>(buffer, buffer + num_digits, out);
  1055. }
  1056. // A converter from UTF-8 to UTF-16.
  1057. class utf8_to_utf16 {
  1058. private:
  1059. basic_memory_buffer<wchar_t> buffer_;
  1060. public:
  1061. FMT_API explicit utf8_to_utf16(string_view s);
  1062. operator basic_string_view<wchar_t>() const { return {&buffer_[0], size()}; }
  1063. auto size() const -> size_t { return buffer_.size() - 1; }
  1064. auto c_str() const -> const wchar_t* { return &buffer_[0]; }
  1065. auto str() const -> std::wstring { return {&buffer_[0], size()}; }
  1066. };
  1067. namespace dragonbox {
  1068. // Type-specific information that Dragonbox uses.
  1069. template <class T> struct float_info;
  1070. template <> struct float_info<float> {
  1071. using carrier_uint = uint32_t;
  1072. static const int significand_bits = 23;
  1073. static const int exponent_bits = 8;
  1074. static const int min_exponent = -126;
  1075. static const int max_exponent = 127;
  1076. static const int exponent_bias = -127;
  1077. static const int decimal_digits = 9;
  1078. static const int kappa = 1;
  1079. static const int big_divisor = 100;
  1080. static const int small_divisor = 10;
  1081. static const int min_k = -31;
  1082. static const int max_k = 46;
  1083. static const int cache_bits = 64;
  1084. static const int divisibility_check_by_5_threshold = 39;
  1085. static const int case_fc_pm_half_lower_threshold = -1;
  1086. static const int case_fc_pm_half_upper_threshold = 6;
  1087. static const int case_fc_lower_threshold = -2;
  1088. static const int case_fc_upper_threshold = 6;
  1089. static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
  1090. static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
  1091. static const int shorter_interval_tie_lower_threshold = -35;
  1092. static const int shorter_interval_tie_upper_threshold = -35;
  1093. static const int max_trailing_zeros = 7;
  1094. };
  1095. template <> struct float_info<double> {
  1096. using carrier_uint = uint64_t;
  1097. static const int significand_bits = 52;
  1098. static const int exponent_bits = 11;
  1099. static const int min_exponent = -1022;
  1100. static const int max_exponent = 1023;
  1101. static const int exponent_bias = -1023;
  1102. static const int decimal_digits = 17;
  1103. static const int kappa = 2;
  1104. static const int big_divisor = 1000;
  1105. static const int small_divisor = 100;
  1106. static const int min_k = -292;
  1107. static const int max_k = 326;
  1108. static const int cache_bits = 128;
  1109. static const int divisibility_check_by_5_threshold = 86;
  1110. static const int case_fc_pm_half_lower_threshold = -2;
  1111. static const int case_fc_pm_half_upper_threshold = 9;
  1112. static const int case_fc_lower_threshold = -4;
  1113. static const int case_fc_upper_threshold = 9;
  1114. static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
  1115. static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
  1116. static const int shorter_interval_tie_lower_threshold = -77;
  1117. static const int shorter_interval_tie_upper_threshold = -77;
  1118. static const int max_trailing_zeros = 16;
  1119. };
  1120. template <typename T> struct decimal_fp {
  1121. using significand_type = typename float_info<T>::carrier_uint;
  1122. significand_type significand;
  1123. int exponent;
  1124. };
  1125. template <typename T>
  1126. FMT_API auto to_decimal(T x) FMT_NOEXCEPT -> decimal_fp<T>;
  1127. } // namespace dragonbox
  1128. template <typename T>
  1129. constexpr auto exponent_mask() ->
  1130. typename dragonbox::float_info<T>::carrier_uint {
  1131. using uint = typename dragonbox::float_info<T>::carrier_uint;
  1132. return ((uint(1) << dragonbox::float_info<T>::exponent_bits) - 1)
  1133. << dragonbox::float_info<T>::significand_bits;
  1134. }
  1135. // Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
  1136. template <typename Char, typename It>
  1137. FMT_CONSTEXPR auto write_exponent(int exp, It it) -> It {
  1138. FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
  1139. if (exp < 0) {
  1140. *it++ = static_cast<Char>('-');
  1141. exp = -exp;
  1142. } else {
  1143. *it++ = static_cast<Char>('+');
  1144. }
  1145. if (exp >= 100) {
  1146. const char* top = digits2(to_unsigned(exp / 100));
  1147. if (exp >= 1000) *it++ = static_cast<Char>(top[0]);
  1148. *it++ = static_cast<Char>(top[1]);
  1149. exp %= 100;
  1150. }
  1151. const char* d = digits2(to_unsigned(exp));
  1152. *it++ = static_cast<Char>(d[0]);
  1153. *it++ = static_cast<Char>(d[1]);
  1154. return it;
  1155. }
  1156. template <typename T>
  1157. FMT_HEADER_ONLY_CONSTEXPR20 auto format_float(T value, int precision,
  1158. float_specs specs,
  1159. buffer<char>& buf) -> int;
  1160. // Formats a floating-point number with snprintf.
  1161. template <typename T>
  1162. auto snprintf_float(T value, int precision, float_specs specs,
  1163. buffer<char>& buf) -> int;
  1164. template <typename T> constexpr auto promote_float(T value) -> T {
  1165. return value;
  1166. }
  1167. constexpr auto promote_float(float value) -> double {
  1168. return static_cast<double>(value);
  1169. }
  1170. template <typename OutputIt, typename Char>
  1171. FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n,
  1172. const fill_t<Char>& fill) -> OutputIt {
  1173. auto fill_size = fill.size();
  1174. if (fill_size == 1) return detail::fill_n(it, n, fill[0]);
  1175. auto data = fill.data();
  1176. for (size_t i = 0; i < n; ++i)
  1177. it = copy_str<Char>(data, data + fill_size, it);
  1178. return it;
  1179. }
  1180. // Writes the output of f, padded according to format specifications in specs.
  1181. // size: output size in code units.
  1182. // width: output display width in (terminal) column positions.
  1183. template <align::type align = align::left, typename OutputIt, typename Char,
  1184. typename F>
  1185. FMT_CONSTEXPR auto write_padded(OutputIt out,
  1186. const basic_format_specs<Char>& specs,
  1187. size_t size, size_t width, F&& f) -> OutputIt {
  1188. static_assert(align == align::left || align == align::right, "");
  1189. unsigned spec_width = to_unsigned(specs.width);
  1190. size_t padding = spec_width > width ? spec_width - width : 0;
  1191. // Shifts are encoded as string literals because static constexpr is not
  1192. // supported in constexpr functions.
  1193. auto* shifts = align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01";
  1194. size_t left_padding = padding >> shifts[specs.align];
  1195. size_t right_padding = padding - left_padding;
  1196. auto it = reserve(out, size + padding * specs.fill.size());
  1197. if (left_padding != 0) it = fill(it, left_padding, specs.fill);
  1198. it = f(it);
  1199. if (right_padding != 0) it = fill(it, right_padding, specs.fill);
  1200. return base_iterator(out, it);
  1201. }
  1202. template <align::type align = align::left, typename OutputIt, typename Char,
  1203. typename F>
  1204. constexpr auto write_padded(OutputIt out, const basic_format_specs<Char>& specs,
  1205. size_t size, F&& f) -> OutputIt {
  1206. return write_padded<align>(out, specs, size, size, f);
  1207. }
  1208. template <align::type align = align::left, typename Char, typename OutputIt>
  1209. FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,
  1210. const basic_format_specs<Char>& specs)
  1211. -> OutputIt {
  1212. return write_padded<align>(
  1213. out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {
  1214. const char* data = bytes.data();
  1215. return copy_str<Char>(data, data + bytes.size(), it);
  1216. });
  1217. }
  1218. template <typename Char, typename OutputIt, typename UIntPtr>
  1219. auto write_ptr(OutputIt out, UIntPtr value,
  1220. const basic_format_specs<Char>* specs) -> OutputIt {
  1221. int num_digits = count_digits<4>(value);
  1222. auto size = to_unsigned(num_digits) + size_t(2);
  1223. auto write = [=](reserve_iterator<OutputIt> it) {
  1224. *it++ = static_cast<Char>('0');
  1225. *it++ = static_cast<Char>('x');
  1226. return format_uint<4, Char>(it, value, num_digits);
  1227. };
  1228. return specs ? write_padded<align::right>(out, *specs, size, write)
  1229. : base_iterator(out, write(reserve(out, size)));
  1230. }
  1231. template <typename Char, typename OutputIt>
  1232. FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
  1233. const basic_format_specs<Char>& specs)
  1234. -> OutputIt {
  1235. return write_padded(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
  1236. *it++ = value;
  1237. return it;
  1238. });
  1239. }
  1240. template <typename Char, typename OutputIt>
  1241. FMT_CONSTEXPR auto write(OutputIt out, Char value,
  1242. const basic_format_specs<Char>& specs,
  1243. locale_ref loc = {}) -> OutputIt {
  1244. return check_char_specs(specs)
  1245. ? write_char(out, value, specs)
  1246. : write(out, static_cast<int>(value), specs, loc);
  1247. }
  1248. // Data for write_int that doesn't depend on output iterator type. It is used to
  1249. // avoid template code bloat.
  1250. template <typename Char> struct write_int_data {
  1251. size_t size;
  1252. size_t padding;
  1253. FMT_CONSTEXPR write_int_data(int num_digits, unsigned prefix,
  1254. const basic_format_specs<Char>& specs)
  1255. : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {
  1256. if (specs.align == align::numeric) {
  1257. auto width = to_unsigned(specs.width);
  1258. if (width > size) {
  1259. padding = width - size;
  1260. size = width;
  1261. }
  1262. } else if (specs.precision > num_digits) {
  1263. size = (prefix >> 24) + to_unsigned(specs.precision);
  1264. padding = to_unsigned(specs.precision - num_digits);
  1265. }
  1266. }
  1267. };
  1268. // Writes an integer in the format
  1269. // <left-padding><prefix><numeric-padding><digits><right-padding>
  1270. // where <digits> are written by write_digits(it).
  1271. // prefix contains chars in three lower bytes and the size in the fourth byte.
  1272. template <typename OutputIt, typename Char, typename W>
  1273. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, int num_digits,
  1274. unsigned prefix,
  1275. const basic_format_specs<Char>& specs,
  1276. W write_digits) -> OutputIt {
  1277. // Slightly faster check for specs.width == 0 && specs.precision == -1.
  1278. if ((specs.width | (specs.precision + 1)) == 0) {
  1279. auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));
  1280. if (prefix != 0) {
  1281. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1282. *it++ = static_cast<Char>(p & 0xff);
  1283. }
  1284. return base_iterator(out, write_digits(it));
  1285. }
  1286. auto data = write_int_data<Char>(num_digits, prefix, specs);
  1287. return write_padded<align::right>(
  1288. out, specs, data.size, [=](reserve_iterator<OutputIt> it) {
  1289. for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
  1290. *it++ = static_cast<Char>(p & 0xff);
  1291. it = detail::fill_n(it, data.padding, static_cast<Char>('0'));
  1292. return write_digits(it);
  1293. });
  1294. }
  1295. template <typename Char> class digit_grouping {
  1296. private:
  1297. thousands_sep_result<Char> sep_;
  1298. struct next_state {
  1299. std::string::const_iterator group;
  1300. int pos;
  1301. };
  1302. next_state initial_state() const { return {sep_.grouping.begin(), 0}; }
  1303. // Returns the next digit group separator position.
  1304. int next(next_state& state) const {
  1305. if (!sep_.thousands_sep) return max_value<int>();
  1306. if (state.group == sep_.grouping.end())
  1307. return state.pos += sep_.grouping.back();
  1308. if (*state.group <= 0 || *state.group == max_value<char>())
  1309. return max_value<int>();
  1310. state.pos += *state.group++;
  1311. return state.pos;
  1312. }
  1313. public:
  1314. explicit digit_grouping(locale_ref loc, bool localized = true) {
  1315. if (localized)
  1316. sep_ = thousands_sep<Char>(loc);
  1317. else
  1318. sep_.thousands_sep = Char();
  1319. }
  1320. explicit digit_grouping(thousands_sep_result<Char> sep) : sep_(sep) {}
  1321. Char separator() const { return sep_.thousands_sep; }
  1322. int count_separators(int num_digits) const {
  1323. int count = 0;
  1324. auto state = initial_state();
  1325. while (num_digits > next(state)) ++count;
  1326. return count;
  1327. }
  1328. // Applies grouping to digits and write the output to out.
  1329. template <typename Out, typename C>
  1330. Out apply(Out out, basic_string_view<C> digits) const {
  1331. auto num_digits = static_cast<int>(digits.size());
  1332. auto separators = basic_memory_buffer<int>();
  1333. separators.push_back(0);
  1334. auto state = initial_state();
  1335. while (int i = next(state)) {
  1336. if (i >= num_digits) break;
  1337. separators.push_back(i);
  1338. }
  1339. for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);
  1340. i < num_digits; ++i) {
  1341. if (num_digits - i == separators[sep_index]) {
  1342. *out++ = separator();
  1343. --sep_index;
  1344. }
  1345. *out++ = static_cast<Char>(digits[to_unsigned(i)]);
  1346. }
  1347. return out;
  1348. }
  1349. };
  1350. template <typename OutputIt, typename UInt, typename Char>
  1351. auto write_int_localized(OutputIt out, UInt value, unsigned prefix,
  1352. const basic_format_specs<Char>& specs,
  1353. const digit_grouping<Char>& grouping) -> OutputIt {
  1354. static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, "");
  1355. int num_digits = count_digits(value);
  1356. char digits[40];
  1357. format_decimal(digits, value, num_digits);
  1358. unsigned size = to_unsigned((prefix != 0 ? 1 : 0) + num_digits +
  1359. grouping.count_separators(num_digits));
  1360. return write_padded<align::right>(
  1361. out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
  1362. if (prefix != 0) *it++ = static_cast<Char>(prefix);
  1363. return grouping.apply(it, string_view(digits, to_unsigned(num_digits)));
  1364. });
  1365. }
  1366. template <typename OutputIt, typename UInt, typename Char>
  1367. auto write_int_localized(OutputIt& out, UInt value, unsigned prefix,
  1368. const basic_format_specs<Char>& specs, locale_ref loc)
  1369. -> bool {
  1370. auto grouping = digit_grouping<Char>(loc);
  1371. out = write_int_localized(out, value, prefix, specs, grouping);
  1372. return true;
  1373. }
  1374. FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {
  1375. prefix |= prefix != 0 ? value << 8 : value;
  1376. prefix += (1u + (value > 0xff ? 1 : 0)) << 24;
  1377. }
  1378. template <typename UInt> struct write_int_arg {
  1379. UInt abs_value;
  1380. unsigned prefix;
  1381. };
  1382. template <typename T>
  1383. FMT_CONSTEXPR auto make_write_int_arg(T value, sign_t sign)
  1384. -> write_int_arg<uint32_or_64_or_128_t<T>> {
  1385. auto prefix = 0u;
  1386. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  1387. if (is_negative(value)) {
  1388. prefix = 0x01000000 | '-';
  1389. abs_value = 0 - abs_value;
  1390. } else {
  1391. constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+',
  1392. 0x1000000u | ' '};
  1393. prefix = prefixes[sign];
  1394. }
  1395. return {abs_value, prefix};
  1396. }
  1397. template <typename Char, typename OutputIt, typename T>
  1398. FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,
  1399. const basic_format_specs<Char>& specs,
  1400. locale_ref loc) -> OutputIt {
  1401. static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, "");
  1402. auto abs_value = arg.abs_value;
  1403. auto prefix = arg.prefix;
  1404. switch (specs.type) {
  1405. case presentation_type::none:
  1406. case presentation_type::dec: {
  1407. if (specs.localized &&
  1408. write_int_localized(out, static_cast<uint64_or_128_t<T>>(abs_value),
  1409. prefix, specs, loc)) {
  1410. return out;
  1411. }
  1412. auto num_digits = count_digits(abs_value);
  1413. return write_int(
  1414. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1415. return format_decimal<Char>(it, abs_value, num_digits).end;
  1416. });
  1417. }
  1418. case presentation_type::hex_lower:
  1419. case presentation_type::hex_upper: {
  1420. bool upper = specs.type == presentation_type::hex_upper;
  1421. if (specs.alt)
  1422. prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0');
  1423. int num_digits = count_digits<4>(abs_value);
  1424. return write_int(
  1425. out, num_digits, prefix, specs, [=](reserve_iterator<OutputIt> it) {
  1426. return format_uint<4, Char>(it, abs_value, num_digits, upper);
  1427. });
  1428. }
  1429. case presentation_type::bin_lower:
  1430. case presentation_type::bin_upper: {
  1431. bool upper = specs.type == presentation_type::bin_upper;
  1432. if (specs.alt)
  1433. prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0');
  1434. int num_digits = count_digits<1>(abs_value);
  1435. return write_int(out, num_digits, prefix, specs,
  1436. [=](reserve_iterator<OutputIt> it) {
  1437. return format_uint<1, Char>(it, abs_value, num_digits);
  1438. });
  1439. }
  1440. case presentation_type::oct: {
  1441. int num_digits = count_digits<3>(abs_value);
  1442. // Octal prefix '0' is counted as a digit, so only add it if precision
  1443. // is not greater than the number of digits.
  1444. if (specs.alt && specs.precision <= num_digits && abs_value != 0)
  1445. prefix_append(prefix, '0');
  1446. return write_int(out, num_digits, prefix, specs,
  1447. [=](reserve_iterator<OutputIt> it) {
  1448. return format_uint<3, Char>(it, abs_value, num_digits);
  1449. });
  1450. }
  1451. case presentation_type::chr:
  1452. return write_char(out, static_cast<Char>(abs_value), specs);
  1453. default:
  1454. throw_format_error("invalid type specifier");
  1455. }
  1456. return out;
  1457. }
  1458. template <typename Char, typename OutputIt, typename T>
  1459. FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(
  1460. OutputIt out, write_int_arg<T> arg, const basic_format_specs<Char>& specs,
  1461. locale_ref loc) -> OutputIt {
  1462. return write_int(out, arg, specs, loc);
  1463. }
  1464. template <typename Char, typename OutputIt, typename T,
  1465. FMT_ENABLE_IF(is_integral<T>::value &&
  1466. !std::is_same<T, bool>::value &&
  1467. std::is_same<OutputIt, buffer_appender<Char>>::value)>
  1468. FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
  1469. const basic_format_specs<Char>& specs,
  1470. locale_ref loc) -> OutputIt {
  1471. return write_int_noinline(out, make_write_int_arg(value, specs.sign), specs,
  1472. loc);
  1473. }
  1474. // An inlined version of write used in format string compilation.
  1475. template <typename Char, typename OutputIt, typename T,
  1476. FMT_ENABLE_IF(is_integral<T>::value &&
  1477. !std::is_same<T, bool>::value &&
  1478. !std::is_same<OutputIt, buffer_appender<Char>>::value)>
  1479. FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
  1480. const basic_format_specs<Char>& specs,
  1481. locale_ref loc) -> OutputIt {
  1482. return write_int(out, make_write_int_arg(value, specs.sign), specs, loc);
  1483. }
  1484. template <typename Char, typename OutputIt>
  1485. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
  1486. const basic_format_specs<Char>& specs) -> OutputIt {
  1487. auto data = s.data();
  1488. auto size = s.size();
  1489. if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
  1490. size = code_point_index(s, to_unsigned(specs.precision));
  1491. auto width =
  1492. specs.width != 0 ? compute_width(basic_string_view<Char>(data, size)) : 0;
  1493. return write_padded(out, specs, size, width,
  1494. [=](reserve_iterator<OutputIt> it) {
  1495. return copy_str<Char>(data, data + size, it);
  1496. });
  1497. }
  1498. template <typename Char, typename OutputIt>
  1499. FMT_CONSTEXPR auto write(OutputIt out,
  1500. basic_string_view<type_identity_t<Char>> s,
  1501. const basic_format_specs<Char>& specs, locale_ref)
  1502. -> OutputIt {
  1503. check_string_type_spec(specs.type);
  1504. return write(out, s, specs);
  1505. }
  1506. template <typename Char, typename OutputIt>
  1507. FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
  1508. const basic_format_specs<Char>& specs, locale_ref)
  1509. -> OutputIt {
  1510. return check_cstring_type_spec(specs.type)
  1511. ? write(out, basic_string_view<Char>(s), specs, {})
  1512. : write_ptr<Char>(out, to_uintptr(s), &specs);
  1513. }
  1514. template <typename Char, typename OutputIt>
  1515. FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isinf,
  1516. basic_format_specs<Char> specs,
  1517. const float_specs& fspecs) -> OutputIt {
  1518. auto str =
  1519. isinf ? (fspecs.upper ? "INF" : "inf") : (fspecs.upper ? "NAN" : "nan");
  1520. constexpr size_t str_size = 3;
  1521. auto sign = fspecs.sign;
  1522. auto size = str_size + (sign ? 1 : 0);
  1523. // Replace '0'-padding with space for non-finite values.
  1524. const bool is_zero_fill =
  1525. specs.fill.size() == 1 && *specs.fill.data() == static_cast<Char>('0');
  1526. if (is_zero_fill) specs.fill[0] = static_cast<Char>(' ');
  1527. return write_padded(out, specs, size, [=](reserve_iterator<OutputIt> it) {
  1528. if (sign) *it++ = detail::sign<Char>(sign);
  1529. return copy_str<Char>(str, str + str_size, it);
  1530. });
  1531. }
  1532. // A decimal floating-point number significand * pow(10, exp).
  1533. struct big_decimal_fp {
  1534. const char* significand;
  1535. int significand_size;
  1536. int exponent;
  1537. };
  1538. constexpr auto get_significand_size(const big_decimal_fp& fp) -> int {
  1539. return fp.significand_size;
  1540. }
  1541. template <typename T>
  1542. inline auto get_significand_size(const dragonbox::decimal_fp<T>& fp) -> int {
  1543. return count_digits(fp.significand);
  1544. }
  1545. template <typename Char, typename OutputIt>
  1546. constexpr auto write_significand(OutputIt out, const char* significand,
  1547. int significand_size) -> OutputIt {
  1548. return copy_str<Char>(significand, significand + significand_size, out);
  1549. }
  1550. template <typename Char, typename OutputIt, typename UInt>
  1551. inline auto write_significand(OutputIt out, UInt significand,
  1552. int significand_size) -> OutputIt {
  1553. return format_decimal<Char>(out, significand, significand_size).end;
  1554. }
  1555. template <typename Char, typename OutputIt, typename T, typename Grouping>
  1556. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  1557. int significand_size, int exponent,
  1558. const Grouping& grouping) -> OutputIt {
  1559. if (!grouping.separator()) {
  1560. out = write_significand<Char>(out, significand, significand_size);
  1561. return detail::fill_n(out, exponent, static_cast<Char>('0'));
  1562. }
  1563. auto buffer = memory_buffer();
  1564. write_significand<char>(appender(buffer), significand, significand_size);
  1565. detail::fill_n(appender(buffer), exponent, '0');
  1566. return grouping.apply(out, string_view(buffer.data(), buffer.size()));
  1567. }
  1568. template <typename Char, typename UInt,
  1569. FMT_ENABLE_IF(std::is_integral<UInt>::value)>
  1570. inline auto write_significand(Char* out, UInt significand, int significand_size,
  1571. int integral_size, Char decimal_point) -> Char* {
  1572. if (!decimal_point)
  1573. return format_decimal(out, significand, significand_size).end;
  1574. out += significand_size + 1;
  1575. Char* end = out;
  1576. int floating_size = significand_size - integral_size;
  1577. for (int i = floating_size / 2; i > 0; --i) {
  1578. out -= 2;
  1579. copy2(out, digits2(significand % 100));
  1580. significand /= 100;
  1581. }
  1582. if (floating_size % 2 != 0) {
  1583. *--out = static_cast<Char>('0' + significand % 10);
  1584. significand /= 10;
  1585. }
  1586. *--out = decimal_point;
  1587. format_decimal(out - integral_size, significand, integral_size);
  1588. return end;
  1589. }
  1590. template <typename OutputIt, typename UInt, typename Char,
  1591. FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
  1592. inline auto write_significand(OutputIt out, UInt significand,
  1593. int significand_size, int integral_size,
  1594. Char decimal_point) -> OutputIt {
  1595. // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
  1596. Char buffer[digits10<UInt>() + 2];
  1597. auto end = write_significand(buffer, significand, significand_size,
  1598. integral_size, decimal_point);
  1599. return detail::copy_str_noinline<Char>(buffer, end, out);
  1600. }
  1601. template <typename OutputIt, typename Char>
  1602. FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,
  1603. int significand_size, int integral_size,
  1604. Char decimal_point) -> OutputIt {
  1605. out = detail::copy_str_noinline<Char>(significand,
  1606. significand + integral_size, out);
  1607. if (!decimal_point) return out;
  1608. *out++ = decimal_point;
  1609. return detail::copy_str_noinline<Char>(significand + integral_size,
  1610. significand + significand_size, out);
  1611. }
  1612. template <typename OutputIt, typename Char, typename T, typename Grouping>
  1613. FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
  1614. int significand_size, int integral_size,
  1615. Char decimal_point,
  1616. const Grouping& grouping) -> OutputIt {
  1617. if (!grouping.separator()) {
  1618. return write_significand(out, significand, significand_size, integral_size,
  1619. decimal_point);
  1620. }
  1621. auto buffer = basic_memory_buffer<Char>();
  1622. write_significand(buffer_appender<Char>(buffer), significand,
  1623. significand_size, integral_size, decimal_point);
  1624. grouping.apply(
  1625. out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));
  1626. return detail::copy_str_noinline<Char>(buffer.data() + integral_size,
  1627. buffer.end(), out);
  1628. }
  1629. template <typename OutputIt, typename DecimalFP, typename Char,
  1630. typename Grouping = digit_grouping<Char>>
  1631. FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& fp,
  1632. const basic_format_specs<Char>& specs,
  1633. float_specs fspecs, locale_ref loc)
  1634. -> OutputIt {
  1635. auto significand = fp.significand;
  1636. int significand_size = get_significand_size(fp);
  1637. constexpr Char zero = static_cast<Char>('0');
  1638. auto sign = fspecs.sign;
  1639. size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
  1640. using iterator = reserve_iterator<OutputIt>;
  1641. Char decimal_point =
  1642. fspecs.locale ? detail::decimal_point<Char>(loc) : static_cast<Char>('.');
  1643. int output_exp = fp.exponent + significand_size - 1;
  1644. auto use_exp_format = [=]() {
  1645. if (fspecs.format == float_format::exp) return true;
  1646. if (fspecs.format != float_format::general) return false;
  1647. // Use the fixed notation if the exponent is in [exp_lower, exp_upper),
  1648. // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
  1649. const int exp_lower = -4, exp_upper = 16;
  1650. return output_exp < exp_lower ||
  1651. output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper);
  1652. };
  1653. if (use_exp_format()) {
  1654. int num_zeros = 0;
  1655. if (fspecs.showpoint) {
  1656. num_zeros = fspecs.precision - significand_size;
  1657. if (num_zeros < 0) num_zeros = 0;
  1658. size += to_unsigned(num_zeros);
  1659. } else if (significand_size == 1) {
  1660. decimal_point = Char();
  1661. }
  1662. auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp;
  1663. int exp_digits = 2;
  1664. if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3;
  1665. size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits);
  1666. char exp_char = fspecs.upper ? 'E' : 'e';
  1667. auto write = [=](iterator it) {
  1668. if (sign) *it++ = detail::sign<Char>(sign);
  1669. // Insert a decimal point after the first digit and add an exponent.
  1670. it = write_significand(it, significand, significand_size, 1,
  1671. decimal_point);
  1672. if (num_zeros > 0) it = detail::fill_n(it, num_zeros, zero);
  1673. *it++ = static_cast<Char>(exp_char);
  1674. return write_exponent<Char>(output_exp, it);
  1675. };
  1676. return specs.width > 0 ? write_padded<align::right>(out, specs, size, write)
  1677. : base_iterator(out, write(reserve(out, size)));
  1678. }
  1679. int exp = fp.exponent + significand_size;
  1680. if (fp.exponent >= 0) {
  1681. // 1234e5 -> 123400000[.0+]
  1682. size += to_unsigned(fp.exponent);
  1683. int num_zeros = fspecs.precision - exp;
  1684. #ifdef FMT_FUZZ
  1685. if (num_zeros > 5000)
  1686. throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
  1687. #endif
  1688. if (fspecs.showpoint) {
  1689. if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1;
  1690. if (num_zeros > 0) size += to_unsigned(num_zeros) + 1;
  1691. }
  1692. auto grouping = Grouping(loc, fspecs.locale);
  1693. size += to_unsigned(grouping.count_separators(significand_size));
  1694. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  1695. if (sign) *it++ = detail::sign<Char>(sign);
  1696. it = write_significand<Char>(it, significand, significand_size,
  1697. fp.exponent, grouping);
  1698. if (!fspecs.showpoint) return it;
  1699. *it++ = decimal_point;
  1700. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  1701. });
  1702. } else if (exp > 0) {
  1703. // 1234e-2 -> 12.34[0+]
  1704. int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0;
  1705. size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0);
  1706. auto grouping = Grouping(loc, fspecs.locale);
  1707. size += to_unsigned(grouping.count_separators(significand_size));
  1708. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  1709. if (sign) *it++ = detail::sign<Char>(sign);
  1710. it = write_significand(it, significand, significand_size, exp,
  1711. decimal_point, grouping);
  1712. return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it;
  1713. });
  1714. }
  1715. // 1234e-6 -> 0.001234
  1716. int num_zeros = -exp;
  1717. if (significand_size == 0 && fspecs.precision >= 0 &&
  1718. fspecs.precision < num_zeros) {
  1719. num_zeros = fspecs.precision;
  1720. }
  1721. bool pointy = num_zeros != 0 || significand_size != 0 || fspecs.showpoint;
  1722. size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros);
  1723. return write_padded<align::right>(out, specs, size, [&](iterator it) {
  1724. if (sign) *it++ = detail::sign<Char>(sign);
  1725. *it++ = zero;
  1726. if (!pointy) return it;
  1727. *it++ = decimal_point;
  1728. it = detail::fill_n(it, num_zeros, zero);
  1729. return write_significand<Char>(it, significand, significand_size);
  1730. });
  1731. }
  1732. template <typename Char> class fallback_digit_grouping {
  1733. public:
  1734. constexpr fallback_digit_grouping(locale_ref, bool) {}
  1735. constexpr Char separator() const { return Char(); }
  1736. constexpr int count_separators(int) const { return 0; }
  1737. template <typename Out, typename C>
  1738. constexpr Out apply(Out out, basic_string_view<C>) const {
  1739. return out;
  1740. }
  1741. };
  1742. template <typename OutputIt, typename DecimalFP, typename Char>
  1743. FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& fp,
  1744. const basic_format_specs<Char>& specs,
  1745. float_specs fspecs, locale_ref loc)
  1746. -> OutputIt {
  1747. if (is_constant_evaluated()) {
  1748. return do_write_float<OutputIt, DecimalFP, Char,
  1749. fallback_digit_grouping<Char>>(out, fp, specs, fspecs,
  1750. loc);
  1751. } else {
  1752. return do_write_float(out, fp, specs, fspecs, loc);
  1753. }
  1754. }
  1755. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  1756. FMT_CONSTEXPR20 bool isinf(T value) {
  1757. if (is_constant_evaluated()) {
  1758. #if defined(__cpp_if_constexpr)
  1759. if constexpr (std::numeric_limits<double>::is_iec559) {
  1760. auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
  1761. constexpr auto significand_bits =
  1762. dragonbox::float_info<double>::significand_bits;
  1763. return (bits & exponent_mask<double>()) &&
  1764. !(bits & ((uint64_t(1) << significand_bits) - 1));
  1765. }
  1766. #endif
  1767. }
  1768. return std::isinf(value);
  1769. }
  1770. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  1771. FMT_CONSTEXPR20 bool isfinite(T value) {
  1772. if (is_constant_evaluated()) {
  1773. #if defined(__cpp_if_constexpr)
  1774. if constexpr (std::numeric_limits<double>::is_iec559) {
  1775. auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
  1776. return (bits & exponent_mask<double>()) != exponent_mask<double>();
  1777. }
  1778. #endif
  1779. }
  1780. return std::isfinite(value);
  1781. }
  1782. template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  1783. FMT_INLINE FMT_CONSTEXPR bool signbit(T value) {
  1784. if (is_constant_evaluated()) {
  1785. #ifdef __cpp_if_constexpr
  1786. if constexpr (std::numeric_limits<double>::is_iec559) {
  1787. auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
  1788. return (bits & (uint64_t(1) << (num_bits<uint64_t>() - 1))) != 0;
  1789. }
  1790. #endif
  1791. }
  1792. return std::signbit(value);
  1793. }
  1794. template <typename Char, typename OutputIt, typename T,
  1795. FMT_ENABLE_IF(std::is_floating_point<T>::value)>
  1796. FMT_CONSTEXPR20 auto write(OutputIt out, T value,
  1797. basic_format_specs<Char> specs, locale_ref loc = {})
  1798. -> OutputIt {
  1799. if (const_check(!is_supported_floating_point(value))) return out;
  1800. float_specs fspecs = parse_float_type_spec(specs);
  1801. fspecs.sign = specs.sign;
  1802. if (detail::signbit(value)) { // value < 0 is false for NaN so use signbit.
  1803. fspecs.sign = sign::minus;
  1804. value = -value;
  1805. } else if (fspecs.sign == sign::minus) {
  1806. fspecs.sign = sign::none;
  1807. }
  1808. if (!detail::isfinite(value))
  1809. return write_nonfinite(out, detail::isinf(value), specs, fspecs);
  1810. if (specs.align == align::numeric && fspecs.sign) {
  1811. auto it = reserve(out, 1);
  1812. *it++ = detail::sign<Char>(fspecs.sign);
  1813. out = base_iterator(out, it);
  1814. fspecs.sign = sign::none;
  1815. if (specs.width != 0) --specs.width;
  1816. }
  1817. memory_buffer buffer;
  1818. if (fspecs.format == float_format::hex) {
  1819. if (fspecs.sign) buffer.push_back(detail::sign<char>(fspecs.sign));
  1820. snprintf_float(promote_float(value), specs.precision, fspecs, buffer);
  1821. return write_bytes<align::right>(out, {buffer.data(), buffer.size()},
  1822. specs);
  1823. }
  1824. int precision = specs.precision >= 0 || specs.type == presentation_type::none
  1825. ? specs.precision
  1826. : 6;
  1827. if (fspecs.format == float_format::exp) {
  1828. if (precision == max_value<int>())
  1829. throw_format_error("number is too big");
  1830. else
  1831. ++precision;
  1832. }
  1833. if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
  1834. if (!is_fast_float<T>()) fspecs.fallback = true;
  1835. int exp = format_float(promote_float(value), precision, fspecs, buffer);
  1836. fspecs.precision = precision;
  1837. auto fp = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
  1838. return write_float(out, fp, specs, fspecs, loc);
  1839. }
  1840. template <typename Char, typename OutputIt, typename T,
  1841. FMT_ENABLE_IF(is_fast_float<T>::value)>
  1842. FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
  1843. if (is_constant_evaluated()) {
  1844. return write(out, value, basic_format_specs<Char>());
  1845. }
  1846. if (const_check(!is_supported_floating_point(value))) return out;
  1847. using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
  1848. using uint = typename dragonbox::float_info<floaty>::carrier_uint;
  1849. auto bits = bit_cast<uint>(value);
  1850. auto fspecs = float_specs();
  1851. if (detail::signbit(value)) {
  1852. fspecs.sign = sign::minus;
  1853. value = -value;
  1854. }
  1855. constexpr auto specs = basic_format_specs<Char>();
  1856. uint mask = exponent_mask<floaty>();
  1857. if ((bits & mask) == mask)
  1858. return write_nonfinite(out, std::isinf(value), specs, fspecs);
  1859. auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
  1860. return write_float(out, dec, specs, fspecs, {});
  1861. }
  1862. template <typename Char, typename OutputIt, typename T,
  1863. FMT_ENABLE_IF(std::is_floating_point<T>::value &&
  1864. !is_fast_float<T>::value)>
  1865. inline auto write(OutputIt out, T value) -> OutputIt {
  1866. return write(out, value, basic_format_specs<Char>());
  1867. }
  1868. template <typename Char, typename OutputIt>
  1869. auto write(OutputIt out, monostate, basic_format_specs<Char> = {},
  1870. locale_ref = {}) -> OutputIt {
  1871. FMT_ASSERT(false, "");
  1872. return out;
  1873. }
  1874. template <typename Char, typename OutputIt>
  1875. FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)
  1876. -> OutputIt {
  1877. auto it = reserve(out, value.size());
  1878. it = copy_str_noinline<Char>(value.begin(), value.end(), it);
  1879. return base_iterator(out, it);
  1880. }
  1881. template <typename Char, typename OutputIt, typename T,
  1882. FMT_ENABLE_IF(is_string<T>::value)>
  1883. constexpr auto write(OutputIt out, const T& value) -> OutputIt {
  1884. return write<Char>(out, to_string_view(value));
  1885. }
  1886. template <typename Char, typename OutputIt, typename T,
  1887. FMT_ENABLE_IF(is_integral<T>::value &&
  1888. !std::is_same<T, bool>::value &&
  1889. !std::is_same<T, Char>::value)>
  1890. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  1891. auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
  1892. bool negative = is_negative(value);
  1893. // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
  1894. if (negative) abs_value = ~abs_value + 1;
  1895. int num_digits = count_digits(abs_value);
  1896. auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
  1897. auto it = reserve(out, size);
  1898. if (auto ptr = to_pointer<Char>(it, size)) {
  1899. if (negative) *ptr++ = static_cast<Char>('-');
  1900. format_decimal<Char>(ptr, abs_value, num_digits);
  1901. return out;
  1902. }
  1903. if (negative) *it++ = static_cast<Char>('-');
  1904. it = format_decimal<Char>(it, abs_value, num_digits).end;
  1905. return base_iterator(out, it);
  1906. }
  1907. // FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
  1908. template <
  1909. typename Char, typename OutputIt, typename T,
  1910. bool check =
  1911. std::is_enum<T>::value && !std::is_same<T, Char>::value &&
  1912. mapped_type_constant<T, basic_format_context<OutputIt, Char>>::value !=
  1913. type::custom_type,
  1914. FMT_ENABLE_IF(check)>
  1915. FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
  1916. return write<Char>(
  1917. out, static_cast<typename std::underlying_type<T>::type>(value));
  1918. }
  1919. template <typename Char, typename OutputIt, typename T,
  1920. FMT_ENABLE_IF(std::is_same<T, bool>::value)>
  1921. FMT_CONSTEXPR auto write(OutputIt out, T value,
  1922. const basic_format_specs<Char>& specs = {},
  1923. locale_ref = {}) -> OutputIt {
  1924. return specs.type != presentation_type::none &&
  1925. specs.type != presentation_type::string
  1926. ? write(out, value ? 1 : 0, specs, {})
  1927. : write_bytes(out, value ? "true" : "false", specs);
  1928. }
  1929. template <typename Char, typename OutputIt>
  1930. FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {
  1931. auto it = reserve(out, 1);
  1932. *it++ = value;
  1933. return base_iterator(out, it);
  1934. }
  1935. template <typename Char, typename OutputIt>
  1936. FMT_CONSTEXPR_CHAR_TRAITS auto write(OutputIt out, const Char* value)
  1937. -> OutputIt {
  1938. if (!value) {
  1939. throw_format_error("string pointer is null");
  1940. } else {
  1941. out = write(out, basic_string_view<Char>(value));
  1942. }
  1943. return out;
  1944. }
  1945. template <typename Char, typename OutputIt, typename T,
  1946. FMT_ENABLE_IF(std::is_same<T, void>::value)>
  1947. auto write(OutputIt out, const T* value,
  1948. const basic_format_specs<Char>& specs = {}, locale_ref = {})
  1949. -> OutputIt {
  1950. check_pointer_type_spec(specs.type, error_handler());
  1951. return write_ptr<Char>(out, to_uintptr(value), &specs);
  1952. }
  1953. // A write overload that handles implicit conversions.
  1954. template <typename Char, typename OutputIt, typename T,
  1955. typename Context = basic_format_context<OutputIt, Char>>
  1956. FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> enable_if_t<
  1957. std::is_class<T>::value && !is_string<T>::value &&
  1958. !std::is_same<T, Char>::value &&
  1959. !std::is_same<const T&,
  1960. decltype(arg_mapper<Context>().map(value))>::value,
  1961. OutputIt> {
  1962. return write<Char>(out, arg_mapper<Context>().map(value));
  1963. }
  1964. template <typename Char, typename OutputIt, typename T,
  1965. typename Context = basic_format_context<OutputIt, Char>>
  1966. FMT_CONSTEXPR auto write(OutputIt out, const T& value)
  1967. -> enable_if_t<mapped_type_constant<T, Context>::value == type::custom_type,
  1968. OutputIt> {
  1969. using formatter_type =
  1970. conditional_t<has_formatter<T, Context>::value,
  1971. typename Context::template formatter_type<T>,
  1972. fallback_formatter<T, Char>>;
  1973. auto ctx = Context(out, {}, {});
  1974. return formatter_type().format(value, ctx);
  1975. }
  1976. // An argument visitor that formats the argument and writes it via the output
  1977. // iterator. It's a class and not a generic lambda for compatibility with C++11.
  1978. template <typename Char> struct default_arg_formatter {
  1979. using iterator = buffer_appender<Char>;
  1980. using context = buffer_context<Char>;
  1981. iterator out;
  1982. basic_format_args<context> args;
  1983. locale_ref loc;
  1984. template <typename T> auto operator()(T value) -> iterator {
  1985. return write<Char>(out, value);
  1986. }
  1987. auto operator()(typename basic_format_arg<context>::handle h) -> iterator {
  1988. basic_format_parse_context<Char> parse_ctx({});
  1989. context format_ctx(out, args, loc);
  1990. h.format(parse_ctx, format_ctx);
  1991. return format_ctx.out();
  1992. }
  1993. };
  1994. template <typename Char> struct arg_formatter {
  1995. using iterator = buffer_appender<Char>;
  1996. using context = buffer_context<Char>;
  1997. iterator out;
  1998. const basic_format_specs<Char>& specs;
  1999. locale_ref locale;
  2000. template <typename T>
  2001. FMT_CONSTEXPR FMT_INLINE auto operator()(T value) -> iterator {
  2002. return detail::write(out, value, specs, locale);
  2003. }
  2004. auto operator()(typename basic_format_arg<context>::handle) -> iterator {
  2005. // User-defined types are handled separately because they require access
  2006. // to the parse context.
  2007. return out;
  2008. }
  2009. };
  2010. template <typename Char> struct custom_formatter {
  2011. basic_format_parse_context<Char>& parse_ctx;
  2012. buffer_context<Char>& ctx;
  2013. void operator()(
  2014. typename basic_format_arg<buffer_context<Char>>::handle h) const {
  2015. h.format(parse_ctx, ctx);
  2016. }
  2017. template <typename T> void operator()(T) const {}
  2018. };
  2019. template <typename T>
  2020. using is_integer =
  2021. bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
  2022. !std::is_same<T, char>::value &&
  2023. !std::is_same<T, wchar_t>::value>;
  2024. template <typename ErrorHandler> class width_checker {
  2025. public:
  2026. explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
  2027. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  2028. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  2029. if (is_negative(value)) handler_.on_error("negative width");
  2030. return static_cast<unsigned long long>(value);
  2031. }
  2032. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  2033. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  2034. handler_.on_error("width is not integer");
  2035. return 0;
  2036. }
  2037. private:
  2038. ErrorHandler& handler_;
  2039. };
  2040. template <typename ErrorHandler> class precision_checker {
  2041. public:
  2042. explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
  2043. template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
  2044. FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
  2045. if (is_negative(value)) handler_.on_error("negative precision");
  2046. return static_cast<unsigned long long>(value);
  2047. }
  2048. template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
  2049. FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
  2050. handler_.on_error("precision is not integer");
  2051. return 0;
  2052. }
  2053. private:
  2054. ErrorHandler& handler_;
  2055. };
  2056. template <template <typename> class Handler, typename FormatArg,
  2057. typename ErrorHandler>
  2058. FMT_CONSTEXPR auto get_dynamic_spec(FormatArg arg, ErrorHandler eh) -> int {
  2059. unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg);
  2060. if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big");
  2061. return static_cast<int>(value);
  2062. }
  2063. template <typename Context, typename ID>
  2064. FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) ->
  2065. typename Context::format_arg {
  2066. auto arg = ctx.arg(id);
  2067. if (!arg) ctx.on_error("argument not found");
  2068. return arg;
  2069. }
  2070. // The standard format specifier handler with checking.
  2071. template <typename Char> class specs_handler : public specs_setter<Char> {
  2072. private:
  2073. basic_format_parse_context<Char>& parse_context_;
  2074. buffer_context<Char>& context_;
  2075. // This is only needed for compatibility with gcc 4.4.
  2076. using format_arg = basic_format_arg<buffer_context<Char>>;
  2077. FMT_CONSTEXPR auto get_arg(auto_id) -> format_arg {
  2078. return detail::get_arg(context_, parse_context_.next_arg_id());
  2079. }
  2080. FMT_CONSTEXPR auto get_arg(int arg_id) -> format_arg {
  2081. parse_context_.check_arg_id(arg_id);
  2082. return detail::get_arg(context_, arg_id);
  2083. }
  2084. FMT_CONSTEXPR auto get_arg(basic_string_view<Char> arg_id) -> format_arg {
  2085. parse_context_.check_arg_id(arg_id);
  2086. return detail::get_arg(context_, arg_id);
  2087. }
  2088. public:
  2089. FMT_CONSTEXPR specs_handler(basic_format_specs<Char>& specs,
  2090. basic_format_parse_context<Char>& parse_ctx,
  2091. buffer_context<Char>& ctx)
  2092. : specs_setter<Char>(specs), parse_context_(parse_ctx), context_(ctx) {}
  2093. template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
  2094. this->specs_.width = get_dynamic_spec<width_checker>(
  2095. get_arg(arg_id), context_.error_handler());
  2096. }
  2097. template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
  2098. this->specs_.precision = get_dynamic_spec<precision_checker>(
  2099. get_arg(arg_id), context_.error_handler());
  2100. }
  2101. void on_error(const char* message) { context_.on_error(message); }
  2102. };
  2103. template <template <typename> class Handler, typename Context>
  2104. FMT_CONSTEXPR void handle_dynamic_spec(int& value,
  2105. arg_ref<typename Context::char_type> ref,
  2106. Context& ctx) {
  2107. switch (ref.kind) {
  2108. case arg_id_kind::none:
  2109. break;
  2110. case arg_id_kind::index:
  2111. value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.index),
  2112. ctx.error_handler());
  2113. break;
  2114. case arg_id_kind::name:
  2115. value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.name),
  2116. ctx.error_handler());
  2117. break;
  2118. }
  2119. }
  2120. #define FMT_STRING_IMPL(s, base, explicit) \
  2121. [] { \
  2122. /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
  2123. /* Use a macro-like name to avoid shadowing warnings. */ \
  2124. struct FMT_GCC_VISIBILITY_HIDDEN FMT_COMPILE_STRING : base { \
  2125. using char_type = fmt::remove_cvref_t<decltype(s[0])>; \
  2126. FMT_MAYBE_UNUSED FMT_CONSTEXPR explicit \
  2127. operator fmt::basic_string_view<char_type>() const { \
  2128. return fmt::detail_exported::compile_string_to_view<char_type>(s); \
  2129. } \
  2130. }; \
  2131. return FMT_COMPILE_STRING(); \
  2132. }()
  2133. /**
  2134. \rst
  2135. Constructs a compile-time format string from a string literal *s*.
  2136. **Example**::
  2137. // A compile-time error because 'd' is an invalid specifier for strings.
  2138. std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
  2139. \endrst
  2140. */
  2141. #define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::compile_string, )
  2142. #if FMT_USE_USER_DEFINED_LITERALS
  2143. template <typename Char> struct udl_formatter {
  2144. basic_string_view<Char> str;
  2145. template <typename... T>
  2146. auto operator()(T&&... args) const -> std::basic_string<Char> {
  2147. return vformat(str, fmt::make_args_checked<T...>(str, args...));
  2148. }
  2149. };
  2150. # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
  2151. template <typename T, typename Char, size_t N,
  2152. fmt::detail_exported::fixed_string<Char, N> Str>
  2153. struct statically_named_arg : view {
  2154. static constexpr auto name = Str.data;
  2155. const T& value;
  2156. statically_named_arg(const T& v) : value(v) {}
  2157. };
  2158. template <typename T, typename Char, size_t N,
  2159. fmt::detail_exported::fixed_string<Char, N> Str>
  2160. struct is_named_arg<statically_named_arg<T, Char, N, Str>> : std::true_type {};
  2161. template <typename T, typename Char, size_t N,
  2162. fmt::detail_exported::fixed_string<Char, N> Str>
  2163. struct is_statically_named_arg<statically_named_arg<T, Char, N, Str>>
  2164. : std::true_type {};
  2165. template <typename Char, size_t N,
  2166. fmt::detail_exported::fixed_string<Char, N> Str>
  2167. struct udl_arg {
  2168. template <typename T> auto operator=(T&& value) const {
  2169. return statically_named_arg<T, Char, N, Str>(std::forward<T>(value));
  2170. }
  2171. };
  2172. # else
  2173. template <typename Char> struct udl_arg {
  2174. const Char* str;
  2175. template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {
  2176. return {str, std::forward<T>(value)};
  2177. }
  2178. };
  2179. # endif
  2180. #endif // FMT_USE_USER_DEFINED_LITERALS
  2181. template <typename Locale, typename Char>
  2182. auto vformat(const Locale& loc, basic_string_view<Char> format_str,
  2183. basic_format_args<buffer_context<type_identity_t<Char>>> args)
  2184. -> std::basic_string<Char> {
  2185. basic_memory_buffer<Char> buffer;
  2186. detail::vformat_to(buffer, format_str, args, detail::locale_ref(loc));
  2187. return {buffer.data(), buffer.size()};
  2188. }
  2189. using format_func = void (*)(detail::buffer<char>&, int, const char*);
  2190. FMT_API void format_error_code(buffer<char>& out, int error_code,
  2191. string_view message) FMT_NOEXCEPT;
  2192. FMT_API void report_error(format_func func, int error_code,
  2193. const char* message) FMT_NOEXCEPT;
  2194. FMT_END_DETAIL_NAMESPACE
  2195. FMT_API auto vsystem_error(int error_code, string_view format_str,
  2196. format_args args) -> std::system_error;
  2197. /**
  2198. \rst
  2199. Constructs :class:`std::system_error` with a message formatted with
  2200. ``fmt::format(fmt, args...)``.
  2201. *error_code* is a system error code as given by ``errno``.
  2202. **Example**::
  2203. // This throws std::system_error with the description
  2204. // cannot open file 'madeup': No such file or directory
  2205. // or similar (system message may vary).
  2206. const char* filename = "madeup";
  2207. std::FILE* file = std::fopen(filename, "r");
  2208. if (!file)
  2209. throw fmt::system_error(errno, "cannot open file '{}'", filename);
  2210. \endrst
  2211. */
  2212. template <typename... T>
  2213. auto system_error(int error_code, format_string<T...> fmt, T&&... args)
  2214. -> std::system_error {
  2215. return vsystem_error(error_code, fmt, fmt::make_format_args(args...));
  2216. }
  2217. /**
  2218. \rst
  2219. Formats an error message for an error returned by an operating system or a
  2220. language runtime, for example a file opening error, and writes it to *out*.
  2221. The format is the same as the one used by ``std::system_error(ec, message)``
  2222. where ``ec`` is ``std::error_code(error_code, std::generic_category()})``.
  2223. It is implementation-defined but normally looks like:
  2224. .. parsed-literal::
  2225. *<message>*: *<system-message>*
  2226. where *<message>* is the passed message and *<system-message>* is the system
  2227. message corresponding to the error code.
  2228. *error_code* is a system error code as given by ``errno``.
  2229. \endrst
  2230. */
  2231. FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
  2232. const char* message) FMT_NOEXCEPT;
  2233. // Reports a system error without throwing an exception.
  2234. // Can be used to report errors from destructors.
  2235. FMT_API void report_system_error(int error_code,
  2236. const char* message) FMT_NOEXCEPT;
  2237. /** Fast integer formatter. */
  2238. class format_int {
  2239. private:
  2240. // Buffer should be large enough to hold all digits (digits10 + 1),
  2241. // a sign and a null character.
  2242. enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
  2243. mutable char buffer_[buffer_size];
  2244. char* str_;
  2245. template <typename UInt> auto format_unsigned(UInt value) -> char* {
  2246. auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
  2247. return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
  2248. }
  2249. template <typename Int> auto format_signed(Int value) -> char* {
  2250. auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
  2251. bool negative = value < 0;
  2252. if (negative) abs_value = 0 - abs_value;
  2253. auto begin = format_unsigned(abs_value);
  2254. if (negative) *--begin = '-';
  2255. return begin;
  2256. }
  2257. public:
  2258. explicit format_int(int value) : str_(format_signed(value)) {}
  2259. explicit format_int(long value) : str_(format_signed(value)) {}
  2260. explicit format_int(long long value) : str_(format_signed(value)) {}
  2261. explicit format_int(unsigned value) : str_(format_unsigned(value)) {}
  2262. explicit format_int(unsigned long value) : str_(format_unsigned(value)) {}
  2263. explicit format_int(unsigned long long value)
  2264. : str_(format_unsigned(value)) {}
  2265. /** Returns the number of characters written to the output buffer. */
  2266. auto size() const -> size_t {
  2267. return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
  2268. }
  2269. /**
  2270. Returns a pointer to the output buffer content. No terminating null
  2271. character is appended.
  2272. */
  2273. auto data() const -> const char* { return str_; }
  2274. /**
  2275. Returns a pointer to the output buffer content with terminating null
  2276. character appended.
  2277. */
  2278. auto c_str() const -> const char* {
  2279. buffer_[buffer_size - 1] = '\0';
  2280. return str_;
  2281. }
  2282. /**
  2283. \rst
  2284. Returns the content of the output buffer as an ``std::string``.
  2285. \endrst
  2286. */
  2287. auto str() const -> std::string { return std::string(str_, size()); }
  2288. };
  2289. template <typename T, typename Char>
  2290. template <typename FormatContext>
  2291. FMT_CONSTEXPR FMT_INLINE auto
  2292. formatter<T, Char,
  2293. enable_if_t<detail::type_constant<T, Char>::value !=
  2294. detail::type::custom_type>>::format(const T& val,
  2295. FormatContext& ctx)
  2296. const -> decltype(ctx.out()) {
  2297. if (specs_.width_ref.kind != detail::arg_id_kind::none ||
  2298. specs_.precision_ref.kind != detail::arg_id_kind::none) {
  2299. auto specs = specs_;
  2300. detail::handle_dynamic_spec<detail::width_checker>(specs.width,
  2301. specs.width_ref, ctx);
  2302. detail::handle_dynamic_spec<detail::precision_checker>(
  2303. specs.precision, specs.precision_ref, ctx);
  2304. return detail::write<Char>(ctx.out(), val, specs, ctx.locale());
  2305. }
  2306. return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
  2307. }
  2308. #define FMT_FORMAT_AS(Type, Base) \
  2309. template <typename Char> \
  2310. struct formatter<Type, Char> : formatter<Base, Char> { \
  2311. template <typename FormatContext> \
  2312. auto format(Type const& val, FormatContext& ctx) const \
  2313. -> decltype(ctx.out()) { \
  2314. return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
  2315. } \
  2316. }
  2317. FMT_FORMAT_AS(signed char, int);
  2318. FMT_FORMAT_AS(unsigned char, unsigned);
  2319. FMT_FORMAT_AS(short, int);
  2320. FMT_FORMAT_AS(unsigned short, unsigned);
  2321. FMT_FORMAT_AS(long, long long);
  2322. FMT_FORMAT_AS(unsigned long, unsigned long long);
  2323. FMT_FORMAT_AS(Char*, const Char*);
  2324. FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
  2325. FMT_FORMAT_AS(std::nullptr_t, const void*);
  2326. FMT_FORMAT_AS(detail::byte, unsigned char);
  2327. FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
  2328. template <typename Char>
  2329. struct formatter<void*, Char> : formatter<const void*, Char> {
  2330. template <typename FormatContext>
  2331. auto format(void* val, FormatContext& ctx) const -> decltype(ctx.out()) {
  2332. return formatter<const void*, Char>::format(val, ctx);
  2333. }
  2334. };
  2335. template <typename Char, size_t N>
  2336. struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
  2337. template <typename FormatContext>
  2338. FMT_CONSTEXPR auto format(const Char* val, FormatContext& ctx) const
  2339. -> decltype(ctx.out()) {
  2340. return formatter<basic_string_view<Char>, Char>::format(val, ctx);
  2341. }
  2342. };
  2343. // A formatter for types known only at run time such as variant alternatives.
  2344. //
  2345. // Usage:
  2346. // using variant = std::variant<int, std::string>;
  2347. // template <>
  2348. // struct formatter<variant>: dynamic_formatter<> {
  2349. // auto format(const variant& v, format_context& ctx) {
  2350. // return visit([&](const auto& val) {
  2351. // return dynamic_formatter<>::format(val, ctx);
  2352. // }, v);
  2353. // }
  2354. // };
  2355. template <typename Char = char> class dynamic_formatter {
  2356. private:
  2357. detail::dynamic_format_specs<Char> specs_;
  2358. const Char* format_str_;
  2359. struct null_handler : detail::error_handler {
  2360. void on_align(align_t) {}
  2361. void on_sign(sign_t) {}
  2362. void on_hash() {}
  2363. };
  2364. template <typename Context> void handle_specs(Context& ctx) {
  2365. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  2366. specs_.width_ref, ctx);
  2367. detail::handle_dynamic_spec<detail::precision_checker>(
  2368. specs_.precision, specs_.precision_ref, ctx);
  2369. }
  2370. public:
  2371. template <typename ParseContext>
  2372. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2373. format_str_ = ctx.begin();
  2374. // Checks are deferred to formatting time when the argument type is known.
  2375. detail::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
  2376. return detail::parse_format_specs(ctx.begin(), ctx.end(), handler);
  2377. }
  2378. template <typename T, typename FormatContext>
  2379. auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
  2380. handle_specs(ctx);
  2381. detail::specs_checker<null_handler> checker(
  2382. null_handler(), detail::mapped_type_constant<T, FormatContext>::value);
  2383. checker.on_align(specs_.align);
  2384. if (specs_.sign != sign::none) checker.on_sign(specs_.sign);
  2385. if (specs_.alt) checker.on_hash();
  2386. if (specs_.precision >= 0) checker.end_precision();
  2387. return detail::write<Char>(ctx.out(), val, specs_, ctx.locale());
  2388. }
  2389. };
  2390. /**
  2391. \rst
  2392. Converts ``p`` to ``const void*`` for pointer formatting.
  2393. **Example**::
  2394. auto s = fmt::format("{}", fmt::ptr(p));
  2395. \endrst
  2396. */
  2397. template <typename T> auto ptr(T p) -> const void* {
  2398. static_assert(std::is_pointer<T>::value, "");
  2399. return detail::bit_cast<const void*>(p);
  2400. }
  2401. template <typename T> auto ptr(const std::unique_ptr<T>& p) -> const void* {
  2402. return p.get();
  2403. }
  2404. template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
  2405. return p.get();
  2406. }
  2407. class bytes {
  2408. private:
  2409. string_view data_;
  2410. friend struct formatter<bytes>;
  2411. public:
  2412. explicit bytes(string_view data) : data_(data) {}
  2413. };
  2414. template <> struct formatter<bytes> {
  2415. private:
  2416. detail::dynamic_format_specs<char> specs_;
  2417. public:
  2418. template <typename ParseContext>
  2419. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2420. using handler_type = detail::dynamic_specs_handler<ParseContext>;
  2421. detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
  2422. detail::type::string_type);
  2423. auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
  2424. detail::check_string_type_spec(specs_.type, ctx.error_handler());
  2425. return it;
  2426. }
  2427. template <typename FormatContext>
  2428. auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) {
  2429. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  2430. specs_.width_ref, ctx);
  2431. detail::handle_dynamic_spec<detail::precision_checker>(
  2432. specs_.precision, specs_.precision_ref, ctx);
  2433. return detail::write_bytes(ctx.out(), b.data_, specs_);
  2434. }
  2435. };
  2436. // group_digits_view is not derived from view because it copies the argument.
  2437. template <typename T> struct group_digits_view { T value; };
  2438. /**
  2439. \rst
  2440. Returns a view that formats an integer value using ',' as a locale-independent
  2441. thousands separator.
  2442. **Example**::
  2443. fmt::print("{}", fmt::group_digits(12345));
  2444. // Output: "12,345"
  2445. \endrst
  2446. */
  2447. template <typename T> auto group_digits(T value) -> group_digits_view<T> {
  2448. return {value};
  2449. }
  2450. template <typename T> struct formatter<group_digits_view<T>> : formatter<T> {
  2451. private:
  2452. detail::dynamic_format_specs<char> specs_;
  2453. public:
  2454. template <typename ParseContext>
  2455. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2456. using handler_type = detail::dynamic_specs_handler<ParseContext>;
  2457. detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
  2458. detail::type::int_type);
  2459. auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
  2460. detail::check_string_type_spec(specs_.type, ctx.error_handler());
  2461. return it;
  2462. }
  2463. template <typename FormatContext>
  2464. auto format(group_digits_view<T> t, FormatContext& ctx)
  2465. -> decltype(ctx.out()) {
  2466. detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
  2467. specs_.width_ref, ctx);
  2468. detail::handle_dynamic_spec<detail::precision_checker>(
  2469. specs_.precision, specs_.precision_ref, ctx);
  2470. return detail::write_int_localized(
  2471. ctx.out(), static_cast<detail::uint64_or_128_t<T>>(t.value), 0, specs_,
  2472. detail::digit_grouping<char>({"\3", ','}));
  2473. }
  2474. };
  2475. template <typename It, typename Sentinel, typename Char = char>
  2476. struct join_view : detail::view {
  2477. It begin;
  2478. Sentinel end;
  2479. basic_string_view<Char> sep;
  2480. join_view(It b, Sentinel e, basic_string_view<Char> s)
  2481. : begin(b), end(e), sep(s) {}
  2482. };
  2483. template <typename It, typename Sentinel, typename Char>
  2484. using arg_join FMT_DEPRECATED_ALIAS = join_view<It, Sentinel, Char>;
  2485. template <typename It, typename Sentinel, typename Char>
  2486. struct formatter<join_view<It, Sentinel, Char>, Char> {
  2487. private:
  2488. using value_type =
  2489. #ifdef __cpp_lib_ranges
  2490. std::iter_value_t<It>;
  2491. #else
  2492. typename std::iterator_traits<It>::value_type;
  2493. #endif
  2494. using context = buffer_context<Char>;
  2495. using mapper = detail::arg_mapper<context>;
  2496. template <typename T, FMT_ENABLE_IF(has_formatter<T, context>::value)>
  2497. static auto map(const T& value) -> const T& {
  2498. return value;
  2499. }
  2500. template <typename T, FMT_ENABLE_IF(!has_formatter<T, context>::value)>
  2501. static auto map(const T& value) -> decltype(mapper().map(value)) {
  2502. return mapper().map(value);
  2503. }
  2504. using formatter_type =
  2505. conditional_t<is_formattable<value_type, Char>::value,
  2506. formatter<remove_cvref_t<decltype(map(
  2507. std::declval<const value_type&>()))>,
  2508. Char>,
  2509. detail::fallback_formatter<value_type, Char>>;
  2510. formatter_type value_formatter_;
  2511. public:
  2512. template <typename ParseContext>
  2513. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2514. return value_formatter_.parse(ctx);
  2515. }
  2516. template <typename FormatContext>
  2517. auto format(const join_view<It, Sentinel, Char>& value, FormatContext& ctx)
  2518. -> decltype(ctx.out()) {
  2519. auto it = value.begin;
  2520. auto out = ctx.out();
  2521. if (it != value.end) {
  2522. out = value_formatter_.format(map(*it), ctx);
  2523. ++it;
  2524. while (it != value.end) {
  2525. out = detail::copy_str<Char>(value.sep.begin(), value.sep.end(), out);
  2526. ctx.advance_to(out);
  2527. out = value_formatter_.format(map(*it), ctx);
  2528. ++it;
  2529. }
  2530. }
  2531. return out;
  2532. }
  2533. };
  2534. /**
  2535. Returns a view that formats the iterator range `[begin, end)` with elements
  2536. separated by `sep`.
  2537. */
  2538. template <typename It, typename Sentinel>
  2539. auto join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel> {
  2540. return {begin, end, sep};
  2541. }
  2542. /**
  2543. \rst
  2544. Returns a view that formats `range` with elements separated by `sep`.
  2545. **Example**::
  2546. std::vector<int> v = {1, 2, 3};
  2547. fmt::print("{}", fmt::join(v, ", "));
  2548. // Output: "1, 2, 3"
  2549. ``fmt::join`` applies passed format specifiers to the range elements::
  2550. fmt::print("{:02}", fmt::join(v, ", "));
  2551. // Output: "01, 02, 03"
  2552. \endrst
  2553. */
  2554. template <typename Range>
  2555. auto join(Range&& range, string_view sep)
  2556. -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>> {
  2557. return join(std::begin(range), std::end(range), sep);
  2558. }
  2559. /**
  2560. \rst
  2561. Converts *value* to ``std::string`` using the default format for type *T*.
  2562. **Example**::
  2563. #include <fmt/format.h>
  2564. std::string answer = fmt::to_string(42);
  2565. \endrst
  2566. */
  2567. template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
  2568. inline auto to_string(const T& value) -> std::string {
  2569. auto result = std::string();
  2570. detail::write<char>(std::back_inserter(result), value);
  2571. return result;
  2572. }
  2573. template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
  2574. FMT_NODISCARD inline auto to_string(T value) -> std::string {
  2575. // The buffer should be large enough to store the number including the sign
  2576. // or "false" for bool.
  2577. constexpr int max_size = detail::digits10<T>() + 2;
  2578. char buffer[max_size > 5 ? static_cast<unsigned>(max_size) : 5];
  2579. char* begin = buffer;
  2580. return std::string(begin, detail::write<char>(begin, value));
  2581. }
  2582. template <typename Char, size_t SIZE>
  2583. FMT_NODISCARD auto to_string(const basic_memory_buffer<Char, SIZE>& buf)
  2584. -> std::basic_string<Char> {
  2585. auto size = buf.size();
  2586. detail::assume(size < std::basic_string<Char>().max_size());
  2587. return std::basic_string<Char>(buf.data(), size);
  2588. }
  2589. FMT_BEGIN_DETAIL_NAMESPACE
  2590. template <typename Char>
  2591. void vformat_to(
  2592. buffer<Char>& buf, basic_string_view<Char> fmt,
  2593. basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
  2594. locale_ref loc) {
  2595. // workaround for msvc bug regarding name-lookup in module
  2596. // link names into function scope
  2597. using detail::arg_formatter;
  2598. using detail::buffer_appender;
  2599. using detail::custom_formatter;
  2600. using detail::default_arg_formatter;
  2601. using detail::get_arg;
  2602. using detail::locale_ref;
  2603. using detail::parse_format_specs;
  2604. using detail::specs_checker;
  2605. using detail::specs_handler;
  2606. using detail::to_unsigned;
  2607. using detail::type;
  2608. using detail::write;
  2609. auto out = buffer_appender<Char>(buf);
  2610. if (fmt.size() == 2 && equal2(fmt.data(), "{}")) {
  2611. auto arg = args.get(0);
  2612. if (!arg) error_handler().on_error("argument not found");
  2613. visit_format_arg(default_arg_formatter<Char>{out, args, loc}, arg);
  2614. return;
  2615. }
  2616. struct format_handler : error_handler {
  2617. basic_format_parse_context<Char> parse_context;
  2618. buffer_context<Char> context;
  2619. format_handler(buffer_appender<Char> out, basic_string_view<Char> str,
  2620. basic_format_args<buffer_context<Char>> args, locale_ref loc)
  2621. : parse_context(str), context(out, args, loc) {}
  2622. void on_text(const Char* begin, const Char* end) {
  2623. auto text = basic_string_view<Char>(begin, to_unsigned(end - begin));
  2624. context.advance_to(write<Char>(context.out(), text));
  2625. }
  2626. FMT_CONSTEXPR auto on_arg_id() -> int {
  2627. return parse_context.next_arg_id();
  2628. }
  2629. FMT_CONSTEXPR auto on_arg_id(int id) -> int {
  2630. return parse_context.check_arg_id(id), id;
  2631. }
  2632. FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
  2633. int arg_id = context.arg_id(id);
  2634. if (arg_id < 0) on_error("argument not found");
  2635. return arg_id;
  2636. }
  2637. FMT_INLINE void on_replacement_field(int id, const Char*) {
  2638. auto arg = get_arg(context, id);
  2639. context.advance_to(visit_format_arg(
  2640. default_arg_formatter<Char>{context.out(), context.args(),
  2641. context.locale()},
  2642. arg));
  2643. }
  2644. auto on_format_specs(int id, const Char* begin, const Char* end)
  2645. -> const Char* {
  2646. auto arg = get_arg(context, id);
  2647. if (arg.type() == type::custom_type) {
  2648. parse_context.advance_to(parse_context.begin() +
  2649. (begin - &*parse_context.begin()));
  2650. visit_format_arg(custom_formatter<Char>{parse_context, context}, arg);
  2651. return parse_context.begin();
  2652. }
  2653. auto specs = basic_format_specs<Char>();
  2654. specs_checker<specs_handler<Char>> handler(
  2655. specs_handler<Char>(specs, parse_context, context), arg.type());
  2656. begin = parse_format_specs(begin, end, handler);
  2657. if (begin == end || *begin != '}')
  2658. on_error("missing '}' in format string");
  2659. auto f = arg_formatter<Char>{context.out(), specs, context.locale()};
  2660. context.advance_to(visit_format_arg(f, arg));
  2661. return begin;
  2662. }
  2663. };
  2664. detail::parse_format_string<false>(fmt, format_handler(out, fmt, args, loc));
  2665. }
  2666. #ifndef FMT_HEADER_ONLY
  2667. extern template FMT_API auto thousands_sep_impl<char>(locale_ref)
  2668. -> thousands_sep_result<char>;
  2669. extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
  2670. -> thousands_sep_result<wchar_t>;
  2671. extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
  2672. extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
  2673. extern template auto format_float<double>(double value, int precision,
  2674. float_specs specs, buffer<char>& buf)
  2675. -> int;
  2676. extern template auto format_float<long double>(long double value, int precision,
  2677. float_specs specs,
  2678. buffer<char>& buf) -> int;
  2679. void snprintf_float(float, int, float_specs, buffer<char>&) = delete;
  2680. extern template auto snprintf_float<double>(double value, int precision,
  2681. float_specs specs,
  2682. buffer<char>& buf) -> int;
  2683. extern template auto snprintf_float<long double>(long double value,
  2684. int precision,
  2685. float_specs specs,
  2686. buffer<char>& buf) -> int;
  2687. #endif // FMT_HEADER_ONLY
  2688. FMT_END_DETAIL_NAMESPACE
  2689. #if FMT_USE_USER_DEFINED_LITERALS
  2690. inline namespace literals {
  2691. /**
  2692. \rst
  2693. User-defined literal equivalent of :func:`fmt::arg`.
  2694. **Example**::
  2695. using namespace fmt::literals;
  2696. fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
  2697. \endrst
  2698. */
  2699. # if FMT_USE_NONTYPE_TEMPLATE_PARAMETERS
  2700. template <detail_exported::fixed_string Str>
  2701. constexpr auto operator""_a()
  2702. -> detail::udl_arg<remove_cvref_t<decltype(Str.data[0])>,
  2703. sizeof(Str.data) / sizeof(decltype(Str.data[0])), Str> {
  2704. return {};
  2705. }
  2706. # else
  2707. constexpr auto operator"" _a(const char* s, size_t) -> detail::udl_arg<char> {
  2708. return {s};
  2709. }
  2710. # endif
  2711. // DEPRECATED!
  2712. // User-defined literal equivalent of fmt::format.
  2713. FMT_DEPRECATED constexpr auto operator"" _format(const char* s, size_t n)
  2714. -> detail::udl_formatter<char> {
  2715. return {{s, n}};
  2716. }
  2717. } // namespace literals
  2718. #endif // FMT_USE_USER_DEFINED_LITERALS
  2719. template <typename Locale, FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  2720. inline auto vformat(const Locale& loc, string_view fmt, format_args args)
  2721. -> std::string {
  2722. return detail::vformat(loc, fmt, args);
  2723. }
  2724. template <typename Locale, typename... T,
  2725. FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
  2726. inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
  2727. -> std::string {
  2728. return vformat(loc, string_view(fmt), fmt::make_format_args(args...));
  2729. }
  2730. template <typename... T, size_t SIZE, typename Allocator>
  2731. FMT_DEPRECATED auto format_to(basic_memory_buffer<char, SIZE, Allocator>& buf,
  2732. format_string<T...> fmt, T&&... args)
  2733. -> appender {
  2734. detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...));
  2735. return appender(buf);
  2736. }
  2737. template <typename OutputIt, typename Locale,
  2738. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  2739. detail::is_locale<Locale>::value)>
  2740. auto vformat_to(OutputIt out, const Locale& loc, string_view fmt,
  2741. format_args args) -> OutputIt {
  2742. using detail::get_buffer;
  2743. auto&& buf = get_buffer<char>(out);
  2744. detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
  2745. return detail::get_iterator(buf);
  2746. }
  2747. template <typename OutputIt, typename Locale, typename... T,
  2748. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value&&
  2749. detail::is_locale<Locale>::value)>
  2750. FMT_INLINE auto format_to(OutputIt out, const Locale& loc,
  2751. format_string<T...> fmt, T&&... args) -> OutputIt {
  2752. return vformat_to(out, loc, fmt, fmt::make_format_args(args...));
  2753. }
  2754. FMT_MODULE_EXPORT_END
  2755. FMT_END_NAMESPACE
  2756. #ifdef FMT_DEPRECATED_INCLUDE_XCHAR
  2757. # include "xchar.h"
  2758. #endif
  2759. #ifdef FMT_HEADER_ONLY
  2760. # define FMT_FUNC inline
  2761. # include "format-inl.h"
  2762. #else
  2763. # define FMT_FUNC
  2764. #endif
  2765. #endif // FMT_FORMAT_H_