base.h 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. // Formatting library for C++ - the base API for char/UTF-8
  3. //
  4. // Copyright (c) 2012 - present, Victor Zverovich
  5. // All rights reserved.
  6. //
  7. // For the license information refer to format.h.
  8. #ifndef FMT_BASE_H_
  9. #define FMT_BASE_H_
  10. #if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE)
  11. # define FMT_MODULE
  12. #endif
  13. #ifndef FMT_MODULE
  14. # include <limits.h> // CHAR_BIT
  15. # include <stdio.h> // FILE
  16. # include <string.h> // memcmp
  17. # include <type_traits> // std::enable_if
  18. #endif
  19. // The fmt library version in the form major * 10000 + minor * 100 + patch.
  20. #define FMT_VERSION 120100
  21. // Detect compiler versions.
  22. #if defined(__clang__) && !defined(__ibmxl__)
  23. # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
  24. #else
  25. # define FMT_CLANG_VERSION 0
  26. #endif
  27. #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
  28. # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  29. #else
  30. # define FMT_GCC_VERSION 0
  31. #endif
  32. #if defined(__ICL)
  33. # define FMT_ICC_VERSION __ICL
  34. #elif defined(__INTEL_COMPILER)
  35. # define FMT_ICC_VERSION __INTEL_COMPILER
  36. #else
  37. # define FMT_ICC_VERSION 0
  38. #endif
  39. #if defined(_MSC_VER)
  40. # define FMT_MSC_VERSION _MSC_VER
  41. #else
  42. # define FMT_MSC_VERSION 0
  43. #endif
  44. // Detect standard library versions.
  45. #ifdef _GLIBCXX_RELEASE
  46. # define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE
  47. #else
  48. # define FMT_GLIBCXX_RELEASE 0
  49. #endif
  50. #ifdef _LIBCPP_VERSION
  51. # define FMT_LIBCPP_VERSION _LIBCPP_VERSION
  52. #else
  53. # define FMT_LIBCPP_VERSION 0
  54. #endif
  55. #ifdef _MSVC_LANG
  56. # define FMT_CPLUSPLUS _MSVC_LANG
  57. #else
  58. # define FMT_CPLUSPLUS __cplusplus
  59. #endif
  60. // Detect __has_*.
  61. #ifdef __has_feature
  62. # define FMT_HAS_FEATURE(x) __has_feature(x)
  63. #else
  64. # define FMT_HAS_FEATURE(x) 0
  65. #endif
  66. #ifdef __has_include
  67. # define FMT_HAS_INCLUDE(x) __has_include(x)
  68. #else
  69. # define FMT_HAS_INCLUDE(x) 0
  70. #endif
  71. #ifdef __has_builtin
  72. # define FMT_HAS_BUILTIN(x) __has_builtin(x)
  73. #else
  74. # define FMT_HAS_BUILTIN(x) 0
  75. #endif
  76. #ifdef __has_cpp_attribute
  77. # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
  78. #else
  79. # define FMT_HAS_CPP_ATTRIBUTE(x) 0
  80. #endif
  81. #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
  82. (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  83. #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
  84. (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  85. // Detect C++14 relaxed constexpr.
  86. #ifdef FMT_USE_CONSTEXPR
  87. // Use the provided definition.
  88. #elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L
  89. // GCC only allows constexpr member functions in non-literal types since 7.2:
  90. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297.
  91. # define FMT_USE_CONSTEXPR 1
  92. #elif FMT_ICC_VERSION
  93. # define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628
  94. #elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912
  95. # define FMT_USE_CONSTEXPR 1
  96. #else
  97. # define FMT_USE_CONSTEXPR 0
  98. #endif
  99. #if FMT_USE_CONSTEXPR
  100. # define FMT_CONSTEXPR constexpr
  101. #else
  102. # define FMT_CONSTEXPR
  103. #endif
  104. // Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.
  105. #ifdef FMT_USE_CONSTEVAL
  106. // Use the provided definition.
  107. #elif !defined(__cpp_lib_is_constant_evaluated)
  108. # define FMT_USE_CONSTEVAL 0
  109. #elif FMT_CPLUSPLUS < 201709L
  110. # define FMT_USE_CONSTEVAL 0
  111. #elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10
  112. # define FMT_USE_CONSTEVAL 0
  113. #elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000
  114. # define FMT_USE_CONSTEVAL 0
  115. #elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L
  116. # define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14.
  117. #elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929
  118. # define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10.
  119. #elif defined(__cpp_consteval)
  120. # define FMT_USE_CONSTEVAL 1
  121. #elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101
  122. # define FMT_USE_CONSTEVAL 1
  123. #else
  124. # define FMT_USE_CONSTEVAL 0
  125. #endif
  126. #if FMT_USE_CONSTEVAL
  127. # define FMT_CONSTEVAL consteval
  128. # define FMT_CONSTEXPR20 constexpr
  129. #else
  130. # define FMT_CONSTEVAL
  131. # define FMT_CONSTEXPR20
  132. #endif
  133. // Check if exceptions are disabled.
  134. #ifdef FMT_USE_EXCEPTIONS
  135. // Use the provided definition.
  136. #elif defined(__GNUC__) && !defined(__EXCEPTIONS)
  137. # define FMT_USE_EXCEPTIONS 0
  138. #elif defined(__clang__) && !defined(__cpp_exceptions)
  139. # define FMT_USE_EXCEPTIONS 0
  140. #elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS
  141. # define FMT_USE_EXCEPTIONS 0
  142. #else
  143. # define FMT_USE_EXCEPTIONS 1
  144. #endif
  145. #if FMT_USE_EXCEPTIONS
  146. # define FMT_TRY try
  147. # define FMT_CATCH(x) catch (x)
  148. #else
  149. # define FMT_TRY if (true)
  150. # define FMT_CATCH(x) if (false)
  151. #endif
  152. #ifdef FMT_NO_UNIQUE_ADDRESS
  153. // Use the provided definition.
  154. #elif FMT_CPLUSPLUS < 202002L
  155. // Not supported.
  156. #elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address)
  157. # define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]]
  158. // VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485).
  159. #elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION
  160. # define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
  161. #endif
  162. #ifndef FMT_NO_UNIQUE_ADDRESS
  163. # define FMT_NO_UNIQUE_ADDRESS
  164. #endif
  165. #if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
  166. # define FMT_FALLTHROUGH [[fallthrough]]
  167. #elif defined(__clang__)
  168. # define FMT_FALLTHROUGH [[clang::fallthrough]]
  169. #elif FMT_GCC_VERSION >= 700 && \
  170. (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
  171. # define FMT_FALLTHROUGH [[gnu::fallthrough]]
  172. #else
  173. # define FMT_FALLTHROUGH
  174. #endif
  175. // Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.
  176. #if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__)
  177. # define FMT_NORETURN [[noreturn]]
  178. #else
  179. # define FMT_NORETURN
  180. #endif
  181. #ifdef FMT_NODISCARD
  182. // Use the provided definition.
  183. #elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
  184. # define FMT_NODISCARD [[nodiscard]]
  185. #else
  186. # define FMT_NODISCARD
  187. #endif
  188. #if FMT_GCC_VERSION || FMT_CLANG_VERSION
  189. # define FMT_VISIBILITY(value) __attribute__((visibility(value)))
  190. #else
  191. # define FMT_VISIBILITY(value)
  192. #endif
  193. // Detect pragmas.
  194. #define FMT_PRAGMA_IMPL(x) _Pragma(#x)
  195. #if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER)
  196. // Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884
  197. // and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582.
  198. # define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x)
  199. #else
  200. # define FMT_PRAGMA_GCC(x)
  201. #endif
  202. #if FMT_CLANG_VERSION
  203. # define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x)
  204. #else
  205. # define FMT_PRAGMA_CLANG(x)
  206. #endif
  207. #if FMT_MSC_VERSION
  208. # define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
  209. #else
  210. # define FMT_MSC_WARNING(...)
  211. #endif
  212. // Enable minimal optimizations for more compact code in debug mode.
  213. FMT_PRAGMA_GCC(push_options)
  214. #if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE)
  215. FMT_PRAGMA_GCC(optimize("Og"))
  216. # define FMT_GCC_OPTIMIZED
  217. #endif
  218. FMT_PRAGMA_CLANG(diagnostic push)
  219. FMT_PRAGMA_GCC(diagnostic push)
  220. #ifdef FMT_ALWAYS_INLINE
  221. // Use the provided definition.
  222. #elif FMT_GCC_VERSION || FMT_CLANG_VERSION
  223. # define FMT_ALWAYS_INLINE inline __attribute__((always_inline))
  224. #else
  225. # define FMT_ALWAYS_INLINE inline
  226. #endif
  227. // A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode.
  228. #if defined(NDEBUG) || defined(FMT_GCC_OPTIMIZED)
  229. # define FMT_INLINE FMT_ALWAYS_INLINE
  230. #else
  231. # define FMT_INLINE inline
  232. #endif
  233. #ifndef FMT_BEGIN_NAMESPACE
  234. # define FMT_BEGIN_NAMESPACE \
  235. namespace fmt { \
  236. inline namespace v12 {
  237. # define FMT_END_NAMESPACE \
  238. } \
  239. }
  240. #endif
  241. #ifndef FMT_EXPORT
  242. # define FMT_EXPORT
  243. # define FMT_BEGIN_EXPORT
  244. # define FMT_END_EXPORT
  245. #endif
  246. #ifdef _WIN32
  247. # define FMT_WIN32 1
  248. #else
  249. # define FMT_WIN32 0
  250. #endif
  251. #if !defined(FMT_HEADER_ONLY) && FMT_WIN32
  252. # if defined(FMT_LIB_EXPORT)
  253. # define FMT_API __declspec(dllexport)
  254. # elif defined(FMT_SHARED)
  255. # define FMT_API __declspec(dllimport)
  256. # endif
  257. #elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
  258. # define FMT_API FMT_VISIBILITY("default")
  259. #endif
  260. #ifndef FMT_API
  261. # define FMT_API
  262. #endif
  263. #ifndef FMT_OPTIMIZE_SIZE
  264. # define FMT_OPTIMIZE_SIZE 0
  265. #endif
  266. // FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher
  267. // per-call binary size by passing built-in types through the extension API.
  268. #ifndef FMT_BUILTIN_TYPES
  269. # define FMT_BUILTIN_TYPES 1
  270. #endif
  271. #define FMT_APPLY_VARIADIC(expr) \
  272. using unused = int[]; \
  273. (void)unused { 0, (expr, 0)... }
  274. FMT_BEGIN_NAMESPACE
  275. // Implementations of enable_if_t and other metafunctions for older systems.
  276. template <bool B, typename T = void>
  277. using enable_if_t = typename std::enable_if<B, T>::type;
  278. template <bool B, typename T, typename F>
  279. using conditional_t = typename std::conditional<B, T, F>::type;
  280. template <bool B> using bool_constant = std::integral_constant<bool, B>;
  281. template <typename T>
  282. using remove_reference_t = typename std::remove_reference<T>::type;
  283. template <typename T>
  284. using remove_const_t = typename std::remove_const<T>::type;
  285. template <typename T>
  286. using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
  287. template <typename T>
  288. using make_unsigned_t = typename std::make_unsigned<T>::type;
  289. template <typename T>
  290. using underlying_t = typename std::underlying_type<T>::type;
  291. template <typename T> using decay_t = typename std::decay<T>::type;
  292. using nullptr_t = decltype(nullptr);
  293. #if (FMT_GCC_VERSION && FMT_GCC_VERSION < 500) || FMT_MSC_VERSION
  294. // A workaround for gcc 4.9 & MSVC v141 to make void_t work in a SFINAE context.
  295. template <typename...> struct void_t_impl {
  296. using type = void;
  297. };
  298. template <typename... T> using void_t = typename void_t_impl<T...>::type;
  299. #else
  300. template <typename...> using void_t = void;
  301. #endif
  302. struct monostate {
  303. constexpr monostate() {}
  304. };
  305. // An enable_if helper to be used in template parameters which results in much
  306. // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
  307. // to workaround a bug in MSVC 2019 (see #1140 and #1186).
  308. #ifdef FMT_DOC
  309. # define FMT_ENABLE_IF(...)
  310. #else
  311. # define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0
  312. #endif
  313. template <typename T> constexpr auto min_of(T a, T b) -> T {
  314. return a < b ? a : b;
  315. }
  316. template <typename T> constexpr auto max_of(T a, T b) -> T {
  317. return a > b ? a : b;
  318. }
  319. FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
  320. const char* message);
  321. namespace detail {
  322. // Suppresses "unused variable" warnings with the method described in
  323. // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
  324. // (void)var does not work on many Intel compilers.
  325. template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
  326. constexpr auto is_constant_evaluated(bool default_value = false) noexcept
  327. -> bool {
  328. // Workaround for incompatibility between clang 14 and libstdc++ consteval-based
  329. // std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247.
  330. #if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \
  331. (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500)
  332. ignore_unused(default_value);
  333. return __builtin_is_constant_evaluated();
  334. #elif defined(__cpp_lib_is_constant_evaluated)
  335. ignore_unused(default_value);
  336. return std::is_constant_evaluated();
  337. #else
  338. return default_value;
  339. #endif
  340. }
  341. // Suppresses "conditional expression is constant" warnings.
  342. template <typename T> FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T {
  343. return val;
  344. }
  345. FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
  346. const char* message);
  347. #if defined(FMT_ASSERT)
  348. // Use the provided definition.
  349. #elif defined(NDEBUG)
  350. // FMT_ASSERT is not empty to avoid -Wempty-body.
  351. # define FMT_ASSERT(condition, message) \
  352. fmt::detail::ignore_unused((condition), (message))
  353. #else
  354. # define FMT_ASSERT(condition, message) \
  355. ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
  356. ? (void)0 \
  357. : ::fmt::assert_fail(__FILE__, __LINE__, (message)))
  358. #endif
  359. #ifdef FMT_USE_INT128
  360. // Use the provided definition.
  361. #elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
  362. !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
  363. # define FMT_USE_INT128 1
  364. using int128_opt = __int128_t; // An optional native 128-bit integer.
  365. using uint128_opt = __uint128_t;
  366. inline auto map(int128_opt x) -> int128_opt { return x; }
  367. inline auto map(uint128_opt x) -> uint128_opt { return x; }
  368. #else
  369. # define FMT_USE_INT128 0
  370. #endif
  371. #if !FMT_USE_INT128
  372. enum class int128_opt {};
  373. enum class uint128_opt {};
  374. // Reduce template instantiations.
  375. inline auto map(int128_opt) -> monostate { return {}; }
  376. inline auto map(uint128_opt) -> monostate { return {}; }
  377. #endif
  378. #ifdef FMT_USE_BITINT
  379. // Use the provided definition.
  380. #elif FMT_CLANG_VERSION >= 1500 && !defined(__CUDACC__)
  381. # define FMT_USE_BITINT 1
  382. #else
  383. # define FMT_USE_BITINT 0
  384. #endif
  385. #if FMT_USE_BITINT
  386. FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension")
  387. template <int N> using bitint = _BitInt(N);
  388. template <int N> using ubitint = unsigned _BitInt(N);
  389. #else
  390. template <int N> struct bitint {};
  391. template <int N> struct ubitint {};
  392. #endif // FMT_USE_BITINT
  393. // Casts a nonnegative integer to unsigned.
  394. template <typename Int>
  395. FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t<Int> {
  396. FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
  397. return static_cast<make_unsigned_t<Int>>(value);
  398. }
  399. template <typename Char>
  400. using unsigned_char = conditional_t<sizeof(Char) == 1, unsigned char, unsigned>;
  401. // A heuristic to detect std::string and std::[experimental::]string_view.
  402. // It is mainly used to avoid dependency on <[experimental/]string_view>.
  403. template <typename T, typename Enable = void>
  404. struct is_std_string_like : std::false_type {};
  405. template <typename T>
  406. struct is_std_string_like<T, void_t<decltype(std::declval<T>().find_first_of(
  407. typename T::value_type(), 0))>>
  408. : std::is_convertible<decltype(std::declval<T>().data()),
  409. const typename T::value_type*> {};
  410. // Check if the literal encoding is UTF-8.
  411. enum { is_utf8_enabled = "\u00A7"[1] == '\xA7' };
  412. enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled };
  413. #ifndef FMT_UNICODE
  414. # define FMT_UNICODE 1
  415. #endif
  416. static_assert(!FMT_UNICODE || use_utf8,
  417. "Unicode support requires compiling with /utf-8");
  418. template <typename T> constexpr auto narrow(T*) -> char* { return nullptr; }
  419. constexpr FMT_ALWAYS_INLINE auto narrow(const char* s) -> const char* {
  420. return s;
  421. }
  422. template <typename Char>
  423. FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, size_t n) -> int {
  424. if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n);
  425. for (; n != 0; ++s1, ++s2, --n) {
  426. if (*s1 < *s2) return -1;
  427. if (*s1 > *s2) return 1;
  428. }
  429. return 0;
  430. }
  431. namespace adl {
  432. using namespace std;
  433. template <typename Container>
  434. auto invoke_back_inserter()
  435. -> decltype(back_inserter(std::declval<Container&>()));
  436. } // namespace adl
  437. template <typename It, typename Enable = std::true_type>
  438. struct is_back_insert_iterator : std::false_type {};
  439. template <typename It>
  440. struct is_back_insert_iterator<
  441. It, bool_constant<std::is_same<
  442. decltype(adl::invoke_back_inserter<typename It::container_type>()),
  443. It>::value>> : std::true_type {};
  444. // Extracts a reference to the container from *insert_iterator.
  445. template <typename OutputIt>
  446. inline FMT_CONSTEXPR20 auto get_container(OutputIt it) ->
  447. typename OutputIt::container_type& {
  448. struct accessor : OutputIt {
  449. FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {}
  450. using OutputIt::container;
  451. };
  452. return *accessor(it).container;
  453. }
  454. } // namespace detail
  455. // Parsing-related public API and forward declarations.
  456. FMT_BEGIN_EXPORT
  457. /**
  458. * An implementation of `std::basic_string_view` for pre-C++17. It provides a
  459. * subset of the API. `fmt::basic_string_view` is used for format strings even
  460. * if `std::basic_string_view` is available to prevent issues when a library is
  461. * compiled with a different `-std` option than the client code (which is not
  462. * recommended).
  463. */
  464. template <typename Char> class basic_string_view {
  465. private:
  466. const Char* data_;
  467. size_t size_;
  468. public:
  469. using value_type = Char;
  470. using iterator = const Char*;
  471. constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
  472. /// Constructs a string view object from a C string and a size.
  473. constexpr basic_string_view(const Char* s, size_t count) noexcept
  474. : data_(s), size_(count) {}
  475. constexpr basic_string_view(nullptr_t) = delete;
  476. /// Constructs a string view object from a C string.
  477. #if FMT_GCC_VERSION
  478. FMT_ALWAYS_INLINE
  479. #endif
  480. FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) {
  481. #if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION
  482. if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) {
  483. size_ = __builtin_strlen(detail::narrow(s)); // strlen is not constexpr.
  484. return;
  485. }
  486. #endif
  487. size_t len = 0;
  488. while (*s++) ++len;
  489. size_ = len;
  490. }
  491. /// Constructs a string view from a `std::basic_string` or a
  492. /// `std::basic_string_view` object.
  493. template <typename S,
  494. FMT_ENABLE_IF(detail::is_std_string_like<S>::value&& std::is_same<
  495. typename S::value_type, Char>::value)>
  496. FMT_CONSTEXPR basic_string_view(const S& s) noexcept
  497. : data_(s.data()), size_(s.size()) {}
  498. /// Returns a pointer to the string data.
  499. constexpr auto data() const noexcept -> const Char* { return data_; }
  500. /// Returns the string size.
  501. constexpr auto size() const noexcept -> size_t { return size_; }
  502. constexpr auto begin() const noexcept -> iterator { return data_; }
  503. constexpr auto end() const noexcept -> iterator { return data_ + size_; }
  504. constexpr auto operator[](size_t pos) const noexcept -> const Char& {
  505. return data_[pos];
  506. }
  507. FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
  508. data_ += n;
  509. size_ -= n;
  510. }
  511. FMT_CONSTEXPR auto starts_with(basic_string_view<Char> sv) const noexcept
  512. -> bool {
  513. return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0;
  514. }
  515. FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool {
  516. return size_ >= 1 && *data_ == c;
  517. }
  518. FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool {
  519. return starts_with(basic_string_view<Char>(s));
  520. }
  521. FMT_CONSTEXPR auto compare(basic_string_view other) const -> int {
  522. int result =
  523. detail::compare(data_, other.data_, min_of(size_, other.size_));
  524. if (result != 0) return result;
  525. return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
  526. }
  527. FMT_CONSTEXPR friend auto operator==(basic_string_view lhs,
  528. basic_string_view rhs) -> bool {
  529. return lhs.compare(rhs) == 0;
  530. }
  531. friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
  532. return lhs.compare(rhs) != 0;
  533. }
  534. friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
  535. return lhs.compare(rhs) < 0;
  536. }
  537. friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
  538. return lhs.compare(rhs) <= 0;
  539. }
  540. friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
  541. return lhs.compare(rhs) > 0;
  542. }
  543. friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
  544. return lhs.compare(rhs) >= 0;
  545. }
  546. };
  547. using string_view = basic_string_view<char>;
  548. template <typename T> class basic_appender;
  549. using appender = basic_appender<char>;
  550. // Checks whether T is a container with contiguous storage.
  551. template <typename T> struct is_contiguous : std::false_type {};
  552. class context;
  553. template <typename OutputIt, typename Char> class generic_context;
  554. template <typename Char> class parse_context;
  555. // Longer aliases for C++20 compatibility.
  556. template <typename Char> using basic_format_parse_context = parse_context<Char>;
  557. using format_parse_context = parse_context<char>;
  558. template <typename OutputIt, typename Char>
  559. using basic_format_context =
  560. conditional_t<std::is_same<OutputIt, appender>::value, context,
  561. generic_context<OutputIt, Char>>;
  562. using format_context = context;
  563. template <typename Char>
  564. using buffered_context =
  565. conditional_t<std::is_same<Char, char>::value, context,
  566. generic_context<basic_appender<Char>, Char>>;
  567. template <typename Context> class basic_format_arg;
  568. template <typename Context> class basic_format_args;
  569. // A separate type would result in shorter symbols but break ABI compatibility
  570. // between clang and gcc on ARM (#1919).
  571. using format_args = basic_format_args<context>;
  572. // A formatter for objects of type T.
  573. template <typename T, typename Char = char, typename Enable = void>
  574. struct formatter {
  575. // A deleted default constructor indicates a disabled formatter.
  576. formatter() = delete;
  577. };
  578. /// Reports a format error at compile time or, via a `format_error` exception,
  579. /// at runtime.
  580. // This function is intentionally not constexpr to give a compile-time error.
  581. FMT_NORETURN FMT_API void report_error(const char* message);
  582. enum class presentation_type : unsigned char {
  583. // Common specifiers:
  584. none = 0,
  585. debug = 1, // '?'
  586. string = 2, // 's' (string, bool)
  587. // Integral, bool and character specifiers:
  588. dec = 3, // 'd'
  589. hex, // 'x' or 'X'
  590. oct, // 'o'
  591. bin, // 'b' or 'B'
  592. chr, // 'c'
  593. // String and pointer specifiers:
  594. pointer = 3, // 'p'
  595. // Floating-point specifiers:
  596. exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation)
  597. fixed, // 'f' or 'F'
  598. general, // 'g' or 'G'
  599. hexfloat // 'a' or 'A'
  600. };
  601. enum class align { none, left, right, center, numeric };
  602. enum class sign { none, minus, plus, space };
  603. enum class arg_id_kind { none, index, name };
  604. // Basic format specifiers for built-in and string types.
  605. class basic_specs {
  606. private:
  607. // Data is arranged as follows:
  608. //
  609. // 0 1 2 3
  610. // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  611. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  612. // |type |align| w | p | s |u|#|L| f | unused |
  613. // +-----+-----+---+---+---+-+-+-+-----+---------------------------+
  614. //
  615. // w - dynamic width info
  616. // p - dynamic precision info
  617. // s - sign
  618. // u - uppercase (e.g. 'X' for 'x')
  619. // # - alternate form ('#')
  620. // L - localized
  621. // f - fill size
  622. //
  623. // Bitfields are not used because of compiler bugs such as gcc bug 61414.
  624. enum : unsigned {
  625. type_mask = 0x00007,
  626. align_mask = 0x00038,
  627. width_mask = 0x000C0,
  628. precision_mask = 0x00300,
  629. sign_mask = 0x00C00,
  630. uppercase_mask = 0x01000,
  631. alternate_mask = 0x02000,
  632. localized_mask = 0x04000,
  633. fill_size_mask = 0x38000,
  634. align_shift = 3,
  635. width_shift = 6,
  636. precision_shift = 8,
  637. sign_shift = 10,
  638. fill_size_shift = 15,
  639. max_fill_size = 4
  640. };
  641. unsigned data_ = 1 << fill_size_shift;
  642. static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, "");
  643. // Character (code unit) type is erased to prevent template bloat.
  644. char fill_data_[max_fill_size] = {' '};
  645. FMT_CONSTEXPR void set_fill_size(size_t size) {
  646. data_ = (data_ & ~fill_size_mask) |
  647. (static_cast<unsigned>(size) << fill_size_shift);
  648. }
  649. public:
  650. constexpr auto type() const -> presentation_type {
  651. return static_cast<presentation_type>(data_ & type_mask);
  652. }
  653. FMT_CONSTEXPR void set_type(presentation_type t) {
  654. data_ = (data_ & ~type_mask) | static_cast<unsigned>(t);
  655. }
  656. constexpr auto align() const -> align {
  657. return static_cast<fmt::align>((data_ & align_mask) >> align_shift);
  658. }
  659. FMT_CONSTEXPR void set_align(fmt::align a) {
  660. data_ = (data_ & ~align_mask) | (static_cast<unsigned>(a) << align_shift);
  661. }
  662. constexpr auto dynamic_width() const -> arg_id_kind {
  663. return static_cast<arg_id_kind>((data_ & width_mask) >> width_shift);
  664. }
  665. FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) {
  666. data_ = (data_ & ~width_mask) | (static_cast<unsigned>(w) << width_shift);
  667. }
  668. FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind {
  669. return static_cast<arg_id_kind>((data_ & precision_mask) >>
  670. precision_shift);
  671. }
  672. FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) {
  673. data_ = (data_ & ~precision_mask) |
  674. (static_cast<unsigned>(p) << precision_shift);
  675. }
  676. constexpr auto dynamic() const -> bool {
  677. return (data_ & (width_mask | precision_mask)) != 0;
  678. }
  679. constexpr auto sign() const -> sign {
  680. return static_cast<fmt::sign>((data_ & sign_mask) >> sign_shift);
  681. }
  682. FMT_CONSTEXPR void set_sign(fmt::sign s) {
  683. data_ = (data_ & ~sign_mask) | (static_cast<unsigned>(s) << sign_shift);
  684. }
  685. constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; }
  686. FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; }
  687. constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; }
  688. FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; }
  689. FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; }
  690. constexpr auto localized() const -> bool {
  691. return (data_ & localized_mask) != 0;
  692. }
  693. FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; }
  694. constexpr auto fill_size() const -> size_t {
  695. return (data_ & fill_size_mask) >> fill_size_shift;
  696. }
  697. template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char>::value)>
  698. constexpr auto fill() const -> const Char* {
  699. return fill_data_;
  700. }
  701. template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
  702. constexpr auto fill() const -> const Char* {
  703. return nullptr;
  704. }
  705. template <typename Char> constexpr auto fill_unit() const -> Char {
  706. using uchar = unsigned char;
  707. return static_cast<Char>(static_cast<uchar>(fill_data_[0]) |
  708. (static_cast<uchar>(fill_data_[1]) << 8) |
  709. (static_cast<uchar>(fill_data_[2]) << 16));
  710. }
  711. FMT_CONSTEXPR void set_fill(char c) {
  712. fill_data_[0] = c;
  713. set_fill_size(1);
  714. }
  715. template <typename Char>
  716. FMT_CONSTEXPR void set_fill(basic_string_view<Char> s) {
  717. auto size = s.size();
  718. set_fill_size(size);
  719. if (size == 1) {
  720. unsigned uchar = static_cast<detail::unsigned_char<Char>>(s[0]);
  721. fill_data_[0] = static_cast<char>(uchar);
  722. fill_data_[1] = static_cast<char>(uchar >> 8);
  723. fill_data_[2] = static_cast<char>(uchar >> 16);
  724. return;
  725. }
  726. FMT_ASSERT(size <= max_fill_size, "invalid fill");
  727. for (size_t i = 0; i < size; ++i)
  728. fill_data_[i & 3] = static_cast<char>(s[i]);
  729. }
  730. FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) {
  731. set_fill_size(specs.fill_size());
  732. for (size_t i = 0; i < max_fill_size; ++i)
  733. fill_data_[i] = specs.fill_data_[i];
  734. }
  735. };
  736. // Format specifiers for built-in and string types.
  737. struct format_specs : basic_specs {
  738. int width;
  739. int precision;
  740. constexpr format_specs() : width(0), precision(-1) {}
  741. };
  742. /**
  743. * Parsing context consisting of a format string range being parsed and an
  744. * argument counter for automatic indexing.
  745. */
  746. template <typename Char = char> class parse_context {
  747. private:
  748. basic_string_view<Char> fmt_;
  749. int next_arg_id_;
  750. enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 };
  751. FMT_CONSTEXPR void do_check_arg_id(int arg_id);
  752. public:
  753. using char_type = Char;
  754. using iterator = const Char*;
  755. constexpr explicit parse_context(basic_string_view<Char> fmt,
  756. int next_arg_id = 0)
  757. : fmt_(fmt), next_arg_id_(next_arg_id) {}
  758. /// Returns an iterator to the beginning of the format string range being
  759. /// parsed.
  760. constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); }
  761. /// Returns an iterator past the end of the format string range being parsed.
  762. constexpr auto end() const noexcept -> iterator { return fmt_.end(); }
  763. /// Advances the begin iterator to `it`.
  764. FMT_CONSTEXPR void advance_to(iterator it) {
  765. fmt_.remove_prefix(detail::to_unsigned(it - begin()));
  766. }
  767. /// Reports an error if using the manual argument indexing; otherwise returns
  768. /// the next argument index and switches to the automatic indexing.
  769. FMT_CONSTEXPR auto next_arg_id() -> int {
  770. if (next_arg_id_ < 0) {
  771. report_error("cannot switch from manual to automatic argument indexing");
  772. return 0;
  773. }
  774. int id = next_arg_id_++;
  775. do_check_arg_id(id);
  776. return id;
  777. }
  778. /// Reports an error if using the automatic argument indexing; otherwise
  779. /// switches to the manual indexing.
  780. FMT_CONSTEXPR void check_arg_id(int id) {
  781. if (next_arg_id_ > 0) {
  782. report_error("cannot switch from automatic to manual argument indexing");
  783. return;
  784. }
  785. next_arg_id_ = -1;
  786. do_check_arg_id(id);
  787. }
  788. FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {
  789. next_arg_id_ = -1;
  790. }
  791. FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
  792. };
  793. #ifndef FMT_USE_LOCALE
  794. # define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1)
  795. #endif
  796. // A type-erased reference to std::locale to avoid the heavy <locale> include.
  797. class locale_ref {
  798. #if FMT_USE_LOCALE
  799. private:
  800. const void* locale_; // A type-erased pointer to std::locale.
  801. public:
  802. constexpr locale_ref() : locale_(nullptr) {}
  803. template <typename Locale, FMT_ENABLE_IF(sizeof(Locale::collate) != 0)>
  804. locale_ref(const Locale& loc) : locale_(&loc) {
  805. // Check if std::isalpha is found via ADL to reduce the chance of misuse.
  806. isalpha('x', loc);
  807. }
  808. inline explicit operator bool() const noexcept { return locale_ != nullptr; }
  809. #endif // FMT_USE_LOCALE
  810. public:
  811. template <typename Locale> auto get() const -> Locale;
  812. };
  813. FMT_END_EXPORT
  814. namespace detail {
  815. // Specifies if `T` is a code unit type.
  816. template <typename T> struct is_code_unit : std::false_type {};
  817. template <> struct is_code_unit<char> : std::true_type {};
  818. template <> struct is_code_unit<wchar_t> : std::true_type {};
  819. template <> struct is_code_unit<char16_t> : std::true_type {};
  820. template <> struct is_code_unit<char32_t> : std::true_type {};
  821. #ifdef __cpp_char8_t
  822. template <> struct is_code_unit<char8_t> : bool_constant<is_utf8_enabled> {};
  823. #endif
  824. // Constructs fmt::basic_string_view<Char> from types implicitly convertible
  825. // to it, deducing Char. Explicitly convertible types such as the ones returned
  826. // from FMT_STRING are intentionally excluded.
  827. template <typename Char, FMT_ENABLE_IF(is_code_unit<Char>::value)>
  828. constexpr auto to_string_view(const Char* s) -> basic_string_view<Char> {
  829. return s;
  830. }
  831. template <typename T, FMT_ENABLE_IF(is_std_string_like<T>::value)>
  832. constexpr auto to_string_view(const T& s)
  833. -> basic_string_view<typename T::value_type> {
  834. return s;
  835. }
  836. template <typename Char>
  837. constexpr auto to_string_view(basic_string_view<Char> s)
  838. -> basic_string_view<Char> {
  839. return s;
  840. }
  841. template <typename T, typename Enable = void>
  842. struct has_to_string_view : std::false_type {};
  843. // detail:: is intentional since to_string_view is not an extension point.
  844. template <typename T>
  845. struct has_to_string_view<
  846. T, void_t<decltype(detail::to_string_view(std::declval<T>()))>>
  847. : std::true_type {};
  848. /// String's character (code unit) type. detail:: is intentional to prevent ADL.
  849. template <typename S,
  850. typename V = decltype(detail::to_string_view(std::declval<S>()))>
  851. using char_t = typename V::value_type;
  852. enum class type {
  853. none_type,
  854. // Integer types should go first,
  855. int_type,
  856. uint_type,
  857. long_long_type,
  858. ulong_long_type,
  859. int128_type,
  860. uint128_type,
  861. bool_type,
  862. char_type,
  863. last_integer_type = char_type,
  864. // followed by floating-point types.
  865. float_type,
  866. double_type,
  867. long_double_type,
  868. last_numeric_type = long_double_type,
  869. cstring_type,
  870. string_type,
  871. pointer_type,
  872. custom_type
  873. };
  874. // Maps core type T to the corresponding type enum constant.
  875. template <typename T, typename Char>
  876. struct type_constant : std::integral_constant<type, type::custom_type> {};
  877. #define FMT_TYPE_CONSTANT(Type, constant) \
  878. template <typename Char> \
  879. struct type_constant<Type, Char> \
  880. : std::integral_constant<type, type::constant> {}
  881. FMT_TYPE_CONSTANT(int, int_type);
  882. FMT_TYPE_CONSTANT(unsigned, uint_type);
  883. FMT_TYPE_CONSTANT(long long, long_long_type);
  884. FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
  885. FMT_TYPE_CONSTANT(int128_opt, int128_type);
  886. FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
  887. FMT_TYPE_CONSTANT(bool, bool_type);
  888. FMT_TYPE_CONSTANT(Char, char_type);
  889. FMT_TYPE_CONSTANT(float, float_type);
  890. FMT_TYPE_CONSTANT(double, double_type);
  891. FMT_TYPE_CONSTANT(long double, long_double_type);
  892. FMT_TYPE_CONSTANT(const Char*, cstring_type);
  893. FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
  894. FMT_TYPE_CONSTANT(const void*, pointer_type);
  895. constexpr auto is_integral_type(type t) -> bool {
  896. return t > type::none_type && t <= type::last_integer_type;
  897. }
  898. constexpr auto is_arithmetic_type(type t) -> bool {
  899. return t > type::none_type && t <= type::last_numeric_type;
  900. }
  901. constexpr auto set(type rhs) -> int { return 1 << static_cast<int>(rhs); }
  902. constexpr auto in(type t, int set) -> bool {
  903. return ((set >> static_cast<int>(t)) & 1) != 0;
  904. }
  905. // Bitsets of types.
  906. enum {
  907. sint_set =
  908. set(type::int_type) | set(type::long_long_type) | set(type::int128_type),
  909. uint_set = set(type::uint_type) | set(type::ulong_long_type) |
  910. set(type::uint128_type),
  911. bool_set = set(type::bool_type),
  912. char_set = set(type::char_type),
  913. float_set = set(type::float_type) | set(type::double_type) |
  914. set(type::long_double_type),
  915. string_set = set(type::string_type),
  916. cstring_set = set(type::cstring_type),
  917. pointer_set = set(type::pointer_type)
  918. };
  919. struct view {};
  920. template <typename T, typename Enable = std::true_type>
  921. struct is_view : std::false_type {};
  922. template <typename T>
  923. struct is_view<T, bool_constant<sizeof(T) != 0>> : std::is_base_of<view, T> {};
  924. template <typename Char, typename T> struct named_arg;
  925. template <typename T> struct is_named_arg : std::false_type {};
  926. template <typename T> struct is_static_named_arg : std::false_type {};
  927. template <typename Char, typename T>
  928. struct is_named_arg<named_arg<Char, T>> : std::true_type {};
  929. template <typename Char, typename T> struct named_arg : view {
  930. const Char* name;
  931. const T& value;
  932. named_arg(const Char* n, const T& v) : name(n), value(v) {}
  933. static_assert(!is_named_arg<T>::value, "nested named arguments");
  934. };
  935. template <bool B = false> constexpr auto count() -> int { return B ? 1 : 0; }
  936. template <bool B1, bool B2, bool... Tail> constexpr auto count() -> int {
  937. return (B1 ? 1 : 0) + count<B2, Tail...>();
  938. }
  939. template <typename... T> constexpr auto count_named_args() -> int {
  940. return count<is_named_arg<T>::value...>();
  941. }
  942. template <typename... T> constexpr auto count_static_named_args() -> int {
  943. return count<is_static_named_arg<T>::value...>();
  944. }
  945. template <typename Char> struct named_arg_info {
  946. const Char* name;
  947. int id;
  948. };
  949. // named_args is non-const to suppress a bogus -Wmaybe-uninitialized in gcc 13.
  950. template <typename Char>
  951. FMT_CONSTEXPR void check_for_duplicate(named_arg_info<Char>* named_args,
  952. int named_arg_index,
  953. basic_string_view<Char> arg_name) {
  954. for (int i = 0; i < named_arg_index; ++i) {
  955. if (named_args[i].name == arg_name) report_error("duplicate named arg");
  956. }
  957. }
  958. template <typename Char, typename T, FMT_ENABLE_IF(!is_named_arg<T>::value)>
  959. void init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {
  960. ++arg_index;
  961. }
  962. template <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
  963. void init_named_arg(named_arg_info<Char>* named_args, int& arg_index,
  964. int& named_arg_index, const T& arg) {
  965. check_for_duplicate<Char>(named_args, named_arg_index, arg.name);
  966. named_args[named_arg_index++] = {arg.name, arg_index++};
  967. }
  968. template <typename T, typename Char,
  969. FMT_ENABLE_IF(!is_static_named_arg<T>::value)>
  970. FMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>*, int& arg_index,
  971. int&) {
  972. ++arg_index;
  973. }
  974. template <typename T, typename Char,
  975. FMT_ENABLE_IF(is_static_named_arg<T>::value)>
  976. FMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>* named_args,
  977. int& arg_index, int& named_arg_index) {
  978. check_for_duplicate<Char>(named_args, named_arg_index, T::name);
  979. named_args[named_arg_index++] = {T::name, arg_index++};
  980. }
  981. // To minimize the number of types we need to deal with, long is translated
  982. // either to int or to long long depending on its size.
  983. enum { long_short = sizeof(long) == sizeof(int) && FMT_BUILTIN_TYPES };
  984. using long_type = conditional_t<long_short, int, long long>;
  985. using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
  986. template <typename T>
  987. using format_as_result =
  988. remove_cvref_t<decltype(format_as(std::declval<const T&>()))>;
  989. template <typename T>
  990. using format_as_member_result =
  991. remove_cvref_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>;
  992. template <typename T, typename Enable = std::true_type>
  993. struct use_format_as : std::false_type {};
  994. // format_as member is only used to avoid injection into the std namespace.
  995. template <typename T, typename Enable = std::true_type>
  996. struct use_format_as_member : std::false_type {};
  997. // Only map owning types because mapping views can be unsafe.
  998. template <typename T>
  999. struct use_format_as<
  1000. T, bool_constant<std::is_arithmetic<format_as_result<T>>::value>>
  1001. : std::true_type {};
  1002. template <typename T>
  1003. struct use_format_as_member<
  1004. T, bool_constant<std::is_arithmetic<format_as_member_result<T>>::value>>
  1005. : std::true_type {};
  1006. template <typename T, typename U = remove_const_t<T>>
  1007. using use_formatter =
  1008. bool_constant<(std::is_class<T>::value || std::is_enum<T>::value ||
  1009. std::is_union<T>::value || std::is_array<T>::value) &&
  1010. !has_to_string_view<T>::value && !is_named_arg<T>::value &&
  1011. !use_format_as<T>::value && !use_format_as_member<U>::value>;
  1012. template <typename Char, typename T, typename U = remove_const_t<T>>
  1013. auto has_formatter_impl(T* p, buffered_context<Char>* ctx = nullptr)
  1014. -> decltype(formatter<U, Char>().format(*p, *ctx), std::true_type());
  1015. template <typename Char> auto has_formatter_impl(...) -> std::false_type;
  1016. // T can be const-qualified to check if it is const-formattable.
  1017. template <typename T, typename Char> constexpr auto has_formatter() -> bool {
  1018. return decltype(has_formatter_impl<Char>(static_cast<T*>(nullptr)))::value;
  1019. }
  1020. // Maps formatting argument types to natively supported types or user-defined
  1021. // types with formatters. Returns void on errors to be SFINAE-friendly.
  1022. template <typename Char> struct type_mapper {
  1023. static auto map(signed char) -> int;
  1024. static auto map(unsigned char) -> unsigned;
  1025. static auto map(short) -> int;
  1026. static auto map(unsigned short) -> unsigned;
  1027. static auto map(int) -> int;
  1028. static auto map(unsigned) -> unsigned;
  1029. static auto map(long) -> long_type;
  1030. static auto map(unsigned long) -> ulong_type;
  1031. static auto map(long long) -> long long;
  1032. static auto map(unsigned long long) -> unsigned long long;
  1033. static auto map(int128_opt) -> int128_opt;
  1034. static auto map(uint128_opt) -> uint128_opt;
  1035. static auto map(bool) -> bool;
  1036. template <int N>
  1037. static auto map(bitint<N>) -> conditional_t<N <= 64, long long, void>;
  1038. template <int N>
  1039. static auto map(ubitint<N>)
  1040. -> conditional_t<N <= 64, unsigned long long, void>;
  1041. template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>
  1042. static auto map(T) -> conditional_t<
  1043. std::is_same<T, char>::value || std::is_same<T, Char>::value, Char, void>;
  1044. static auto map(float) -> float;
  1045. static auto map(double) -> double;
  1046. static auto map(long double) -> long double;
  1047. static auto map(Char*) -> const Char*;
  1048. static auto map(const Char*) -> const Char*;
  1049. template <typename T, typename C = char_t<T>,
  1050. FMT_ENABLE_IF(!std::is_pointer<T>::value)>
  1051. static auto map(const T&) -> conditional_t<std::is_same<C, Char>::value,
  1052. basic_string_view<C>, void>;
  1053. static auto map(void*) -> const void*;
  1054. static auto map(const void*) -> const void*;
  1055. static auto map(volatile void*) -> const void*;
  1056. static auto map(const volatile void*) -> const void*;
  1057. static auto map(nullptr_t) -> const void*;
  1058. template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||
  1059. std::is_member_pointer<T>::value)>
  1060. static auto map(const T&) -> void;
  1061. template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>
  1062. static auto map(const T& x) -> decltype(map(format_as(x)));
  1063. template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>
  1064. static auto map(const T& x) -> decltype(map(formatter<T>::format_as(x)));
  1065. template <typename T, FMT_ENABLE_IF(use_formatter<T>::value)>
  1066. static auto map(T&) -> conditional_t<has_formatter<T, Char>(), T&, void>;
  1067. template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
  1068. static auto map(const T& named_arg) -> decltype(map(named_arg.value));
  1069. };
  1070. // detail:: is used to workaround a bug in MSVC 2017.
  1071. template <typename T, typename Char>
  1072. using mapped_t = decltype(detail::type_mapper<Char>::map(std::declval<T&>()));
  1073. // A type constant after applying type_mapper.
  1074. template <typename T, typename Char = char>
  1075. using mapped_type_constant = type_constant<mapped_t<T, Char>, Char>;
  1076. template <typename T, typename Context,
  1077. type TYPE =
  1078. mapped_type_constant<T, typename Context::char_type>::value>
  1079. using stored_type_constant = std::integral_constant<
  1080. type, Context::builtin_types || TYPE == type::int_type ? TYPE
  1081. : type::custom_type>;
  1082. // A parse context with extra data used only in compile-time checks.
  1083. template <typename Char>
  1084. class compile_parse_context : public parse_context<Char> {
  1085. private:
  1086. int num_args_;
  1087. const type* types_;
  1088. using base = parse_context<Char>;
  1089. public:
  1090. FMT_CONSTEXPR explicit compile_parse_context(basic_string_view<Char> fmt,
  1091. int num_args, const type* types,
  1092. int next_arg_id = 0)
  1093. : base(fmt, next_arg_id), num_args_(num_args), types_(types) {}
  1094. constexpr auto num_args() const -> int { return num_args_; }
  1095. constexpr auto arg_type(int id) const -> type { return types_[id]; }
  1096. FMT_CONSTEXPR auto next_arg_id() -> int {
  1097. int id = base::next_arg_id();
  1098. if (id >= num_args_) report_error("argument not found");
  1099. return id;
  1100. }
  1101. FMT_CONSTEXPR void check_arg_id(int id) {
  1102. base::check_arg_id(id);
  1103. if (id >= num_args_) report_error("argument not found");
  1104. }
  1105. using base::check_arg_id;
  1106. FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
  1107. ignore_unused(arg_id);
  1108. if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
  1109. report_error("width/precision is not integer");
  1110. }
  1111. };
  1112. // An argument reference.
  1113. template <typename Char> union arg_ref {
  1114. FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {}
  1115. FMT_CONSTEXPR arg_ref(basic_string_view<Char> n) : name(n) {}
  1116. int index;
  1117. basic_string_view<Char> name;
  1118. };
  1119. // Format specifiers with width and precision resolved at formatting rather
  1120. // than parsing time to allow reusing the same parsed specifiers with
  1121. // different sets of arguments (precompilation of format strings).
  1122. template <typename Char = char> struct dynamic_format_specs : format_specs {
  1123. arg_ref<Char> width_ref;
  1124. arg_ref<Char> precision_ref;
  1125. };
  1126. // Converts a character to ASCII. Returns '\0' on conversion failure.
  1127. template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
  1128. constexpr auto to_ascii(Char c) -> char {
  1129. return c <= 0xff ? static_cast<char>(c) : '\0';
  1130. }
  1131. // Returns the number of code units in a code point or 1 on error.
  1132. template <typename Char>
  1133. FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
  1134. if (const_check(sizeof(Char) != 1)) return 1;
  1135. auto c = static_cast<unsigned char>(*begin);
  1136. return static_cast<int>((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1;
  1137. }
  1138. // Parses the range [begin, end) as an unsigned integer. This function assumes
  1139. // that the range is non-empty and the first character is a digit.
  1140. template <typename Char>
  1141. FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
  1142. int error_value) noexcept -> int {
  1143. FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
  1144. unsigned value = 0, prev = 0;
  1145. auto p = begin;
  1146. do {
  1147. prev = value;
  1148. value = value * 10 + unsigned(*p - '0');
  1149. ++p;
  1150. } while (p != end && '0' <= *p && *p <= '9');
  1151. auto num_digits = p - begin;
  1152. begin = p;
  1153. int digits10 = static_cast<int>(sizeof(int) * CHAR_BIT * 3 / 10);
  1154. if (num_digits <= digits10) return static_cast<int>(value);
  1155. // Check for overflow.
  1156. unsigned max = INT_MAX;
  1157. return num_digits == digits10 + 1 &&
  1158. prev * 10ull + unsigned(p[-1] - '0') <= max
  1159. ? static_cast<int>(value)
  1160. : error_value;
  1161. }
  1162. FMT_CONSTEXPR inline auto parse_align(char c) -> align {
  1163. switch (c) {
  1164. case '<': return align::left;
  1165. case '>': return align::right;
  1166. case '^': return align::center;
  1167. }
  1168. return align::none;
  1169. }
  1170. template <typename Char> constexpr auto is_name_start(Char c) -> bool {
  1171. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_';
  1172. }
  1173. template <typename Char, typename Handler>
  1174. FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end,
  1175. Handler&& handler) -> const Char* {
  1176. Char c = *begin;
  1177. if (c >= '0' && c <= '9') {
  1178. int index = 0;
  1179. if (c != '0')
  1180. index = parse_nonnegative_int(begin, end, INT_MAX);
  1181. else
  1182. ++begin;
  1183. if (begin == end || (*begin != '}' && *begin != ':'))
  1184. report_error("invalid format string");
  1185. else
  1186. handler.on_index(index);
  1187. return begin;
  1188. }
  1189. if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) {
  1190. report_error("invalid format string");
  1191. return begin;
  1192. }
  1193. auto it = begin;
  1194. do {
  1195. ++it;
  1196. } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9')));
  1197. handler.on_name({begin, to_unsigned(it - begin)});
  1198. return it;
  1199. }
  1200. template <typename Char> struct dynamic_spec_handler {
  1201. parse_context<Char>& ctx;
  1202. arg_ref<Char>& ref;
  1203. arg_id_kind& kind;
  1204. FMT_CONSTEXPR void on_index(int id) {
  1205. ref = id;
  1206. kind = arg_id_kind::index;
  1207. ctx.check_arg_id(id);
  1208. ctx.check_dynamic_spec(id);
  1209. }
  1210. FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
  1211. ref = id;
  1212. kind = arg_id_kind::name;
  1213. ctx.check_arg_id(id);
  1214. }
  1215. };
  1216. template <typename Char> struct parse_dynamic_spec_result {
  1217. const Char* end;
  1218. arg_id_kind kind;
  1219. };
  1220. // Parses integer | "{" [arg_id] "}".
  1221. template <typename Char>
  1222. FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end,
  1223. int& value, arg_ref<Char>& ref,
  1224. parse_context<Char>& ctx)
  1225. -> parse_dynamic_spec_result<Char> {
  1226. FMT_ASSERT(begin != end, "");
  1227. auto kind = arg_id_kind::none;
  1228. if ('0' <= *begin && *begin <= '9') {
  1229. int val = parse_nonnegative_int(begin, end, -1);
  1230. if (val == -1) report_error("number is too big");
  1231. value = val;
  1232. } else {
  1233. if (*begin == '{') {
  1234. ++begin;
  1235. if (begin != end) {
  1236. Char c = *begin;
  1237. if (c == '}' || c == ':') {
  1238. int id = ctx.next_arg_id();
  1239. ref = id;
  1240. kind = arg_id_kind::index;
  1241. ctx.check_dynamic_spec(id);
  1242. } else {
  1243. begin = parse_arg_id(begin, end,
  1244. dynamic_spec_handler<Char>{ctx, ref, kind});
  1245. }
  1246. }
  1247. if (begin != end && *begin == '}') return {++begin, kind};
  1248. }
  1249. report_error("invalid format string");
  1250. }
  1251. return {begin, kind};
  1252. }
  1253. template <typename Char>
  1254. FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,
  1255. format_specs& specs, arg_ref<Char>& width_ref,
  1256. parse_context<Char>& ctx) -> const Char* {
  1257. auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx);
  1258. specs.set_dynamic_width(result.kind);
  1259. return result.end;
  1260. }
  1261. template <typename Char>
  1262. FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
  1263. format_specs& specs,
  1264. arg_ref<Char>& precision_ref,
  1265. parse_context<Char>& ctx) -> const Char* {
  1266. ++begin;
  1267. if (begin == end) {
  1268. report_error("invalid precision");
  1269. return begin;
  1270. }
  1271. auto result =
  1272. parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx);
  1273. specs.set_dynamic_precision(result.kind);
  1274. return result.end;
  1275. }
  1276. enum class state { start, align, sign, hash, zero, width, precision, locale };
  1277. // Parses standard format specifiers.
  1278. template <typename Char>
  1279. FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,
  1280. dynamic_format_specs<Char>& specs,
  1281. parse_context<Char>& ctx, type arg_type)
  1282. -> const Char* {
  1283. auto c = '\0';
  1284. if (end - begin > 1) {
  1285. auto next = to_ascii(begin[1]);
  1286. c = parse_align(next) == align::none ? to_ascii(*begin) : '\0';
  1287. } else {
  1288. if (begin == end) return begin;
  1289. c = to_ascii(*begin);
  1290. }
  1291. struct {
  1292. state current_state = state::start;
  1293. FMT_CONSTEXPR void operator()(state s, bool valid = true) {
  1294. if (current_state >= s || !valid)
  1295. report_error("invalid format specifier");
  1296. current_state = s;
  1297. }
  1298. } enter_state;
  1299. using pres = presentation_type;
  1300. constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
  1301. struct {
  1302. const Char*& begin;
  1303. format_specs& specs;
  1304. type arg_type;
  1305. FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* {
  1306. if (!in(arg_type, set)) report_error("invalid format specifier");
  1307. specs.set_type(pres_type);
  1308. return begin + 1;
  1309. }
  1310. } parse_presentation_type{begin, specs, arg_type};
  1311. for (;;) {
  1312. switch (c) {
  1313. case '<':
  1314. case '>':
  1315. case '^':
  1316. enter_state(state::align);
  1317. specs.set_align(parse_align(c));
  1318. ++begin;
  1319. break;
  1320. case '+':
  1321. case ' ':
  1322. specs.set_sign(c == ' ' ? sign::space : sign::plus);
  1323. FMT_FALLTHROUGH;
  1324. case '-':
  1325. enter_state(state::sign, in(arg_type, sint_set | float_set));
  1326. ++begin;
  1327. break;
  1328. case '#':
  1329. enter_state(state::hash, is_arithmetic_type(arg_type));
  1330. specs.set_alt();
  1331. ++begin;
  1332. break;
  1333. case '0':
  1334. enter_state(state::zero);
  1335. if (!is_arithmetic_type(arg_type))
  1336. report_error("format specifier requires numeric argument");
  1337. if (specs.align() == align::none) {
  1338. // Ignore 0 if align is specified for compatibility with std::format.
  1339. specs.set_align(align::numeric);
  1340. specs.set_fill('0');
  1341. }
  1342. ++begin;
  1343. break;
  1344. // clang-format off
  1345. case '1': case '2': case '3': case '4': case '5':
  1346. case '6': case '7': case '8': case '9': case '{':
  1347. // clang-format on
  1348. enter_state(state::width);
  1349. begin = parse_width(begin, end, specs, specs.width_ref, ctx);
  1350. break;
  1351. case '.':
  1352. enter_state(state::precision,
  1353. in(arg_type, float_set | string_set | cstring_set));
  1354. begin = parse_precision(begin, end, specs, specs.precision_ref, ctx);
  1355. break;
  1356. case 'L':
  1357. enter_state(state::locale, is_arithmetic_type(arg_type));
  1358. specs.set_localized();
  1359. ++begin;
  1360. break;
  1361. case 'd': return parse_presentation_type(pres::dec, integral_set);
  1362. case 'X': specs.set_upper(); FMT_FALLTHROUGH;
  1363. case 'x': return parse_presentation_type(pres::hex, integral_set);
  1364. case 'o': return parse_presentation_type(pres::oct, integral_set);
  1365. case 'B': specs.set_upper(); FMT_FALLTHROUGH;
  1366. case 'b': return parse_presentation_type(pres::bin, integral_set);
  1367. case 'E': specs.set_upper(); FMT_FALLTHROUGH;
  1368. case 'e': return parse_presentation_type(pres::exp, float_set);
  1369. case 'F': specs.set_upper(); FMT_FALLTHROUGH;
  1370. case 'f': return parse_presentation_type(pres::fixed, float_set);
  1371. case 'G': specs.set_upper(); FMT_FALLTHROUGH;
  1372. case 'g': return parse_presentation_type(pres::general, float_set);
  1373. case 'A': specs.set_upper(); FMT_FALLTHROUGH;
  1374. case 'a': return parse_presentation_type(pres::hexfloat, float_set);
  1375. case 'c':
  1376. if (arg_type == type::bool_type) report_error("invalid format specifier");
  1377. return parse_presentation_type(pres::chr, integral_set);
  1378. case 's':
  1379. return parse_presentation_type(pres::string,
  1380. bool_set | string_set | cstring_set);
  1381. case 'p':
  1382. return parse_presentation_type(pres::pointer, pointer_set | cstring_set);
  1383. case '?':
  1384. return parse_presentation_type(pres::debug,
  1385. char_set | string_set | cstring_set);
  1386. case '}': return begin;
  1387. default: {
  1388. if (*begin == '}') return begin;
  1389. // Parse fill and alignment.
  1390. auto fill_end = begin + code_point_length(begin);
  1391. if (end - fill_end <= 0) {
  1392. report_error("invalid format specifier");
  1393. return begin;
  1394. }
  1395. if (*begin == '{') {
  1396. report_error("invalid fill character '{'");
  1397. return begin;
  1398. }
  1399. auto alignment = parse_align(to_ascii(*fill_end));
  1400. enter_state(state::align, alignment != align::none);
  1401. specs.set_fill(
  1402. basic_string_view<Char>(begin, to_unsigned(fill_end - begin)));
  1403. specs.set_align(alignment);
  1404. begin = fill_end + 1;
  1405. }
  1406. }
  1407. if (begin == end) return begin;
  1408. c = to_ascii(*begin);
  1409. }
  1410. }
  1411. template <typename Char, typename Handler>
  1412. FMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin,
  1413. const Char* end,
  1414. Handler&& handler)
  1415. -> const Char* {
  1416. ++begin;
  1417. if (begin == end) {
  1418. handler.on_error("invalid format string");
  1419. return end;
  1420. }
  1421. int arg_id = 0;
  1422. switch (*begin) {
  1423. case '}':
  1424. handler.on_replacement_field(handler.on_arg_id(), begin);
  1425. return begin + 1;
  1426. case '{': handler.on_text(begin, begin + 1); return begin + 1;
  1427. case ':': arg_id = handler.on_arg_id(); break;
  1428. default: {
  1429. struct id_adapter {
  1430. Handler& handler;
  1431. int arg_id;
  1432. FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); }
  1433. FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
  1434. arg_id = handler.on_arg_id(id);
  1435. }
  1436. } adapter = {handler, 0};
  1437. begin = parse_arg_id(begin, end, adapter);
  1438. arg_id = adapter.arg_id;
  1439. Char c = begin != end ? *begin : Char();
  1440. if (c == '}') {
  1441. handler.on_replacement_field(arg_id, begin);
  1442. return begin + 1;
  1443. }
  1444. if (c != ':') {
  1445. handler.on_error("missing '}' in format string");
  1446. return end;
  1447. }
  1448. break;
  1449. }
  1450. }
  1451. begin = handler.on_format_specs(arg_id, begin + 1, end);
  1452. if (begin == end || *begin != '}')
  1453. return handler.on_error("unknown format specifier"), end;
  1454. return begin + 1;
  1455. }
  1456. template <typename Char, typename Handler>
  1457. FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> fmt,
  1458. Handler&& handler) {
  1459. auto begin = fmt.data(), end = begin + fmt.size();
  1460. auto p = begin;
  1461. while (p != end) {
  1462. auto c = *p++;
  1463. if (c == '{') {
  1464. handler.on_text(begin, p - 1);
  1465. begin = p = parse_replacement_field(p - 1, end, handler);
  1466. } else if (c == '}') {
  1467. if (p == end || *p != '}')
  1468. return handler.on_error("unmatched '}' in format string");
  1469. handler.on_text(begin, p);
  1470. begin = ++p;
  1471. }
  1472. }
  1473. handler.on_text(begin, end);
  1474. }
  1475. // Checks char specs and returns true iff the presentation type is char-like.
  1476. FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool {
  1477. auto type = specs.type();
  1478. if (type != presentation_type::none && type != presentation_type::chr &&
  1479. type != presentation_type::debug) {
  1480. return false;
  1481. }
  1482. if (specs.align() == align::numeric || specs.sign() != sign::none ||
  1483. specs.alt()) {
  1484. report_error("invalid format specifier for char");
  1485. }
  1486. return true;
  1487. }
  1488. // A base class for compile-time strings.
  1489. struct compile_string {};
  1490. template <typename T, typename Char>
  1491. FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769).
  1492. FMT_CONSTEXPR auto invoke_parse(parse_context<Char>& ctx) -> const Char* {
  1493. using mapped_type = remove_cvref_t<mapped_t<T, Char>>;
  1494. constexpr bool formattable =
  1495. std::is_constructible<formatter<mapped_type, Char>>::value;
  1496. if (!formattable) return ctx.begin(); // Error is reported in the value ctor.
  1497. using formatted_type = conditional_t<formattable, mapped_type, int>;
  1498. return formatter<formatted_type, Char>().parse(ctx);
  1499. }
  1500. template <typename... T> struct arg_pack {};
  1501. template <typename Char, int NUM_ARGS, int NUM_NAMED_ARGS, bool DYNAMIC_NAMES>
  1502. class format_string_checker {
  1503. private:
  1504. type types_[max_of<size_t>(1, NUM_ARGS)];
  1505. named_arg_info<Char> named_args_[max_of<size_t>(1, NUM_NAMED_ARGS)];
  1506. compile_parse_context<Char> context_;
  1507. using parse_func = auto (*)(parse_context<Char>&) -> const Char*;
  1508. parse_func parse_funcs_[max_of<size_t>(1, NUM_ARGS)];
  1509. public:
  1510. template <typename... T>
  1511. FMT_CONSTEXPR explicit format_string_checker(basic_string_view<Char> fmt,
  1512. arg_pack<T...>)
  1513. : types_{mapped_type_constant<T, Char>::value...},
  1514. named_args_{},
  1515. context_(fmt, NUM_ARGS, types_),
  1516. parse_funcs_{&invoke_parse<T, Char>...} {
  1517. int arg_index = 0, named_arg_index = 0;
  1518. FMT_APPLY_VARIADIC(
  1519. init_static_named_arg<T>(named_args_, arg_index, named_arg_index));
  1520. ignore_unused(arg_index, named_arg_index);
  1521. }
  1522. FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
  1523. FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
  1524. FMT_CONSTEXPR auto on_arg_id(int id) -> int {
  1525. context_.check_arg_id(id);
  1526. return id;
  1527. }
  1528. FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
  1529. for (int i = 0; i < NUM_NAMED_ARGS; ++i) {
  1530. if (named_args_[i].name == id) return named_args_[i].id;
  1531. }
  1532. if (!DYNAMIC_NAMES) on_error("argument not found");
  1533. return -1;
  1534. }
  1535. FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) {
  1536. on_format_specs(id, begin, begin); // Call parse() on empty specs.
  1537. }
  1538. FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end)
  1539. -> const Char* {
  1540. context_.advance_to(begin);
  1541. if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_);
  1542. // If id is out of range, it means we do not know the type and cannot parse
  1543. // the format at compile time. Instead, skip over content until we finish
  1544. // the format spec, accounting for any nested replacements.
  1545. for (int bracket_count = 0;
  1546. begin != end && (bracket_count > 0 || *begin != '}'); ++begin) {
  1547. if (*begin == '{')
  1548. ++bracket_count;
  1549. else if (*begin == '}')
  1550. --bracket_count;
  1551. }
  1552. return begin;
  1553. }
  1554. FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) {
  1555. report_error(message);
  1556. }
  1557. };
  1558. /// A contiguous memory buffer with an optional growing ability. It is an
  1559. /// internal class and shouldn't be used directly, only via `memory_buffer`.
  1560. template <typename T> class buffer {
  1561. private:
  1562. T* ptr_;
  1563. size_t size_;
  1564. size_t capacity_;
  1565. using grow_fun = void (*)(buffer& buf, size_t capacity);
  1566. grow_fun grow_;
  1567. protected:
  1568. // Don't initialize ptr_ since it is not accessed to save a few cycles.
  1569. FMT_MSC_WARNING(suppress : 26495)
  1570. FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept
  1571. : size_(sz), capacity_(sz), grow_(grow) {}
  1572. constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0,
  1573. size_t cap = 0) noexcept
  1574. : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {}
  1575. FMT_CONSTEXPR20 ~buffer() = default;
  1576. buffer(buffer&&) = default;
  1577. /// Sets the buffer data and capacity.
  1578. FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
  1579. ptr_ = buf_data;
  1580. capacity_ = buf_capacity;
  1581. }
  1582. public:
  1583. using value_type = T;
  1584. using const_reference = const T&;
  1585. buffer(const buffer&) = delete;
  1586. void operator=(const buffer&) = delete;
  1587. auto begin() noexcept -> T* { return ptr_; }
  1588. auto end() noexcept -> T* { return ptr_ + size_; }
  1589. auto begin() const noexcept -> const T* { return ptr_; }
  1590. auto end() const noexcept -> const T* { return ptr_ + size_; }
  1591. /// Returns the size of this buffer.
  1592. constexpr auto size() const noexcept -> size_t { return size_; }
  1593. /// Returns the capacity of this buffer.
  1594. constexpr auto capacity() const noexcept -> size_t { return capacity_; }
  1595. /// Returns a pointer to the buffer data (not null-terminated).
  1596. FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
  1597. FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
  1598. /// Clears this buffer.
  1599. FMT_CONSTEXPR void clear() { size_ = 0; }
  1600. // Tries resizing the buffer to contain `count` elements. If T is a POD type
  1601. // the new elements may not be initialized.
  1602. FMT_CONSTEXPR void try_resize(size_t count) {
  1603. try_reserve(count);
  1604. size_ = min_of(count, capacity_);
  1605. }
  1606. // Tries increasing the buffer capacity to `new_capacity`. It can increase the
  1607. // capacity by a smaller amount than requested but guarantees there is space
  1608. // for at least one additional element either by increasing the capacity or by
  1609. // flushing the buffer if it is full.
  1610. FMT_CONSTEXPR void try_reserve(size_t new_capacity) {
  1611. if (new_capacity > capacity_) grow_(*this, new_capacity);
  1612. }
  1613. FMT_CONSTEXPR void push_back(const T& value) {
  1614. try_reserve(size_ + 1);
  1615. ptr_[size_++] = value;
  1616. }
  1617. /// Appends data to the end of the buffer.
  1618. template <typename U>
  1619. // Workaround for MSVC2019 to fix error C2893: Failed to specialize function
  1620. // template 'void fmt::v11::detail::buffer<T>::append(const U *,const U *)'.
  1621. #if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940
  1622. FMT_CONSTEXPR20
  1623. #endif
  1624. void
  1625. append(const U* begin, const U* end) {
  1626. while (begin != end) {
  1627. auto size = size_;
  1628. auto free_cap = capacity_ - size;
  1629. auto count = to_unsigned(end - begin);
  1630. if (free_cap < count) {
  1631. grow_(*this, size + count);
  1632. size = size_;
  1633. free_cap = capacity_ - size;
  1634. count = count < free_cap ? count : free_cap;
  1635. }
  1636. // A loop is faster than memcpy on small sizes.
  1637. T* out = ptr_ + size;
  1638. for (size_t i = 0; i < count; ++i) out[i] = begin[i];
  1639. size_ += count;
  1640. begin += count;
  1641. }
  1642. }
  1643. template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
  1644. return ptr_[index];
  1645. }
  1646. template <typename Idx>
  1647. FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
  1648. return ptr_[index];
  1649. }
  1650. };
  1651. struct buffer_traits {
  1652. constexpr explicit buffer_traits(size_t) {}
  1653. constexpr auto count() const -> size_t { return 0; }
  1654. constexpr auto limit(size_t size) const -> size_t { return size; }
  1655. };
  1656. class fixed_buffer_traits {
  1657. private:
  1658. size_t count_ = 0;
  1659. size_t limit_;
  1660. public:
  1661. constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
  1662. constexpr auto count() const -> size_t { return count_; }
  1663. FMT_CONSTEXPR auto limit(size_t size) -> size_t {
  1664. size_t n = limit_ > count_ ? limit_ - count_ : 0;
  1665. count_ += size;
  1666. return min_of(size, n);
  1667. }
  1668. };
  1669. // A buffer that writes to an output iterator when flushed.
  1670. template <typename OutputIt, typename T, typename Traits = buffer_traits>
  1671. class iterator_buffer : public Traits, public buffer<T> {
  1672. private:
  1673. OutputIt out_;
  1674. enum { buffer_size = 256 };
  1675. T data_[buffer_size];
  1676. static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
  1677. if (buf.size() == buffer_size) static_cast<iterator_buffer&>(buf).flush();
  1678. }
  1679. void flush() {
  1680. auto size = this->size();
  1681. this->clear();
  1682. const T* begin = data_;
  1683. const T* end = begin + this->limit(size);
  1684. while (begin != end) *out_++ = *begin++;
  1685. }
  1686. public:
  1687. explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
  1688. : Traits(n), buffer<T>(grow, data_, 0, buffer_size), out_(out) {}
  1689. iterator_buffer(iterator_buffer&& other) noexcept
  1690. : Traits(other),
  1691. buffer<T>(grow, data_, 0, buffer_size),
  1692. out_(other.out_) {}
  1693. ~iterator_buffer() {
  1694. // Don't crash if flush fails during unwinding.
  1695. FMT_TRY { flush(); }
  1696. FMT_CATCH(...) {}
  1697. }
  1698. auto out() -> OutputIt {
  1699. flush();
  1700. return out_;
  1701. }
  1702. auto count() const -> size_t { return Traits::count() + this->size(); }
  1703. };
  1704. template <typename T>
  1705. class iterator_buffer<T*, T, fixed_buffer_traits> : public fixed_buffer_traits,
  1706. public buffer<T> {
  1707. private:
  1708. T* out_;
  1709. enum { buffer_size = 256 };
  1710. T data_[buffer_size];
  1711. static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
  1712. if (buf.size() == buf.capacity())
  1713. static_cast<iterator_buffer&>(buf).flush();
  1714. }
  1715. void flush() {
  1716. size_t n = this->limit(this->size());
  1717. if (this->data() == out_) {
  1718. out_ += n;
  1719. this->set(data_, buffer_size);
  1720. }
  1721. this->clear();
  1722. }
  1723. public:
  1724. explicit iterator_buffer(T* out, size_t n = buffer_size)
  1725. : fixed_buffer_traits(n), buffer<T>(grow, out, 0, n), out_(out) {}
  1726. iterator_buffer(iterator_buffer&& other) noexcept
  1727. : fixed_buffer_traits(other),
  1728. buffer<T>(static_cast<iterator_buffer&&>(other)),
  1729. out_(other.out_) {
  1730. if (this->data() != out_) {
  1731. this->set(data_, buffer_size);
  1732. this->clear();
  1733. }
  1734. }
  1735. ~iterator_buffer() { flush(); }
  1736. auto out() -> T* {
  1737. flush();
  1738. return out_;
  1739. }
  1740. auto count() const -> size_t {
  1741. return fixed_buffer_traits::count() + this->size();
  1742. }
  1743. };
  1744. template <typename T> class iterator_buffer<T*, T> : public buffer<T> {
  1745. public:
  1746. explicit iterator_buffer(T* out, size_t = 0)
  1747. : buffer<T>([](buffer<T>&, size_t) {}, out, 0, ~size_t()) {}
  1748. auto out() -> T* { return &*this->end(); }
  1749. };
  1750. template <typename Container>
  1751. class container_buffer : public buffer<typename Container::value_type> {
  1752. private:
  1753. using value_type = typename Container::value_type;
  1754. static FMT_CONSTEXPR void grow(buffer<value_type>& buf, size_t capacity) {
  1755. auto& self = static_cast<container_buffer&>(buf);
  1756. self.container.resize(capacity);
  1757. self.set(&self.container[0], capacity);
  1758. }
  1759. public:
  1760. Container& container;
  1761. explicit container_buffer(Container& c)
  1762. : buffer<value_type>(grow, c.size()), container(c) {}
  1763. };
  1764. // A buffer that writes to a container with the contiguous storage.
  1765. template <typename OutputIt>
  1766. class iterator_buffer<
  1767. OutputIt,
  1768. enable_if_t<is_back_insert_iterator<OutputIt>::value &&
  1769. is_contiguous<typename OutputIt::container_type>::value,
  1770. typename OutputIt::container_type::value_type>>
  1771. : public container_buffer<typename OutputIt::container_type> {
  1772. private:
  1773. using base = container_buffer<typename OutputIt::container_type>;
  1774. public:
  1775. explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {}
  1776. explicit iterator_buffer(OutputIt out, size_t = 0)
  1777. : base(get_container(out)) {}
  1778. auto out() -> OutputIt { return OutputIt(this->container); }
  1779. };
  1780. // A buffer that counts the number of code units written discarding the output.
  1781. template <typename T = char> class counting_buffer : public buffer<T> {
  1782. private:
  1783. enum { buffer_size = 256 };
  1784. T data_[buffer_size];
  1785. size_t count_ = 0;
  1786. static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
  1787. if (buf.size() != buffer_size) return;
  1788. static_cast<counting_buffer&>(buf).count_ += buf.size();
  1789. buf.clear();
  1790. }
  1791. public:
  1792. FMT_CONSTEXPR counting_buffer() : buffer<T>(grow, data_, 0, buffer_size) {}
  1793. constexpr auto count() const noexcept -> size_t {
  1794. return count_ + this->size();
  1795. }
  1796. };
  1797. template <typename T>
  1798. struct is_back_insert_iterator<basic_appender<T>> : std::true_type {};
  1799. template <typename OutputIt, typename InputIt, typename = void>
  1800. struct has_back_insert_iterator_container_append : std::false_type {};
  1801. template <typename OutputIt, typename InputIt>
  1802. struct has_back_insert_iterator_container_append<
  1803. OutputIt, InputIt,
  1804. void_t<decltype(get_container(std::declval<OutputIt>())
  1805. .append(std::declval<InputIt>(),
  1806. std::declval<InputIt>()))>> : std::true_type {};
  1807. template <typename OutputIt, typename InputIt, typename = void>
  1808. struct has_back_insert_iterator_container_insert_at_end : std::false_type {};
  1809. template <typename OutputIt, typename InputIt>
  1810. struct has_back_insert_iterator_container_insert_at_end<
  1811. OutputIt, InputIt,
  1812. void_t<decltype(get_container(std::declval<OutputIt>())
  1813. .insert(get_container(std::declval<OutputIt>()).end(),
  1814. std::declval<InputIt>(),
  1815. std::declval<InputIt>()))>> : std::true_type {};
  1816. // An optimized version of std::copy with the output value type (T).
  1817. template <typename T, typename InputIt, typename OutputIt,
  1818. FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
  1819. has_back_insert_iterator_container_append<
  1820. OutputIt, InputIt>::value)>
  1821. FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
  1822. -> OutputIt {
  1823. get_container(out).append(begin, end);
  1824. return out;
  1825. }
  1826. template <typename T, typename InputIt, typename OutputIt,
  1827. FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value &&
  1828. !has_back_insert_iterator_container_append<
  1829. OutputIt, InputIt>::value &&
  1830. has_back_insert_iterator_container_insert_at_end<
  1831. OutputIt, InputIt>::value)>
  1832. FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
  1833. -> OutputIt {
  1834. auto& c = get_container(out);
  1835. c.insert(c.end(), begin, end);
  1836. return out;
  1837. }
  1838. template <typename T, typename InputIt, typename OutputIt,
  1839. FMT_ENABLE_IF(!(is_back_insert_iterator<OutputIt>::value &&
  1840. (has_back_insert_iterator_container_append<
  1841. OutputIt, InputIt>::value ||
  1842. has_back_insert_iterator_container_insert_at_end<
  1843. OutputIt, InputIt>::value)))>
  1844. FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
  1845. while (begin != end) *out++ = static_cast<T>(*begin++);
  1846. return out;
  1847. }
  1848. template <typename T, typename V, typename OutputIt>
  1849. FMT_CONSTEXPR auto copy(basic_string_view<V> s, OutputIt out) -> OutputIt {
  1850. return copy<T>(s.begin(), s.end(), out);
  1851. }
  1852. template <typename It, typename Enable = std::true_type>
  1853. struct is_buffer_appender : std::false_type {};
  1854. template <typename It>
  1855. struct is_buffer_appender<
  1856. It, bool_constant<
  1857. is_back_insert_iterator<It>::value &&
  1858. std::is_base_of<buffer<typename It::container_type::value_type>,
  1859. typename It::container_type>::value>>
  1860. : std::true_type {};
  1861. // Maps an output iterator to a buffer.
  1862. template <typename T, typename OutputIt,
  1863. FMT_ENABLE_IF(!is_buffer_appender<OutputIt>::value)>
  1864. auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
  1865. return iterator_buffer<OutputIt, T>(out);
  1866. }
  1867. template <typename T, typename OutputIt,
  1868. FMT_ENABLE_IF(is_buffer_appender<OutputIt>::value)>
  1869. auto get_buffer(OutputIt out) -> buffer<T>& {
  1870. return get_container(out);
  1871. }
  1872. template <typename Buf, typename OutputIt>
  1873. auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {
  1874. return buf.out();
  1875. }
  1876. template <typename T, typename OutputIt>
  1877. auto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {
  1878. return out;
  1879. }
  1880. // This type is intentionally undefined, only used for errors.
  1881. template <typename T, typename Char> struct type_is_unformattable_for;
  1882. template <typename Char> struct string_value {
  1883. const Char* data;
  1884. size_t size;
  1885. auto str() const -> basic_string_view<Char> { return {data, size}; }
  1886. };
  1887. template <typename Context> struct custom_value {
  1888. using char_type = typename Context::char_type;
  1889. void* value;
  1890. void (*format)(void* arg, parse_context<char_type>& parse_ctx, Context& ctx);
  1891. };
  1892. template <typename Char> struct named_arg_value {
  1893. const named_arg_info<Char>* data;
  1894. size_t size;
  1895. };
  1896. struct custom_tag {};
  1897. #if !FMT_BUILTIN_TYPES
  1898. # define FMT_BUILTIN , monostate
  1899. #else
  1900. # define FMT_BUILTIN
  1901. #endif
  1902. // A formatting argument value.
  1903. template <typename Context> class value {
  1904. public:
  1905. using char_type = typename Context::char_type;
  1906. union {
  1907. monostate no_value;
  1908. int int_value;
  1909. unsigned uint_value;
  1910. long long long_long_value;
  1911. unsigned long long ulong_long_value;
  1912. int128_opt int128_value;
  1913. uint128_opt uint128_value;
  1914. bool bool_value;
  1915. char_type char_value;
  1916. float float_value;
  1917. double double_value;
  1918. long double long_double_value;
  1919. const void* pointer;
  1920. string_value<char_type> string;
  1921. custom_value<Context> custom;
  1922. named_arg_value<char_type> named_args;
  1923. };
  1924. constexpr FMT_INLINE value() : no_value() {}
  1925. constexpr FMT_INLINE value(signed char x) : int_value(x) {}
  1926. constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {}
  1927. constexpr FMT_INLINE value(signed short x) : int_value(x) {}
  1928. constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {}
  1929. constexpr FMT_INLINE value(int x) : int_value(x) {}
  1930. constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {}
  1931. FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {}
  1932. FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN)
  1933. : value(ulong_type(x)) {}
  1934. constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {}
  1935. constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN)
  1936. : ulong_long_value(x) {}
  1937. FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {}
  1938. FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {}
  1939. constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {}
  1940. template <int N>
  1941. constexpr FMT_INLINE value(bitint<N> x FMT_BUILTIN) : long_long_value(x) {
  1942. static_assert(N <= 64, "unsupported _BitInt");
  1943. }
  1944. template <int N>
  1945. constexpr FMT_INLINE value(ubitint<N> x FMT_BUILTIN) : ulong_long_value(x) {
  1946. static_assert(N <= 64, "unsupported _BitInt");
  1947. }
  1948. template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>
  1949. constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) {
  1950. static_assert(
  1951. std::is_same<T, char>::value || std::is_same<T, char_type>::value,
  1952. "mixing character types is disallowed");
  1953. }
  1954. constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {}
  1955. constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {}
  1956. FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {}
  1957. FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) {
  1958. string.data = x;
  1959. if (is_constant_evaluated()) string.size = 0;
  1960. }
  1961. FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) {
  1962. string.data = x;
  1963. if (is_constant_evaluated()) string.size = 0;
  1964. }
  1965. template <typename T, typename C = char_t<T>,
  1966. FMT_ENABLE_IF(!std::is_pointer<T>::value)>
  1967. FMT_CONSTEXPR value(const T& x FMT_BUILTIN) {
  1968. static_assert(std::is_same<C, char_type>::value,
  1969. "mixing character types is disallowed");
  1970. auto sv = to_string_view(x);
  1971. string.data = sv.data();
  1972. string.size = sv.size();
  1973. }
  1974. FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {}
  1975. FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {}
  1976. FMT_INLINE value(volatile void* x FMT_BUILTIN)
  1977. : pointer(const_cast<const void*>(x)) {}
  1978. FMT_INLINE value(const volatile void* x FMT_BUILTIN)
  1979. : pointer(const_cast<const void*>(x)) {}
  1980. FMT_INLINE value(nullptr_t) : pointer(nullptr) {}
  1981. template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||
  1982. std::is_member_pointer<T>::value)>
  1983. value(const T&) {
  1984. // Formatting of arbitrary pointers is disallowed. If you want to format a
  1985. // pointer cast it to `void*` or `const void*`. In particular, this forbids
  1986. // formatting of `[const] volatile char*` printed as bool by iostreams.
  1987. static_assert(sizeof(T) == 0,
  1988. "formatting of non-void pointers is disallowed");
  1989. }
  1990. template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>
  1991. value(const T& x) : value(format_as(x)) {}
  1992. template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>
  1993. value(const T& x) : value(formatter<T>::format_as(x)) {}
  1994. template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
  1995. value(const T& named_arg) : value(named_arg.value) {}
  1996. template <typename T,
  1997. FMT_ENABLE_IF(use_formatter<T>::value || !FMT_BUILTIN_TYPES)>
  1998. FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {}
  1999. FMT_ALWAYS_INLINE value(const named_arg_info<char_type>* args, size_t size)
  2000. : named_args{args, size} {}
  2001. private:
  2002. template <typename T, FMT_ENABLE_IF(has_formatter<T, char_type>())>
  2003. FMT_CONSTEXPR value(T& x, custom_tag) {
  2004. using value_type = remove_const_t<T>;
  2005. // T may overload operator& e.g. std::vector<bool>::reference in libc++.
  2006. if (!is_constant_evaluated()) {
  2007. custom.value =
  2008. const_cast<char*>(&reinterpret_cast<const volatile char&>(x));
  2009. } else {
  2010. custom.value = nullptr;
  2011. #if defined(__cpp_if_constexpr)
  2012. if constexpr (std::is_same<decltype(&x), remove_reference_t<T>*>::value)
  2013. custom.value = const_cast<value_type*>(&x);
  2014. #endif
  2015. }
  2016. custom.format = format_custom<value_type>;
  2017. }
  2018. template <typename T, FMT_ENABLE_IF(!has_formatter<T, char_type>())>
  2019. FMT_CONSTEXPR value(const T&, custom_tag) {
  2020. // Cannot format an argument; to make type T formattable provide a
  2021. // formatter<T> specialization: https://fmt.dev/latest/api.html#udt.
  2022. type_is_unformattable_for<T, char_type> _;
  2023. }
  2024. // Formats an argument of a custom type, such as a user-defined class.
  2025. template <typename T>
  2026. static void format_custom(void* arg, parse_context<char_type>& parse_ctx,
  2027. Context& ctx) {
  2028. auto f = formatter<T, char_type>();
  2029. parse_ctx.advance_to(f.parse(parse_ctx));
  2030. using qualified_type =
  2031. conditional_t<has_formatter<const T, char_type>(), const T, T>;
  2032. // format must be const for compatibility with std::format and compilation.
  2033. const auto& cf = f;
  2034. ctx.advance_to(cf.format(*static_cast<qualified_type*>(arg), ctx));
  2035. }
  2036. };
  2037. enum { packed_arg_bits = 4 };
  2038. // Maximum number of arguments with packed types.
  2039. enum { max_packed_args = 62 / packed_arg_bits };
  2040. enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
  2041. enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
  2042. template <typename It, typename T, typename Enable = void>
  2043. struct is_output_iterator : std::false_type {};
  2044. template <> struct is_output_iterator<appender, char> : std::true_type {};
  2045. template <typename It, typename T>
  2046. struct is_output_iterator<
  2047. It, T,
  2048. enable_if_t<std::is_assignable<decltype(*std::declval<decay_t<It>&>()++),
  2049. T>::value>> : std::true_type {};
  2050. template <typename> constexpr auto encode_types() -> unsigned long long {
  2051. return 0;
  2052. }
  2053. template <typename Context, typename First, typename... T>
  2054. constexpr auto encode_types() -> unsigned long long {
  2055. return static_cast<unsigned>(stored_type_constant<First, Context>::value) |
  2056. (encode_types<Context, T...>() << packed_arg_bits);
  2057. }
  2058. template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>
  2059. constexpr auto make_descriptor() -> unsigned long long {
  2060. return NUM_ARGS <= max_packed_args ? encode_types<Context, T...>()
  2061. : is_unpacked_bit | NUM_ARGS;
  2062. }
  2063. template <typename Context, int NUM_ARGS>
  2064. using arg_t = conditional_t<NUM_ARGS <= max_packed_args, value<Context>,
  2065. basic_format_arg<Context>>;
  2066. template <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,
  2067. unsigned long long DESC>
  2068. struct named_arg_store {
  2069. // args_[0].named_args points to named_args to avoid bloating format_args.
  2070. arg_t<Context, NUM_ARGS> args[1u + NUM_ARGS];
  2071. named_arg_info<typename Context::char_type>
  2072. named_args[static_cast<size_t>(NUM_NAMED_ARGS)];
  2073. template <typename... T>
  2074. FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values)
  2075. : args{{named_args, NUM_NAMED_ARGS}, values...} {
  2076. int arg_index = 0, named_arg_index = 0;
  2077. FMT_APPLY_VARIADIC(
  2078. init_named_arg(named_args, arg_index, named_arg_index, values));
  2079. }
  2080. named_arg_store(named_arg_store&& rhs) {
  2081. args[0] = {named_args, NUM_NAMED_ARGS};
  2082. for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i)
  2083. args[i] = rhs.args[i];
  2084. for (size_t i = 0; i < NUM_NAMED_ARGS; ++i)
  2085. named_args[i] = rhs.named_args[i];
  2086. }
  2087. named_arg_store(const named_arg_store& rhs) = delete;
  2088. auto operator=(const named_arg_store& rhs) -> named_arg_store& = delete;
  2089. auto operator=(named_arg_store&& rhs) -> named_arg_store& = delete;
  2090. operator const arg_t<Context, NUM_ARGS>*() const { return args + 1; }
  2091. };
  2092. // An array of references to arguments. It can be implicitly converted to
  2093. // `basic_format_args` for passing into type-erased formatting functions
  2094. // such as `vformat`. It is a plain struct to reduce binary size in debug mode.
  2095. template <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,
  2096. unsigned long long DESC>
  2097. struct format_arg_store {
  2098. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
  2099. using type =
  2100. conditional_t<NUM_NAMED_ARGS == 0,
  2101. arg_t<Context, NUM_ARGS>[max_of<size_t>(1, NUM_ARGS)],
  2102. named_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>>;
  2103. type args;
  2104. };
  2105. // TYPE can be different from type_constant<T>, e.g. for __float128.
  2106. template <typename T, typename Char, type TYPE> struct native_formatter {
  2107. private:
  2108. dynamic_format_specs<Char> specs_;
  2109. public:
  2110. using nonlocking = void;
  2111. FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
  2112. if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();
  2113. auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE);
  2114. if (const_check(TYPE == type::char_type)) check_char_specs(specs_);
  2115. return end;
  2116. }
  2117. template <type U = TYPE,
  2118. FMT_ENABLE_IF(U == type::string_type || U == type::cstring_type ||
  2119. U == type::char_type)>
  2120. FMT_CONSTEXPR void set_debug_format(bool set = true) {
  2121. specs_.set_type(set ? presentation_type::debug : presentation_type::none);
  2122. }
  2123. FMT_PRAGMA_CLANG(diagnostic ignored "-Wundefined-inline")
  2124. template <typename FormatContext>
  2125. FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
  2126. -> decltype(ctx.out());
  2127. };
  2128. template <typename T, typename Enable = void>
  2129. struct locking
  2130. : bool_constant<mapped_type_constant<T>::value == type::custom_type> {};
  2131. template <typename T>
  2132. struct locking<T, void_t<typename formatter<remove_cvref_t<T>>::nonlocking>>
  2133. : std::false_type {};
  2134. template <typename T = int> FMT_CONSTEXPR inline auto is_locking() -> bool {
  2135. return locking<T>::value;
  2136. }
  2137. template <typename T1, typename T2, typename... Tail>
  2138. FMT_CONSTEXPR inline auto is_locking() -> bool {
  2139. return locking<T1>::value || is_locking<T2, Tail...>();
  2140. }
  2141. FMT_API void vformat_to(buffer<char>& buf, string_view fmt, format_args args,
  2142. locale_ref loc = {});
  2143. #if FMT_WIN32
  2144. FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool);
  2145. #else // format_args is passed by reference since it is defined later.
  2146. inline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {}
  2147. #endif
  2148. } // namespace detail
  2149. // The main public API.
  2150. template <typename Char>
  2151. FMT_CONSTEXPR void parse_context<Char>::do_check_arg_id(int arg_id) {
  2152. // Argument id is only checked at compile time during parsing because
  2153. // formatting has its own validation.
  2154. if (detail::is_constant_evaluated() && use_constexpr_cast) {
  2155. auto ctx = static_cast<detail::compile_parse_context<Char>*>(this);
  2156. if (arg_id >= ctx->num_args()) report_error("argument not found");
  2157. }
  2158. }
  2159. template <typename Char>
  2160. FMT_CONSTEXPR void parse_context<Char>::check_dynamic_spec(int arg_id) {
  2161. using detail::compile_parse_context;
  2162. if (detail::is_constant_evaluated() && use_constexpr_cast)
  2163. static_cast<compile_parse_context<Char>*>(this)->check_dynamic_spec(arg_id);
  2164. }
  2165. FMT_BEGIN_EXPORT
  2166. // An output iterator that appends to a buffer. It is used instead of
  2167. // back_insert_iterator to reduce symbol sizes and avoid <iterator> dependency.
  2168. template <typename T> class basic_appender {
  2169. protected:
  2170. detail::buffer<T>* container;
  2171. public:
  2172. using container_type = detail::buffer<T>;
  2173. FMT_CONSTEXPR basic_appender(detail::buffer<T>& buf) : container(&buf) {}
  2174. FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& {
  2175. container->push_back(c);
  2176. return *this;
  2177. }
  2178. FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; }
  2179. FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; }
  2180. FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; }
  2181. };
  2182. // A formatting argument. Context is a template parameter for the compiled API
  2183. // where output can be unbuffered.
  2184. template <typename Context> class basic_format_arg {
  2185. private:
  2186. detail::value<Context> value_;
  2187. detail::type type_;
  2188. friend class basic_format_args<Context>;
  2189. using char_type = typename Context::char_type;
  2190. public:
  2191. class handle {
  2192. private:
  2193. detail::custom_value<Context> custom_;
  2194. public:
  2195. explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
  2196. void format(parse_context<char_type>& parse_ctx, Context& ctx) const {
  2197. custom_.format(custom_.value, parse_ctx, ctx);
  2198. }
  2199. };
  2200. constexpr basic_format_arg() : type_(detail::type::none_type) {}
  2201. basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
  2202. : value_(args, size) {}
  2203. template <typename T>
  2204. basic_format_arg(T&& val)
  2205. : value_(val), type_(detail::stored_type_constant<T, Context>::value) {}
  2206. constexpr explicit operator bool() const noexcept {
  2207. return type_ != detail::type::none_type;
  2208. }
  2209. auto type() const -> detail::type { return type_; }
  2210. /**
  2211. * Visits an argument dispatching to the appropriate visit method based on
  2212. * the argument type. For example, if the argument type is `double` then
  2213. * `vis(value)` will be called with the value of type `double`.
  2214. */
  2215. template <typename Visitor>
  2216. FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) {
  2217. using detail::map;
  2218. switch (type_) {
  2219. case detail::type::none_type: break;
  2220. case detail::type::int_type: return vis(value_.int_value);
  2221. case detail::type::uint_type: return vis(value_.uint_value);
  2222. case detail::type::long_long_type: return vis(value_.long_long_value);
  2223. case detail::type::ulong_long_type: return vis(value_.ulong_long_value);
  2224. case detail::type::int128_type: return vis(map(value_.int128_value));
  2225. case detail::type::uint128_type: return vis(map(value_.uint128_value));
  2226. case detail::type::bool_type: return vis(value_.bool_value);
  2227. case detail::type::char_type: return vis(value_.char_value);
  2228. case detail::type::float_type: return vis(value_.float_value);
  2229. case detail::type::double_type: return vis(value_.double_value);
  2230. case detail::type::long_double_type: return vis(value_.long_double_value);
  2231. case detail::type::cstring_type: return vis(value_.string.data);
  2232. case detail::type::string_type: return vis(value_.string.str());
  2233. case detail::type::pointer_type: return vis(value_.pointer);
  2234. case detail::type::custom_type: return vis(handle(value_.custom));
  2235. }
  2236. return vis(monostate());
  2237. }
  2238. auto format_custom(const char_type* parse_begin,
  2239. parse_context<char_type>& parse_ctx, Context& ctx)
  2240. -> bool {
  2241. if (type_ != detail::type::custom_type) return false;
  2242. parse_ctx.advance_to(parse_begin);
  2243. value_.custom.format(value_.custom.value, parse_ctx, ctx);
  2244. return true;
  2245. }
  2246. };
  2247. /**
  2248. * A view of a collection of formatting arguments. To avoid lifetime issues it
  2249. * should only be used as a parameter type in type-erased functions such as
  2250. * `vformat`:
  2251. *
  2252. * void vlog(fmt::string_view fmt, fmt::format_args args); // OK
  2253. * fmt::format_args args = fmt::make_format_args(); // Dangling reference
  2254. */
  2255. template <typename Context> class basic_format_args {
  2256. private:
  2257. // A descriptor that contains information about formatting arguments.
  2258. // If the number of arguments is less or equal to max_packed_args then
  2259. // argument types are passed in the descriptor. This reduces binary code size
  2260. // per formatting function call.
  2261. unsigned long long desc_;
  2262. union {
  2263. // If is_packed() returns true then argument values are stored in values_;
  2264. // otherwise they are stored in args_. This is done to improve cache
  2265. // locality and reduce compiled code size since storing larger objects
  2266. // may require more code (at least on x86-64) even if the same amount of
  2267. // data is actually copied to stack. It saves ~10% on the bloat test.
  2268. const detail::value<Context>* values_;
  2269. const basic_format_arg<Context>* args_;
  2270. };
  2271. constexpr auto is_packed() const -> bool {
  2272. return (desc_ & detail::is_unpacked_bit) == 0;
  2273. }
  2274. constexpr auto has_named_args() const -> bool {
  2275. return (desc_ & detail::has_named_args_bit) != 0;
  2276. }
  2277. FMT_CONSTEXPR auto type(int index) const -> detail::type {
  2278. int shift = index * detail::packed_arg_bits;
  2279. unsigned mask = (1 << detail::packed_arg_bits) - 1;
  2280. return static_cast<detail::type>((desc_ >> shift) & mask);
  2281. }
  2282. template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC>
  2283. using store =
  2284. detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>;
  2285. public:
  2286. using format_arg = basic_format_arg<Context>;
  2287. constexpr basic_format_args() : desc_(0), args_(nullptr) {}
  2288. /// Constructs a `basic_format_args` object from `format_arg_store`.
  2289. template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,
  2290. FMT_ENABLE_IF(NUM_ARGS <= detail::max_packed_args)>
  2291. constexpr FMT_ALWAYS_INLINE basic_format_args(
  2292. const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)
  2293. : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),
  2294. values_(s.args) {}
  2295. template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,
  2296. FMT_ENABLE_IF(NUM_ARGS > detail::max_packed_args)>
  2297. constexpr basic_format_args(const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)
  2298. : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),
  2299. args_(s.args) {}
  2300. /// Constructs a `basic_format_args` object from a dynamic list of arguments.
  2301. constexpr basic_format_args(const format_arg* args, int count,
  2302. bool has_named = false)
  2303. : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) |
  2304. (has_named ? +detail::has_named_args_bit : 0)),
  2305. args_(args) {}
  2306. /// Returns the argument with the specified id.
  2307. FMT_CONSTEXPR auto get(int id) const -> format_arg {
  2308. auto arg = format_arg();
  2309. if (!is_packed()) {
  2310. if (id < max_size()) arg = args_[id];
  2311. return arg;
  2312. }
  2313. if (static_cast<unsigned>(id) >= detail::max_packed_args) return arg;
  2314. arg.type_ = type(id);
  2315. if (arg.type_ != detail::type::none_type) arg.value_ = values_[id];
  2316. return arg;
  2317. }
  2318. template <typename Char>
  2319. auto get(basic_string_view<Char> name) const -> format_arg {
  2320. int id = get_id(name);
  2321. return id >= 0 ? get(id) : format_arg();
  2322. }
  2323. template <typename Char>
  2324. FMT_CONSTEXPR auto get_id(basic_string_view<Char> name) const -> int {
  2325. if (!has_named_args()) return -1;
  2326. const auto& named_args =
  2327. (is_packed() ? values_[-1] : args_[-1].value_).named_args;
  2328. for (size_t i = 0; i < named_args.size; ++i) {
  2329. if (named_args.data[i].name == name) return named_args.data[i].id;
  2330. }
  2331. return -1;
  2332. }
  2333. auto max_size() const -> int {
  2334. unsigned long long max_packed = detail::max_packed_args;
  2335. return static_cast<int>(is_packed() ? max_packed
  2336. : desc_ & ~detail::is_unpacked_bit);
  2337. }
  2338. };
  2339. // A formatting context.
  2340. class context {
  2341. private:
  2342. appender out_;
  2343. format_args args_;
  2344. FMT_NO_UNIQUE_ADDRESS locale_ref loc_;
  2345. public:
  2346. using char_type = char; ///< The character type for the output.
  2347. using iterator = appender;
  2348. using format_arg = basic_format_arg<context>;
  2349. enum { builtin_types = FMT_BUILTIN_TYPES };
  2350. /// Constructs a `context` object. References to the arguments are stored
  2351. /// in the object so make sure they have appropriate lifetimes.
  2352. FMT_CONSTEXPR context(iterator out, format_args args, locale_ref loc = {})
  2353. : out_(out), args_(args), loc_(loc) {}
  2354. context(context&&) = default;
  2355. context(const context&) = delete;
  2356. void operator=(const context&) = delete;
  2357. FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); }
  2358. inline auto arg(string_view name) const -> format_arg {
  2359. return args_.get(name);
  2360. }
  2361. FMT_CONSTEXPR auto arg_id(string_view name) const -> int {
  2362. return args_.get_id(name);
  2363. }
  2364. auto args() const -> const format_args& { return args_; }
  2365. // Returns an iterator to the beginning of the output range.
  2366. FMT_CONSTEXPR auto out() const -> iterator { return out_; }
  2367. // Advances the begin iterator to `it`.
  2368. FMT_CONSTEXPR void advance_to(iterator) {}
  2369. FMT_CONSTEXPR auto locale() const -> locale_ref { return loc_; }
  2370. };
  2371. template <typename Char = char> struct runtime_format_string {
  2372. basic_string_view<Char> str;
  2373. };
  2374. /**
  2375. * Creates a runtime format string.
  2376. *
  2377. * **Example**:
  2378. *
  2379. * // Check format string at runtime instead of compile-time.
  2380. * fmt::print(fmt::runtime("{:d}"), "I am not a number");
  2381. */
  2382. inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; }
  2383. /// A compile-time format string. Use `format_string` in the public API to
  2384. /// prevent type deduction.
  2385. template <typename... T> struct fstring {
  2386. private:
  2387. static constexpr int num_static_named_args =
  2388. detail::count_static_named_args<T...>();
  2389. using checker = detail::format_string_checker<
  2390. char, static_cast<int>(sizeof...(T)), num_static_named_args,
  2391. num_static_named_args != detail::count_named_args<T...>()>;
  2392. using arg_pack = detail::arg_pack<T...>;
  2393. public:
  2394. string_view str;
  2395. using t = fstring;
  2396. // Reports a compile-time error if S is not a valid format string for T.
  2397. template <size_t N>
  2398. FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) {
  2399. using namespace detail;
  2400. static_assert(count<(is_view<remove_cvref_t<T>>::value &&
  2401. std::is_reference<T>::value)...>() == 0,
  2402. "passing views as lvalues is disallowed");
  2403. if (FMT_USE_CONSTEVAL) parse_format_string<char>(s, checker(s, arg_pack()));
  2404. #ifdef FMT_ENFORCE_COMPILE_STRING
  2405. static_assert(
  2406. FMT_USE_CONSTEVAL && sizeof(s) != 0,
  2407. "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING");
  2408. #endif
  2409. }
  2410. template <typename S,
  2411. FMT_ENABLE_IF(std::is_convertible<const S&, string_view>::value)>
  2412. FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) {
  2413. auto sv = string_view(str);
  2414. if (FMT_USE_CONSTEVAL)
  2415. detail::parse_format_string<char>(sv, checker(sv, arg_pack()));
  2416. #ifdef FMT_ENFORCE_COMPILE_STRING
  2417. static_assert(
  2418. FMT_USE_CONSTEVAL && sizeof(s) != 0,
  2419. "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING");
  2420. #endif
  2421. }
  2422. template <typename S,
  2423. FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&
  2424. std::is_same<typename S::char_type, char>::value)>
  2425. FMT_ALWAYS_INLINE fstring(const S&) : str(S()) {
  2426. FMT_CONSTEXPR auto sv = string_view(S());
  2427. FMT_CONSTEXPR int unused =
  2428. (parse_format_string(sv, checker(sv, arg_pack())), 0);
  2429. detail::ignore_unused(unused);
  2430. }
  2431. fstring(runtime_format_string<> fmt) : str(fmt.str) {}
  2432. // Returning by reference generates better code in debug mode.
  2433. FMT_ALWAYS_INLINE operator const string_view&() const { return str; }
  2434. auto get() const -> string_view { return str; }
  2435. };
  2436. template <typename... T> using format_string = typename fstring<T...>::t;
  2437. template <typename T, typename Char = char>
  2438. using is_formattable = bool_constant<!std::is_same<
  2439. detail::mapped_t<conditional_t<std::is_void<T>::value, int*, T>, Char>,
  2440. void>::value>;
  2441. #ifdef __cpp_concepts
  2442. template <typename T, typename Char = char>
  2443. concept formattable = is_formattable<remove_reference_t<T>, Char>::value;
  2444. #endif
  2445. // A formatter specialization for natively supported types.
  2446. template <typename T, typename Char>
  2447. struct formatter<T, Char,
  2448. enable_if_t<detail::type_constant<T, Char>::value !=
  2449. detail::type::custom_type>>
  2450. : detail::native_formatter<T, Char, detail::type_constant<T, Char>::value> {
  2451. };
  2452. /**
  2453. * Constructs an object that stores references to arguments and can be
  2454. * implicitly converted to `format_args`. `Context` can be omitted in which case
  2455. * it defaults to `context`. See `arg` for lifetime considerations.
  2456. */
  2457. // Take arguments by lvalue references to avoid some lifetime issues, e.g.
  2458. // auto args = make_format_args(std::string());
  2459. template <typename Context = context, typename... T,
  2460. int NUM_ARGS = sizeof...(T),
  2461. int NUM_NAMED_ARGS = detail::count_named_args<T...>(),
  2462. unsigned long long DESC = detail::make_descriptor<Context, T...>()>
  2463. constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args)
  2464. -> detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC> {
  2465. // Suppress warnings for pathological types convertible to detail::value.
  2466. FMT_PRAGMA_GCC(diagnostic ignored "-Wconversion")
  2467. return {{args...}};
  2468. }
  2469. template <typename... T>
  2470. using vargs =
  2471. detail::format_arg_store<context, sizeof...(T),
  2472. detail::count_named_args<T...>(),
  2473. detail::make_descriptor<context, T...>()>;
  2474. /**
  2475. * Returns a named argument to be used in a formatting function.
  2476. * It should only be used in a call to a formatting function.
  2477. *
  2478. * **Example**:
  2479. *
  2480. * fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
  2481. */
  2482. template <typename Char, typename T>
  2483. inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
  2484. return {name, arg};
  2485. }
  2486. /// Formats a string and writes the output to `out`.
  2487. template <typename OutputIt,
  2488. FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
  2489. char>::value)>
  2490. auto vformat_to(OutputIt&& out, string_view fmt, format_args args)
  2491. -> remove_cvref_t<OutputIt> {
  2492. auto&& buf = detail::get_buffer<char>(out);
  2493. detail::vformat_to(buf, fmt, args, {});
  2494. return detail::get_iterator(buf, out);
  2495. }
  2496. /**
  2497. * Formats `args` according to specifications in `fmt`, writes the result to
  2498. * the output iterator `out` and returns the iterator past the end of the output
  2499. * range. `format_to` does not append a terminating null character.
  2500. *
  2501. * **Example**:
  2502. *
  2503. * auto out = std::vector<char>();
  2504. * fmt::format_to(std::back_inserter(out), "{}", 42);
  2505. */
  2506. template <typename OutputIt, typename... T,
  2507. FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
  2508. char>::value)>
  2509. FMT_INLINE auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args)
  2510. -> remove_cvref_t<OutputIt> {
  2511. return vformat_to(out, fmt.str, vargs<T...>{{args...}});
  2512. }
  2513. template <typename OutputIt> struct format_to_n_result {
  2514. /// Iterator past the end of the output range.
  2515. OutputIt out;
  2516. /// Total (not truncated) output size.
  2517. size_t size;
  2518. };
  2519. template <typename OutputIt, typename... T,
  2520. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2521. auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
  2522. -> format_to_n_result<OutputIt> {
  2523. using traits = detail::fixed_buffer_traits;
  2524. auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
  2525. detail::vformat_to(buf, fmt, args, {});
  2526. return {buf.out(), buf.count()};
  2527. }
  2528. /**
  2529. * Formats `args` according to specifications in `fmt`, writes up to `n`
  2530. * characters of the result to the output iterator `out` and returns the total
  2531. * (not truncated) output size and the iterator past the end of the output
  2532. * range. `format_to_n` does not append a terminating null character.
  2533. */
  2534. template <typename OutputIt, typename... T,
  2535. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2536. FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
  2537. T&&... args) -> format_to_n_result<OutputIt> {
  2538. return vformat_to_n(out, n, fmt.str, vargs<T...>{{args...}});
  2539. }
  2540. struct format_to_result {
  2541. /// Pointer to just after the last successful write in the array.
  2542. char* out;
  2543. /// Specifies if the output was truncated.
  2544. bool truncated;
  2545. FMT_CONSTEXPR operator char*() const {
  2546. // Report truncation to prevent silent data loss.
  2547. if (truncated) report_error("output is truncated");
  2548. return out;
  2549. }
  2550. };
  2551. template <size_t N>
  2552. auto vformat_to(char (&out)[N], string_view fmt, format_args args)
  2553. -> format_to_result {
  2554. auto result = vformat_to_n(out, N, fmt, args);
  2555. return {result.out, result.size > N};
  2556. }
  2557. template <size_t N, typename... T>
  2558. FMT_INLINE auto format_to(char (&out)[N], format_string<T...> fmt, T&&... args)
  2559. -> format_to_result {
  2560. auto result = vformat_to_n(out, N, fmt.str, vargs<T...>{{args...}});
  2561. return {result.out, result.size > N};
  2562. }
  2563. /// Returns the number of chars in the output of `format(fmt, args...)`.
  2564. template <typename... T>
  2565. FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
  2566. T&&... args) -> size_t {
  2567. auto buf = detail::counting_buffer<>();
  2568. detail::vformat_to(buf, fmt.str, vargs<T...>{{args...}}, {});
  2569. return buf.count();
  2570. }
  2571. FMT_API void vprint(string_view fmt, format_args args);
  2572. FMT_API void vprint(FILE* f, string_view fmt, format_args args);
  2573. FMT_API void vprintln(FILE* f, string_view fmt, format_args args);
  2574. FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args);
  2575. /**
  2576. * Formats `args` according to specifications in `fmt` and writes the output
  2577. * to `stdout`.
  2578. *
  2579. * **Example**:
  2580. *
  2581. * fmt::print("The answer is {}.", 42);
  2582. */
  2583. template <typename... T>
  2584. FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
  2585. vargs<T...> va = {{args...}};
  2586. if (detail::const_check(!detail::use_utf8))
  2587. return detail::vprint_mojibake(stdout, fmt.str, va, false);
  2588. return detail::is_locking<T...>() ? vprint_buffered(stdout, fmt.str, va)
  2589. : vprint(fmt.str, va);
  2590. }
  2591. /**
  2592. * Formats `args` according to specifications in `fmt` and writes the
  2593. * output to the file `f`.
  2594. *
  2595. * **Example**:
  2596. *
  2597. * fmt::print(stderr, "Don't {}!", "panic");
  2598. */
  2599. template <typename... T>
  2600. FMT_INLINE void print(FILE* f, format_string<T...> fmt, T&&... args) {
  2601. vargs<T...> va = {{args...}};
  2602. if (detail::const_check(!detail::use_utf8))
  2603. return detail::vprint_mojibake(f, fmt.str, va, false);
  2604. return detail::is_locking<T...>() ? vprint_buffered(f, fmt.str, va)
  2605. : vprint(f, fmt.str, va);
  2606. }
  2607. /// Formats `args` according to specifications in `fmt` and writes the output
  2608. /// to the file `f` followed by a newline.
  2609. template <typename... T>
  2610. FMT_INLINE void println(FILE* f, format_string<T...> fmt, T&&... args) {
  2611. vargs<T...> va = {{args...}};
  2612. return detail::const_check(detail::use_utf8)
  2613. ? vprintln(f, fmt.str, va)
  2614. : detail::vprint_mojibake(f, fmt.str, va, true);
  2615. }
  2616. /// Formats `args` according to specifications in `fmt` and writes the output
  2617. /// to `stdout` followed by a newline.
  2618. template <typename... T>
  2619. FMT_INLINE void println(format_string<T...> fmt, T&&... args) {
  2620. return fmt::println(stdout, fmt, static_cast<T&&>(args)...);
  2621. }
  2622. FMT_PRAGMA_GCC(diagnostic pop)
  2623. FMT_PRAGMA_CLANG(diagnostic pop)
  2624. FMT_PRAGMA_GCC(pop_options)
  2625. FMT_END_EXPORT
  2626. FMT_END_NAMESPACE
  2627. #ifdef FMT_HEADER_ONLY
  2628. # include "format.h"
  2629. #endif
  2630. #endif // FMT_BASE_H_
  2631. #else
  2632. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  2633. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)