core.h 96 KB

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