base.h 100 KB

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