Debian Codegraph @

src/libs/alibxx/str/format.hpp

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