base.h 102 KB

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