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