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