You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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