format.h 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. /*
  2. Formatting library for C++
  3. Copyright (c) 2012 - 2014, Victor Zverovich
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. 1. Redistributions of source code must retain the above copyright notice, this
  8. list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  13. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  16. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  21. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #ifndef FMT_FORMAT_H_
  24. #define FMT_FORMAT_H_
  25. #include <stdint.h>
  26. #include <cassert>
  27. #include <cstddef> // for std::ptrdiff_t
  28. #include <cstdio>
  29. #include <algorithm>
  30. #include <limits>
  31. #include <stdexcept>
  32. #include <string>
  33. #include <sstream>
  34. #if _SECURE_SCL
  35. # include <iterator>
  36. #endif
  37. #ifdef __GNUC__
  38. # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  39. # define FMT_GCC_EXTENSION __extension__
  40. // Disable warning about "long long" which is sometimes reported even
  41. // when using __extension__.
  42. # if FMT_GCC_VERSION >= 406
  43. # pragma GCC diagnostic push
  44. # pragma GCC diagnostic ignored "-Wlong-long"
  45. # endif
  46. #else
  47. # define FMT_GCC_EXTENSION
  48. #endif
  49. #ifdef __GNUC_LIBSTD__
  50. # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
  51. #endif
  52. #ifdef __has_feature
  53. # define FMT_HAS_FEATURE(x) __has_feature(x)
  54. #else
  55. # define FMT_HAS_FEATURE(x) 0
  56. #endif
  57. #ifdef __has_builtin
  58. # define FMT_HAS_BUILTIN(x) __has_builtin(x)
  59. #else
  60. # define FMT_HAS_BUILTIN(x) 0
  61. #endif
  62. #ifndef FMT_USE_VARIADIC_TEMPLATES
  63. // Variadic templates are available in GCC since version 4.4
  64. // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++
  65. // since version 2013.
  66. # define FMT_USE_VARIADIC_TEMPLATES \
  67. (FMT_HAS_FEATURE(cxx_variadic_templates) || \
  68. (FMT_GCC_VERSION >= 404 && __cplusplus >= 201103) || _MSC_VER >= 1800)
  69. #endif
  70. #ifndef FMT_USE_RVALUE_REFERENCES
  71. // Don't use rvalue references when compiling with clang and an old libstdc++
  72. // as the latter doesn't provide std::move.
  73. # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402
  74. # define FMT_USE_RVALUE_REFERENCES 0
  75. # else
  76. # define FMT_USE_RVALUE_REFERENCES \
  77. (FMT_HAS_FEATURE(cxx_rvalue_references) || \
  78. (FMT_GCC_VERSION >= 403 && __cplusplus >= 201103) || _MSC_VER >= 1600)
  79. # endif
  80. #endif
  81. #if FMT_USE_RVALUE_REFERENCES
  82. # include <utility> // for std::move
  83. #endif
  84. // Define FMT_USE_NOEXCEPT to make C++ Format use noexcept (C++11 feature).
  85. #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
  86. (FMT_GCC_VERSION >= 408 && __cplusplus >= 201103)
  87. # define FMT_NOEXCEPT(expr) noexcept(expr)
  88. #else
  89. # define FMT_NOEXCEPT(expr)
  90. #endif
  91. // A macro to disallow the copy constructor and operator= functions
  92. // This should be used in the private: declarations for a class
  93. #define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
  94. TypeName(const TypeName&); \
  95. void operator=(const TypeName&)
  96. namespace fmt {
  97. // Fix the warning about long long on older versions of GCC
  98. // that don't support the diagnostic pragma.
  99. FMT_GCC_EXTENSION typedef long long LongLong;
  100. FMT_GCC_EXTENSION typedef unsigned long long ULongLong;
  101. #if FMT_USE_RVALUE_REFERENCES
  102. using std::move;
  103. #endif
  104. template <typename Char>
  105. class BasicWriter;
  106. typedef BasicWriter<char> Writer;
  107. typedef BasicWriter<wchar_t> WWriter;
  108. template <typename Char>
  109. class BasicFormatter;
  110. template <typename Char, typename T>
  111. void format(BasicFormatter<Char> &f, const Char *format_str, const T &value);
  112. /**
  113. \rst
  114. A string reference. It can be constructed from a C string or
  115. ``std::string``.
  116. You can use one of the following typedefs for common character types:
  117. +------------+-------------------------+
  118. | Type | Definition |
  119. +============+=========================+
  120. | StringRef | BasicStringRef<char> |
  121. +------------+-------------------------+
  122. | WStringRef | BasicStringRef<wchar_t> |
  123. +------------+-------------------------+
  124. This class is most useful as a parameter type to allow passing
  125. different types of strings to a function, for example::
  126. template<typename... Args>
  127. std::string format(StringRef format, const Args & ... args);
  128. format("{}", 42);
  129. format(std::string("{}"), 42);
  130. \endrst
  131. */
  132. template <typename Char>
  133. class BasicStringRef {
  134. private:
  135. const Char *data_;
  136. mutable std::size_t size_;
  137. public:
  138. /**
  139. Constructs a string reference object from a C string and a size.
  140. If *size* is zero, which is the default, the size is computed
  141. automatically.
  142. */
  143. BasicStringRef(const Char *s, std::size_t size = 0) : data_(s), size_(size) {}
  144. /**
  145. Constructs a string reference from an `std::string` object.
  146. */
  147. BasicStringRef(const std::basic_string<Char> &s)
  148. : data_(s.c_str()), size_(s.size()) {}
  149. /**
  150. Converts a string reference to an `std::string` object.
  151. */
  152. operator std::basic_string<Char>() const {
  153. return std::basic_string<Char>(data_, size());
  154. }
  155. /**
  156. Returns the pointer to a C string.
  157. */
  158. const Char *c_str() const { return data_; }
  159. /**
  160. Returns the string size.
  161. */
  162. std::size_t size() const {
  163. if (size_ == 0 && data_) size_ = std::char_traits<Char>::length(data_);
  164. return size_;
  165. }
  166. friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) {
  167. return lhs.data_ == rhs.data_;
  168. }
  169. friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) {
  170. return lhs.data_ != rhs.data_;
  171. }
  172. };
  173. typedef BasicStringRef<char> StringRef;
  174. typedef BasicStringRef<wchar_t> WStringRef;
  175. /**
  176. A formatting error such as invalid format string.
  177. */
  178. class FormatError : public std::runtime_error {
  179. public:
  180. explicit FormatError(const std::string &message)
  181. : std::runtime_error(message) {}
  182. };
  183. namespace internal {
  184. // The number of characters to store in the Array object, representing the
  185. // output buffer, itself to avoid dynamic memory allocation.
  186. enum { INLINE_BUFFER_SIZE = 500 };
  187. #if _SECURE_SCL
  188. // Use checked iterator to avoid warnings on MSVC.
  189. template <typename T>
  190. inline stdext::checked_array_iterator<T*> CheckPtr(T *ptr, std::size_t size) {
  191. return stdext::checked_array_iterator<T*>(ptr, size);
  192. }
  193. #else
  194. template <typename T>
  195. inline T *CheckPtr(T *ptr, std::size_t) { return ptr; }
  196. #endif
  197. // A simple array for POD types with the first SIZE elements stored in
  198. // the object itself. It supports a subset of std::vector's operations.
  199. template <typename T, std::size_t SIZE>
  200. class Array {
  201. private:
  202. std::size_t size_;
  203. std::size_t capacity_;
  204. T *ptr_;
  205. T data_[SIZE];
  206. void grow(std::size_t size);
  207. // Free memory allocated by the array.
  208. void free() {
  209. if (ptr_ != data_) delete [] ptr_;
  210. }
  211. // Move data from other to this array.
  212. void move(Array &other) {
  213. size_ = other.size_;
  214. capacity_ = other.capacity_;
  215. if (other.ptr_ == other.data_) {
  216. ptr_ = data_;
  217. std::copy(other.data_, other.data_ + size_, CheckPtr(data_, capacity_));
  218. } else {
  219. ptr_ = other.ptr_;
  220. // Set pointer to the inline array so that delete is not called
  221. // when freeing.
  222. other.ptr_ = other.data_;
  223. }
  224. }
  225. FMT_DISALLOW_COPY_AND_ASSIGN(Array);
  226. public:
  227. Array() : size_(0), capacity_(SIZE), ptr_(data_) {}
  228. ~Array() { free(); }
  229. #if FMT_USE_RVALUE_REFERENCES
  230. Array(Array &&other) {
  231. move(other);
  232. }
  233. Array& operator=(Array &&other) {
  234. assert(this != &other);
  235. free();
  236. move(other);
  237. return *this;
  238. }
  239. #endif
  240. // Returns the size of this array.
  241. std::size_t size() const { return size_; }
  242. // Returns the capacity of this array.
  243. std::size_t capacity() const { return capacity_; }
  244. // Resizes the array. If T is a POD type new elements are not initialized.
  245. void resize(std::size_t new_size) {
  246. if (new_size > capacity_)
  247. grow(new_size);
  248. size_ = new_size;
  249. }
  250. // Reserves space to store at least capacity elements.
  251. void reserve(std::size_t capacity) {
  252. if (capacity > capacity_)
  253. grow(capacity);
  254. }
  255. void clear() { size_ = 0; }
  256. void push_back(const T &value) {
  257. if (size_ == capacity_)
  258. grow(size_ + 1);
  259. ptr_[size_++] = value;
  260. }
  261. // Appends data to the end of the array.
  262. void append(const T *begin, const T *end);
  263. T &operator[](std::size_t index) { return ptr_[index]; }
  264. const T &operator[](std::size_t index) const { return ptr_[index]; }
  265. };
  266. template <typename T, std::size_t SIZE>
  267. void Array<T, SIZE>::grow(std::size_t size) {
  268. capacity_ = (std::max)(size, capacity_ + capacity_ / 2);
  269. T *p = new T[capacity_];
  270. std::copy(ptr_, ptr_ + size_, CheckPtr(p, capacity_));
  271. if (ptr_ != data_)
  272. delete [] ptr_;
  273. ptr_ = p;
  274. }
  275. template <typename T, std::size_t SIZE>
  276. void Array<T, SIZE>::append(const T *begin, const T *end) {
  277. std::ptrdiff_t num_elements = end - begin;
  278. if (size_ + num_elements > capacity_)
  279. grow(size_ + num_elements);
  280. std::copy(begin, end, CheckPtr(ptr_, capacity_) + size_);
  281. size_ += num_elements;
  282. }
  283. template <typename Char>
  284. class BasicCharTraits {
  285. public:
  286. #if _SECURE_SCL
  287. typedef stdext::checked_array_iterator<Char*> CharPtr;
  288. #else
  289. typedef Char *CharPtr;
  290. #endif
  291. };
  292. template <typename Char>
  293. class CharTraits;
  294. template <>
  295. class CharTraits<char> : public BasicCharTraits<char> {
  296. private:
  297. // Conversion from wchar_t to char is not allowed.
  298. static char convert(wchar_t);
  299. public:
  300. typedef const wchar_t *UnsupportedStrType;
  301. static char convert(char value) { return value; }
  302. template <typename T>
  303. static int FormatFloat(char *buffer, std::size_t size,
  304. const char *format, unsigned width, int precision, T value);
  305. };
  306. template <>
  307. class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> {
  308. public:
  309. typedef const char *UnsupportedStrType;
  310. static wchar_t convert(char value) { return value; }
  311. static wchar_t convert(wchar_t value) { return value; }
  312. template <typename T>
  313. static int FormatFloat(wchar_t *buffer, std::size_t size,
  314. const wchar_t *format, unsigned width, int precision, T value);
  315. };
  316. // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise.
  317. template <bool FitsIn32Bits>
  318. struct TypeSelector { typedef uint32_t Type; };
  319. template <>
  320. struct TypeSelector<false> { typedef uint64_t Type; };
  321. // Checks if a number is negative - used to avoid warnings.
  322. template <bool IsSigned>
  323. struct SignChecker {
  324. template <typename T>
  325. static bool IsNegative(T) { return false; }
  326. };
  327. template <>
  328. struct SignChecker<true> {
  329. template <typename T>
  330. static bool IsNegative(T value) { return value < 0; }
  331. };
  332. // Returns true if value is negative, false otherwise.
  333. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
  334. template <typename T>
  335. inline bool IsNegative(T value) {
  336. return SignChecker<std::numeric_limits<T>::is_signed>::IsNegative(value);
  337. }
  338. int SignBitNoInline(double value);
  339. template <typename T>
  340. struct IntTraits {
  341. // Smallest of uint32_t and uint64_t that is large enough to represent
  342. // all values of T.
  343. typedef typename
  344. TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType;
  345. };
  346. template <typename T>
  347. struct IsLongDouble { enum {VALUE = 0}; };
  348. template <>
  349. struct IsLongDouble<long double> { enum {VALUE = 1}; };
  350. void ReportUnknownType(char code, const char *type);
  351. extern const uint32_t POWERS_OF_10_32[];
  352. extern const uint64_t POWERS_OF_10_64[];
  353. #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
  354. // Returns the number of decimal digits in n. Leading zeros are not counted
  355. // except for n == 0 in which case CountDigits returns 1.
  356. inline unsigned CountDigits(uint64_t n) {
  357. // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
  358. // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
  359. uint64_t t = (64 - __builtin_clzll(n | 1)) * 1233 >> 12;
  360. return t - (n < POWERS_OF_10_64[t]) + 1;
  361. }
  362. # if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
  363. // Optional version of CountDigits for better performance on 32-bit platforms.
  364. inline unsigned CountDigits(uint32_t n) {
  365. uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12;
  366. return t - (n < POWERS_OF_10_32[t]) + 1;
  367. }
  368. # endif
  369. #else
  370. // Slower version of CountDigits used when __builtin_clz is not available.
  371. inline unsigned CountDigits(uint64_t n) {
  372. unsigned count = 1;
  373. for (;;) {
  374. // Integer division is slow so do it for a group of four digits instead
  375. // of for every digit. The idea comes from the talk by Alexandrescu
  376. // "Three Optimization Tips for C++". See speed-test for a comparison.
  377. if (n < 10) return count;
  378. if (n < 100) return count + 1;
  379. if (n < 1000) return count + 2;
  380. if (n < 10000) return count + 3;
  381. n /= 10000u;
  382. count += 4;
  383. }
  384. }
  385. #endif
  386. extern const char DIGITS[];
  387. // Formats a decimal unsigned integer value writing into buffer.
  388. template <typename UInt, typename Char>
  389. void FormatDecimal(Char *buffer, UInt value, unsigned num_digits) {
  390. --num_digits;
  391. while (value >= 100) {
  392. // Integer division is slow so do it for a group of two digits instead
  393. // of for every digit. The idea comes from the talk by Alexandrescu
  394. // "Three Optimization Tips for C++". See speed-test for a comparison.
  395. unsigned index = (value % 100) * 2;
  396. value /= 100;
  397. buffer[num_digits] = DIGITS[index + 1];
  398. buffer[num_digits - 1] = DIGITS[index];
  399. num_digits -= 2;
  400. }
  401. if (value < 10) {
  402. *buffer = static_cast<char>('0' + value);
  403. return;
  404. }
  405. unsigned index = static_cast<unsigned>(value * 2);
  406. buffer[1] = DIGITS[index + 1];
  407. buffer[0] = DIGITS[index];
  408. }
  409. #ifdef _WIN32
  410. // A converter from UTF-8 to UTF-16.
  411. // It is only provided for Windows since other systems use UTF-8.
  412. class UTF8ToUTF16 {
  413. private:
  414. Array<wchar_t, INLINE_BUFFER_SIZE> buffer_;
  415. public:
  416. explicit UTF8ToUTF16(StringRef s);
  417. operator WStringRef() const { return WStringRef(&buffer_[0], size()); }
  418. size_t size() const { return buffer_.size() - 1; }
  419. const wchar_t *c_str() const { return &buffer_[0]; }
  420. std::wstring str() const { return std::wstring(&buffer_[0], size()); }
  421. };
  422. // A converter from UTF-16 to UTF-8.
  423. // It is only provided for Windows since other systems use UTF-8.
  424. class UTF16ToUTF8 {
  425. private:
  426. Array<char, INLINE_BUFFER_SIZE> buffer_;
  427. public:
  428. UTF16ToUTF8() {}
  429. explicit UTF16ToUTF8(WStringRef s);
  430. operator StringRef() const { return StringRef(&buffer_[0], size()); }
  431. size_t size() const { return buffer_.size() - 1; }
  432. const char *c_str() const { return &buffer_[0]; }
  433. std::string str() const { return std::string(&buffer_[0], size()); }
  434. // Performs conversion returning a system error code instead of
  435. // throwing exception on error.
  436. int Convert(WStringRef s);
  437. };
  438. #endif
  439. // Portable thread-safe version of strerror.
  440. // Sets buffer to point to a string describing the error code.
  441. // This can be either a pointer to a string stored in buffer,
  442. // or a pointer to some static immutable string.
  443. // Returns one of the following values:
  444. // 0 - success
  445. // ERANGE - buffer is not large enough to store the error message
  446. // other - failure
  447. // Buffer should be at least of size 1.
  448. int StrError(int error_code,
  449. char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT(true);
  450. void FormatSystemErrorMessage(
  451. fmt::Writer &out, int error_code, fmt::StringRef message);
  452. #ifdef _WIN32
  453. void FormatWinErrorMessage(
  454. fmt::Writer &out, int error_code, fmt::StringRef message);
  455. #endif
  456. struct SimpleErrorReporter {
  457. void operator()(const void *, fmt::StringRef message) const {
  458. throw fmt::FormatError(message);
  459. }
  460. };
  461. // Throws Exception(message) if format contains '}', otherwise throws
  462. // FormatError reporting unmatched '{'. The idea is that unmatched '{'
  463. // should override other errors.
  464. template <typename Char>
  465. struct FormatErrorReporter {
  466. int num_open_braces;
  467. void operator()(const Char *s, fmt::StringRef message) const;
  468. };
  469. // Computes max(Arg, 1) at compile time. It is used to avoid errors about
  470. // allocating an array of 0 size.
  471. template <unsigned Arg>
  472. struct NonZero {
  473. enum { VALUE = Arg };
  474. };
  475. template <>
  476. struct NonZero<0> {
  477. enum { VALUE = 1 };
  478. };
  479. // A formatting argument. It is a POD type to allow storage in internal::Array.
  480. struct Arg {
  481. enum Type {
  482. // Integer types should go first,
  483. INT, UINT, LONG_LONG, ULONG_LONG, LAST_INTEGER_TYPE = ULONG_LONG,
  484. // followed by floating-point types.
  485. DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE,
  486. CHAR, STRING, WSTRING, POINTER, CUSTOM
  487. };
  488. Type type;
  489. template <typename Char>
  490. struct StringValue {
  491. const Char *value;
  492. std::size_t size;
  493. };
  494. typedef void (*FormatFunc)(
  495. void *formatter, const void *arg, const void *format_str);
  496. struct CustomValue {
  497. const void *value;
  498. FormatFunc format;
  499. };
  500. union {
  501. int int_value;
  502. unsigned uint_value;
  503. LongLong long_long_value;
  504. ULongLong ulong_long_value;
  505. double double_value;
  506. long double long_double_value;
  507. const void *pointer_value;
  508. StringValue<char> string;
  509. StringValue<wchar_t> wstring;
  510. CustomValue custom;
  511. };
  512. };
  513. // Makes an Arg object from any type.
  514. template <typename Char>
  515. class MakeArg : public Arg {
  516. private:
  517. // The following two methods are private to disallow formatting of
  518. // arbitrary pointers. If you want to output a pointer cast it to
  519. // "void *" or "const void *". In particular, this forbids formatting
  520. // of "[const] volatile char *" which is printed as bool by iostreams.
  521. // Do not implement!
  522. template <typename T>
  523. MakeArg(const T *value);
  524. template <typename T>
  525. MakeArg(T *value);
  526. void set_string(StringRef str) {
  527. type = STRING;
  528. string.value = str.c_str();
  529. string.size = str.size();
  530. }
  531. void set_string(WStringRef str) {
  532. type = WSTRING;
  533. CharTraits<Char>::convert(wchar_t());
  534. wstring.value = str.c_str();
  535. wstring.size = str.size();
  536. }
  537. // Formats an argument of a custom type, such as a user-defined class.
  538. template <typename T>
  539. static void format_custom_arg(
  540. void *formatter, const void *arg, const void *format_str) {
  541. format(*static_cast<BasicFormatter<Char>*>(formatter),
  542. static_cast<const Char*>(format_str), *static_cast<const T*>(arg));
  543. }
  544. public:
  545. MakeArg() {}
  546. MakeArg(bool value) { type = INT; int_value = value; }
  547. MakeArg(short value) { type = INT; int_value = value; }
  548. MakeArg(unsigned short value) { type = UINT; uint_value = value; }
  549. MakeArg(int value) { type = INT; int_value = value; }
  550. MakeArg(unsigned value) { type = UINT; uint_value = value; }
  551. MakeArg(long value) {
  552. // To minimize the number of types we need to deal with, long is
  553. // translated either to int or to long long depending on its size.
  554. if (sizeof(long) == sizeof(int)) {
  555. type = INT;
  556. int_value = static_cast<int>(value);
  557. } else {
  558. type = LONG_LONG;
  559. long_long_value = value;
  560. }
  561. }
  562. MakeArg(unsigned long value) {
  563. if (sizeof(unsigned long) == sizeof(unsigned)) {
  564. type = UINT;
  565. uint_value = static_cast<unsigned>(value);
  566. } else {
  567. type = ULONG_LONG;
  568. ulong_long_value = value;
  569. }
  570. }
  571. MakeArg(LongLong value) { type = LONG_LONG; long_long_value = value; }
  572. MakeArg(ULongLong value) { type = ULONG_LONG; ulong_long_value = value; }
  573. MakeArg(float value) { type = DOUBLE; double_value = value; }
  574. MakeArg(double value) { type = DOUBLE; double_value = value; }
  575. MakeArg(long double value) { type = LONG_DOUBLE; long_double_value = value; }
  576. MakeArg(signed char value) { type = CHAR; int_value = value; }
  577. MakeArg(unsigned char value) { type = CHAR; int_value = value; }
  578. MakeArg(char value) { type = CHAR; int_value = value; }
  579. MakeArg(wchar_t value) {
  580. type = CHAR;
  581. int_value = internal::CharTraits<Char>::convert(value);
  582. }
  583. MakeArg(char *value) { set_string(value); }
  584. MakeArg(const char *value) { set_string(value); }
  585. MakeArg(const std::string &value) { set_string(value); }
  586. MakeArg(StringRef value) { set_string(value); }
  587. MakeArg(wchar_t *value) { set_string(value); }
  588. MakeArg(const wchar_t *value) { set_string(value); }
  589. MakeArg(const std::wstring &value) { set_string(value); }
  590. MakeArg(WStringRef value) { set_string(value); }
  591. MakeArg(void *value) { type = POINTER; pointer_value = value; }
  592. MakeArg(const void *value) { type = POINTER; pointer_value = value; }
  593. template <typename T>
  594. MakeArg(const T &value) {
  595. type = CUSTOM;
  596. custom.value = &value;
  597. custom.format = &format_custom_arg<T>;
  598. }
  599. };
  600. #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call
  601. // An argument visitor.
  602. // To use ArgVisitor define a subclass that implements some or all of the
  603. // visit methods with the same signatures as the methods in ArgVisitor,
  604. // for example, visit_int(int).
  605. // Specify the subclass name as the Impl template parameter. Then calling
  606. // ArgVisitor::visit for some argument will dispatch to a visit method
  607. // specific to the argument type. For example, if the argument type is
  608. // double then visit_double(double) method of a subclass will be called.
  609. // If the subclass doesn't contain a method with this signature, then
  610. // a corresponding method of ArgVisitor will be called.
  611. //
  612. // Example:
  613. // class MyArgVisitor : public ArgVisitor<MyArgVisitor, void> {
  614. // public:
  615. // void visit_int(int value) { print("{}", value); }
  616. // void visit_double(double value) { print("{}", value ); }
  617. // };
  618. //
  619. // ArgVisitor uses the curiously recurring template pattern:
  620. // http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
  621. template <typename Impl, typename Result>
  622. class ArgVisitor {
  623. public:
  624. Result visit_unhandled_arg() { return Result(); }
  625. Result visit_int(int value) {
  626. return FMT_DISPATCH(visit_any_int(value));
  627. }
  628. Result visit_long_long(LongLong value) {
  629. return FMT_DISPATCH(visit_any_int(value));
  630. }
  631. Result visit_any_int(LongLong) {
  632. return FMT_DISPATCH(visit_unhandled_arg());
  633. }
  634. Result visit_uint(unsigned value) {
  635. return FMT_DISPATCH(visit_any_uint(value));
  636. }
  637. Result visit_ulong_long(ULongLong value) {
  638. return FMT_DISPATCH(visit_any_uint(value));
  639. }
  640. Result visit_any_uint(ULongLong) {
  641. return FMT_DISPATCH(visit_unhandled_arg());
  642. }
  643. Result visit_double(double) {
  644. return FMT_DISPATCH(visit_unhandled_arg());
  645. }
  646. Result visit_long_double(long double) {
  647. return FMT_DISPATCH(visit_unhandled_arg());
  648. }
  649. Result visit_char(int) {
  650. return FMT_DISPATCH(visit_unhandled_arg());
  651. }
  652. Result visit_string(Arg::StringValue<char>) {
  653. return FMT_DISPATCH(visit_unhandled_arg());
  654. }
  655. Result visit_wstring(Arg::StringValue<wchar_t>) {
  656. return FMT_DISPATCH(visit_unhandled_arg());
  657. }
  658. Result visit_pointer(const void *) {
  659. return FMT_DISPATCH(visit_unhandled_arg());
  660. }
  661. Result visit_custom(Arg::CustomValue) {
  662. return FMT_DISPATCH(visit_unhandled_arg());
  663. }
  664. Result visit(const Arg &arg) {
  665. switch (arg.type) {
  666. default:
  667. assert(false);
  668. // Fall through.
  669. case Arg::INT:
  670. return FMT_DISPATCH(visit_int(arg.int_value));
  671. case Arg::UINT:
  672. return FMT_DISPATCH(visit_uint(arg.uint_value));
  673. case Arg::LONG_LONG:
  674. return FMT_DISPATCH(visit_long_long(arg.long_long_value));
  675. case Arg::ULONG_LONG:
  676. return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value));
  677. case Arg::DOUBLE:
  678. return FMT_DISPATCH(visit_double(arg.double_value));
  679. case Arg::LONG_DOUBLE:
  680. return FMT_DISPATCH(visit_long_double(arg.long_double_value));
  681. case Arg::CHAR:
  682. return FMT_DISPATCH(visit_char(arg.int_value));
  683. case Arg::STRING:
  684. return FMT_DISPATCH(visit_string(arg.string));
  685. case Arg::WSTRING:
  686. return FMT_DISPATCH(visit_wstring(arg.wstring));
  687. case Arg::POINTER:
  688. return FMT_DISPATCH(visit_pointer(arg.pointer_value));
  689. case Arg::CUSTOM:
  690. return FMT_DISPATCH(visit_custom(arg.custom));
  691. }
  692. }
  693. };
  694. class RuntimeError : public std::runtime_error {
  695. protected:
  696. RuntimeError() : std::runtime_error("") {}
  697. };
  698. template <typename Char>
  699. class ArgFormatter;
  700. } // namespace internal
  701. /**
  702. An argument list.
  703. */
  704. class ArgList {
  705. private:
  706. const internal::Arg *args_;
  707. std::size_t size_;
  708. public:
  709. ArgList() : size_(0) {}
  710. ArgList(const internal::Arg *args, std::size_t size)
  711. : args_(args), size_(size) {}
  712. /**
  713. Returns the list size (the number of arguments).
  714. */
  715. std::size_t size() const { return size_; }
  716. /**
  717. Returns the argument at specified index.
  718. */
  719. const internal::Arg &operator[](std::size_t index) const {
  720. return args_[index];
  721. }
  722. };
  723. struct FormatSpec;
  724. // A formatter.
  725. template <typename Char>
  726. class BasicFormatter {
  727. private:
  728. BasicWriter<Char> &writer_;
  729. ArgList args_;
  730. int next_arg_index_;
  731. const Char *start_;
  732. internal::FormatErrorReporter<Char> report_error_;
  733. // Parses argument index and returns an argument with this index.
  734. const internal::Arg &ParseArgIndex(const Char *&s);
  735. void CheckSign(const Char *&s, const internal::Arg &arg);
  736. public:
  737. explicit BasicFormatter(BasicWriter<Char> &w) : writer_(w) {}
  738. BasicWriter<Char> &writer() { return writer_; }
  739. void Format(BasicStringRef<Char> format_str, const ArgList &args);
  740. const Char *format(const Char *format_str, const internal::Arg &arg);
  741. };
  742. namespace internal {
  743. // Printf format string parser.
  744. template <typename Char>
  745. class PrintfParser {
  746. private:
  747. ArgList args_;
  748. int next_arg_index_;
  749. void ParseFlags(FormatSpec &spec, const Char *&s);
  750. // Parses argument index, flags and width and returns the parsed
  751. // argument index.
  752. unsigned ParseHeader(const Char *&s, FormatSpec &spec, const char *&error);
  753. const internal::Arg &HandleArgIndex(unsigned arg_index, const char *&error);
  754. public:
  755. void Format(BasicWriter<Char> &writer,
  756. BasicStringRef<Char> format, const ArgList &args);
  757. };
  758. } // namespace internal
  759. enum Alignment {
  760. ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
  761. };
  762. // Flags.
  763. enum { SIGN_FLAG = 1, PLUS_FLAG = 2, HASH_FLAG = 4 };
  764. // An empty format specifier.
  765. struct EmptySpec {};
  766. // A type specifier.
  767. template <char TYPE>
  768. struct TypeSpec : EmptySpec {
  769. Alignment align() const { return ALIGN_DEFAULT; }
  770. unsigned width() const { return 0; }
  771. int precision() const { return -1; }
  772. bool sign_flag() const { return false; }
  773. bool plus_flag() const { return false; }
  774. bool hash_flag() const { return false; }
  775. char type() const { return TYPE; }
  776. char fill() const { return ' '; }
  777. };
  778. // A width specifier.
  779. struct WidthSpec {
  780. unsigned width_;
  781. // Fill is always wchar_t and cast to char if necessary to avoid having
  782. // two specialization of WidthSpec and its subclasses.
  783. wchar_t fill_;
  784. WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {}
  785. unsigned width() const { return width_; }
  786. wchar_t fill() const { return fill_; }
  787. };
  788. // An alignment specifier.
  789. struct AlignSpec : WidthSpec {
  790. Alignment align_;
  791. AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT)
  792. : WidthSpec(width, fill), align_(align) {}
  793. Alignment align() const { return align_; }
  794. int precision() const { return -1; }
  795. };
  796. // An alignment and type specifier.
  797. template <char TYPE>
  798. struct AlignTypeSpec : AlignSpec {
  799. AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {}
  800. bool sign_flag() const { return false; }
  801. bool plus_flag() const { return false; }
  802. bool hash_flag() const { return false; }
  803. char type() const { return TYPE; }
  804. };
  805. // A full format specifier.
  806. struct FormatSpec : AlignSpec {
  807. unsigned flags_;
  808. int precision_;
  809. char type_;
  810. FormatSpec(
  811. unsigned width = 0, char type = 0, wchar_t fill = ' ')
  812. : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {}
  813. bool sign_flag() const { return (flags_ & SIGN_FLAG) != 0; }
  814. bool plus_flag() const { return (flags_ & PLUS_FLAG) != 0; }
  815. bool hash_flag() const { return (flags_ & HASH_FLAG) != 0; }
  816. int precision() const { return precision_; }
  817. char type() const { return type_; }
  818. };
  819. // An integer format specifier.
  820. template <typename T, typename SpecT = TypeSpec<0>, typename Char = char>
  821. class IntFormatSpec : public SpecT {
  822. private:
  823. T value_;
  824. public:
  825. IntFormatSpec(T value, const SpecT &spec = SpecT())
  826. : SpecT(spec), value_(value) {}
  827. T value() const { return value_; }
  828. };
  829. // A string format specifier.
  830. template <typename T>
  831. class StrFormatSpec : public AlignSpec {
  832. private:
  833. const T *str_;
  834. public:
  835. StrFormatSpec(const T *str, unsigned width, wchar_t fill)
  836. : AlignSpec(width, fill), str_(str) {}
  837. const T *str() const { return str_; }
  838. };
  839. /**
  840. Returns an integer format specifier to format the value in base 2.
  841. */
  842. IntFormatSpec<int, TypeSpec<'b'> > bin(int value);
  843. /**
  844. Returns an integer format specifier to format the value in base 8.
  845. */
  846. IntFormatSpec<int, TypeSpec<'o'> > oct(int value);
  847. /**
  848. Returns an integer format specifier to format the value in base 16 using
  849. lower-case letters for the digits above 9.
  850. */
  851. IntFormatSpec<int, TypeSpec<'x'> > hex(int value);
  852. /**
  853. Returns an integer formatter format specifier to format in base 16 using
  854. upper-case letters for the digits above 9.
  855. */
  856. IntFormatSpec<int, TypeSpec<'X'> > hexu(int value);
  857. /**
  858. \rst
  859. Returns an integer format specifier to pad the formatted argument with the
  860. fill character to the specified width using the default (right) numeric
  861. alignment.
  862. **Example**::
  863. Writer out;
  864. out << pad(hex(0xcafe), 8, '0');
  865. // out.str() == "0000cafe"
  866. \endrst
  867. */
  868. template <char TYPE_CODE, typename Char>
  869. IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(
  870. int value, unsigned width, Char fill = ' ');
  871. #define FMT_DEFINE_INT_FORMATTERS(TYPE) \
  872. inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \
  873. return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \
  874. } \
  875. \
  876. inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \
  877. return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \
  878. } \
  879. \
  880. inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \
  881. return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \
  882. } \
  883. \
  884. inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \
  885. return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \
  886. } \
  887. \
  888. template <char TYPE_CODE> \
  889. inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \
  890. IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \
  891. return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \
  892. f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \
  893. } \
  894. \
  895. /* For compatibility with older compilers we provide two overloads for pad, */ \
  896. /* one that takes a fill character and one that doesn't. In the future this */ \
  897. /* can be replaced with one overload making the template argument Char */ \
  898. /* default to char (C++11). */ \
  899. template <char TYPE_CODE, typename Char> \
  900. inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \
  901. IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \
  902. unsigned width, Char fill) { \
  903. return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \
  904. f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \
  905. } \
  906. \
  907. inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \
  908. TYPE value, unsigned width) { \
  909. return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \
  910. value, AlignTypeSpec<0>(width, ' ')); \
  911. } \
  912. \
  913. template <typename Char> \
  914. inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \
  915. TYPE value, unsigned width, Char fill) { \
  916. return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \
  917. value, AlignTypeSpec<0>(width, fill)); \
  918. }
  919. FMT_DEFINE_INT_FORMATTERS(int)
  920. FMT_DEFINE_INT_FORMATTERS(long)
  921. FMT_DEFINE_INT_FORMATTERS(unsigned)
  922. FMT_DEFINE_INT_FORMATTERS(unsigned long)
  923. FMT_DEFINE_INT_FORMATTERS(LongLong)
  924. FMT_DEFINE_INT_FORMATTERS(ULongLong)
  925. /**
  926. \rst
  927. Returns a string formatter that pads the formatted argument with the fill
  928. character to the specified width using the default (left) string alignment.
  929. **Example**::
  930. std::string s = str(Writer() << pad("abc", 8));
  931. // s == "abc "
  932. \endrst
  933. */
  934. template <typename Char>
  935. inline StrFormatSpec<Char> pad(
  936. const Char *str, unsigned width, Char fill = ' ') {
  937. return StrFormatSpec<Char>(str, width, fill);
  938. }
  939. inline StrFormatSpec<wchar_t> pad(
  940. const wchar_t *str, unsigned width, char fill = ' ') {
  941. return StrFormatSpec<wchar_t>(str, width, fill);
  942. }
  943. // Generates a comma-separated list with results of applying f to numbers 0..n-1.
  944. # define FMT_GEN(n, f) FMT_GEN##n(f)
  945. # define FMT_GEN1(f) f(0)
  946. # define FMT_GEN2(f) FMT_GEN1(f), f(1)
  947. # define FMT_GEN3(f) FMT_GEN2(f), f(2)
  948. # define FMT_GEN4(f) FMT_GEN3(f), f(3)
  949. # define FMT_GEN5(f) FMT_GEN4(f), f(4)
  950. # define FMT_GEN6(f) FMT_GEN5(f), f(5)
  951. # define FMT_GEN7(f) FMT_GEN6(f), f(6)
  952. # define FMT_GEN8(f) FMT_GEN7(f), f(7)
  953. # define FMT_GEN9(f) FMT_GEN8(f), f(8)
  954. # define FMT_GEN10(f) FMT_GEN9(f), f(9)
  955. # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n
  956. # define FMT_MAKE_ARG(n) const T##n &v##n
  957. # define FMT_MAKE_REF_char(n) fmt::internal::MakeArg<char>(v##n)
  958. # define FMT_MAKE_REF_wchar_t(n) fmt::internal::MakeArg<wchar_t>(v##n)
  959. #if FMT_USE_VARIADIC_TEMPLATES
  960. // Defines a variadic function returning void.
  961. # define FMT_VARIADIC_VOID(func, arg_type) \
  962. template<typename... Args> \
  963. void func(arg_type arg1, const Args & ... args) { \
  964. using fmt::internal::Arg; \
  965. const Arg arg_array[fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
  966. fmt::internal::MakeArg<Char>(args)... \
  967. }; \
  968. func(arg1, ArgList(arg_array, sizeof...(Args))); \
  969. }
  970. // Defines a variadic constructor.
  971. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
  972. template<typename... Args> \
  973. ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \
  974. using fmt::internal::Arg; \
  975. const Arg arg_array[fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
  976. fmt::internal::MakeArg<Char>(args)... \
  977. }; \
  978. func(arg0, arg1, ArgList(arg_array, sizeof...(Args))); \
  979. }
  980. #else
  981. # define FMT_MAKE_REF(n) fmt::internal::MakeArg<Char>(v##n)
  982. // Defines a wrapper for a function taking one argument of type arg_type
  983. // and n additional arguments of arbitrary types.
  984. # define FMT_WRAP1(func, arg_type, n) \
  985. template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
  986. inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
  987. const fmt::internal::Arg args[] = {FMT_GEN(n, FMT_MAKE_REF)}; \
  988. func(arg1, fmt::ArgList(args, sizeof(args) / sizeof(*args))); \
  989. }
  990. // Emulates a variadic function returning void on a pre-C++11 compiler.
  991. # define FMT_VARIADIC_VOID(func, arg_type) \
  992. FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \
  993. FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \
  994. FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \
  995. FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \
  996. FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10)
  997. # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \
  998. template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
  999. ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
  1000. const fmt::internal::Arg args[] = {FMT_GEN(n, FMT_MAKE_REF)}; \
  1001. func(arg0, arg1, fmt::ArgList(args, sizeof(args) / sizeof(*args))); \
  1002. }
  1003. // Emulates a variadic constructor on a pre-C++11 compiler.
  1004. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
  1005. FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \
  1006. FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \
  1007. FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \
  1008. FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \
  1009. FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \
  1010. FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \
  1011. FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \
  1012. FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \
  1013. FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \
  1014. FMT_CTOR(ctor, func, arg0_type, arg1_type, 10)
  1015. #endif
  1016. // Generates a comma-separated list with results of applying f to pairs
  1017. // (argument, index).
  1018. #define FMT_FOR_EACH1(f, x0) f(x0, 0)
  1019. #define FMT_FOR_EACH2(f, x0, x1) \
  1020. FMT_FOR_EACH1(f, x0), f(x1, 1)
  1021. #define FMT_FOR_EACH3(f, x0, x1, x2) \
  1022. FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2)
  1023. #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \
  1024. FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3)
  1025. #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \
  1026. FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4)
  1027. #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \
  1028. FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5)
  1029. #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \
  1030. FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6)
  1031. #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \
  1032. FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7)
  1033. #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \
  1034. FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8)
  1035. #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \
  1036. FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9)
  1037. /**
  1038. An error returned by an operating system or a language runtime,
  1039. for example a file opening error.
  1040. */
  1041. class SystemError : public internal::RuntimeError {
  1042. private:
  1043. void init(int error_code, StringRef format_str, const ArgList &args);
  1044. protected:
  1045. int error_code_;
  1046. typedef char Char; // For FMT_VARIADIC_CTOR.
  1047. SystemError() {}
  1048. public:
  1049. /**
  1050. \rst
  1051. Constructs a :cpp:class:`fmt::SystemError` object with the description
  1052. of the form "*<message>*: *<system-message>*", where *<message>* is the
  1053. formatted message and *<system-message>* is the system message corresponding
  1054. to the error code.
  1055. *error_code* is a system error code as given by ``errno``.
  1056. \endrst
  1057. */
  1058. SystemError(int error_code, StringRef message) {
  1059. init(error_code, message, ArgList());
  1060. }
  1061. FMT_VARIADIC_CTOR(SystemError, init, int, StringRef)
  1062. int error_code() const { return error_code_; }
  1063. };
  1064. /**
  1065. \rst
  1066. This template provides operations for formatting and writing data into
  1067. a character stream. The output is stored in a memory buffer that grows
  1068. dynamically.
  1069. You can use one of the following typedefs for common character types:
  1070. +---------+----------------------+
  1071. | Type | Definition |
  1072. +=========+======================+
  1073. | Writer | BasicWriter<char> |
  1074. +---------+----------------------+
  1075. | WWriter | BasicWriter<wchar_t> |
  1076. +---------+----------------------+
  1077. **Example**::
  1078. Writer out;
  1079. out << "The answer is " << 42 << "\n";
  1080. out.write("({:+f}, {:+f})", -3.14, 3.14);
  1081. This will write the following output to the ``out`` object:
  1082. .. code-block:: none
  1083. The answer is 42
  1084. (-3.140000, +3.140000)
  1085. The output can be converted to an ``std::string`` with ``out.str()`` or
  1086. accessed as a C string with ``out.c_str()``.
  1087. \endrst
  1088. */
  1089. template <typename Char>
  1090. class BasicWriter {
  1091. private:
  1092. // Output buffer.
  1093. mutable internal::Array<Char, internal::INLINE_BUFFER_SIZE> buffer_;
  1094. typedef typename internal::CharTraits<Char>::CharPtr CharPtr;
  1095. #if _SECURE_SCL
  1096. static Char *GetBase(CharPtr p) { return p.base(); }
  1097. #else
  1098. static Char *GetBase(Char *p) { return p; }
  1099. #endif
  1100. static CharPtr FillPadding(CharPtr buffer,
  1101. unsigned total_size, std::size_t content_size, wchar_t fill);
  1102. // Grows the buffer by n characters and returns a pointer to the newly
  1103. // allocated area.
  1104. CharPtr GrowBuffer(std::size_t n) {
  1105. std::size_t size = buffer_.size();
  1106. buffer_.resize(size + n);
  1107. return internal::CheckPtr(&buffer_[size], n);
  1108. }
  1109. // Prepare a buffer for integer formatting.
  1110. CharPtr PrepareBufferForInt(unsigned num_digits,
  1111. const EmptySpec &, const char *prefix, unsigned prefix_size) {
  1112. unsigned size = prefix_size + num_digits;
  1113. CharPtr p = GrowBuffer(size);
  1114. std::copy(prefix, prefix + prefix_size, p);
  1115. return p + size - 1;
  1116. }
  1117. template <typename Spec>
  1118. CharPtr PrepareBufferForInt(unsigned num_digits,
  1119. const Spec &spec, const char *prefix, unsigned prefix_size);
  1120. // Formats an integer.
  1121. template <typename T, typename Spec>
  1122. void FormatInt(T value, const Spec &spec);
  1123. // Formats a floating-point number (double or long double).
  1124. template <typename T>
  1125. void FormatDouble(T value, const FormatSpec &spec);
  1126. // Writes a formatted string.
  1127. template <typename StringChar>
  1128. CharPtr write_str(
  1129. const StringChar *s, std::size_t size, const AlignSpec &spec);
  1130. template <typename StringChar>
  1131. void write_str(
  1132. const internal::Arg::StringValue<StringChar> &str, const FormatSpec &spec);
  1133. // This method is private to disallow writing a wide string to a
  1134. // char stream and vice versa. If you want to print a wide string
  1135. // as a pointer as std::ostream does, cast it to const void*.
  1136. // Do not implement!
  1137. void operator<<(typename internal::CharTraits<Char>::UnsupportedStrType);
  1138. friend class internal::ArgFormatter<Char>;
  1139. friend class BasicFormatter<Char>;
  1140. friend class internal::PrintfParser<Char>;
  1141. public:
  1142. /**
  1143. Constructs a ``BasicWriter`` object.
  1144. */
  1145. BasicWriter() {}
  1146. #if FMT_USE_RVALUE_REFERENCES
  1147. /**
  1148. Constructs a ``BasicWriter`` object moving the content of the other
  1149. object to it.
  1150. */
  1151. BasicWriter(BasicWriter &&other) : buffer_(std::move(other.buffer_)) {}
  1152. /**
  1153. Moves the content of the other ``BasicWriter`` object to this one.
  1154. */
  1155. BasicWriter& operator=(BasicWriter &&other) {
  1156. assert(this != &other);
  1157. buffer_ = std::move(other.buffer_);
  1158. return *this;
  1159. }
  1160. #endif
  1161. /**
  1162. Returns the total number of characters written.
  1163. */
  1164. std::size_t size() const { return buffer_.size(); }
  1165. /**
  1166. Returns a pointer to the output buffer content. No terminating null
  1167. character is appended.
  1168. */
  1169. const Char *data() const { return &buffer_[0]; }
  1170. /**
  1171. Returns a pointer to the output buffer content with terminating null
  1172. character appended.
  1173. */
  1174. const Char *c_str() const {
  1175. std::size_t size = buffer_.size();
  1176. buffer_.reserve(size + 1);
  1177. buffer_[size] = '\0';
  1178. return &buffer_[0];
  1179. }
  1180. /**
  1181. Returns the content of the output buffer as an `std::string`.
  1182. */
  1183. std::basic_string<Char> str() const {
  1184. return std::basic_string<Char>(&buffer_[0], buffer_.size());
  1185. }
  1186. /**
  1187. \rst
  1188. Writes formatted data.
  1189. *args* is an argument list representing arbitrary arguments.
  1190. **Example**::
  1191. Writer out;
  1192. out.write("Current point:\n");
  1193. out.write("({:+f}, {:+f})", -3.14, 3.14);
  1194. This will write the following output to the ``out`` object:
  1195. .. code-block:: none
  1196. Current point:
  1197. (-3.140000, +3.140000)
  1198. The output can be accessed using :meth:`data`, :meth:`c_str` or :meth:`str`
  1199. methods.
  1200. See also `Format String Syntax`_.
  1201. \endrst
  1202. */
  1203. void write(BasicStringRef<Char> format, const ArgList &args) {
  1204. BasicFormatter<Char>(*this).Format(format, args);
  1205. }
  1206. FMT_VARIADIC_VOID(write, fmt::BasicStringRef<Char>)
  1207. BasicWriter &operator<<(int value) {
  1208. return *this << IntFormatSpec<int>(value);
  1209. }
  1210. BasicWriter &operator<<(unsigned value) {
  1211. return *this << IntFormatSpec<unsigned>(value);
  1212. }
  1213. BasicWriter &operator<<(long value) {
  1214. return *this << IntFormatSpec<long>(value);
  1215. }
  1216. BasicWriter &operator<<(unsigned long value) {
  1217. return *this << IntFormatSpec<unsigned long>(value);
  1218. }
  1219. BasicWriter &operator<<(LongLong value) {
  1220. return *this << IntFormatSpec<LongLong>(value);
  1221. }
  1222. /**
  1223. Formats *value* and writes it to the stream.
  1224. */
  1225. BasicWriter &operator<<(ULongLong value) {
  1226. return *this << IntFormatSpec<ULongLong>(value);
  1227. }
  1228. BasicWriter &operator<<(double value) {
  1229. FormatDouble(value, FormatSpec());
  1230. return *this;
  1231. }
  1232. /**
  1233. Formats *value* using the general format for floating-point numbers
  1234. (``'g'``) and writes it to the stream.
  1235. */
  1236. BasicWriter &operator<<(long double value) {
  1237. FormatDouble(value, FormatSpec());
  1238. return *this;
  1239. }
  1240. /**
  1241. Writes a character to the stream.
  1242. */
  1243. BasicWriter &operator<<(char value) {
  1244. *GrowBuffer(1) = value;
  1245. return *this;
  1246. }
  1247. BasicWriter &operator<<(wchar_t value) {
  1248. *GrowBuffer(1) = internal::CharTraits<Char>::convert(value);
  1249. return *this;
  1250. }
  1251. /**
  1252. Writes *value* to the stream.
  1253. */
  1254. BasicWriter &operator<<(const fmt::BasicStringRef<Char> value) {
  1255. const Char *str = value.c_str();
  1256. std::size_t size = value.size();
  1257. std::copy(str, str + size, GrowBuffer(size));
  1258. return *this;
  1259. }
  1260. template <typename T, typename Spec, typename FillChar>
  1261. BasicWriter &operator<<(const IntFormatSpec<T, Spec, FillChar> &spec) {
  1262. internal::CharTraits<Char>::convert(FillChar());
  1263. FormatInt(spec.value(), spec);
  1264. return *this;
  1265. }
  1266. template <typename StringChar>
  1267. BasicWriter &operator<<(const StrFormatSpec<StringChar> &spec) {
  1268. const StringChar *s = spec.str();
  1269. // TODO: error if fill is not convertible to Char
  1270. write_str(s, std::char_traits<Char>::length(s), spec);
  1271. return *this;
  1272. }
  1273. void clear() { buffer_.clear(); }
  1274. };
  1275. template <typename Char>
  1276. template <typename StringChar>
  1277. typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str(
  1278. const StringChar *s, std::size_t size, const AlignSpec &spec) {
  1279. CharPtr out = CharPtr();
  1280. if (spec.width() > size) {
  1281. out = GrowBuffer(spec.width());
  1282. Char fill = static_cast<Char>(spec.fill());
  1283. if (spec.align() == ALIGN_RIGHT) {
  1284. std::fill_n(out, spec.width() - size, fill);
  1285. out += spec.width() - size;
  1286. } else if (spec.align() == ALIGN_CENTER) {
  1287. out = FillPadding(out, spec.width(), size, fill);
  1288. } else {
  1289. std::fill_n(out + size, spec.width() - size, fill);
  1290. }
  1291. } else {
  1292. out = GrowBuffer(size);
  1293. }
  1294. std::copy(s, s + size, out);
  1295. return out;
  1296. }
  1297. template <typename Char>
  1298. template <typename Spec>
  1299. typename fmt::BasicWriter<Char>::CharPtr
  1300. fmt::BasicWriter<Char>::PrepareBufferForInt(
  1301. unsigned num_digits, const Spec &spec,
  1302. const char *prefix, unsigned prefix_size) {
  1303. unsigned width = spec.width();
  1304. Alignment align = spec.align();
  1305. Char fill = static_cast<Char>(spec.fill());
  1306. if (spec.precision() > static_cast<int>(num_digits)) {
  1307. // Octal prefix '0' is counted as a digit, so ignore it if precision
  1308. // is specified.
  1309. if (prefix_size > 0 && prefix[prefix_size - 1] == '0')
  1310. --prefix_size;
  1311. unsigned number_size = prefix_size + spec.precision();
  1312. AlignSpec subspec(number_size, '0', ALIGN_NUMERIC);
  1313. if (number_size >= width)
  1314. return PrepareBufferForInt(num_digits, subspec, prefix, prefix_size);
  1315. buffer_.reserve(width);
  1316. unsigned fill_size = width - number_size;
  1317. if (align != ALIGN_LEFT) {
  1318. CharPtr p = GrowBuffer(fill_size);
  1319. std::fill(p, p + fill_size, fill);
  1320. }
  1321. CharPtr result = PrepareBufferForInt(num_digits, subspec, prefix, prefix_size);
  1322. if (align == ALIGN_LEFT) {
  1323. CharPtr p = GrowBuffer(fill_size);
  1324. std::fill(p, p + fill_size, fill);
  1325. }
  1326. return result;
  1327. }
  1328. unsigned size = prefix_size + num_digits;
  1329. if (width <= size) {
  1330. CharPtr p = GrowBuffer(size);
  1331. std::copy(prefix, prefix + prefix_size, p);
  1332. return p + size - 1;
  1333. }
  1334. CharPtr p = GrowBuffer(width);
  1335. CharPtr end = p + width;
  1336. if (align == ALIGN_LEFT) {
  1337. std::copy(prefix, prefix + prefix_size, p);
  1338. p += size;
  1339. std::fill(p, end, fill);
  1340. } else if (align == ALIGN_CENTER) {
  1341. p = FillPadding(p, width, size, fill);
  1342. std::copy(prefix, prefix + prefix_size, p);
  1343. p += size;
  1344. } else {
  1345. if (align == ALIGN_NUMERIC) {
  1346. if (prefix_size != 0) {
  1347. p = std::copy(prefix, prefix + prefix_size, p);
  1348. size -= prefix_size;
  1349. }
  1350. } else {
  1351. std::copy(prefix, prefix + prefix_size, end - size);
  1352. }
  1353. std::fill(p, end - size, fill);
  1354. p = end;
  1355. }
  1356. return p - 1;
  1357. }
  1358. template <typename Char>
  1359. template <typename T, typename Spec>
  1360. void BasicWriter<Char>::FormatInt(T value, const Spec &spec) {
  1361. unsigned prefix_size = 0;
  1362. typedef typename internal::IntTraits<T>::MainType UnsignedType;
  1363. UnsignedType abs_value = value;
  1364. char prefix[4] = "";
  1365. if (internal::IsNegative(value)) {
  1366. prefix[0] = '-';
  1367. ++prefix_size;
  1368. abs_value = 0 - abs_value;
  1369. } else if (spec.sign_flag()) {
  1370. prefix[0] = spec.plus_flag() ? '+' : ' ';
  1371. ++prefix_size;
  1372. }
  1373. switch (spec.type()) {
  1374. case 0: case 'd': {
  1375. unsigned num_digits = internal::CountDigits(abs_value);
  1376. CharPtr p = PrepareBufferForInt(
  1377. num_digits, spec, prefix, prefix_size) + 1 - num_digits;
  1378. internal::FormatDecimal(GetBase(p), abs_value, num_digits);
  1379. break;
  1380. }
  1381. case 'x': case 'X': {
  1382. UnsignedType n = abs_value;
  1383. if (spec.hash_flag()) {
  1384. prefix[prefix_size++] = '0';
  1385. prefix[prefix_size++] = spec.type();
  1386. }
  1387. unsigned num_digits = 0;
  1388. do {
  1389. ++num_digits;
  1390. } while ((n >>= 4) != 0);
  1391. Char *p = GetBase(PrepareBufferForInt(
  1392. num_digits, spec, prefix, prefix_size));
  1393. n = abs_value;
  1394. const char *digits = spec.type() == 'x' ?
  1395. "0123456789abcdef" : "0123456789ABCDEF";
  1396. do {
  1397. *p-- = digits[n & 0xf];
  1398. } while ((n >>= 4) != 0);
  1399. break;
  1400. }
  1401. case 'b': case 'B': {
  1402. UnsignedType n = abs_value;
  1403. if (spec.hash_flag()) {
  1404. prefix[prefix_size++] = '0';
  1405. prefix[prefix_size++] = spec.type();
  1406. }
  1407. unsigned num_digits = 0;
  1408. do {
  1409. ++num_digits;
  1410. } while ((n >>= 1) != 0);
  1411. Char *p = GetBase(PrepareBufferForInt(num_digits, spec, prefix, prefix_size));
  1412. n = abs_value;
  1413. do {
  1414. *p-- = '0' + (n & 1);
  1415. } while ((n >>= 1) != 0);
  1416. break;
  1417. }
  1418. case 'o': {
  1419. UnsignedType n = abs_value;
  1420. if (spec.hash_flag())
  1421. prefix[prefix_size++] = '0';
  1422. unsigned num_digits = 0;
  1423. do {
  1424. ++num_digits;
  1425. } while ((n >>= 3) != 0);
  1426. Char *p = GetBase(PrepareBufferForInt(
  1427. num_digits, spec, prefix, prefix_size));
  1428. n = abs_value;
  1429. do {
  1430. *p-- = '0' + (n & 7);
  1431. } while ((n >>= 3) != 0);
  1432. break;
  1433. }
  1434. default:
  1435. internal::ReportUnknownType(spec.type(), "integer");
  1436. break;
  1437. }
  1438. }
  1439. // Formats a value.
  1440. template <typename Char, typename T>
  1441. void format(BasicFormatter<Char> &f, const Char *format_str, const T &value) {
  1442. std::basic_ostringstream<Char> os;
  1443. os << value;
  1444. f.format(format_str, internal::MakeArg<Char>(os.str()));
  1445. }
  1446. // Reports a system error without throwing an exception.
  1447. // Can be used to report errors from destructors.
  1448. void ReportSystemError(int error_code, StringRef message) FMT_NOEXCEPT(true);
  1449. #ifdef _WIN32
  1450. /**
  1451. A Windows error.
  1452. */
  1453. class WindowsError : public SystemError {
  1454. private:
  1455. void init(int error_code, StringRef format_str, const ArgList &args);
  1456. public:
  1457. /**
  1458. \rst
  1459. Constructs a :cpp:class:`fmt::WindowsError` object with the description
  1460. of the form "*<message>*: *<system-message>*", where *<message>* is the
  1461. formatted message and *<system-message>* is the system message corresponding
  1462. to the error code.
  1463. *error_code* is a Windows error code as given by ``GetLastError``.
  1464. \endrst
  1465. */
  1466. WindowsError(int error_code, StringRef message) {
  1467. init(error_code, message, ArgList());
  1468. }
  1469. FMT_VARIADIC_CTOR(WindowsError, init, int, StringRef)
  1470. };
  1471. // Reports a Windows error without throwing an exception.
  1472. // Can be used to report errors from destructors.
  1473. void ReportWinError(int error_code, StringRef message) FMT_NOEXCEPT(true);
  1474. #endif
  1475. enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE };
  1476. /**
  1477. Formats a string and prints it to stdout using ANSI escape sequences
  1478. to specify color (experimental).
  1479. Example:
  1480. PrintColored(fmt::RED, "Elapsed time: {0:.2f} seconds") << 1.23;
  1481. */
  1482. void print_colored(Color c, StringRef format, const ArgList &args);
  1483. /**
  1484. \rst
  1485. Formats a string similarly to Python's `str.format
  1486. <http://docs.python.org/3/library/stdtypes.html#str.format>`__ function
  1487. and returns the result as a string.
  1488. *format_str* is a format string that contains literal text and replacement
  1489. fields surrounded by braces ``{}``. The fields are replaced with formatted
  1490. arguments in the resulting string.
  1491. *args* is an argument list representing arbitrary arguments.
  1492. **Example**::
  1493. std::string message = format("The answer is {}", 42);
  1494. See also `Format String Syntax`_.
  1495. \endrst
  1496. */
  1497. inline std::string format(StringRef format_str, const ArgList &args) {
  1498. Writer w;
  1499. w.write(format_str, args);
  1500. return w.str();
  1501. }
  1502. inline std::wstring format(WStringRef format, const ArgList &args) {
  1503. WWriter w;
  1504. w.write(format, args);
  1505. return w.str();
  1506. }
  1507. /**
  1508. \rst
  1509. Prints formatted data to ``stdout``.
  1510. **Example**::
  1511. print("Elapsed time: {0:.2f} seconds", 1.23);
  1512. \endrst
  1513. */
  1514. void print(StringRef format, const ArgList &args);
  1515. /**
  1516. \rst
  1517. Prints formatted data to a file.
  1518. **Example**::
  1519. print(stderr, "Don't {}!", "panic");
  1520. \endrst
  1521. */
  1522. void print(std::FILE *f, StringRef format, const ArgList &args);
  1523. /**
  1524. \rst
  1525. Prints formatted data to a stream.
  1526. **Example**::
  1527. print(cerr, "Don't {}!", "panic");
  1528. \endrst
  1529. */
  1530. void print(std::ostream &os, StringRef format, const ArgList &args);
  1531. template <typename Char>
  1532. void printf(BasicWriter<Char> &w,
  1533. BasicStringRef<Char> format, const ArgList &args) {
  1534. internal::PrintfParser<Char>().Format(w, format, args);
  1535. }
  1536. inline std::string sprintf(StringRef format, const ArgList &args) {
  1537. Writer w;
  1538. printf(w, format, args);
  1539. return w.str();
  1540. }
  1541. void printf(StringRef format, const ArgList &args);
  1542. /**
  1543. Fast integer formatter.
  1544. */
  1545. class FormatInt {
  1546. private:
  1547. // Buffer should be large enough to hold all digits (digits10 + 1),
  1548. // a sign and a null character.
  1549. enum {BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3};
  1550. mutable char buffer_[BUFFER_SIZE];
  1551. char *str_;
  1552. // Formats value in reverse and returns the number of digits.
  1553. char *FormatDecimal(ULongLong value) {
  1554. char *buffer_end = buffer_ + BUFFER_SIZE - 1;
  1555. while (value >= 100) {
  1556. // Integer division is slow so do it for a group of two digits instead
  1557. // of for every digit. The idea comes from the talk by Alexandrescu
  1558. // "Three Optimization Tips for C++". See speed-test for a comparison.
  1559. unsigned index = (value % 100) * 2;
  1560. value /= 100;
  1561. *--buffer_end = internal::DIGITS[index + 1];
  1562. *--buffer_end = internal::DIGITS[index];
  1563. }
  1564. if (value < 10) {
  1565. *--buffer_end = static_cast<char>('0' + value);
  1566. return buffer_end;
  1567. }
  1568. unsigned index = static_cast<unsigned>(value * 2);
  1569. *--buffer_end = internal::DIGITS[index + 1];
  1570. *--buffer_end = internal::DIGITS[index];
  1571. return buffer_end;
  1572. }
  1573. void FormatSigned(LongLong value) {
  1574. ULongLong abs_value = value;
  1575. bool negative = value < 0;
  1576. if (negative)
  1577. abs_value = 0 - value;
  1578. str_ = FormatDecimal(abs_value);
  1579. if (negative)
  1580. *--str_ = '-';
  1581. }
  1582. public:
  1583. explicit FormatInt(int value) { FormatSigned(value); }
  1584. explicit FormatInt(long value) { FormatSigned(value); }
  1585. explicit FormatInt(LongLong value) { FormatSigned(value); }
  1586. explicit FormatInt(unsigned value) : str_(FormatDecimal(value)) {}
  1587. explicit FormatInt(unsigned long value) : str_(FormatDecimal(value)) {}
  1588. explicit FormatInt(ULongLong value) : str_(FormatDecimal(value)) {}
  1589. /**
  1590. Returns the number of characters written to the output buffer.
  1591. */
  1592. std::size_t size() const { return buffer_ - str_ + BUFFER_SIZE - 1; }
  1593. /**
  1594. Returns a pointer to the output buffer content. No terminating null
  1595. character is appended.
  1596. */
  1597. const char *data() const { return str_; }
  1598. /**
  1599. Returns a pointer to the output buffer content with terminating null
  1600. character appended.
  1601. */
  1602. const char *c_str() const {
  1603. buffer_[BUFFER_SIZE - 1] = '\0';
  1604. return str_;
  1605. }
  1606. /**
  1607. Returns the content of the output buffer as an `std::string`.
  1608. */
  1609. std::string str() const { return std::string(str_, size()); }
  1610. };
  1611. // Formats a decimal integer value writing into buffer and returns
  1612. // a pointer to the end of the formatted string. This function doesn't
  1613. // write a terminating null character.
  1614. template <typename T>
  1615. inline void FormatDec(char *&buffer, T value) {
  1616. typename internal::IntTraits<T>::MainType abs_value = value;
  1617. if (internal::IsNegative(value)) {
  1618. *buffer++ = '-';
  1619. abs_value = 0 - abs_value;
  1620. }
  1621. if (abs_value < 100) {
  1622. if (abs_value < 10) {
  1623. *buffer++ = static_cast<char>('0' + abs_value);
  1624. return;
  1625. }
  1626. unsigned index = static_cast<unsigned>(abs_value * 2);
  1627. *buffer++ = internal::DIGITS[index];
  1628. *buffer++ = internal::DIGITS[index + 1];
  1629. return;
  1630. }
  1631. unsigned num_digits = internal::CountDigits(abs_value);
  1632. internal::FormatDecimal(buffer, abs_value, num_digits);
  1633. buffer += num_digits;
  1634. }
  1635. }
  1636. #if FMT_GCC_VERSION
  1637. // Use the system_header pragma to suppress warnings about variadic macros
  1638. // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't work.
  1639. // It is used at the end because we want to suppress as little warnings as
  1640. // possible.
  1641. # pragma GCC system_header
  1642. #endif
  1643. // This is used to work around VC++ bugs in handling variadic macros.
  1644. #define FMT_EXPAND(args) args
  1645. // Returns the number of arguments.
  1646. // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s.
  1647. #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N())
  1648. #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__))
  1649. #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  1650. #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
  1651. #define FMT_CONCAT(a, b) a##b
  1652. #define FMT_FOR_EACH_(N, f, ...) \
  1653. FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__))
  1654. #define FMT_FOR_EACH(f, ...) \
  1655. FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__))
  1656. #define FMT_ADD_ARG_NAME(type, index) type arg##index
  1657. #define FMT_GET_ARG_NAME(type, index) arg##index
  1658. #if FMT_USE_VARIADIC_TEMPLATES
  1659. # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
  1660. template<typename... Args> \
  1661. ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
  1662. const Args & ... args) { \
  1663. using fmt::internal::Arg; \
  1664. const Arg array[fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
  1665. fmt::internal::MakeArg<Char>(args)... \
  1666. }; \
  1667. call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \
  1668. fmt::ArgList(array, sizeof...(Args))); \
  1669. }
  1670. #else
  1671. // Defines a wrapper for a function taking __VA_ARGS__ arguments
  1672. // and n additional arguments of arbitrary types.
  1673. # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \
  1674. template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
  1675. inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
  1676. FMT_GEN(n, FMT_MAKE_ARG)) { \
  1677. const fmt::internal::Arg args[] = {FMT_GEN(n, FMT_MAKE_REF_##Char)}; \
  1678. call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \
  1679. fmt::ArgList(args, sizeof(args) / sizeof(*args))); \
  1680. }
  1681. # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
  1682. inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \
  1683. call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \
  1684. } \
  1685. FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \
  1686. FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \
  1687. FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \
  1688. FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \
  1689. FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \
  1690. FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \
  1691. FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \
  1692. FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \
  1693. FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \
  1694. FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__)
  1695. #endif // FMT_USE_VARIADIC_TEMPLATES
  1696. /**
  1697. \rst
  1698. Defines a variadic function with the specified return type, function name
  1699. and argument types passed as variable arguments to this macro.
  1700. **Example**::
  1701. void print_error(const char *file, int line, const char *format,
  1702. const fmt::ArgList &args) {
  1703. fmt::print("{}: {}: ", file, line);
  1704. fmt::print(format, args);
  1705. }
  1706. FMT_VARIADIC(void, print_error, const char *, int, const char *)
  1707. \endrst
  1708. */
  1709. #define FMT_VARIADIC(ReturnType, func, ...) \
  1710. FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__)
  1711. #define FMT_VARIADIC_W(ReturnType, func, ...) \
  1712. FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__)
  1713. namespace fmt {
  1714. FMT_VARIADIC(std::string, format, StringRef)
  1715. FMT_VARIADIC_W(std::wstring, format, WStringRef)
  1716. FMT_VARIADIC(void, print, StringRef)
  1717. FMT_VARIADIC(void, print, std::FILE *, StringRef)
  1718. FMT_VARIADIC(void, print, std::ostream &, StringRef)
  1719. FMT_VARIADIC(void, print_colored, Color, StringRef)
  1720. FMT_VARIADIC(std::string, sprintf, StringRef)
  1721. FMT_VARIADIC(void, printf, StringRef)
  1722. }
  1723. // Restore warnings.
  1724. #if FMT_GCC_VERSION >= 406
  1725. # pragma GCC diagnostic pop
  1726. #endif
  1727. #endif // FMT_FORMAT_H_