core.h 98 KB

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