base.h 102 KB

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