1 /*
2 Forked form cppformat (original author Victor Zverovich)
3 */
4
5 #ifndef FMT_FORMAT_HPP_
6 #define FMT_FORMAT_HPP_
7
8 #include <stdint.h>
9
10 #include <cassert>
11 #include <cmath>
12 #include <cstddef> // for std::ptrdiff_t
13 #include <cstdio>
14 #include <algorithm>
15 #include <limits>
16 #include <stdexcept>
17 #include <string>
18 #include <sstream>
19
20 // define A_LIB_NAMESPACE to empty if not define
21 // trigger compilation error if not defined properly
22 #ifndef A_LIB_NAMESPACE
23 #error "A_LIB_NAMESPACE need to be defined"
24 #endif
25
26 namespace A_LIB_NAMESPACE {
27
28
29 #if _SECURE_SCL
30 # include <iterator>
31 #endif
32
33 #ifdef __GNUC__
34 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
35 # define FMT_GCC_EXTENSION __extension__
36 // Disable warning about "long long" which is sometimes reported even
37 // when using __extension__.
38 # if FMT_GCC_VERSION >= 406
39 # pragma GCC diagnostic push
40 # pragma GCC diagnostic ignored "-Wlong-long"
41 # endif
42 #else
43 # define FMT_GCC_EXTENSION
44 #endif
45
46 #ifdef __GNUC_LIBSTD__
47 # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
48 #endif
49
50 #ifdef __has_feature
51 # define FMT_HAS_FEATURE(x) __has_feature(x)
52 #else
53 # define FMT_HAS_FEATURE(x) 0
54 #endif
55
56 #ifdef __has_builtin
57 # define FMT_HAS_BUILTIN(x) __has_builtin(x)
58 #else
59 # define FMT_HAS_BUILTIN(x) 0
60 #endif
61
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
71 #ifndef FMT_USE_RVALUE_REFERENCES
72 // Don't use rvalue references when compiling with clang and an old libstdc++
73 // as the latter doesn't provide std::move.
74 # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402
75 # define FMT_USE_RVALUE_REFERENCES 0
76 # else
77 # define FMT_USE_RVALUE_REFERENCES \
78 (FMT_HAS_FEATURE(cxx_rvalue_references) || \
79 (FMT_GCC_VERSION >= 403 && __cplusplus >= 201103) || _MSC_VER >= 1600)
80 # endif
81 #endif
82
83 #if FMT_USE_RVALUE_REFERENCES
84 # include <utility> // for std::move
85 #endif
86
87 // Define FMT_USE_NOEXCEPT to make C++ Format use noexcept (C++11 feature).
88 #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
89 (FMT_GCC_VERSION >= 408 && __cplusplus >= 201103)
90 # define FMT_NOEXCEPT(expr) noexcept(expr)
91 #else
92 # define FMT_NOEXCEPT(expr)
93 #endif
94
95 // A macro to disallow the copy constructor and operator= functions
96 // This should be used in the private: declarations for a class
97 #define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
98 TypeName(const TypeName&); \
99 void operator=(const TypeName&)
100
101 namespace fmt {
102
103 // Fix the warning about long long on older versions of GCC
104 // that don't support the diagnostic pragma.
105 FMT_GCC_EXTENSION typedef long long LongLong;
106 FMT_GCC_EXTENSION typedef unsigned long long ULongLong;
107
108 #if FMT_USE_RVALUE_REFERENCES
109 using std::move;
110 #endif
111
112 template <typename Char>
113 class BasicWriter;
114
115 typedef BasicWriter<char> Writer;
116 typedef BasicWriter<wchar_t> WWriter;
117
118 template <typename Char>
119 class BasicFormatter;
120
121 template <typename Char, typename T>
122 void format(BasicFormatter<Char> &f, const Char *&format_str, const T &value);
123
124 /**
125 \rst
126 A string reference. It can be constructed from a C string or
127 ``std::string``.
128
129 You can use one of the following typedefs for common character types:
130
131 +------------+-------------------------+
132 | Type | Definition |
133 +============+=========================+
134 | StringRef | BasicStringRef<char> |
135 +------------+-------------------------+
136 | WStringRef | BasicStringRef<wchar_t> |
137 +------------+-------------------------+
138
139 This class is most useful as a parameter type to allow passing
140 different types of strings to a function, for example::
141
142 template <typename... Args>
143 std::string format(StringRef format, const Args & ... args);
144
145 format("{}", 42);
146 format(std::string("{}"), 42);
147 \endrst
148 */
149 template <typename Char>
150 class BasicStringRef {
151 private:
152 const Char *data_;
153 std::size_t size_;
154
155 public:
156 /**
157 Constructs a string reference object from a C string and a size.
158 */
BasicStringRef(const Char * s,std::size_t size)159 BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {}
160
161 /**
162 Constructs a string reference object from a C string computing
163 the size with ``std::char_traits<Char>::length``.
164 */
BasicStringRef(const Char * s)165 BasicStringRef(const Char *s)
166 : data_(s), size_(std::char_traits<Char>::length(s)) {}
167
168 /**
169 Constructs a string reference from an `std::string` object.
170 */
BasicStringRef(const std::basic_string<Char> & s)171 BasicStringRef(const std::basic_string<Char> &s)
172 : data_(s.c_str()), size_(s.size()) {}
173
174 /**
175 Converts a string reference to an `std::string` object.
176 */
operator std::basic_string<Char>() const177 operator std::basic_string<Char>() const {
178 return std::basic_string<Char>(data_, size());
179 }
180
181 /**
182 Returns the pointer to a C string.
183 */
c_str() const184 const Char *c_str() const { return data_; }
185
186 /**
187 Returns the string size.
188 */
size() const189 std::size_t size() const { return size_; }
190
operator ==(BasicStringRef lhs,BasicStringRef rhs)191 friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) {
192 return lhs.data_ == rhs.data_;
193 }
operator !=(BasicStringRef lhs,BasicStringRef rhs)194 friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) {
195 return lhs.data_ != rhs.data_;
196 }
197 };
198
199 typedef BasicStringRef<char> StringRef;
200 typedef BasicStringRef<wchar_t> WStringRef;
201
202 /**
203 A formatting error such as invalid format string.
204 */
205 class FormatError : public std::runtime_error {
206 public:
FormatError(StringRef message)207 explicit FormatError(StringRef message)
208 : std::runtime_error(message.c_str()) {}
209 };
210
211 namespace internal {
212
213 // The number of characters to store in the MemoryBuffer object itself
214 // to avoid dynamic memory allocation.
215 enum { INLINE_BUFFER_SIZE = 500 };
216
217 #if _SECURE_SCL
218 // Use checked iterator to avoid warnings on MSVC.
219 template <typename T>
make_ptr(T * ptr,std::size_t size)220 inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) {
221 return stdext::checked_array_iterator<T*>(ptr, size);
222 }
223 #else
224 template <typename T>
make_ptr(T * ptr,std::size_t)225 inline T *make_ptr(T *ptr, std::size_t) { return ptr; }
226 #endif
227
228 // A buffer for POD types. It supports a subset of std::vector's operations.
229 template <typename T>
230 class Buffer {
231 private:
232 FMT_DISALLOW_COPY_AND_ASSIGN(Buffer);
233
234 protected:
235 T *ptr_;
236 std::size_t size_;
237 std::size_t capacity_;
238
Buffer(T * ptr=0,std::size_t capacity=0)239 Buffer(T *ptr = 0, std::size_t capacity = 0)
240 : ptr_(ptr), size_(0), capacity_(capacity) {}
241
242 virtual void grow(std::size_t size) = 0;
243
244 public:
~Buffer()245 virtual ~Buffer() {}
246
247 // Returns the size of this buffer.
size() const248 std::size_t size() const { return size_; }
249
250 // Returns the capacity of this buffer.
capacity() const251 std::size_t capacity() const { return capacity_; }
252
253 // Resizes the buffer. If T is a POD type new elements are not initialized.
resize(std::size_t new_size)254 void resize(std::size_t new_size) {
255 if (new_size > capacity_)
256 grow(new_size);
257 size_ = new_size;
258 }
259
260 // Reserves space to store at least capacity elements.
reserve(std::size_t capacity)261 void reserve(std::size_t capacity) {
262 if (capacity > capacity_)
263 grow(capacity);
264 }
265
clear()266 void clear() FMT_NOEXCEPT(true) { size_ = 0; }
267
push_back(const T & value)268 void push_back(const T &value) {
269 if (size_ == capacity_)
270 grow(size_ + 1);
271 ptr_[size_++] = value;
272 }
273
274 // Appends data to the end of the buffer.
275 void append(const T *begin, const T *end);
276
operator [](std::size_t index)277 T &operator[](std::size_t index) { return ptr_[index]; }
operator [](std::size_t index) const278 const T &operator[](std::size_t index) const { return ptr_[index]; }
279 };
280
281 template <typename T>
append(const T * begin,const T * end)282 void Buffer<T>::append(const T *begin, const T *end) {
283 std::ptrdiff_t num_elements = end - begin;
284 if (size_ + num_elements > capacity_)
285 grow(size_ + num_elements);
286 std::copy(begin, end, make_ptr(ptr_, capacity_) + size_);
287 size_ += num_elements;
288 }
289
290 // A memory buffer for POD types with the first SIZE elements stored in
291 // the object itself.
292 template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> >
293 class MemoryBuffer : private Allocator, public Buffer<T> {
294 private:
295 T data_[SIZE];
296
297 // Free memory allocated by the buffer.
free()298 void free() {
299 if (this->ptr_ != data_) this->deallocate(this->ptr_, this->capacity_);
300 }
301
302 protected:
303 void grow(std::size_t size);
304
305 public:
MemoryBuffer(const Allocator & alloc=Allocator ())306 explicit MemoryBuffer(const Allocator &alloc = Allocator())
307 : Allocator(alloc), Buffer<T>(data_, SIZE) {}
~MemoryBuffer()308 ~MemoryBuffer() { free(); }
309
310 #if FMT_USE_RVALUE_REFERENCES
311 private:
312 // Move data from other to this buffer.
move(MemoryBuffer & other)313 void move(MemoryBuffer &other) {
314 Allocator &this_alloc = *this, &other_alloc = other;
315 this_alloc = std::move(other_alloc);
316 this->size_ = other.size_;
317 this->capacity_ = other.capacity_;
318 if (other.ptr_ == other.data_) {
319 this->ptr_ = data_;
320 std::copy(other.data_,
321 other.data_ + this->size_, make_ptr(data_, this->capacity_));
322 } else {
323 this->ptr_ = other.ptr_;
324 // Set pointer to the inline array so that delete is not called
325 // when freeing.
326 other.ptr_ = other.data_;
327 }
328 }
329
330 public:
MemoryBuffer(MemoryBuffer && other)331 MemoryBuffer(MemoryBuffer &&other) {
332 move(other);
333 }
334
operator =(MemoryBuffer && other)335 MemoryBuffer &operator=(MemoryBuffer &&other) {
336 assert(this != &other);
337 free();
338 move(other);
339 return *this;
340 }
341 #endif
342
343 // Returns a copy of the allocator associated with this buffer.
get_allocator() const344 Allocator get_allocator() const { return *this; }
345 };
346
347 template <typename T, std::size_t SIZE, typename Allocator>
grow(std::size_t size)348 void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) {
349 std::size_t new_capacity =
350 (std::max)(size, this->capacity_ + this->capacity_ / 2);
351 T *new_ptr = this->allocate(new_capacity);
352 // The following code doesn't throw, so the raw pointer above doesn't leak.
353 std::copy(this->ptr_,
354 this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity));
355 std::size_t old_capacity = this->capacity_;
356 T *old_ptr = this->ptr_;
357 this->capacity_ = new_capacity;
358 this->ptr_ = new_ptr;
359 // deallocate may throw (at least in principle), but it doesn't matter since
360 // the buffer already uses the new storage and will deallocate it in case
361 // of exception.
362 if (old_ptr != data_)
363 this->deallocate(old_ptr, old_capacity);
364 }
365
366 #ifndef _MSC_VER
367 // Portable version of signbit.
getsign(double x)368 inline int getsign(double x) {
369 // When compiled in C++11 mode signbit is no longer a macro but a function
370 // defined in namespace std and the macro is undefined.
371 # ifdef signbit
372 return signbit(x);
373 # else
374 return std::signbit(x);
375 # endif
376 }
377
378 // Portable version of isinf.
379 # ifdef isinf
isinfinity(double x)380 inline int isinfinity(double x) { return isinf(x); }
isinfinity(long double x)381 inline int isinfinity(long double x) { return isinf(x); }
382 # else
isinfinity(double x)383 inline int isinfinity(double x) { return std::isinf(x); }
isinfinity(long double x)384 inline int isinfinity(long double x) { return std::isinf(x); }
385 # endif
386 #else
getsign(double value)387 inline int getsign(double value) {
388 if (value < 0) return 1;
389 if (value == value) return 0;
390 int dec = 0, sign = 0;
391 char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail.
392 _ecvt_s(buffer, sizeof(buffer), value, 0, &dec, &sign);
393 return sign;
394 }
isinfinity(double x)395 inline int isinfinity(double x) { return !_finite(x); }
396 #endif
397
398 template <typename T>
399 struct IsLongDouble { enum {VALUE = 0}; };
400
401 template <>
402 struct IsLongDouble<long double> { enum {VALUE = 1}; };
403
404 template <typename Char>
405 class BasicCharTraits {
406 public:
407 #if _SECURE_SCL
408 typedef stdext::checked_array_iterator<Char*> CharPtr;
409 #else
410 typedef Char *CharPtr;
411 #endif
412 };
413
414 template <typename Char>
415 class CharTraits;
416
417 template <>
418 class CharTraits<char> : public BasicCharTraits<char> {
419 private:
420 // Conversion from wchar_t to char is not allowed.
421 static char convert(wchar_t);
422
423 public:
424 typedef const wchar_t *UnsupportedStrType;
425
convert(char value)426 static char convert(char value) { return value; }
427
428 // Formats a floating-point number.
429 template <typename T>
430 static int format_float(char *buffer, std::size_t size,
431 const char *format, unsigned width, int precision, T value);
432 };
433
434 template <>
435 class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> {
436 public:
437 typedef const char *UnsupportedStrType;
438
convert(char value)439 static wchar_t convert(char value) { return value; }
convert(wchar_t value)440 static wchar_t convert(wchar_t value) { return value; }
441
442 template <typename T>
443 static int format_float(wchar_t *buffer, std::size_t size,
444 const wchar_t *format, unsigned width, int precision, T value);
445 };
446
447 // Checks if a number is negative - used to avoid warnings.
448 template <bool IsSigned>
449 struct SignChecker {
450 template <typename T>
is_negativeA_LIB_NAMESPACE::fmt::internal::SignChecker451 static bool is_negative(T value) { return value < 0; }
452 };
453
454 template <>
455 struct SignChecker<false> {
456 template <typename T>
is_negativeA_LIB_NAMESPACE::fmt::internal::SignChecker457 static bool is_negative(T) { return false; }
458 };
459
460 // Returns true if value is negative, false otherwise.
461 // Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
462 template <typename T>
is_negative(T value)463 inline bool is_negative(T value) {
464 return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value);
465 }
466
467 // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise.
468 template <bool FitsIn32Bits>
469 struct TypeSelector { typedef uint32_t Type; };
470
471 template <>
472 struct TypeSelector<false> { typedef uint64_t Type; };
473
474 template <typename T>
475 struct IntTraits {
476 // Smallest of uint32_t and uint64_t that is large enough to represent
477 // all values of T.
478 typedef typename
479 TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType;
480 };
481
482 // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T.
483 template <typename T>
484 struct MakeUnsigned { typedef T Type; };
485
486 #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \
487 template <> \
488 struct MakeUnsigned<T> { typedef U Type; }
489
490 FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char);
491 FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char);
492 FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short);
493 FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned);
494 FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long);
495 FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong);
496
497 void report_unknown_type(char code, const char *type);
498
499 extern const uint32_t POWERS_OF_10_32[];
500 extern const uint64_t POWERS_OF_10_64[];
501
502 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
503 // Returns the number of decimal digits in n. Leading zeros are not counted
504 // except for n == 0 in which case count_digits returns 1.
count_digits(uint64_t n)505 inline unsigned count_digits(uint64_t n) {
506 // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
507 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
508 unsigned t = (64 - __builtin_clzll(n | 1)) * 1233 >> 12;
509 return t - (n < POWERS_OF_10_64[t]) + 1;
510 }
511 # if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
512 // Optional version of count_digits for better performance on 32-bit platforms.
count_digits(uint32_t n)513 inline unsigned count_digits(uint32_t n) {
514 uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12;
515 return t - (n < POWERS_OF_10_32[t]) + 1;
516 }
517 # endif
518 #else
519 // Fallback version of count_digits used when __builtin_clz is not available.
count_digits(uint64_t n)520 inline unsigned count_digits(uint64_t n) {
521 unsigned count = 1;
522 for (;;) {
523 // Integer division is slow so do it for a group of four digits instead
524 // of for every digit. The idea comes from the talk by Alexandrescu
525 // "Three Optimization Tips for C++". See speed-test for a comparison.
526 if (n < 10) return count;
527 if (n < 100) return count + 1;
528 if (n < 1000) return count + 2;
529 if (n < 10000) return count + 3;
530 n /= 10000u;
531 count += 4;
532 }
533 }
534 #endif
535
536 extern const char DIGITS[];
537
538 // Formats a decimal unsigned integer value writing into buffer.
539 template <typename UInt, typename Char>
format_decimal(Char * buffer,UInt value,unsigned num_digits)540 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) {
541 --num_digits;
542 while (value >= 100) {
543 // Integer division is slow so do it for a group of two digits instead
544 // of for every digit. The idea comes from the talk by Alexandrescu
545 // "Three Optimization Tips for C++". See speed-test for a comparison.
546 unsigned index = (value % 100) * 2;
547 value /= 100;
548 buffer[num_digits] = DIGITS[index + 1];
549 buffer[num_digits - 1] = DIGITS[index];
550 num_digits -= 2;
551 }
552 if (value < 10) {
553 *buffer = static_cast<char>('0' + value);
554 return;
555 }
556 unsigned index = static_cast<unsigned>(value * 2);
557 buffer[1] = DIGITS[index + 1];
558 buffer[0] = DIGITS[index];
559 }
560
561 #ifdef _WIN32
562 // A converter from UTF-8 to UTF-16.
563 // It is only provided for Windows since other systems support UTF-8 natively.
564 class UTF8ToUTF16 {
565 private:
566 MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_;
567
568 public:
569 explicit UTF8ToUTF16(StringRef s);
operator WStringRef() const570 operator WStringRef() const { return WStringRef(&buffer_[0], size()); }
size() const571 size_t size() const { return buffer_.size() - 1; }
c_str() const572 const wchar_t *c_str() const { return &buffer_[0]; }
str() const573 std::wstring str() const { return std::wstring(&buffer_[0], size()); }
574 };
575
576 // A converter from UTF-16 to UTF-8.
577 // It is only provided for Windows since other systems support UTF-8 natively.
578 class UTF16ToUTF8 {
579 private:
580 MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_;
581
582 public:
UTF16ToUTF8()583 UTF16ToUTF8() {}
584 explicit UTF16ToUTF8(WStringRef s);
operator StringRef() const585 operator StringRef() const { return StringRef(&buffer_[0], size()); }
size() const586 size_t size() const { return buffer_.size() - 1; }
c_str() const587 const char *c_str() const { return &buffer_[0]; }
str() const588 std::string str() const { return std::string(&buffer_[0], size()); }
589
590 // Performs conversion returning a system error code instead of
591 // throwing exception on conversion error. This method may still throw
592 // in case of memory allocation error.
593 int convert(WStringRef s);
594 };
595 #endif
596
597 void format_system_error(fmt::Writer &out, int error_code,
598 fmt::StringRef message) FMT_NOEXCEPT(true);
599
600 #ifdef _WIN32
601 void format_windows_error(fmt::Writer &out, int error_code,
602 fmt::StringRef message) FMT_NOEXCEPT(true);
603 #endif
604
605 // Computes max(Arg, 1) at compile time. It is used to avoid errors about
606 // allocating an array of 0 size.
607 template <unsigned Arg>
608 struct NonZero {
609 enum { VALUE = Arg };
610 };
611
612 template <>
613 struct NonZero<0> {
614 enum { VALUE = 1 };
615 };
616
617 // The value of a formatting argument. It is a POD type to allow storage in
618 // internal::MemoryBuffer.
619 struct Value {
620 template <typename Char>
621 struct StringValue {
622 const Char *value;
623 std::size_t size;
624 };
625
626 typedef void (*FormatFunc)(
627 void *formatter, const void *arg, void *format_str_ptr);
628
629 struct CustomValue {
630 const void *value;
631 FormatFunc format;
632 };
633
634 union {
635 int int_value;
636 unsigned uint_value;
637 LongLong long_long_value;
638 ULongLong ulong_long_value;
639 double double_value;
640 long double long_double_value;
641 const void *pointer;
642 StringValue<char> string;
643 StringValue<signed char> sstring;
644 StringValue<unsigned char> ustring;
645 StringValue<wchar_t> wstring;
646 CustomValue custom;
647 };
648 };
649
650 struct Arg : Value {
651 enum Type {
652 NONE,
653 // Integer types should go first,
654 INT, UINT, LONG_LONG, ULONG_LONG, CHAR, LAST_INTEGER_TYPE = CHAR,
655 // followed by floating-point types.
656 DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE,
657 CSTRING, STRING, WSTRING, POINTER, CUSTOM
658 };
659 Type type;
660 };
661
662 // Makes a Value object from any type.
663 template <typename Char>
664 class MakeValue : public Value {
665 private:
666 // The following two methods are private to disallow formatting of
667 // arbitrary pointers. If you want to output a pointer cast it to
668 // "void *" or "const void *". In particular, this forbids formatting
669 // of "[const] volatile char *" which is printed as bool by iostreams.
670 // Do not implement!
671 template <typename T>
672 MakeValue(const T *value);
673 template <typename T>
674 MakeValue(T *value);
675
set_string(StringRef str)676 void set_string(StringRef str) {
677 string.value = str.c_str();
678 string.size = str.size();
679 }
680
set_string(WStringRef str)681 void set_string(WStringRef str) {
682 CharTraits<Char>::convert(wchar_t());
683 wstring.value = str.c_str();
684 wstring.size = str.size();
685 }
686
687 // Formats an argument of a custom type, such as a user-defined class.
688 template <typename T>
format_custom_arg(void * formatter,const void * arg,void * format_str_ptr)689 static void format_custom_arg(
690 void *formatter, const void *arg, void *format_str_ptr) {
691 format(*static_cast<BasicFormatter<Char>*>(formatter),
692 *static_cast<const Char**>(format_str_ptr),
693 *static_cast<const T*>(arg));
694 }
695
696 public:
MakeValue()697 MakeValue() {}
698
699 #define FMT_MAKE_VALUE(Type, field, TYPE) \
700 MakeValue(Type value) { field = value; } \
701 static uint64_t type(Type) { return Arg::TYPE; }
702
FMT_MAKE_VALUE(bool,int_value,INT)703 FMT_MAKE_VALUE(bool, int_value, INT)
704 FMT_MAKE_VALUE(short, int_value, INT)
705 FMT_MAKE_VALUE(unsigned short, uint_value, UINT)
706 FMT_MAKE_VALUE(int, int_value, INT)
707 FMT_MAKE_VALUE(unsigned, uint_value, UINT)
708
709 MakeValue(long value) {
710 // To minimize the number of types we need to deal with, long is
711 // translated either to int or to long long depending on its size.
712 if (sizeof(long) == sizeof(int))
713 int_value = static_cast<int>(value);
714 else
715 long_long_value = value;
716 }
type(long)717 static uint64_t type(long) {
718 return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG;
719 }
720
MakeValue(unsigned long value)721 MakeValue(unsigned long value) {
722 if (sizeof(unsigned long) == sizeof(unsigned))
723 uint_value = static_cast<unsigned>(value);
724 else
725 ulong_long_value = value;
726 }
type(unsigned long)727 static uint64_t type(unsigned long) {
728 return sizeof(unsigned long) == sizeof(unsigned) ?
729 Arg::UINT : Arg::ULONG_LONG;
730 }
731
FMT_MAKE_VALUE(LongLong,long_long_value,LONG_LONG)732 FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG)
733 FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG)
734 FMT_MAKE_VALUE(float, double_value, DOUBLE)
735 FMT_MAKE_VALUE(double, double_value, DOUBLE)
736 FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE)
737 FMT_MAKE_VALUE(signed char, int_value, CHAR)
738 FMT_MAKE_VALUE(unsigned char, int_value, CHAR)
739 FMT_MAKE_VALUE(char, int_value, CHAR)
740
741 MakeValue(wchar_t value) {
742 int_value = internal::CharTraits<Char>::convert(value);
743 }
type(wchar_t)744 static uint64_t type(wchar_t) { return Arg::CHAR; }
745
746 #define FMT_MAKE_STR_VALUE(Type, TYPE) \
747 MakeValue(Type value) { set_string(value); } \
748 static uint64_t type(Type) { return Arg::TYPE; }
749
750 FMT_MAKE_VALUE(char *, string.value, CSTRING)
751 FMT_MAKE_VALUE(const char *, string.value, CSTRING)
752 FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING)
753 FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING)
FMT_MAKE_STR_VALUE(const std::string &,STRING)754 FMT_MAKE_STR_VALUE(const std::string &, STRING)
755 FMT_MAKE_STR_VALUE(StringRef, STRING)
756
757 FMT_MAKE_STR_VALUE(wchar_t *, WSTRING)
758 FMT_MAKE_STR_VALUE(const wchar_t *, WSTRING)
759 FMT_MAKE_STR_VALUE(const std::wstring &, WSTRING)
760 FMT_MAKE_STR_VALUE(WStringRef, WSTRING)
761
762 FMT_MAKE_VALUE(void *, pointer, POINTER)
763 FMT_MAKE_VALUE(const void *, pointer, POINTER)
764
765 template <typename T>
766 MakeValue(const T &value) {
767 custom.value = &value;
768 custom.format = &format_custom_arg<T>;
769 }
770 template <typename T>
type(const T &)771 static uint64_t type(const T &) { return Arg::CUSTOM; }
772 };
773
774 #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call
775
776 // An argument visitor.
777 // To use ArgVisitor define a subclass that implements some or all of the
778 // visit methods with the same signatures as the methods in ArgVisitor,
779 // for example, visit_int(int).
780 // Specify the subclass name as the Impl template parameter. Then calling
781 // ArgVisitor::visit for some argument will dispatch to a visit method
782 // specific to the argument type. For example, if the argument type is
783 // double then visit_double(double) method of a subclass will be called.
784 // If the subclass doesn't contain a method with this signature, then
785 // a corresponding method of ArgVisitor will be called.
786 //
787 // Example:
788 // class MyArgVisitor : public ArgVisitor<MyArgVisitor, void> {
789 // public:
790 // void visit_int(int value) { print("{}", value); }
791 // void visit_double(double value) { print("{}", value ); }
792 // };
793 //
794 // ArgVisitor uses the curiously recurring template pattern:
795 // http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
796 template <typename Impl, typename Result>
797 class ArgVisitor {
798 public:
visit_unhandled_arg()799 Result visit_unhandled_arg() { return Result(); }
800
visit_int(int value)801 Result visit_int(int value) {
802 return FMT_DISPATCH(visit_any_int(value));
803 }
visit_long_long(LongLong value)804 Result visit_long_long(LongLong value) {
805 return FMT_DISPATCH(visit_any_int(value));
806 }
visit_uint(unsigned value)807 Result visit_uint(unsigned value) {
808 return FMT_DISPATCH(visit_any_int(value));
809 }
visit_ulong_long(ULongLong value)810 Result visit_ulong_long(ULongLong value) {
811 return FMT_DISPATCH(visit_any_int(value));
812 }
visit_char(int value)813 Result visit_char(int value) {
814 return FMT_DISPATCH(visit_any_int(value));
815 }
816 template <typename T>
visit_any_int(T)817 Result visit_any_int(T) {
818 return FMT_DISPATCH(visit_unhandled_arg());
819 }
820
visit_double(double value)821 Result visit_double(double value) {
822 return FMT_DISPATCH(visit_any_double(value));
823 }
visit_long_double(long double value)824 Result visit_long_double(long double value) {
825 return FMT_DISPATCH(visit_any_double(value));
826 }
827 template <typename T>
visit_any_double(T)828 Result visit_any_double(T) {
829 return FMT_DISPATCH(visit_unhandled_arg());
830 }
831
visit_string(Arg::StringValue<char>)832 Result visit_string(Arg::StringValue<char>) {
833 return FMT_DISPATCH(visit_unhandled_arg());
834 }
visit_wstring(Arg::StringValue<wchar_t>)835 Result visit_wstring(Arg::StringValue<wchar_t>) {
836 return FMT_DISPATCH(visit_unhandled_arg());
837 }
visit_pointer(const void *)838 Result visit_pointer(const void *) {
839 return FMT_DISPATCH(visit_unhandled_arg());
840 }
visit_custom(Arg::CustomValue)841 Result visit_custom(Arg::CustomValue) {
842 return FMT_DISPATCH(visit_unhandled_arg());
843 }
844
visit(const Arg & arg)845 Result visit(const Arg &arg) {
846 switch (arg.type) {
847 default:
848 assert(false);
849 // Fall through.
850 case Arg::INT:
851 return FMT_DISPATCH(visit_int(arg.int_value));
852 case Arg::UINT:
853 return FMT_DISPATCH(visit_uint(arg.uint_value));
854 case Arg::LONG_LONG:
855 return FMT_DISPATCH(visit_long_long(arg.long_long_value));
856 case Arg::ULONG_LONG:
857 return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value));
858 case Arg::DOUBLE:
859 return FMT_DISPATCH(visit_double(arg.double_value));
860 case Arg::LONG_DOUBLE:
861 return FMT_DISPATCH(visit_long_double(arg.long_double_value));
862 case Arg::CHAR:
863 return FMT_DISPATCH(visit_char(arg.int_value));
864 case Arg::CSTRING: {
865 Value::StringValue<char> str = arg.string;
866 str.size = 0;
867 return FMT_DISPATCH(visit_string(str));
868 }
869 case Arg::STRING:
870 return FMT_DISPATCH(visit_string(arg.string));
871 case Arg::WSTRING:
872 return FMT_DISPATCH(visit_wstring(arg.wstring));
873 case Arg::POINTER:
874 return FMT_DISPATCH(visit_pointer(arg.pointer));
875 case Arg::CUSTOM:
876 return FMT_DISPATCH(visit_custom(arg.custom));
877 }
878 }
879 };
880
881 class RuntimeError : public std::runtime_error {
882 protected:
RuntimeError()883 RuntimeError() : std::runtime_error("") {}
884 };
885
886 template <typename Char>
887 class ArgFormatter;
888 } // namespace internal
889
890 /**
891 An argument list.
892 */
893 class ArgList {
894 private:
895 uint64_t types_;
896 const internal::Value *values_;
897
898 public:
899 // Maximum number of arguments that can be passed in ArgList.
900 enum { MAX_ARGS = 16 };
901
ArgList()902 ArgList() : types_(0) {}
ArgList(ULongLong types,const internal::Value * values)903 ArgList(ULongLong types, const internal::Value *values)
904 : types_(types), values_(values) {}
905
906 /**
907 Returns the argument at specified index.
908 */
operator [](unsigned index) const909 internal::Arg operator[](unsigned index) const {
910 using internal::Arg;
911 Arg arg;
912 if (index >= MAX_ARGS) {
913 arg.type = Arg::NONE;
914 return arg;
915 }
916 unsigned shift = index * 4;
917 uint64_t mask = 0xf;
918 Arg::Type type =
919 static_cast<Arg::Type>((types_ & (mask << shift)) >> shift);
920 arg.type = type;
921 if (type != Arg::NONE) {
922 internal::Value &value = arg;
923 value = values_[index];
924 }
925 return arg;
926 }
927 };
928
929 struct FormatSpec;
930
931 namespace internal {
932
933 class FormatterBase {
934 private:
935 ArgList args_;
936 int next_arg_index_;
937
938 // Returns the argument with specified index.
939 Arg do_get_arg(unsigned arg_index, const char *&error);
940
941 protected:
set_args(const ArgList & args)942 void set_args(const ArgList &args) {
943 args_ = args;
944 next_arg_index_ = 0;
945 }
946
947 // Returns the next argument.
948 Arg next_arg(const char *&error);
949
950 // Checks if manual indexing is used and returns the argument with
951 // specified index.
952 Arg get_arg(unsigned arg_index, const char *&error);
953
954 template <typename Char>
write(BasicWriter<Char> & w,const Char * start,const Char * end)955 void write(BasicWriter<Char> &w, const Char *start, const Char *end) {
956 if (start != end)
957 w << BasicStringRef<Char>(start, end - start);
958 }
959 };
960
961 // A printf formatter.
962 template <typename Char>
963 class PrintfFormatter : private FormatterBase {
964 private:
965 void parse_flags(FormatSpec &spec, const Char *&s);
966
967 // Returns the argument with specified index or, if arg_index is equal
968 // to the maximum unsigned value, the next argument.
969 Arg get_arg(const Char *s,
970 unsigned arg_index = (std::numeric_limits<unsigned>::max)());
971
972 // Parses argument index, flags and width and returns the argument index.
973 unsigned parse_header(const Char *&s, FormatSpec &spec);
974
975 public:
976 void format(BasicWriter<Char> &writer,
977 BasicStringRef<Char> format, const ArgList &args);
978 };
979 } // namespace internal
980
981 // A formatter.
982 template <typename Char>
983 class BasicFormatter : private internal::FormatterBase {
984 private:
985 BasicWriter<Char> &writer_;
986 const Char *start_;
987
988 // Parses argument index and returns corresponding argument.
989 internal::Arg parse_arg_index(const Char *&s);
990
991 public:
BasicFormatter(BasicWriter<Char> & w)992 explicit BasicFormatter(BasicWriter<Char> &w) : writer_(w) {}
993
writer()994 BasicWriter<Char> &writer() { return writer_; }
995
996 void format(BasicStringRef<Char> format_str, const ArgList &args);
997
998 const Char *format(const Char *&format_str, const internal::Arg &arg);
999 };
1000
1001 enum Alignment {
1002 ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
1003 };
1004
1005 // Flags.
1006 enum {
1007 SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8,
1008 CHAR_FLAG = 0x10 // Argument has char type - used in error reporting.
1009 };
1010
1011 // An empty format specifier.
1012 struct EmptySpec {};
1013
1014 // A type specifier.
1015 template <char TYPE>
1016 struct TypeSpec : EmptySpec {
alignA_LIB_NAMESPACE::fmt::TypeSpec1017 Alignment align() const { return ALIGN_DEFAULT; }
widthA_LIB_NAMESPACE::fmt::TypeSpec1018 unsigned width() const { return 0; }
precisionA_LIB_NAMESPACE::fmt::TypeSpec1019 int precision() const { return -1; }
flagA_LIB_NAMESPACE::fmt::TypeSpec1020 bool flag(unsigned) const { return false; }
typeA_LIB_NAMESPACE::fmt::TypeSpec1021 char type() const { return TYPE; }
fillA_LIB_NAMESPACE::fmt::TypeSpec1022 char fill() const { return ' '; }
1023 };
1024
1025 // A width specifier.
1026 struct WidthSpec {
1027 unsigned width_;
1028 // Fill is always wchar_t and cast to char if necessary to avoid having
1029 // two specialization of WidthSpec and its subclasses.
1030 wchar_t fill_;
1031
WidthSpecA_LIB_NAMESPACE::fmt::WidthSpec1032 WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {}
1033
widthA_LIB_NAMESPACE::fmt::WidthSpec1034 unsigned width() const { return width_; }
fillA_LIB_NAMESPACE::fmt::WidthSpec1035 wchar_t fill() const { return fill_; }
1036 };
1037
1038 // An alignment specifier.
1039 struct AlignSpec : WidthSpec {
1040 Alignment align_;
1041
AlignSpecA_LIB_NAMESPACE::fmt::AlignSpec1042 AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT)
1043 : WidthSpec(width, fill), align_(align) {}
1044
alignA_LIB_NAMESPACE::fmt::AlignSpec1045 Alignment align() const { return align_; }
1046
precisionA_LIB_NAMESPACE::fmt::AlignSpec1047 int precision() const { return -1; }
1048 };
1049
1050 // An alignment and type specifier.
1051 template <char TYPE>
1052 struct AlignTypeSpec : AlignSpec {
AlignTypeSpecA_LIB_NAMESPACE::fmt::AlignTypeSpec1053 AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {}
1054
flagA_LIB_NAMESPACE::fmt::AlignTypeSpec1055 bool flag(unsigned) const { return false; }
typeA_LIB_NAMESPACE::fmt::AlignTypeSpec1056 char type() const { return TYPE; }
1057 };
1058
1059 // A full format specifier.
1060 struct FormatSpec : AlignSpec {
1061 unsigned flags_;
1062 int precision_;
1063 char type_;
1064
FormatSpecA_LIB_NAMESPACE::fmt::FormatSpec1065 FormatSpec(
1066 unsigned width = 0, char type = 0, wchar_t fill = ' ')
1067 : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {}
1068
flagA_LIB_NAMESPACE::fmt::FormatSpec1069 bool flag(unsigned f) const { return (flags_ & f) != 0; }
precisionA_LIB_NAMESPACE::fmt::FormatSpec1070 int precision() const { return precision_; }
typeA_LIB_NAMESPACE::fmt::FormatSpec1071 char type() const { return type_; }
1072 };
1073
1074 // An integer format specifier.
1075 template <typename T, typename SpecT = TypeSpec<0>, typename Char = char>
1076 class IntFormatSpec : public SpecT {
1077 private:
1078 T value_;
1079
1080 public:
IntFormatSpec(T value,const SpecT & spec=SpecT ())1081 IntFormatSpec(T value, const SpecT &spec = SpecT())
1082 : SpecT(spec), value_(value) {}
1083
value() const1084 T value() const { return value_; }
1085 };
1086
1087 // A string format specifier.
1088 template <typename T>
1089 class StrFormatSpec : public AlignSpec {
1090 private:
1091 const T *str_;
1092
1093 public:
StrFormatSpec(const T * str,unsigned width,wchar_t fill)1094 StrFormatSpec(const T *str, unsigned width, wchar_t fill)
1095 : AlignSpec(width, fill), str_(str) {}
1096
str() const1097 const T *str() const { return str_; }
1098 };
1099
1100 /**
1101 Returns an integer format specifier to format the value in base 2.
1102 */
1103 IntFormatSpec<int, TypeSpec<'b'> > bin(int value);
1104
1105 /**
1106 Returns an integer format specifier to format the value in base 8.
1107 */
1108 IntFormatSpec<int, TypeSpec<'o'> > oct(int value);
1109
1110 /**
1111 Returns an integer format specifier to format the value in base 16 using
1112 lower-case letters for the digits above 9.
1113 */
1114 IntFormatSpec<int, TypeSpec<'x'> > hex(int value);
1115
1116 /**
1117 Returns an integer formatter format specifier to format in base 16 using
1118 upper-case letters for the digits above 9.
1119 */
1120 IntFormatSpec<int, TypeSpec<'X'> > hexu(int value);
1121
1122 /**
1123 \rst
1124 Returns an integer format specifier to pad the formatted argument with the
1125 fill character to the specified width using the default (right) numeric
1126 alignment.
1127
1128 **Example**::
1129
1130 MemoryWriter out;
1131 out << pad(hex(0xcafe), 8, '0');
1132 // out.str() == "0000cafe"
1133
1134 \endrst
1135 */
1136 template <char TYPE_CODE, typename Char>
1137 IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(
1138 int value, unsigned width, Char fill = ' ');
1139
1140 #define FMT_DEFINE_INT_FORMATTERS(TYPE) \
1141 inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \
1142 return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \
1143 } \
1144 \
1145 inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \
1146 return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \
1147 } \
1148 \
1149 inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \
1150 return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \
1151 } \
1152 \
1153 inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \
1154 return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \
1155 } \
1156 \
1157 template <char TYPE_CODE> \
1158 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \
1159 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \
1160 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \
1161 f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \
1162 } \
1163 \
1164 /* For compatibility with older compilers we provide two overloads for pad, */ \
1165 /* one that takes a fill character and one that doesn't. In the future this */ \
1166 /* can be replaced with one overload making the template argument Char */ \
1167 /* default to char (C++11). */ \
1168 template <char TYPE_CODE, typename Char> \
1169 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \
1170 IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \
1171 unsigned width, Char fill) { \
1172 return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \
1173 f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \
1174 } \
1175 \
1176 inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \
1177 TYPE value, unsigned width) { \
1178 return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \
1179 value, AlignTypeSpec<0>(width, ' ')); \
1180 } \
1181 \
1182 template <typename Char> \
1183 inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \
1184 TYPE value, unsigned width, Char fill) { \
1185 return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \
1186 value, AlignTypeSpec<0>(width, fill)); \
1187 }
1188
1189 FMT_DEFINE_INT_FORMATTERS(int)
FMT_DEFINE_INT_FORMATTERS(long)1190 FMT_DEFINE_INT_FORMATTERS(long)
1191 FMT_DEFINE_INT_FORMATTERS(unsigned)
1192 FMT_DEFINE_INT_FORMATTERS(unsigned long)
1193 FMT_DEFINE_INT_FORMATTERS(LongLong)
1194 FMT_DEFINE_INT_FORMATTERS(ULongLong)
1195
1196 /**
1197 \rst
1198 Returns a string formatter that pads the formatted argument with the fill
1199 character to the specified width using the default (left) string alignment.
1200
1201 **Example**::
1202
1203 std::string s = str(MemoryWriter() << pad("abc", 8));
1204 // s == "abc "
1205
1206 \endrst
1207 */
1208 template <typename Char>
1209 inline StrFormatSpec<Char> pad(
1210 const Char *str, unsigned width, Char fill = ' ') {
1211 return StrFormatSpec<Char>(str, width, fill);
1212 }
1213
pad(const wchar_t * str,unsigned width,char fill=' ')1214 inline StrFormatSpec<wchar_t> pad(
1215 const wchar_t *str, unsigned width, char fill = ' ') {
1216 return StrFormatSpec<wchar_t>(str, width, fill);
1217 }
1218
1219 // Generates a comma-separated list with results of applying f to
1220 // numbers 0..n-1.
1221 # define FMT_GEN(n, f) FMT_GEN##n(f)
1222 # define FMT_GEN1(f) f(0)
1223 # define FMT_GEN2(f) FMT_GEN1(f), f(1)
1224 # define FMT_GEN3(f) FMT_GEN2(f), f(2)
1225 # define FMT_GEN4(f) FMT_GEN3(f), f(3)
1226 # define FMT_GEN5(f) FMT_GEN4(f), f(4)
1227 # define FMT_GEN6(f) FMT_GEN5(f), f(5)
1228 # define FMT_GEN7(f) FMT_GEN6(f), f(6)
1229 # define FMT_GEN8(f) FMT_GEN7(f), f(7)
1230 # define FMT_GEN9(f) FMT_GEN8(f), f(8)
1231 # define FMT_GEN10(f) FMT_GEN9(f), f(9)
1232 # define FMT_GEN11(f) FMT_GEN10(f), f(10)
1233 # define FMT_GEN12(f) FMT_GEN11(f), f(11)
1234 # define FMT_GEN13(f) FMT_GEN12(f), f(12)
1235 # define FMT_GEN14(f) FMT_GEN13(f), f(13)
1236 # define FMT_GEN15(f) FMT_GEN14(f), f(14)
1237
1238 namespace internal {
make_type()1239 inline uint64_t make_type() { return 0; }
1240
1241 template <typename T>
make_type(const T & arg)1242 inline uint64_t make_type(const T &arg) { return MakeValue<char>::type(arg); }
1243
1244 #if FMT_USE_VARIADIC_TEMPLATES
1245 template <typename Arg, typename... Args>
make_type(const Arg & first,const Args &...tail)1246 inline uint64_t make_type(const Arg &first, const Args & ... tail) {
1247 return make_type(first) | (make_type(tail...) << 4);
1248 }
1249 #else
1250
1251 struct ArgType {
1252 uint64_t type;
1253
ArgTypeA_LIB_NAMESPACE::fmt::internal::ArgType1254 ArgType() : type(0) {}
1255
1256 template <typename T>
ArgTypeA_LIB_NAMESPACE::fmt::internal::ArgType1257 ArgType(const T &arg) : type(make_type(arg)) {}
1258 };
1259
1260 # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType()
1261
make_type(FMT_GEN15 (FMT_ARG_TYPE_DEFAULT))1262 inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) {
1263 return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) |
1264 (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) |
1265 (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) |
1266 (t12.type << 48) | (t13.type << 52) | (t14.type << 56);
1267 }
1268 #endif
1269 } // namespace internal
1270
1271 # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n
1272 # define FMT_MAKE_ARG_TYPE(n) T##n
1273 # define FMT_MAKE_ARG(n) const T##n &v##n
1274 # define FMT_MAKE_REF_char(n) fmt::internal::MakeValue<char>(v##n)
1275 # define FMT_MAKE_REF_wchar_t(n) fmt::internal::MakeValue<wchar_t>(v##n)
1276
1277 #if FMT_USE_VARIADIC_TEMPLATES
1278 // Defines a variadic function returning void.
1279 # define FMT_VARIADIC_VOID(func, arg_type) \
1280 template <typename... Args> \
1281 void func(arg_type arg1, const Args & ... args) { \
1282 const fmt::internal::Value values[ \
1283 fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
1284 fmt::internal::MakeValue<Char>(args)... \
1285 }; \
1286 func(arg1, ArgList(fmt::internal::make_type(args...), values)); \
1287 }
1288
1289 // Defines a variadic constructor.
1290 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
1291 template <typename... Args> \
1292 ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \
1293 using fmt::internal::MakeValue; \
1294 const fmt::internal::Value values[ \
1295 fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
1296 MakeValue<Char>(args)... \
1297 }; \
1298 func(arg0, arg1, ArgList(fmt::internal::make_type(args...), values)); \
1299 }
1300
1301 #else
1302
1303 # define FMT_MAKE_REF(n) fmt::internal::MakeValue<Char>(v##n)
1304 # define FMT_MAKE_REF2(n) v##n
1305
1306 // Defines a wrapper for a function taking one argument of type arg_type
1307 // and n additional arguments of arbitrary types.
1308 # define FMT_WRAP1(func, arg_type, n) \
1309 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
1310 inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
1311 const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \
1312 func(arg1, fmt::ArgList( \
1313 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \
1314 }
1315
1316 // Emulates a variadic function returning void on a pre-C++11 compiler.
1317 # define FMT_VARIADIC_VOID(func, arg_type) \
1318 FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \
1319 FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \
1320 FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \
1321 FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \
1322 FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10)
1323
1324 # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \
1325 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
1326 ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
1327 const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \
1328 func(arg0, arg1, fmt::ArgList( \
1329 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \
1330 }
1331
1332 // Emulates a variadic constructor on a pre-C++11 compiler.
1333 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
1334 FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \
1335 FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \
1336 FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \
1337 FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \
1338 FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \
1339 FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \
1340 FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \
1341 FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \
1342 FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \
1343 FMT_CTOR(ctor, func, arg0_type, arg1_type, 10)
1344 #endif
1345
1346 // Generates a comma-separated list with results of applying f to pairs
1347 // (argument, index).
1348 #define FMT_FOR_EACH1(f, x0) f(x0, 0)
1349 #define FMT_FOR_EACH2(f, x0, x1) \
1350 FMT_FOR_EACH1(f, x0), f(x1, 1)
1351 #define FMT_FOR_EACH3(f, x0, x1, x2) \
1352 FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2)
1353 #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \
1354 FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3)
1355 #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \
1356 FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4)
1357 #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \
1358 FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5)
1359 #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \
1360 FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6)
1361 #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \
1362 FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7)
1363 #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \
1364 FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8)
1365 #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \
1366 FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9)
1367
1368 /**
1369 An error returned by an operating system or a language runtime,
1370 for example a file opening error.
1371 */
1372 class SystemError : public internal::RuntimeError {
1373 private:
1374 void init(int error_code, StringRef format_str, ArgList args);
1375
1376 protected:
1377 int error_code_;
1378
1379 typedef char Char; // For FMT_VARIADIC_CTOR.
1380
SystemError()1381 SystemError() {}
1382
1383 public:
1384 /**
1385 \rst
1386 Constructs a :cpp:class:`fmt::SystemError` object with the description
1387 of the form "*<message>*: *<system-message>*", where *<message>* is the
1388 formatted message and *<system-message>* is the system message corresponding
1389 to the error code.
1390 *error_code* is a system error code as given by ``errno``.
1391 \endrst
1392 */
SystemError(int error_code,StringRef message)1393 SystemError(int error_code, StringRef message) {
1394 init(error_code, message, ArgList());
1395 }
FMT_VARIADIC_CTOR(SystemError,init,int,StringRef)1396 FMT_VARIADIC_CTOR(SystemError, init, int, StringRef)
1397
1398 int error_code() const { return error_code_; }
1399 };
1400
1401 /**
1402 \rst
1403 This template provides operations for formatting and writing data into
1404 a character stream. The output is stored in a buffer provided by a subclass
1405 such as :cpp:class:`fmt::BasicMemoryWriter`.
1406
1407 You can use one of the following typedefs for common character types:
1408
1409 +---------+----------------------+
1410 | Type | Definition |
1411 +=========+======================+
1412 | Writer | BasicWriter<char> |
1413 +---------+----------------------+
1414 | WWriter | BasicWriter<wchar_t> |
1415 +---------+----------------------+
1416
1417 \endrst
1418 */
1419 template <typename Char>
1420 class BasicWriter {
1421 private:
1422 // Output buffer.
1423 internal::Buffer<Char> &buffer_;
1424
1425 FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter);
1426
1427 typedef typename internal::CharTraits<Char>::CharPtr CharPtr;
1428
1429 #if _SECURE_SCL
1430 // Returns pointer value.
get(CharPtr p)1431 static Char *get(CharPtr p) { return p.base(); }
1432 #else
get(Char * p)1433 static Char *get(Char *p) { return p; }
1434 #endif
1435
1436 // Fills the padding around the content and returns the pointer to the
1437 // content area.
1438 static CharPtr fill_padding(CharPtr buffer,
1439 unsigned total_size, std::size_t content_size, wchar_t fill);
1440
1441 // Grows the buffer by n characters and returns a pointer to the newly
1442 // allocated area.
grow_buffer(std::size_t n)1443 CharPtr grow_buffer(std::size_t n) {
1444 std::size_t size = buffer_.size();
1445 buffer_.resize(size + n);
1446 return internal::make_ptr(&buffer_[size], n);
1447 }
1448
1449 // Prepare a buffer for integer formatting.
prepare_int_buffer(unsigned num_digits,const EmptySpec &,const char * prefix,unsigned prefix_size)1450 CharPtr prepare_int_buffer(unsigned num_digits,
1451 const EmptySpec &, const char *prefix, unsigned prefix_size) {
1452 unsigned size = prefix_size + num_digits;
1453 CharPtr p = grow_buffer(size);
1454 std::copy(prefix, prefix + prefix_size, p);
1455 return p + size - 1;
1456 }
1457
1458 template <typename Spec>
1459 CharPtr prepare_int_buffer(unsigned num_digits,
1460 const Spec &spec, const char *prefix, unsigned prefix_size);
1461
1462 // Formats an integer.
1463 template <typename T, typename Spec>
1464 void write_int(T value, Spec spec);
1465
1466 // Formats a floating-point number (double or long double).
1467 template <typename T>
1468 void write_double(T value, const FormatSpec &spec);
1469
1470 // Writes a formatted string.
1471 template <typename StrChar>
1472 CharPtr write_str(
1473 const StrChar *s, std::size_t size, const AlignSpec &spec);
1474
1475 template <typename StrChar>
1476 void write_str(
1477 const internal::Arg::StringValue<StrChar> &str, const FormatSpec &spec);
1478
1479 // This method is private to disallow writing a wide string to a
1480 // char stream and vice versa. If you want to print a wide string
1481 // as a pointer as std::ostream does, cast it to const void*.
1482 // Do not implement!
1483 void operator<<(typename internal::CharTraits<Char>::UnsupportedStrType);
1484
1485 friend class internal::ArgFormatter<Char>;
1486 friend class internal::PrintfFormatter<Char>;
1487
1488 protected:
1489 /**
1490 Constructs a ``BasicWriter`` object.
1491 */
BasicWriter(internal::Buffer<Char> & b)1492 explicit BasicWriter(internal::Buffer<Char> &b) : buffer_(b) {}
1493
1494 public:
1495 /**
1496 Destroys a ``BasicWriter`` object.
1497 */
~BasicWriter()1498 virtual ~BasicWriter() {}
1499
1500 /**
1501 Returns the total number of characters written.
1502 */
size() const1503 std::size_t size() const { return buffer_.size(); }
1504
1505 /**
1506 Returns a pointer to the output buffer content. No terminating null
1507 character is appended.
1508 */
data() const1509 const Char *data() const FMT_NOEXCEPT(true) { return &buffer_[0]; }
1510
1511 /**
1512 Returns a pointer to the output buffer content with terminating null
1513 character appended.
1514 */
c_str() const1515 const Char *c_str() const {
1516 std::size_t size = buffer_.size();
1517 buffer_.reserve(size + 1);
1518 buffer_[size] = '\0';
1519 return &buffer_[0];
1520 }
1521
1522 /**
1523 Returns the content of the output buffer as an `std::string`.
1524 */
str() const1525 std::basic_string<Char> str() const {
1526 return std::basic_string<Char>(&buffer_[0], buffer_.size());
1527 }
1528
1529 /**
1530 \rst
1531 Writes formatted data.
1532
1533 *args* is an argument list representing arbitrary arguments.
1534
1535 **Example**::
1536
1537 MemoryWriter out;
1538 out.write("Current point:\n");
1539 out.write("({:+f}, {:+f})", -3.14, 3.14);
1540
1541 This will write the following output to the ``out`` object:
1542
1543 .. code-block:: none
1544
1545 Current point:
1546 (-3.140000, +3.140000)
1547
1548 The output can be accessed using :meth:`data`, :meth:`c_str` or :meth:`str`
1549 methods.
1550
1551 See also :ref:`syntax`.
1552 \endrst
1553 */
write(BasicStringRef<Char> format,ArgList args)1554 void write(BasicStringRef<Char> format, ArgList args) {
1555 BasicFormatter<Char>(*this).format(format, args);
1556 }
1557 FMT_VARIADIC_VOID(write, BasicStringRef<Char>)
1558
1559 BasicWriter &operator<<(int value) {
1560 return *this << IntFormatSpec<int>(value);
1561 }
operator <<(unsigned value)1562 BasicWriter &operator<<(unsigned value) {
1563 return *this << IntFormatSpec<unsigned>(value);
1564 }
operator <<(long value)1565 BasicWriter &operator<<(long value) {
1566 return *this << IntFormatSpec<long>(value);
1567 }
operator <<(unsigned long value)1568 BasicWriter &operator<<(unsigned long value) {
1569 return *this << IntFormatSpec<unsigned long>(value);
1570 }
operator <<(LongLong value)1571 BasicWriter &operator<<(LongLong value) {
1572 return *this << IntFormatSpec<LongLong>(value);
1573 }
1574
1575 /**
1576 Formats *value* and writes it to the stream.
1577 */
operator <<(ULongLong value)1578 BasicWriter &operator<<(ULongLong value) {
1579 return *this << IntFormatSpec<ULongLong>(value);
1580 }
1581
operator <<(double value)1582 BasicWriter &operator<<(double value) {
1583 write_double(value, FormatSpec());
1584 return *this;
1585 }
1586
1587 /**
1588 Formats *value* using the general format for floating-point numbers
1589 (``'g'``) and writes it to the stream.
1590 */
operator <<(long double value)1591 BasicWriter &operator<<(long double value) {
1592 write_double(value, FormatSpec());
1593 return *this;
1594 }
1595
1596 /**
1597 Writes a character to the stream.
1598 */
operator <<(char value)1599 BasicWriter &operator<<(char value) {
1600 buffer_.push_back(value);
1601 return *this;
1602 }
1603
operator <<(wchar_t value)1604 BasicWriter &operator<<(wchar_t value) {
1605 buffer_.push_back(internal::CharTraits<Char>::convert(value));
1606 return *this;
1607 }
1608
1609 /**
1610 Writes *value* to the stream.
1611 */
operator <<(fmt::BasicStringRef<Char> value)1612 BasicWriter &operator<<(fmt::BasicStringRef<Char> value) {
1613 const Char *str = value.c_str();
1614 buffer_.append(str, str + value.size());
1615 return *this;
1616 }
1617
1618 template <typename T, typename Spec, typename FillChar>
operator <<(IntFormatSpec<T,Spec,FillChar> spec)1619 BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) {
1620 internal::CharTraits<Char>::convert(FillChar());
1621 write_int(spec.value(), spec);
1622 return *this;
1623 }
1624
1625 template <typename StrChar>
operator <<(const StrFormatSpec<StrChar> & spec)1626 BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) {
1627 const StrChar *s = spec.str();
1628 // TODO: error if fill is not convertible to Char
1629 write_str(s, std::char_traits<Char>::length(s), spec);
1630 return *this;
1631 }
1632
clear()1633 void clear() FMT_NOEXCEPT(true) { buffer_.clear(); }
1634 };
1635
1636 template <typename Char>
1637 template <typename StrChar>
write_str(const StrChar * s,std::size_t size,const AlignSpec & spec)1638 typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str(
1639 const StrChar *s, std::size_t size, const AlignSpec &spec) {
1640 CharPtr out = CharPtr();
1641 if (spec.width() > size) {
1642 out = grow_buffer(spec.width());
1643 Char fill = static_cast<Char>(spec.fill());
1644 if (spec.align() == ALIGN_RIGHT) {
1645 std::fill_n(out, spec.width() - size, fill);
1646 out += spec.width() - size;
1647 } else if (spec.align() == ALIGN_CENTER) {
1648 out = fill_padding(out, spec.width(), size, fill);
1649 } else {
1650 std::fill_n(out + size, spec.width() - size, fill);
1651 }
1652 } else {
1653 out = grow_buffer(size);
1654 }
1655 std::copy(s, s + size, out);
1656 return out;
1657 }
1658
1659 template <typename Char>
1660 typename BasicWriter<Char>::CharPtr
fill_padding(CharPtr buffer,unsigned total_size,std::size_t content_size,wchar_t fill)1661 BasicWriter<Char>::fill_padding(
1662 CharPtr buffer, unsigned total_size,
1663 std::size_t content_size, wchar_t fill) {
1664 std::size_t padding = total_size - content_size;
1665 std::size_t left_padding = padding / 2;
1666 Char fill_char = static_cast<Char>(fill);
1667 std::fill_n(buffer, left_padding, fill_char);
1668 buffer += left_padding;
1669 CharPtr content = buffer;
1670 std::fill_n(buffer + content_size, padding - left_padding, fill_char);
1671 return content;
1672 }
1673
1674 template <typename Char>
1675 template <typename Spec>
1676 typename BasicWriter<Char>::CharPtr
prepare_int_buffer(unsigned num_digits,const Spec & spec,const char * prefix,unsigned prefix_size)1677 BasicWriter<Char>::prepare_int_buffer(
1678 unsigned num_digits, const Spec &spec,
1679 const char *prefix, unsigned prefix_size) {
1680 unsigned width = spec.width();
1681 Alignment align = spec.align();
1682 Char fill = static_cast<Char>(spec.fill());
1683 if (spec.precision() > static_cast<int>(num_digits)) {
1684 // Octal prefix '0' is counted as a digit, so ignore it if precision
1685 // is specified.
1686 if (prefix_size > 0 && prefix[prefix_size - 1] == '0')
1687 --prefix_size;
1688 unsigned number_size = prefix_size + spec.precision();
1689 AlignSpec subspec(number_size, '0', ALIGN_NUMERIC);
1690 if (number_size >= width)
1691 return prepare_int_buffer(num_digits, subspec, prefix, prefix_size);
1692 buffer_.reserve(width);
1693 unsigned fill_size = width - number_size;
1694 if (align != ALIGN_LEFT) {
1695 CharPtr p = grow_buffer(fill_size);
1696 std::fill(p, p + fill_size, fill);
1697 }
1698 CharPtr result = prepare_int_buffer(
1699 num_digits, subspec, prefix, prefix_size);
1700 if (align == ALIGN_LEFT) {
1701 CharPtr p = grow_buffer(fill_size);
1702 std::fill(p, p + fill_size, fill);
1703 }
1704 return result;
1705 }
1706 unsigned size = prefix_size + num_digits;
1707 if (width <= size) {
1708 CharPtr p = grow_buffer(size);
1709 std::copy(prefix, prefix + prefix_size, p);
1710 return p + size - 1;
1711 }
1712 CharPtr p = grow_buffer(width);
1713 CharPtr end = p + width;
1714 if (align == ALIGN_LEFT) {
1715 std::copy(prefix, prefix + prefix_size, p);
1716 p += size;
1717 std::fill(p, end, fill);
1718 } else if (align == ALIGN_CENTER) {
1719 p = fill_padding(p, width, size, fill);
1720 std::copy(prefix, prefix + prefix_size, p);
1721 p += size;
1722 } else {
1723 if (align == ALIGN_NUMERIC) {
1724 if (prefix_size != 0) {
1725 p = std::copy(prefix, prefix + prefix_size, p);
1726 size -= prefix_size;
1727 }
1728 } else {
1729 std::copy(prefix, prefix + prefix_size, end - size);
1730 }
1731 std::fill(p, end - size, fill);
1732 p = end;
1733 }
1734 return p - 1;
1735 }
1736
1737 template <typename Char>
1738 template <typename T, typename Spec>
write_int(T value,Spec spec)1739 void BasicWriter<Char>::write_int(T value, Spec spec) {
1740 unsigned prefix_size = 0;
1741 typedef typename internal::IntTraits<T>::MainType UnsignedType;
1742 UnsignedType abs_value = value;
1743 char prefix[4] = "";
1744 if (internal::is_negative(value)) {
1745 prefix[0] = '-';
1746 ++prefix_size;
1747 abs_value = 0 - abs_value;
1748 } else if (spec.flag(SIGN_FLAG)) {
1749 prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' ';
1750 ++prefix_size;
1751 }
1752 switch (spec.type()) {
1753 case 0: case 'd': {
1754 unsigned num_digits = internal::count_digits(abs_value);
1755 CharPtr p = prepare_int_buffer(
1756 num_digits, spec, prefix, prefix_size) + 1 - num_digits;
1757 internal::format_decimal(get(p), abs_value, num_digits);
1758 break;
1759 }
1760 case 'x': case 'X': {
1761 UnsignedType n = abs_value;
1762 if (spec.flag(HASH_FLAG)) {
1763 prefix[prefix_size++] = '0';
1764 prefix[prefix_size++] = spec.type();
1765 }
1766 unsigned num_digits = 0;
1767 do {
1768 ++num_digits;
1769 } while ((n >>= 4) != 0);
1770 Char *p = get(prepare_int_buffer(
1771 num_digits, spec, prefix, prefix_size));
1772 n = abs_value;
1773 const char *digits = spec.type() == 'x' ?
1774 "0123456789abcdef" : "0123456789ABCDEF";
1775 do {
1776 *p-- = digits[n & 0xf];
1777 } while ((n >>= 4) != 0);
1778 break;
1779 }
1780 case 'b': case 'B': {
1781 UnsignedType n = abs_value;
1782 if (spec.flag(HASH_FLAG)) {
1783 prefix[prefix_size++] = '0';
1784 prefix[prefix_size++] = spec.type();
1785 }
1786 unsigned num_digits = 0;
1787 do {
1788 ++num_digits;
1789 } while ((n >>= 1) != 0);
1790 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
1791 n = abs_value;
1792 do {
1793 *p-- = '0' + (n & 1);
1794 } while ((n >>= 1) != 0);
1795 break;
1796 }
1797 case 'o': {
1798 UnsignedType n = abs_value;
1799 if (spec.flag(HASH_FLAG))
1800 prefix[prefix_size++] = '0';
1801 unsigned num_digits = 0;
1802 do {
1803 ++num_digits;
1804 } while ((n >>= 3) != 0);
1805 Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
1806 n = abs_value;
1807 do {
1808 *p-- = '0' + (n & 7);
1809 } while ((n >>= 3) != 0);
1810 break;
1811 }
1812 default:
1813 internal::report_unknown_type(
1814 spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer");
1815 break;
1816 }
1817 }
1818
1819 template <typename Char>
1820 template <typename T>
write_double(T value,const FormatSpec & spec)1821 void BasicWriter<Char>::write_double(
1822 T value, const FormatSpec &spec) {
1823 // Check type.
1824 char type = spec.type();
1825 bool upper = false;
1826 switch (type) {
1827 case 0:
1828 type = 'g';
1829 break;
1830 case 'e': case 'f': case 'g': case 'a':
1831 break;
1832 case 'F':
1833 #ifdef _MSC_VER
1834 // MSVC's printf doesn't support 'F'.
1835 type = 'f';
1836 #endif
1837 // Fall through.
1838 case 'E': case 'G': case 'A':
1839 upper = true;
1840 break;
1841 default:
1842 internal::report_unknown_type(type, "double");
1843 break;
1844 }
1845
1846 char sign = 0;
1847 // Use getsign instead of value < 0 because the latter is always
1848 // false for NaN.
1849 if (internal::getsign(static_cast<double>(value))) {
1850 sign = '-';
1851 value = -value;
1852 } else if (spec.flag(SIGN_FLAG)) {
1853 sign = spec.flag(PLUS_FLAG) ? '+' : ' ';
1854 }
1855
1856 if (value != value) {
1857 // Format NaN ourselves because sprintf's output is not consistent
1858 // across platforms.
1859 std::size_t size = 4;
1860 const char *nan = upper ? " NAN" : " nan";
1861 if (!sign) {
1862 --size;
1863 ++nan;
1864 }
1865 CharPtr out = write_str(nan, size, spec);
1866 if (sign)
1867 *out = sign;
1868 return;
1869 }
1870
1871 if (internal::isinfinity(value)) {
1872 // Format infinity ourselves because sprintf's output is not consistent
1873 // across platforms.
1874 std::size_t size = 4;
1875 const char *inf = upper ? " INF" : " inf";
1876 if (!sign) {
1877 --size;
1878 ++inf;
1879 }
1880 CharPtr out = write_str(inf, size, spec);
1881 if (sign)
1882 *out = sign;
1883 return;
1884 }
1885
1886 std::size_t offset = buffer_.size();
1887 unsigned width = spec.width();
1888 if (sign) {
1889 buffer_.reserve(buffer_.size() + (std::max)(width, 1u));
1890 if (width > 0)
1891 --width;
1892 ++offset;
1893 }
1894
1895 // Build format string.
1896 enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg
1897 Char format[MAX_FORMAT_SIZE];
1898 Char *format_ptr = format;
1899 *format_ptr++ = '%';
1900 unsigned width_for_sprintf = width;
1901 if (spec.flag(HASH_FLAG))
1902 *format_ptr++ = '#';
1903 if (spec.align() == ALIGN_CENTER) {
1904 width_for_sprintf = 0;
1905 } else {
1906 if (spec.align() == ALIGN_LEFT)
1907 *format_ptr++ = '-';
1908 if (width != 0)
1909 *format_ptr++ = '*';
1910 }
1911 if (spec.precision() >= 0) {
1912 *format_ptr++ = '.';
1913 *format_ptr++ = '*';
1914 }
1915 if (internal::IsLongDouble<T>::VALUE)
1916 *format_ptr++ = 'L';
1917 *format_ptr++ = type;
1918 *format_ptr = '\0';
1919
1920 // Format using snprintf.
1921 Char fill = static_cast<Char>(spec.fill());
1922 for (;;) {
1923 std::size_t size = buffer_.capacity() - offset;
1924 #if _MSC_VER
1925 // MSVC's vsnprintf_s doesn't work with zero size, so reserve
1926 // space for at least one extra character to make the size non-zero.
1927 // Note that the buffer's capacity will increase by more than 1.
1928 if (size == 0) {
1929 buffer_.reserve(offset + 1);
1930 size = buffer_.capacity() - offset;
1931 }
1932 #endif
1933 Char *start = &buffer_[offset];
1934 int n = internal::CharTraits<Char>::format_float(
1935 start, size, format, width_for_sprintf, spec.precision(), value);
1936 if (n >= 0 && offset + n < buffer_.capacity()) {
1937 if (sign) {
1938 if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) ||
1939 *start != ' ') {
1940 *(start - 1) = sign;
1941 sign = 0;
1942 } else {
1943 *(start - 1) = fill;
1944 }
1945 ++n;
1946 }
1947 if (spec.align() == ALIGN_CENTER &&
1948 spec.width() > static_cast<unsigned>(n)) {
1949 unsigned width = spec.width();
1950 CharPtr p = grow_buffer(width);
1951 std::copy(p, p + n, p + (width - n) / 2);
1952 fill_padding(p, spec.width(), n, fill);
1953 return;
1954 }
1955 if (spec.fill() != ' ' || sign) {
1956 while (*start == ' ')
1957 *start++ = fill;
1958 if (sign)
1959 *(start - 1) = sign;
1960 }
1961 grow_buffer(n);
1962 return;
1963 }
1964 // If n is negative we ask to increase the capacity by at least 1,
1965 // but as std::vector, the buffer grows exponentially.
1966 buffer_.reserve(n >= 0 ? offset + n + 1 : buffer_.capacity() + 1);
1967 }
1968 }
1969
1970 /**
1971 \rst
1972 This template provides operations for formatting and writing data into
1973 a character stream. The output is stored in a memory buffer that grows
1974 dynamically.
1975
1976 You can use one of the following typedefs for common character types
1977 and the standard allocator:
1978
1979 +---------------+-----------------------------------------------+
1980 | Type | Definition |
1981 +===============+===============================================+
1982 | MemoryWriter | BasicWriter<char, std::allocator<char>> |
1983 +---------------+-----------------------------------------------+
1984 | WMemoryWriter | BasicWriter<wchar_t, std::allocator<wchar_t>> |
1985 +---------------+-----------------------------------------------+
1986
1987 **Example**::
1988
1989 MemoryWriter out;
1990 out << "The answer is " << 42 << "\n";
1991 out.write("({:+f}, {:+f})", -3.14, 3.14);
1992
1993 This will write the following output to the ``out`` object:
1994
1995 .. code-block:: none
1996
1997 The answer is 42
1998 (-3.140000, +3.140000)
1999
2000 The output can be converted to an ``std::string`` with ``out.str()`` or
2001 accessed as a C string with ``out.c_str()``.
2002 \endrst
2003 */
2004 template <typename Char, typename Allocator = std::allocator<Char> >
2005 class BasicMemoryWriter : public BasicWriter<Char> {
2006 private:
2007 internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_;
2008
2009 public:
BasicMemoryWriter(const Allocator & alloc=Allocator ())2010 explicit BasicMemoryWriter(const Allocator& alloc = Allocator())
2011 : BasicWriter<Char>(buffer_), buffer_(alloc) {}
2012
2013 #if FMT_USE_RVALUE_REFERENCES
2014 /**
2015 Constructs a ``BasicMemoryWriter`` object moving the content of the other
2016 object to it.
2017 */
BasicMemoryWriter(BasicMemoryWriter && other)2018 BasicMemoryWriter(BasicMemoryWriter &&other)
2019 : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) {
2020 }
2021
2022 /**
2023 Moves the content of the other ``BasicMemoryWriter`` object to this one.
2024 */
operator =(BasicMemoryWriter && other)2025 BasicMemoryWriter &operator=(BasicMemoryWriter &&other) {
2026 buffer_ = std::move(other.buffer_);
2027 return *this;
2028 }
2029 #endif
2030 };
2031
2032 typedef BasicMemoryWriter<char> MemoryWriter;
2033 typedef BasicMemoryWriter<wchar_t> WMemoryWriter;
2034
2035 // Formats a value.
2036 template <typename Char, typename T>
format(BasicFormatter<Char> & f,const Char * & format_str,const T & value)2037 void format(BasicFormatter<Char> &f, const Char *&format_str, const T &value) {
2038 std::basic_ostringstream<Char> os;
2039 os << value;
2040 internal::Arg arg;
2041 internal::Value &arg_value = arg;
2042 std::basic_string<Char> str = os.str();
2043 arg_value = internal::MakeValue<Char>(str);
2044 arg.type = internal::Arg::STRING;
2045 format_str = f.format(format_str, arg);
2046 }
2047
2048 // Reports a system error without throwing an exception.
2049 // Can be used to report errors from destructors.
2050 void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT(true);
2051
2052 #ifdef _WIN32
2053
2054 /**
2055 A Windows error.
2056 */
2057 class WindowsError : public SystemError {
2058 private:
2059 void init(int error_code, StringRef format_str, ArgList args);
2060
2061 public:
2062 /**
2063 \rst
2064 Constructs a :cpp:class:`fmt::WindowsError` object with the description
2065 of the form "*<message>*: *<system-message>*", where *<message>* is the
2066 formatted message and *<system-message>* is the system message corresponding
2067 to the error code.
2068 *error_code* is a Windows error code as given by ``GetLastError``.
2069 \endrst
2070 */
WindowsError(int error_code,StringRef message)2071 WindowsError(int error_code, StringRef message) {
2072 init(error_code, message, ArgList());
2073 }
2074 FMT_VARIADIC_CTOR(WindowsError, init, int, StringRef)
2075 };
2076
2077 // Reports a Windows error without throwing an exception.
2078 // Can be used to report errors from destructors.
2079 void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT(true);
2080
2081 #endif
2082
2083 enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE };
2084
2085 /**
2086 Formats a string and prints it to stdout using ANSI escape sequences
2087 to specify color (experimental).
2088 Example:
2089 PrintColored(fmt::RED, "Elapsed time: {0:.2f} seconds") << 1.23;
2090 */
2091 void print_colored(Color c, StringRef format, ArgList args);
2092
2093 /**
2094 \rst
2095 Formats arguments and returns the result as a string.
2096
2097 **Example**::
2098
2099 std::string message = format("The answer is {}", 42);
2100 \endrst
2101 */
format(StringRef format_str,ArgList args)2102 inline std::string format(StringRef format_str, ArgList args) {
2103 MemoryWriter w;
2104 w.write(format_str, args);
2105 return w.str();
2106 }
2107
format(WStringRef format_str,ArgList args)2108 inline std::wstring format(WStringRef format_str, ArgList args) {
2109 WMemoryWriter w;
2110 w.write(format_str, args);
2111 return w.str();
2112 }
2113
2114 /**
2115 \rst
2116 Prints formatted data to the file *f*.
2117
2118 **Example**::
2119
2120 print(stderr, "Don't {}!", "panic");
2121 \endrst
2122 */
2123 void print(std::FILE *f, StringRef format_str, ArgList args);
2124
2125 /**
2126 \rst
2127 Prints formatted data to ``stdout``.
2128
2129 **Example**::
2130
2131 print("Elapsed time: {0:.2f} seconds", 1.23);
2132 \endrst
2133 */
2134 void print(StringRef format_str, ArgList args);
2135
2136 /**
2137 \rst
2138 Prints formatted data to the stream *os*.
2139
2140 **Example**::
2141
2142 print(cerr, "Don't {}!", "panic");
2143 \endrst
2144 */
2145 void print(std::ostream &os, StringRef format_str, ArgList args);
2146
2147 template <typename Char>
printf(BasicWriter<Char> & w,BasicStringRef<Char> format,ArgList args)2148 void printf(BasicWriter<Char> &w, BasicStringRef<Char> format, ArgList args) {
2149 internal::PrintfFormatter<Char>().format(w, format, args);
2150 }
2151
2152 /**
2153 \rst
2154 Formats arguments and returns the result as a string.
2155
2156 **Example**::
2157
2158 std::string message = fmt::sprintf("The answer is %d", 42);
2159 \endrst
2160 */
sprintf(StringRef format,ArgList args)2161 inline std::string sprintf(StringRef format, ArgList args) {
2162 MemoryWriter w;
2163 printf(w, format, args);
2164 return w.str();
2165 }
2166
2167 /**
2168 \rst
2169 Prints formatted data to the file *f*.
2170
2171 **Example**::
2172
2173 fmt::fprintf(stderr, "Don't %s!", "panic");
2174 \endrst
2175 */
2176 int fprintf(std::FILE *f, StringRef format, ArgList args);
2177
2178 /**
2179 \rst
2180 Prints formatted data to ``stdout``.
2181
2182 **Example**::
2183
2184 fmt::printf("Elapsed time: %.2f seconds", 1.23);
2185 \endrst
2186 */
printf(StringRef format,ArgList args)2187 inline int printf(StringRef format, ArgList args) {
2188 return fprintf(stdout, format, args);
2189 }
2190
2191 /**
2192 Fast integer formatter.
2193 */
2194 class FormatInt {
2195 private:
2196 // Buffer should be large enough to hold all digits (digits10 + 1),
2197 // a sign and a null character.
2198 enum {BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3};
2199 mutable char buffer_[BUFFER_SIZE];
2200 char *str_;
2201
2202 // Formats value in reverse and returns the number of digits.
format_decimal(ULongLong value)2203 char *format_decimal(ULongLong value) {
2204 char *buffer_end = buffer_ + BUFFER_SIZE - 1;
2205 while (value >= 100) {
2206 // Integer division is slow so do it for a group of two digits instead
2207 // of for every digit. The idea comes from the talk by Alexandrescu
2208 // "Three Optimization Tips for C++". See speed-test for a comparison.
2209 unsigned index = (value % 100) * 2;
2210 value /= 100;
2211 *--buffer_end = internal::DIGITS[index + 1];
2212 *--buffer_end = internal::DIGITS[index];
2213 }
2214 if (value < 10) {
2215 *--buffer_end = static_cast<char>('0' + value);
2216 return buffer_end;
2217 }
2218 unsigned index = static_cast<unsigned>(value * 2);
2219 *--buffer_end = internal::DIGITS[index + 1];
2220 *--buffer_end = internal::DIGITS[index];
2221 return buffer_end;
2222 }
2223
FormatSigned(LongLong value)2224 void FormatSigned(LongLong value) {
2225 ULongLong abs_value = static_cast<ULongLong>(value);
2226 bool negative = value < 0;
2227 if (negative)
2228 abs_value = 0 - abs_value;
2229 str_ = format_decimal(abs_value);
2230 if (negative)
2231 *--str_ = '-';
2232 }
2233
2234 public:
FormatInt(int value)2235 explicit FormatInt(int value) { FormatSigned(value); }
FormatInt(long value)2236 explicit FormatInt(long value) { FormatSigned(value); }
FormatInt(LongLong value)2237 explicit FormatInt(LongLong value) { FormatSigned(value); }
FormatInt(unsigned value)2238 explicit FormatInt(unsigned value) : str_(format_decimal(value)) {}
FormatInt(unsigned long value)2239 explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {}
FormatInt(ULongLong value)2240 explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {}
2241
2242 /**
2243 Returns the number of characters written to the output buffer.
2244 */
size() const2245 std::size_t size() const { return buffer_ - str_ + BUFFER_SIZE - 1; }
2246
2247 /**
2248 Returns a pointer to the output buffer content. No terminating null
2249 character is appended.
2250 */
data() const2251 const char *data() const { return str_; }
2252
2253 /**
2254 Returns a pointer to the output buffer content with terminating null
2255 character appended.
2256 */
c_str() const2257 const char *c_str() const {
2258 buffer_[BUFFER_SIZE - 1] = '\0';
2259 return str_;
2260 }
2261
2262 /**
2263 Returns the content of the output buffer as an `std::string`.
2264 */
str() const2265 std::string str() const { return std::string(str_, size()); }
2266 };
2267
2268 // Formats a decimal integer value writing into buffer and returns
2269 // a pointer to the end of the formatted string. This function doesn't
2270 // write a terminating null character.
2271 template <typename T>
format_decimal(char * & buffer,T value)2272 inline void format_decimal(char *&buffer, T value) {
2273 typename internal::IntTraits<T>::MainType abs_value = value;
2274 if (internal::is_negative(value)) {
2275 *buffer++ = '-';
2276 abs_value = 0 - abs_value;
2277 }
2278 if (abs_value < 100) {
2279 if (abs_value < 10) {
2280 *buffer++ = static_cast<char>('0' + abs_value);
2281 return;
2282 }
2283 unsigned index = static_cast<unsigned>(abs_value * 2);
2284 *buffer++ = internal::DIGITS[index];
2285 *buffer++ = internal::DIGITS[index + 1];
2286 return;
2287 }
2288 unsigned num_digits = internal::count_digits(abs_value);
2289 internal::format_decimal(buffer, abs_value, num_digits);
2290 buffer += num_digits;
2291 }
2292 }
2293
2294 #if FMT_GCC_VERSION
2295 // Use the system_header pragma to suppress warnings about variadic macros
2296 // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't
2297 // work. It is used at the end because we want to suppress as little warnings
2298 // as possible.
2299 # pragma GCC system_header
2300 #endif
2301
2302 // This is used to work around VC++ bugs in handling variadic macros.
2303 #define FMT_EXPAND(args) args
2304
2305 // Returns the number of arguments.
2306 // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s.
2307 #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N())
2308 #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__))
2309 #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
2310 #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
2311
2312 #define FMT_CONCAT(a, b) a##b
2313 #define FMT_FOR_EACH_(N, f, ...) \
2314 FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__))
2315 #define FMT_FOR_EACH(f, ...) \
2316 FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__))
2317
2318 #define FMT_ADD_ARG_NAME(type, index) type arg##index
2319 #define FMT_GET_ARG_NAME(type, index) arg##index
2320
2321 #if FMT_USE_VARIADIC_TEMPLATES
2322 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
2323 template <typename... Args> \
2324 ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
2325 const Args & ... args) { \
2326 using fmt::internal::Value; \
2327 const Value values[fmt::internal::NonZero<sizeof...(Args)>::VALUE] = { \
2328 fmt::internal::MakeValue<Char>(args)... \
2329 }; \
2330 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \
2331 fmt::internal::make_type(args...), values)); \
2332 }
2333 #else
2334 // Defines a wrapper for a function taking __VA_ARGS__ arguments
2335 // and n additional arguments of arbitrary types.
2336 # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \
2337 template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2338 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
2339 FMT_GEN(n, FMT_MAKE_ARG)) { \
2340 const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF_##Char)}; \
2341 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \
2342 fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \
2343 }
2344
2345 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
2346 inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \
2347 call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \
2348 } \
2349 FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \
2350 FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \
2351 FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \
2352 FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \
2353 FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \
2354 FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \
2355 FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \
2356 FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \
2357 FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \
2358 FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \
2359 FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \
2360 FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \
2361 FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \
2362 FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \
2363 FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__)
2364 #endif // FMT_USE_VARIADIC_TEMPLATES
2365
2366 /**
2367 \rst
2368 Defines a variadic function with the specified return type, function name
2369 and argument types passed as variable arguments to this macro.
2370
2371 **Example**::
2372
2373 void print_error(const char *file, int line, const char *format,
2374 fmt::ArgList args) {
2375 fmt::print("{}: {}: ", file, line);
2376 fmt::print(format, args);
2377 }
2378 FMT_VARIADIC(void, print_error, const char *, int, const char *)
2379
2380 ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that
2381 don't implement variadic templates. You don't have to use this macro if
2382 you don't need legacy compiler support and can use variadic templates
2383 directly::
2384
2385 template <typename... Args>
2386 void print_error(const char *file, int line, const char *format,
2387 const Args & ... args) {
2388 fmt::print("{}: {}: ", file, line);
2389 fmt::print(format, args...);
2390 }
2391 \endrst
2392 */
2393 #define FMT_VARIADIC(ReturnType, func, ...) \
2394 FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__)
2395
2396 #define FMT_VARIADIC_W(ReturnType, func, ...) \
2397 FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__)
2398
2399 namespace fmt {
2400 FMT_VARIADIC(std::string, format, StringRef)
2401 FMT_VARIADIC_W(std::wstring, format, WStringRef)
2402 FMT_VARIADIC(void, print, StringRef)
2403 FMT_VARIADIC(void, print, std::FILE *, StringRef)
2404 FMT_VARIADIC(void, print, std::ostream &, StringRef)
2405 FMT_VARIADIC(void, print_colored, Color, StringRef)
2406 FMT_VARIADIC(std::string, sprintf, StringRef)
2407 FMT_VARIADIC(int, printf, StringRef)
2408 FMT_VARIADIC(int, fprintf, std::FILE *, StringRef)
2409 }
2410
2411 // Restore warnings.
2412 #if FMT_GCC_VERSION >= 406
2413 # pragma GCC diagnostic pop
2414 #endif
2415
2416
2417 } // end generic namespace
2418
2419 #endif // FMT_FORMAT_HPP_
2420