1 /*
2  Formatting library for C++
3 
4  Copyright (c) 2012 - 2016, Victor Zverovich
5  All rights reserved.
6 
7  Redistribution and use in source and binary forms, with or without
8  modification, are permitted provided that the following conditions are met:
9 
10  1. Redistributions of source code must retain the above copyright notice, this
11     list of conditions and the following disclaimer.
12  2. Redistributions in binary form must reproduce the above copyright notice,
13     this list of conditions and the following disclaimer in the documentation
14     and/or other materials provided with the distribution.
15 
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifndef FMT_FORMAT_H_
29 #define FMT_FORMAT_H_
30 
31 #include <cassert>
32 #include <clocale>
33 #include <cmath>
34 #include <cstdio>
35 #include <cstring>
36 #include <limits>
37 #include <memory>
38 #include <stdexcept>
39 #include <string>
40 #include <vector>
41 #include <utility>
42 
43 #ifdef _SECURE_SCL
44 # define FMT_SECURE_SCL _SECURE_SCL
45 #else
46 # define FMT_SECURE_SCL 0
47 #endif
48 
49 #if FMT_SECURE_SCL
50 # include <iterator>
51 #endif
52 
53 #ifdef _MSC_VER
54 # define FMT_MSC_VER _MSC_VER
55 #else
56 # define FMT_MSC_VER 0
57 #endif
58 
59 #if FMT_MSC_VER && FMT_MSC_VER <= 1500
60 typedef unsigned __int32 uint32_t;
61 typedef unsigned __int64 uint64_t;
62 typedef __int64          intmax_t;
63 #else
64 #include <stdint.h>
65 #endif
66 
67 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
68 # ifdef FMT_EXPORT
69 #  define FMT_API __declspec(dllexport)
70 # elif defined(FMT_SHARED)
71 #  define FMT_API __declspec(dllimport)
72 # endif
73 #endif
74 #ifndef FMT_API
75 # define FMT_API
76 #endif
77 
78 #ifdef __GNUC__
79 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
80 # define FMT_GCC_EXTENSION __extension__
81 # if FMT_GCC_VERSION >= 406
82 #  pragma GCC diagnostic push
83 // Disable the warning about "long long" which is sometimes reported even
84 // when using __extension__.
85 #  pragma GCC diagnostic ignored "-Wlong-long"
86 // Disable the warning about declaration shadowing because it affects too
87 // many valid cases.
88 #  pragma GCC diagnostic ignored "-Wshadow"
89 // Disable the warning about implicit conversions that may change the sign of
90 // an integer; silencing it otherwise would require many explicit casts.
91 #  pragma GCC diagnostic ignored "-Wsign-conversion"
92 # endif
93 # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__
94 #  define FMT_HAS_GXX_CXX11 1
95 # endif
96 #else
97 # define FMT_GCC_EXTENSION
98 #endif
99 
100 #if defined(__INTEL_COMPILER)
101 # define FMT_ICC_VERSION __INTEL_COMPILER
102 #elif defined(__ICL)
103 # define FMT_ICC_VERSION __ICL
104 #endif
105 
106 #if defined(__clang__) && !defined(FMT_ICC_VERSION)
107 # pragma clang diagnostic push
108 # pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
109 # pragma clang diagnostic ignored "-Wpadded"
110 #endif
111 
112 #ifdef __GNUC_LIBSTD__
113 # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
114 #endif
115 
116 #ifdef __has_feature
117 # define FMT_HAS_FEATURE(x) __has_feature(x)
118 #else
119 # define FMT_HAS_FEATURE(x) 0
120 #endif
121 
122 #ifdef __has_builtin
123 # define FMT_HAS_BUILTIN(x) __has_builtin(x)
124 #else
125 # define FMT_HAS_BUILTIN(x) 0
126 #endif
127 
128 #ifdef __has_cpp_attribute
129 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
130 #else
131 # define FMT_HAS_CPP_ATTRIBUTE(x) 0
132 #endif
133 
134 #ifndef FMT_USE_VARIADIC_TEMPLATES
135 // Variadic templates are available in GCC since version 4.4
136 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++
137 // since version 2013.
138 # define FMT_USE_VARIADIC_TEMPLATES \
139    (FMT_HAS_FEATURE(cxx_variadic_templates) || \
140        (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800)
141 #endif
142 
143 #ifndef FMT_USE_RVALUE_REFERENCES
144 // Don't use rvalue references when compiling with clang and an old libstdc++
145 // as the latter doesn't provide std::move.
146 # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402
147 #  define FMT_USE_RVALUE_REFERENCES 0
148 # else
149 #  define FMT_USE_RVALUE_REFERENCES \
150     (FMT_HAS_FEATURE(cxx_rvalue_references) || \
151         (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600)
152 # endif
153 #endif
154 
155 #if FMT_USE_RVALUE_REFERENCES
156 # include <utility>  // for std::move
157 #endif
158 
159 // Check if exceptions are disabled.
160 #if defined(__GNUC__) && !defined(__EXCEPTIONS)
161 # define FMT_EXCEPTIONS 0
162 #endif
163 #if FMT_MSC_VER && !_HAS_EXCEPTIONS
164 # define FMT_EXCEPTIONS 0
165 #endif
166 #ifndef FMT_EXCEPTIONS
167 # define FMT_EXCEPTIONS 1
168 #endif
169 
170 #ifndef FMT_THROW
171 # if FMT_EXCEPTIONS
172 #  define FMT_THROW(x) throw x
173 # else
174 #  define FMT_THROW(x) assert(false)
175 # endif
176 #endif
177 
178 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
179 #ifndef FMT_USE_NOEXCEPT
180 # define FMT_USE_NOEXCEPT 0
181 #endif
182 
183 #ifndef FMT_NOEXCEPT
184 # if FMT_EXCEPTIONS
185 #  if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
186     (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
187     FMT_MSC_VER >= 1900
188 #   define FMT_NOEXCEPT noexcept
189 #  else
190 #   define FMT_NOEXCEPT throw()
191 #  endif
192 # else
193 #  define FMT_NOEXCEPT
194 # endif
195 #endif
196 
197 #ifndef FMT_OVERRIDE
198 # if FMT_USE_OVERRIDE || FMT_HAS_FEATURE(cxx_override) || \
199    (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
200    FMT_MSC_VER >= 1900
201 #  define FMT_OVERRIDE override
202 # else
203 #  define FMT_OVERRIDE
204 # endif
205 #endif
206 
207 
208 // A macro to disallow the copy constructor and operator= functions
209 // This should be used in the private: declarations for a class
210 #ifndef FMT_USE_DELETED_FUNCTIONS
211 # define FMT_USE_DELETED_FUNCTIONS 0
212 #endif
213 
214 #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \
215   (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800
216 # define FMT_DELETED_OR_UNDEFINED  = delete
217 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
218     TypeName(const TypeName&) = delete; \
219     TypeName& operator=(const TypeName&) = delete
220 #else
221 # define FMT_DELETED_OR_UNDEFINED
222 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
223     TypeName(const TypeName&); \
224     TypeName& operator=(const TypeName&)
225 #endif
226 
227 #ifndef FMT_USE_USER_DEFINED_LITERALS
228 // All compilers which support UDLs also support variadic templates. This
229 // makes the fmt::literals implementation easier. However, an explicit check
230 // for variadic templates is added here just in case.
231 // For Intel's compiler both it and the system gcc/msc must support UDLs.
232 # define FMT_USE_USER_DEFINED_LITERALS \
233    FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \
234    (FMT_HAS_FEATURE(cxx_user_literals) || \
235      (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \
236    (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500)
237 #endif
238 
239 #ifndef FMT_ASSERT
240 # define FMT_ASSERT(condition, message) assert((condition) && message)
241 #endif
242 
243 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
244 # define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
245 #endif
246 
247 #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
248 # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
249 #endif
250 
251 // Some compilers masquerade as both MSVC and GCC-likes or
252 // otherwise support __builtin_clz and __builtin_clzll, so
253 // only define FMT_BUILTIN_CLZ using the MSVC intrinsics
254 // if the clz and clzll builtins are not available.
255 #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL)
256 # include <intrin.h>  // _BitScanReverse, _BitScanReverse64
257 
258 namespace fmt {
259 namespace internal {
260 # pragma intrinsic(_BitScanReverse)
clz(uint32_t x)261 inline uint32_t clz(uint32_t x) {
262   unsigned long r = 0;
263   _BitScanReverse(&r, x);
264 
265   assert(x != 0);
266   // Static analysis complains about using uninitialized data
267   // "r", but the only way that can happen is if "x" is 0,
268   // which the callers guarantee to not happen.
269 # pragma warning(suppress: 6102)
270   return 31 - r;
271 }
272 # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
273 
274 # ifdef _WIN64
275 #  pragma intrinsic(_BitScanReverse64)
276 # endif
277 
clzll(uint64_t x)278 inline uint32_t clzll(uint64_t x) {
279   unsigned long r = 0;
280 # ifdef _WIN64
281   _BitScanReverse64(&r, x);
282 # else
283   // Scan the high 32 bits.
284   if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
285     return 63 - (r + 32);
286 
287   // Scan the low 32 bits.
288   _BitScanReverse(&r, static_cast<uint32_t>(x));
289 # endif
290 
291   assert(x != 0);
292   // Static analysis complains about using uninitialized data
293   // "r", but the only way that can happen is if "x" is 0,
294   // which the callers guarantee to not happen.
295 # pragma warning(suppress: 6102)
296   return 63 - r;
297 }
298 # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
299 }
300 }
301 #endif
302 
303 namespace fmt {
304 namespace internal {
305 struct DummyInt {
306   int data[2];
307   operator int() const { return 0; }
308 };
309 typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil;
310 
311 // Dummy implementations of system functions such as signbit and ecvt called
312 // if the latter are not available.
signbit(...)313 inline DummyInt signbit(...) { return DummyInt(); }
_ecvt_s(...)314 inline DummyInt _ecvt_s(...) { return DummyInt(); }
isinf(...)315 inline DummyInt isinf(...) { return DummyInt(); }
_finite(...)316 inline DummyInt _finite(...) { return DummyInt(); }
isnan(...)317 inline DummyInt isnan(...) { return DummyInt(); }
_isnan(...)318 inline DummyInt _isnan(...) { return DummyInt(); }
319 
320 // A helper function to suppress bogus "conditional expression is constant"
321 // warnings.
322 template <typename T>
const_check(T value)323 inline T const_check(T value) { return value; }
324 }
325 }  // namespace fmt
326 
327 namespace std {
328 // Standard permits specialization of std::numeric_limits. This specialization
329 // is used to resolve ambiguity between isinf and std::isinf in glibc:
330 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891
331 // and the same for isnan and signbit.
332 template <>
333 class numeric_limits<fmt::internal::DummyInt> :
334     public std::numeric_limits<int> {
335  public:
336   // Portable version of isinf.
337   template <typename T>
isinfinity(T x)338   static bool isinfinity(T x) {
339     using namespace fmt::internal;
340     // The resolution "priority" is:
341     // isinf macro > std::isinf > ::isinf > fmt::internal::isinf
342     if (const_check(sizeof(isinf(x)) == sizeof(bool) ||
343                     sizeof(isinf(x)) == sizeof(int))) {
344       return isinf(x) != 0;
345     }
346     return !_finite(static_cast<double>(x));
347   }
348 
349   // Portable version of isnan.
350   template <typename T>
isnotanumber(T x)351   static bool isnotanumber(T x) {
352     using namespace fmt::internal;
353     if (const_check(sizeof(isnan(x)) == sizeof(bool) ||
354                     sizeof(isnan(x)) == sizeof(int))) {
355       return isnan(x) != 0;
356     }
357     return _isnan(static_cast<double>(x)) != 0;
358   }
359 
360   // Portable version of signbit.
isnegative(double x)361   static bool isnegative(double x) {
362     using namespace fmt::internal;
363     if (const_check(sizeof(signbit(x)) == sizeof(int)))
364       return signbit(x) != 0;
365     if (x < 0) return true;
366     if (!isnotanumber(x)) return false;
367     int dec = 0, sign = 0;
368     char buffer[2];  // The buffer size must be >= 2 or _ecvt_s will fail.
369     _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign);
370     return sign != 0;
371   }
372 };
373 }  // namespace std
374 
375 namespace fmt {
376 
377 // Fix the warning about long long on older versions of GCC
378 // that don't support the diagnostic pragma.
379 FMT_GCC_EXTENSION typedef long long LongLong;
380 FMT_GCC_EXTENSION typedef unsigned long long ULongLong;
381 
382 #if FMT_USE_RVALUE_REFERENCES
383 using std::move;
384 #endif
385 
386 template <typename Char>
387 class BasicWriter;
388 
389 typedef BasicWriter<char> Writer;
390 typedef BasicWriter<wchar_t> WWriter;
391 
392 template <typename Char>
393 class ArgFormatter;
394 
395 template <typename CharType,
396           typename ArgFormatter = fmt::ArgFormatter<CharType> >
397 class BasicFormatter;
398 
399 /**
400   \rst
401   A string reference. It can be constructed from a C string or ``std::string``.
402 
403   You can use one of the following typedefs for common character types:
404 
405   +------------+-------------------------+
406   | Type       | Definition              |
407   +============+=========================+
408   | StringRef  | BasicStringRef<char>    |
409   +------------+-------------------------+
410   | WStringRef | BasicStringRef<wchar_t> |
411   +------------+-------------------------+
412 
413   This class is most useful as a parameter type to allow passing
414   different types of strings to a function, for example::
415 
416     template <typename... Args>
417     std::string format(StringRef format_str, const Args & ... args);
418 
419     format("{}", 42);
420     format(std::string("{}"), 42);
421   \endrst
422  */
423 template <typename Char>
424 class BasicStringRef {
425  private:
426   const Char *data_;
427   std::size_t size_;
428 
429  public:
430   /** Constructs a string reference object from a C string and a size. */
BasicStringRef(const Char * s,std::size_t size)431   BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {}
432 
433   /**
434     \rst
435     Constructs a string reference object from a C string computing
436     the size with ``std::char_traits<Char>::length``.
437     \endrst
438    */
BasicStringRef(const Char * s)439   BasicStringRef(const Char *s)
440     : data_(s), size_(std::char_traits<Char>::length(s)) {}
441 
442   /**
443     \rst
444     Constructs a string reference from an ``std::string`` object.
445     \endrst
446    */
BasicStringRef(const std::basic_string<Char> & s)447   BasicStringRef(const std::basic_string<Char> &s)
448   : data_(s.c_str()), size_(s.size()) {}
449 
450   /**
451     \rst
452     Converts a string reference to an ``std::string`` object.
453     \endrst
454    */
to_string()455   std::basic_string<Char> to_string() const {
456     return std::basic_string<Char>(data_, size_);
457   }
458 
459   /** Returns a pointer to the string data. */
data()460   const Char *data() const { return data_; }
461 
462   /** Returns the string size. */
size()463   std::size_t size() const { return size_; }
464 
465   // Lexicographically compare this string reference to other.
compare(BasicStringRef other)466   int compare(BasicStringRef other) const {
467     std::size_t size = size_ < other.size_ ? size_ : other.size_;
468     int result = std::char_traits<Char>::compare(data_, other.data_, size);
469     if (result == 0)
470       result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
471     return result;
472   }
473 
474   friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) {
475     return lhs.compare(rhs) == 0;
476   }
477   friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) {
478     return lhs.compare(rhs) != 0;
479   }
480   friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) {
481     return lhs.compare(rhs) < 0;
482   }
483   friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) {
484     return lhs.compare(rhs) <= 0;
485   }
486   friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) {
487     return lhs.compare(rhs) > 0;
488   }
489   friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) {
490     return lhs.compare(rhs) >= 0;
491   }
492 };
493 
494 typedef BasicStringRef<char> StringRef;
495 typedef BasicStringRef<wchar_t> WStringRef;
496 
497 /**
498   \rst
499   A reference to a null terminated string. It can be constructed from a C
500   string or ``std::string``.
501 
502   You can use one of the following typedefs for common character types:
503 
504   +-------------+--------------------------+
505   | Type        | Definition               |
506   +=============+==========================+
507   | CStringRef  | BasicCStringRef<char>    |
508   +-------------+--------------------------+
509   | WCStringRef | BasicCStringRef<wchar_t> |
510   +-------------+--------------------------+
511 
512   This class is most useful as a parameter type to allow passing
513   different types of strings to a function, for example::
514 
515     template <typename... Args>
516     std::string format(CStringRef format_str, const Args & ... args);
517 
518     format("{}", 42);
519     format(std::string("{}"), 42);
520   \endrst
521  */
522 template <typename Char>
523 class BasicCStringRef {
524  private:
525   const Char *data_;
526 
527  public:
528   /** Constructs a string reference object from a C string. */
BasicCStringRef(const Char * s)529   BasicCStringRef(const Char *s) : data_(s) {}
530 
531   /**
532     \rst
533     Constructs a string reference from an ``std::string`` object.
534     \endrst
535    */
BasicCStringRef(const std::basic_string<Char> & s)536   BasicCStringRef(const std::basic_string<Char> &s) : data_(s.c_str()) {}
537 
538   /** Returns the pointer to a C string. */
c_str()539   const Char *c_str() const { return data_; }
540 };
541 
542 typedef BasicCStringRef<char> CStringRef;
543 typedef BasicCStringRef<wchar_t> WCStringRef;
544 
545 /** A formatting error such as invalid format string. */
546 class FormatError : public std::runtime_error {
547  public:
FormatError(CStringRef message)548   explicit FormatError(CStringRef message)
549   : std::runtime_error(message.c_str()) {}
550   ~FormatError() throw();
551 };
552 
553 namespace internal {
554 
555 // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T.
556 template <typename T>
557 struct MakeUnsigned { typedef T Type; };
558 
559 #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \
560   template <> \
561   struct MakeUnsigned<T> { typedef U Type; }
562 
563 FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char);
564 FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char);
565 FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short);
566 FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned);
567 FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long);
568 FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong);
569 
570 // Casts nonnegative integer to unsigned.
571 template <typename Int>
to_unsigned(Int value)572 inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) {
573   FMT_ASSERT(value >= 0, "negative value");
574   return static_cast<typename MakeUnsigned<Int>::Type>(value);
575 }
576 
577 // The number of characters to store in the MemoryBuffer object itself
578 // to avoid dynamic memory allocation.
579 enum { INLINE_BUFFER_SIZE = 500 };
580 
581 #if FMT_SECURE_SCL
582 // Use checked iterator to avoid warnings on MSVC.
583 template <typename T>
make_ptr(T * ptr,std::size_t size)584 inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) {
585   return stdext::checked_array_iterator<T*>(ptr, size);
586 }
587 #else
588 template <typename T>
make_ptr(T * ptr,std::size_t)589 inline T *make_ptr(T *ptr, std::size_t) { return ptr; }
590 #endif
591 }  // namespace internal
592 
593 /**
594   \rst
595   A buffer supporting a subset of ``std::vector``'s operations.
596   \endrst
597  */
598 template <typename T>
599 class Buffer {
600  private:
601   FMT_DISALLOW_COPY_AND_ASSIGN(Buffer);
602 
603  protected:
604   T *ptr_;
605   std::size_t size_;
606   std::size_t capacity_;
607 
608   Buffer(T *ptr = 0, std::size_t capacity = 0)
ptr_(ptr)609     : ptr_(ptr), size_(0), capacity_(capacity) {}
610 
611   /**
612     \rst
613     Increases the buffer capacity to hold at least *size* elements updating
614     ``ptr_`` and ``capacity_``.
615     \endrst
616    */
617   virtual void grow(std::size_t size) = 0;
618 
619  public:
~Buffer()620   virtual ~Buffer() {}
621 
622   /** Returns the size of this buffer. */
size()623   std::size_t size() const { return size_; }
624 
625   /** Returns the capacity of this buffer. */
capacity()626   std::size_t capacity() const { return capacity_; }
627 
628   /**
629     Resizes the buffer. If T is a POD type new elements may not be initialized.
630    */
resize(std::size_t new_size)631   void resize(std::size_t new_size) {
632     if (new_size > capacity_)
633       grow(new_size);
634     size_ = new_size;
635   }
636 
637   /**
638     \rst
639     Reserves space to store at least *capacity* elements.
640     \endrst
641    */
reserve(std::size_t capacity)642   void reserve(std::size_t capacity) {
643     if (capacity > capacity_)
644       grow(capacity);
645   }
646 
clear()647   void clear() FMT_NOEXCEPT { size_ = 0; }
648 
push_back(const T & value)649   void push_back(const T &value) {
650     if (size_ == capacity_)
651       grow(size_ + 1);
652     ptr_[size_++] = value;
653   }
654 
655   /** Appends data to the end of the buffer. */
656   template <typename U>
657   void append(const U *begin, const U *end);
658 
659   T &operator[](std::size_t index) { return ptr_[index]; }
660   const T &operator[](std::size_t index) const { return ptr_[index]; }
661 };
662 
663 template <typename T>
664 template <typename U>
append(const U * begin,const U * end)665 void Buffer<T>::append(const U *begin, const U *end) {
666   std::size_t new_size = size_ + internal::to_unsigned(end - begin);
667   if (new_size > capacity_)
668     grow(new_size);
669   std::uninitialized_copy(begin, end,
670                           internal::make_ptr(ptr_, capacity_) + size_);
671   size_ = new_size;
672 }
673 
674 namespace internal {
675 
676 // A memory buffer for trivially copyable/constructible types with the first
677 // SIZE elements stored in the object itself.
678 template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> >
679 class MemoryBuffer : private Allocator, public Buffer<T> {
680  private:
681   T data_[SIZE];
682 
683   // Deallocate memory allocated by the buffer.
deallocate()684   void deallocate() {
685     if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_);
686   }
687 
688  protected:
689   void grow(std::size_t size) FMT_OVERRIDE;
690 
691  public:
692   explicit MemoryBuffer(const Allocator &alloc = Allocator())
Allocator(alloc)693       : Allocator(alloc), Buffer<T>(data_, SIZE) {}
~MemoryBuffer()694   ~MemoryBuffer() { deallocate(); }
695 
696 #if FMT_USE_RVALUE_REFERENCES
697  private:
698   // Move data from other to this buffer.
move(MemoryBuffer & other)699   void move(MemoryBuffer &other) {
700     Allocator &this_alloc = *this, &other_alloc = other;
701     this_alloc = std::move(other_alloc);
702     this->size_ = other.size_;
703     this->capacity_ = other.capacity_;
704     if (other.ptr_ == other.data_) {
705       this->ptr_ = data_;
706       std::uninitialized_copy(other.data_, other.data_ + this->size_,
707                               make_ptr(data_, this->capacity_));
708     } else {
709       this->ptr_ = other.ptr_;
710       // Set pointer to the inline array so that delete is not called
711       // when deallocating.
712       other.ptr_ = other.data_;
713     }
714   }
715 
716  public:
MemoryBuffer(MemoryBuffer && other)717   MemoryBuffer(MemoryBuffer &&other) {
718     move(other);
719   }
720 
721   MemoryBuffer &operator=(MemoryBuffer &&other) {
722     assert(this != &other);
723     deallocate();
724     move(other);
725     return *this;
726   }
727 #endif
728 
729   // Returns a copy of the allocator associated with this buffer.
get_allocator()730   Allocator get_allocator() const { return *this; }
731 };
732 
733 template <typename T, std::size_t SIZE, typename Allocator>
grow(std::size_t size)734 void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) {
735   std::size_t new_capacity = this->capacity_ + this->capacity_ / 2;
736   if (size > new_capacity)
737       new_capacity = size;
738   T *new_ptr = this->allocate(new_capacity);
739   // The following code doesn't throw, so the raw pointer above doesn't leak.
740   std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_,
741                           make_ptr(new_ptr, new_capacity));
742   std::size_t old_capacity = this->capacity_;
743   T *old_ptr = this->ptr_;
744   this->capacity_ = new_capacity;
745   this->ptr_ = new_ptr;
746   // deallocate may throw (at least in principle), but it doesn't matter since
747   // the buffer already uses the new storage and will deallocate it in case
748   // of exception.
749   if (old_ptr != data_)
750     Allocator::deallocate(old_ptr, old_capacity);
751 }
752 
753 // A fixed-size buffer.
754 template <typename Char>
755 class FixedBuffer : public fmt::Buffer<Char> {
756  public:
FixedBuffer(Char * array,std::size_t size)757   FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {}
758 
759  protected:
760   FMT_API void grow(std::size_t size);
761 };
762 
763 template <typename Char>
764 class BasicCharTraits {
765  public:
766 #if FMT_SECURE_SCL
767   typedef stdext::checked_array_iterator<Char*> CharPtr;
768 #else
769   typedef Char *CharPtr;
770 #endif
cast(int value)771   static Char cast(int value) { return static_cast<Char>(value); }
772 };
773 
774 template <typename Char>
775 class CharTraits;
776 
777 template <>
778 class CharTraits<char> : public BasicCharTraits<char> {
779  private:
780   // Conversion from wchar_t to char is not allowed.
781   static char convert(wchar_t);
782 
783  public:
convert(char value)784   static char convert(char value) { return value; }
785 
786   // Formats a floating-point number.
787   template <typename T>
788   FMT_API static int format_float(char *buffer, std::size_t size,
789       const char *format, unsigned width, int precision, T value);
790 };
791 
792 template <>
793 class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> {
794  public:
convert(char value)795   static wchar_t convert(char value) { return value; }
convert(wchar_t value)796   static wchar_t convert(wchar_t value) { return value; }
797 
798   template <typename T>
799   FMT_API static int format_float(wchar_t *buffer, std::size_t size,
800       const wchar_t *format, unsigned width, int precision, T value);
801 };
802 
803 // Checks if a number is negative - used to avoid warnings.
804 template <bool IsSigned>
805 struct SignChecker {
806   template <typename T>
is_negativeSignChecker807   static bool is_negative(T value) { return value < 0; }
808 };
809 
810 template <>
811 struct SignChecker<false> {
812   template <typename T>
813   static bool is_negative(T) { return false; }
814 };
815 
816 // Returns true if value is negative, false otherwise.
817 // Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
818 template <typename T>
819 inline bool is_negative(T value) {
820   return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value);
821 }
822 
823 // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise.
824 template <bool FitsIn32Bits>
825 struct TypeSelector { typedef uint32_t Type; };
826 
827 template <>
828 struct TypeSelector<false> { typedef uint64_t Type; };
829 
830 template <typename T>
831 struct IntTraits {
832   // Smallest of uint32_t and uint64_t that is large enough to represent
833   // all values of T.
834   typedef typename
835     TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType;
836 };
837 
838 FMT_API void report_unknown_type(char code, const char *type);
839 
840 // Static data is placed in this class template to allow header-only
841 // configuration.
842 template <typename T = void>
843 struct FMT_API BasicData {
844   static const uint32_t POWERS_OF_10_32[];
845   static const uint64_t POWERS_OF_10_64[];
846   static const char DIGITS[];
847 };
848 
849 #ifndef FMT_USE_EXTERN_TEMPLATES
850 // Clang doesn't have a feature check for extern templates so we check
851 // for variadic templates which were introduced in the same version.
852 # define FMT_USE_EXTERN_TEMPLATES (__clang__ && FMT_USE_VARIADIC_TEMPLATES)
853 #endif
854 
855 #if FMT_USE_EXTERN_TEMPLATES && !defined(FMT_HEADER_ONLY)
856 extern template struct BasicData<void>;
857 #endif
858 
859 typedef BasicData<> Data;
860 
861 #ifdef FMT_BUILTIN_CLZLL
862 // Returns the number of decimal digits in n. Leading zeros are not counted
863 // except for n == 0 in which case count_digits returns 1.
864 inline unsigned count_digits(uint64_t n) {
865   // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
866   // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
867   int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12;
868   return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1;
869 }
870 #else
871 // Fallback version of count_digits used when __builtin_clz is not available.
872 inline unsigned count_digits(uint64_t n) {
873   unsigned count = 1;
874   for (;;) {
875     // Integer division is slow so do it for a group of four digits instead
876     // of for every digit. The idea comes from the talk by Alexandrescu
877     // "Three Optimization Tips for C++". See speed-test for a comparison.
878     if (n < 10) return count;
879     if (n < 100) return count + 1;
880     if (n < 1000) return count + 2;
881     if (n < 10000) return count + 3;
882     n /= 10000u;
883     count += 4;
884   }
885 }
886 #endif
887 
888 #ifdef FMT_BUILTIN_CLZ
889 // Optional version of count_digits for better performance on 32-bit platforms.
890 inline unsigned count_digits(uint32_t n) {
891   int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12;
892   return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1;
893 }
894 #endif
895 
896 // A functor that doesn't add a thousands separator.
897 struct NoThousandsSep {
898   template <typename Char>
899   void operator()(Char *) {}
900 };
901 
902 // A functor that adds a thousands separator.
903 class ThousandsSep {
904  private:
905   fmt::StringRef sep_;
906 
907   // Index of a decimal digit with the least significant digit having index 0.
908   unsigned digit_index_;
909 
910  public:
911   explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {}
912 
913   template <typename Char>
914   void operator()(Char *&buffer) {
915     if (++digit_index_ % 3 != 0)
916       return;
917     buffer -= sep_.size();
918     std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(),
919                             internal::make_ptr(buffer, sep_.size()));
920   }
921 };
922 
923 // Formats a decimal unsigned integer value writing into buffer.
924 // thousands_sep is a functor that is called after writing each char to
925 // add a thousands separator if necessary.
926 template <typename UInt, typename Char, typename ThousandsSep>
927 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits,
928                            ThousandsSep thousands_sep) {
929   buffer += num_digits;
930   while (value >= 100) {
931     // Integer division is slow so do it for a group of two digits instead
932     // of for every digit. The idea comes from the talk by Alexandrescu
933     // "Three Optimization Tips for C++". See speed-test for a comparison.
934     unsigned index = static_cast<unsigned>((value % 100) * 2);
935     value /= 100;
936     *--buffer = Data::DIGITS[index + 1];
937     thousands_sep(buffer);
938     *--buffer = Data::DIGITS[index];
939     thousands_sep(buffer);
940   }
941   if (value < 10) {
942     *--buffer = static_cast<char>('0' + value);
943     return;
944   }
945   unsigned index = static_cast<unsigned>(value * 2);
946   *--buffer = Data::DIGITS[index + 1];
947   thousands_sep(buffer);
948   *--buffer = Data::DIGITS[index];
949 }
950 
951 template <typename UInt, typename Char>
952 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) {
953   return format_decimal(buffer, value, num_digits, NoThousandsSep());
954 }
955 
956 #ifndef _WIN32
957 # define FMT_USE_WINDOWS_H 0
958 #elif !defined(FMT_USE_WINDOWS_H)
959 # define FMT_USE_WINDOWS_H 1
960 #endif
961 
962 // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h.
963 // All the functionality that relies on it will be disabled too.
964 #if FMT_USE_WINDOWS_H
965 // A converter from UTF-8 to UTF-16.
966 // It is only provided for Windows since other systems support UTF-8 natively.
967 class UTF8ToUTF16 {
968  private:
969   MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_;
970 
971  public:
972   FMT_API explicit UTF8ToUTF16(StringRef s);
973   operator WStringRef() const { return WStringRef(&buffer_[0], size()); }
974   size_t size() const { return buffer_.size() - 1; }
975   const wchar_t *c_str() const { return &buffer_[0]; }
976   std::wstring str() const { return std::wstring(&buffer_[0], size()); }
977 };
978 
979 // A converter from UTF-16 to UTF-8.
980 // It is only provided for Windows since other systems support UTF-8 natively.
981 class UTF16ToUTF8 {
982  private:
983   MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_;
984 
985  public:
986   UTF16ToUTF8() {}
987   FMT_API explicit UTF16ToUTF8(WStringRef s);
988   operator StringRef() const { return StringRef(&buffer_[0], size()); }
989   size_t size() const { return buffer_.size() - 1; }
990   const char *c_str() const { return &buffer_[0]; }
991   std::string str() const { return std::string(&buffer_[0], size()); }
992 
993   // Performs conversion returning a system error code instead of
994   // throwing exception on conversion error. This method may still throw
995   // in case of memory allocation error.
996   FMT_API int convert(WStringRef s);
997 };
998 
999 FMT_API void format_windows_error(fmt::Writer &out, int error_code,
1000                                   fmt::StringRef message) FMT_NOEXCEPT;
1001 #endif
1002 
1003 FMT_API void format_system_error(fmt::Writer &out, int error_code,
1004                                  fmt::StringRef message) FMT_NOEXCEPT;
1005 
1006 // A formatting argument value.
1007 struct Value {
1008   template <typename Char>
1009   struct StringValue {
1010     const Char *value;
1011     std::size_t size;
1012   };
1013 
1014   typedef void (*FormatFunc)(
1015       void *formatter, const void *arg, void *format_str_ptr);
1016 
1017   struct CustomValue {
1018     const void *value;
1019     FormatFunc format;
1020   };
1021 
1022   union {
1023     int int_value;
1024     unsigned uint_value;
1025     LongLong long_long_value;
1026     ULongLong ulong_long_value;
1027     double double_value;
1028     long double long_double_value;
1029     const void *pointer;
1030     StringValue<char> string;
1031     StringValue<signed char> sstring;
1032     StringValue<unsigned char> ustring;
1033     StringValue<wchar_t> wstring;
1034     CustomValue custom;
1035   };
1036 
1037   enum Type {
1038     NONE, NAMED_ARG,
1039     // Integer types should go first,
1040     INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR,
1041     // followed by floating-point types.
1042     DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE,
1043     CSTRING, STRING, WSTRING, POINTER, CUSTOM
1044   };
1045 };
1046 
1047 // A formatting argument. It is a trivially copyable/constructible type to
1048 // allow storage in internal::MemoryBuffer.
1049 struct Arg : Value {
1050   Type type;
1051 };
1052 
1053 template <typename Char>
1054 struct NamedArg;
1055 
1056 template <typename T = void>
1057 struct Null {};
1058 
1059 // A helper class template to enable or disable overloads taking wide
1060 // characters and strings in MakeValue.
1061 template <typename T, typename Char>
1062 struct WCharHelper {
1063   typedef Null<T> Supported;
1064   typedef T Unsupported;
1065 };
1066 
1067 template <typename T>
1068 struct WCharHelper<T, wchar_t> {
1069   typedef T Supported;
1070   typedef Null<T> Unsupported;
1071 };
1072 
1073 typedef char Yes[1];
1074 typedef char No[2];
1075 
1076 template <typename T>
1077 T &get();
1078 
1079 // These are non-members to workaround an overload resolution bug in bcc32.
1080 Yes &convert(fmt::ULongLong);
1081 No &convert(...);
1082 
1083 template<typename T, bool ENABLE_CONVERSION>
1084 struct ConvertToIntImpl {
1085   enum { value = ENABLE_CONVERSION };
1086 };
1087 
1088 template<typename T, bool ENABLE_CONVERSION>
1089 struct ConvertToIntImpl2 {
1090   enum { value = false };
1091 };
1092 
1093 template<typename T>
1094 struct ConvertToIntImpl2<T, true> {
1095   enum {
1096     // Don't convert numeric types.
1097     value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value
1098   };
1099 };
1100 
1101 template<typename T>
1102 struct ConvertToInt {
1103   enum { enable_conversion = sizeof(convert(get<T>())) == sizeof(Yes) };
1104   enum { value = ConvertToIntImpl2<T, enable_conversion>::value };
1105 };
1106 
1107 #define FMT_DISABLE_CONVERSION_TO_INT(Type) \
1108   template <> \
1109   struct ConvertToInt<Type> {  enum { value = 0 }; }
1110 
1111 // Silence warnings about convering float to int.
1112 FMT_DISABLE_CONVERSION_TO_INT(float);
1113 FMT_DISABLE_CONVERSION_TO_INT(double);
1114 FMT_DISABLE_CONVERSION_TO_INT(long double);
1115 
1116 template<bool B, class T = void>
1117 struct EnableIf {};
1118 
1119 template<class T>
1120 struct EnableIf<true, T> { typedef T type; };
1121 
1122 template<bool B, class T, class F>
1123 struct Conditional { typedef T type; };
1124 
1125 template<class T, class F>
1126 struct Conditional<false, T, F> { typedef F type; };
1127 
1128 // For bcc32 which doesn't understand ! in template arguments.
1129 template<bool>
1130 struct Not { enum { value = 0 }; };
1131 
1132 template<>
1133 struct Not<false> { enum { value = 1 }; };
1134 
1135 template<typename T, T> struct LConvCheck {
1136   LConvCheck(int) {}
1137 };
1138 
1139 // Returns the thousands separator for the current locale.
1140 // We check if ``lconv`` contains ``thousands_sep`` because on Android
1141 // ``lconv`` is stubbed as an empty struct.
1142 template <typename LConv>
1143 inline StringRef thousands_sep(
1144     LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0) {
1145   return lc->thousands_sep;
1146 }
1147 
1148 inline fmt::StringRef thousands_sep(...) { return ""; }
1149 
1150 // Makes an Arg object from any type.
1151 template <typename Formatter>
1152 class MakeValue : public Arg {
1153  public:
1154   typedef typename Formatter::Char Char;
1155 
1156  private:
1157   // The following two methods are private to disallow formatting of
1158   // arbitrary pointers. If you want to output a pointer cast it to
1159   // "void *" or "const void *". In particular, this forbids formatting
1160   // of "[const] volatile char *" which is printed as bool by iostreams.
1161   // Do not implement!
1162   template <typename T>
1163   MakeValue(const T *value);
1164   template <typename T>
1165   MakeValue(T *value);
1166 
1167   // The following methods are private to disallow formatting of wide
1168   // characters and strings into narrow strings as in
1169   //   fmt::format("{}", L"test");
1170   // To fix this, use a wide format string: fmt::format(L"{}", L"test").
1171 #if !FMT_MSC_VER || defined(_NATIVE_WCHAR_T_DEFINED)
1172   MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported);
1173 #endif
1174   MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported);
1175   MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported);
1176   MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported);
1177   MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported);
1178 
1179   void set_string(StringRef str) {
1180     string.value = str.data();
1181     string.size = str.size();
1182   }
1183 
1184   void set_string(WStringRef str) {
1185     wstring.value = str.data();
1186     wstring.size = str.size();
1187   }
1188 
1189   // Formats an argument of a custom type, such as a user-defined class.
1190   template <typename T>
1191   static void format_custom_arg(
1192       void *formatter, const void *arg, void *format_str_ptr) {
1193     format(*static_cast<Formatter*>(formatter),
1194            *static_cast<const Char**>(format_str_ptr),
1195            *static_cast<const T*>(arg));
1196   }
1197 
1198  public:
1199   MakeValue() {}
1200 
1201 #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \
1202   MakeValue(Type value) { field = rhs; } \
1203   static uint64_t type(Type) { return Arg::TYPE; }
1204 
1205 #define FMT_MAKE_VALUE(Type, field, TYPE) \
1206   FMT_MAKE_VALUE_(Type, field, TYPE, value)
1207 
1208   FMT_MAKE_VALUE(bool, int_value, BOOL)
1209   FMT_MAKE_VALUE(short, int_value, INT)
1210   FMT_MAKE_VALUE(unsigned short, uint_value, UINT)
1211   FMT_MAKE_VALUE(int, int_value, INT)
1212   FMT_MAKE_VALUE(unsigned, uint_value, UINT)
1213 
1214   MakeValue(long value) {
1215     // To minimize the number of types we need to deal with, long is
1216     // translated either to int or to long long depending on its size.
1217     if (const_check(sizeof(long) == sizeof(int)))
1218       int_value = static_cast<int>(value);
1219     else
1220       long_long_value = value;
1221   }
1222   static uint64_t type(long) {
1223     return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG;
1224   }
1225 
1226   MakeValue(unsigned long value) {
1227     if (const_check(sizeof(unsigned long) == sizeof(unsigned)))
1228       uint_value = static_cast<unsigned>(value);
1229     else
1230       ulong_long_value = value;
1231   }
1232   static uint64_t type(unsigned long) {
1233     return sizeof(unsigned long) == sizeof(unsigned) ?
1234           Arg::UINT : Arg::ULONG_LONG;
1235   }
1236 
1237   FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG)
1238   FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG)
1239   FMT_MAKE_VALUE(float, double_value, DOUBLE)
1240   FMT_MAKE_VALUE(double, double_value, DOUBLE)
1241   FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE)
1242   FMT_MAKE_VALUE(signed char, int_value, INT)
1243   FMT_MAKE_VALUE(unsigned char, uint_value, UINT)
1244   FMT_MAKE_VALUE(char, int_value, CHAR)
1245 
1246 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
1247   MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) {
1248     int_value = value;
1249   }
1250   static uint64_t type(wchar_t) { return Arg::CHAR; }
1251 #endif
1252 
1253 #define FMT_MAKE_STR_VALUE(Type, TYPE) \
1254   MakeValue(Type value) { set_string(value); } \
1255   static uint64_t type(Type) { return Arg::TYPE; }
1256 
1257   FMT_MAKE_VALUE(char *, string.value, CSTRING)
1258   FMT_MAKE_VALUE(const char *, string.value, CSTRING)
1259   FMT_MAKE_VALUE(signed char *, sstring.value, CSTRING)
1260   FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING)
1261   FMT_MAKE_VALUE(unsigned char *, ustring.value, CSTRING)
1262   FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING)
1263   FMT_MAKE_STR_VALUE(const std::string &, STRING)
1264   FMT_MAKE_STR_VALUE(StringRef, STRING)
1265   FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str())
1266 
1267 #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \
1268   MakeValue(typename WCharHelper<Type, Char>::Supported value) { \
1269     set_string(value); \
1270   } \
1271   static uint64_t type(Type) { return Arg::TYPE; }
1272 
1273   FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING)
1274   FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING)
1275   FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING)
1276   FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING)
1277 
1278   FMT_MAKE_VALUE(void *, pointer, POINTER)
1279   FMT_MAKE_VALUE(const void *, pointer, POINTER)
1280 
1281   template <typename T>
1282   MakeValue(const T &value,
1283             typename EnableIf<Not<
1284               ConvertToInt<T>::value>::value, int>::type = 0) {
1285     custom.value = &value;
1286     custom.format = &format_custom_arg<T>;
1287   }
1288 
1289   template <typename T>
1290   MakeValue(const T &value,
1291             typename EnableIf<ConvertToInt<T>::value, int>::type = 0) {
1292     int_value = value;
1293   }
1294 
1295   template <typename T>
1296   static uint64_t type(const T &) {
1297     return ConvertToInt<T>::value ? Arg::INT : Arg::CUSTOM;
1298   }
1299 
1300   // Additional template param `Char_` is needed here because make_type always
1301   // uses char.
1302   template <typename Char_>
1303   MakeValue(const NamedArg<Char_> &value) { pointer = &value; }
1304 
1305   template <typename Char_>
1306   static uint64_t type(const NamedArg<Char_> &) { return Arg::NAMED_ARG; }
1307 };
1308 
1309 template <typename Formatter>
1310 class MakeArg : public Arg {
1311 public:
1312   MakeArg() {
1313     type = Arg::NONE;
1314   }
1315 
1316   template <typename T>
1317   MakeArg(const T &value)
1318   : Arg(MakeValue<Formatter>(value)) {
1319     type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value));
1320   }
1321 };
1322 
1323 template <typename Char>
1324 struct NamedArg : Arg {
1325   BasicStringRef<Char> name;
1326 
1327   template <typename T>
1328   NamedArg(BasicStringRef<Char> argname, const T &value)
1329   : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {}
1330 };
1331 
1332 class RuntimeError : public std::runtime_error {
1333  protected:
1334   RuntimeError() : std::runtime_error("") {}
1335   ~RuntimeError() throw();
1336 };
1337 
1338 template <typename Char>
1339 class PrintfArgFormatter;
1340 
1341 template <typename Char>
1342 class ArgMap;
1343 }  // namespace internal
1344 
1345 /** An argument list. */
1346 class ArgList {
1347  private:
1348   // To reduce compiled code size per formatting function call, types of first
1349   // MAX_PACKED_ARGS arguments are passed in the types_ field.
1350   uint64_t types_;
1351   union {
1352     // If the number of arguments is less than MAX_PACKED_ARGS, the argument
1353     // values are stored in values_, otherwise they are stored in args_.
1354     // This is done to reduce compiled code size as storing larger objects
1355     // may require more code (at least on x86-64) even if the same amount of
1356     // data is actually copied to stack. It saves ~10% on the bloat test.
1357     const internal::Value *values_;
1358     const internal::Arg *args_;
1359   };
1360 
1361   internal::Arg::Type type(unsigned index) const {
1362     unsigned shift = index * 4;
1363     uint64_t mask = 0xf;
1364     return static_cast<internal::Arg::Type>(
1365           (types_ & (mask << shift)) >> shift);
1366   }
1367 
1368   template <typename Char>
1369   friend class internal::ArgMap;
1370 
1371  public:
1372   // Maximum number of arguments with packed types.
1373   enum { MAX_PACKED_ARGS = 16 };
1374 
1375   ArgList() : types_(0) {}
1376 
1377   ArgList(ULongLong types, const internal::Value *values)
1378   : types_(types), values_(values) {}
1379   ArgList(ULongLong types, const internal::Arg *args)
1380   : types_(types), args_(args) {}
1381 
1382   /** Returns the argument at specified index. */
1383   internal::Arg operator[](unsigned index) const {
1384     using internal::Arg;
1385     Arg arg;
1386     bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE;
1387     if (index < MAX_PACKED_ARGS) {
1388       Arg::Type arg_type = type(index);
1389       internal::Value &val = arg;
1390       if (arg_type != Arg::NONE)
1391         val = use_values ? values_[index] : args_[index];
1392       arg.type = arg_type;
1393       return arg;
1394     }
1395     if (use_values) {
1396       // The index is greater than the number of arguments that can be stored
1397       // in values, so return a "none" argument.
1398       arg.type = Arg::NONE;
1399       return arg;
1400     }
1401     for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) {
1402       if (args_[i].type == Arg::NONE)
1403         return args_[i];
1404     }
1405     return args_[index];
1406   }
1407 };
1408 
1409 #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call
1410 
1411 /**
1412   \rst
1413   An argument visitor based on the `curiously recurring template pattern
1414   <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
1415 
1416   To use `~fmt::ArgVisitor` define a subclass that implements some or all of the
1417   visit methods with the same signatures as the methods in `~fmt::ArgVisitor`,
1418   for example, `~fmt::ArgVisitor::visit_int()`.
1419   Pass the subclass as the *Impl* template parameter. Then calling
1420   `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method
1421   specific to the argument type. For example, if the argument type is
1422   ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
1423   will be called. If the subclass doesn't contain a method with this signature,
1424   then a corresponding method of `~fmt::ArgVisitor` will be called.
1425 
1426   **Example**::
1427 
1428     class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> {
1429      public:
1430       void visit_int(int value) { fmt::print("{}", value); }
1431       void visit_double(double value) { fmt::print("{}", value ); }
1432     };
1433   \endrst
1434  */
1435 template <typename Impl, typename Result>
1436 class ArgVisitor {
1437  private:
1438   typedef internal::Arg Arg;
1439 
1440  public:
1441   void report_unhandled_arg() {}
1442 
1443   Result visit_unhandled_arg() {
1444     FMT_DISPATCH(report_unhandled_arg());
1445     return Result();
1446   }
1447 
1448   /** Visits an ``int`` argument. **/
1449   Result visit_int(int value) {
1450     return FMT_DISPATCH(visit_any_int(value));
1451   }
1452 
1453   /** Visits a ``long long`` argument. **/
1454   Result visit_long_long(LongLong value) {
1455     return FMT_DISPATCH(visit_any_int(value));
1456   }
1457 
1458   /** Visits an ``unsigned`` argument. **/
1459   Result visit_uint(unsigned value) {
1460     return FMT_DISPATCH(visit_any_int(value));
1461   }
1462 
1463   /** Visits an ``unsigned long long`` argument. **/
1464   Result visit_ulong_long(ULongLong value) {
1465     return FMT_DISPATCH(visit_any_int(value));
1466   }
1467 
1468   /** Visits a ``bool`` argument. **/
1469   Result visit_bool(bool value) {
1470     return FMT_DISPATCH(visit_any_int(value));
1471   }
1472 
1473   /** Visits a ``char`` or ``wchar_t`` argument. **/
1474   Result visit_char(int value) {
1475     return FMT_DISPATCH(visit_any_int(value));
1476   }
1477 
1478   /** Visits an argument of any integral type. **/
1479   template <typename T>
1480   Result visit_any_int(T) {
1481     return FMT_DISPATCH(visit_unhandled_arg());
1482   }
1483 
1484   /** Visits a ``double`` argument. **/
1485   Result visit_double(double value) {
1486     return FMT_DISPATCH(visit_any_double(value));
1487   }
1488 
1489   /** Visits a ``long double`` argument. **/
1490   Result visit_long_double(long double value) {
1491     return FMT_DISPATCH(visit_any_double(value));
1492   }
1493 
1494   /** Visits a ``double`` or ``long double`` argument. **/
1495   template <typename T>
1496   Result visit_any_double(T) {
1497     return FMT_DISPATCH(visit_unhandled_arg());
1498   }
1499 
1500   /** Visits a null-terminated C string (``const char *``) argument. **/
1501   Result visit_cstring(const char *) {
1502     return FMT_DISPATCH(visit_unhandled_arg());
1503   }
1504 
1505   /** Visits a string argument. **/
1506   Result visit_string(Arg::StringValue<char>) {
1507     return FMT_DISPATCH(visit_unhandled_arg());
1508   }
1509 
1510   /** Visits a wide string argument. **/
1511   Result visit_wstring(Arg::StringValue<wchar_t>) {
1512     return FMT_DISPATCH(visit_unhandled_arg());
1513   }
1514 
1515   /** Visits a pointer argument. **/
1516   Result visit_pointer(const void *) {
1517     return FMT_DISPATCH(visit_unhandled_arg());
1518   }
1519 
1520   /** Visits an argument of a custom (user-defined) type. **/
1521   Result visit_custom(Arg::CustomValue) {
1522     return FMT_DISPATCH(visit_unhandled_arg());
1523   }
1524 
1525   /**
1526     \rst
1527     Visits an argument dispatching to the appropriate visit method based on
1528     the argument type. For example, if the argument type is ``double`` then
1529     the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be
1530     called.
1531     \endrst
1532    */
1533   Result visit(const Arg &arg) {
1534     switch (arg.type) {
1535     case Arg::NONE:
1536     case Arg::NAMED_ARG:
1537       FMT_ASSERT(false, "invalid argument type");
1538       break;
1539     case Arg::INT:
1540       return FMT_DISPATCH(visit_int(arg.int_value));
1541     case Arg::UINT:
1542       return FMT_DISPATCH(visit_uint(arg.uint_value));
1543     case Arg::LONG_LONG:
1544       return FMT_DISPATCH(visit_long_long(arg.long_long_value));
1545     case Arg::ULONG_LONG:
1546       return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value));
1547     case Arg::BOOL:
1548       return FMT_DISPATCH(visit_bool(arg.int_value != 0));
1549     case Arg::CHAR:
1550       return FMT_DISPATCH(visit_char(arg.int_value));
1551     case Arg::DOUBLE:
1552       return FMT_DISPATCH(visit_double(arg.double_value));
1553     case Arg::LONG_DOUBLE:
1554       return FMT_DISPATCH(visit_long_double(arg.long_double_value));
1555     case Arg::CSTRING:
1556       return FMT_DISPATCH(visit_cstring(arg.string.value));
1557     case Arg::STRING:
1558       return FMT_DISPATCH(visit_string(arg.string));
1559     case Arg::WSTRING:
1560       return FMT_DISPATCH(visit_wstring(arg.wstring));
1561     case Arg::POINTER:
1562       return FMT_DISPATCH(visit_pointer(arg.pointer));
1563     case Arg::CUSTOM:
1564       return FMT_DISPATCH(visit_custom(arg.custom));
1565     }
1566     return Result();
1567   }
1568 };
1569 
1570 enum Alignment {
1571   ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
1572 };
1573 
1574 // Flags.
1575 enum {
1576   SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8,
1577   CHAR_FLAG = 0x10  // Argument has char type - used in error reporting.
1578 };
1579 
1580 // An empty format specifier.
1581 struct EmptySpec {};
1582 
1583 // A type specifier.
1584 template <char TYPE>
1585 struct TypeSpec : EmptySpec {
1586   Alignment align() const { return ALIGN_DEFAULT; }
1587   unsigned width() const { return 0; }
1588   int precision() const { return -1; }
1589   bool flag(unsigned) const { return false; }
1590   char type() const { return TYPE; }
1591   char fill() const { return ' '; }
1592 };
1593 
1594 // A width specifier.
1595 struct WidthSpec {
1596   unsigned width_;
1597   // Fill is always wchar_t and cast to char if necessary to avoid having
1598   // two specialization of WidthSpec and its subclasses.
1599   wchar_t fill_;
1600 
1601   WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {}
1602 
1603   unsigned width() const { return width_; }
1604   wchar_t fill() const { return fill_; }
1605 };
1606 
1607 // An alignment specifier.
1608 struct AlignSpec : WidthSpec {
1609   Alignment align_;
1610 
1611   AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT)
1612   : WidthSpec(width, fill), align_(align) {}
1613 
1614   Alignment align() const { return align_; }
1615 
1616   int precision() const { return -1; }
1617 };
1618 
1619 // An alignment and type specifier.
1620 template <char TYPE>
1621 struct AlignTypeSpec : AlignSpec {
1622   AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {}
1623 
1624   bool flag(unsigned) const { return false; }
1625   char type() const { return TYPE; }
1626 };
1627 
1628 // A full format specifier.
1629 struct FormatSpec : AlignSpec {
1630   unsigned flags_;
1631   int precision_;
1632   char type_;
1633 
1634   FormatSpec(
1635     unsigned width = 0, char type = 0, wchar_t fill = ' ')
1636   : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {}
1637 
1638   bool flag(unsigned f) const { return (flags_ & f) != 0; }
1639   int precision() const { return precision_; }
1640   char type() const { return type_; }
1641 };
1642 
1643 // An integer format specifier.
1644 template <typename T, typename SpecT = TypeSpec<0>, typename Char = char>
1645 class IntFormatSpec : public SpecT {
1646  private:
1647   T value_;
1648 
1649  public:
1650   IntFormatSpec(T val, const SpecT &spec = SpecT())
1651   : SpecT(spec), value_(val) {}
1652 
1653   T value() const { return value_; }
1654 };
1655 
1656 // A string format specifier.
1657 template <typename Char>
1658 class StrFormatSpec : public AlignSpec {
1659  private:
1660   const Char *str_;
1661 
1662  public:
1663   template <typename FillChar>
1664   StrFormatSpec(const Char *str, unsigned width, FillChar fill)
1665   : AlignSpec(width, fill), str_(str) {
1666     internal::CharTraits<Char>::convert(FillChar());
1667   }
1668 
1669   const Char *str() const { return str_; }
1670 };
1671 
1672 /**
1673   Returns an integer format specifier to format the value in base 2.
1674  */
1675 IntFormatSpec<int, TypeSpec<'b'> > bin(int value);
1676 
1677 /**
1678   Returns an integer format specifier to format the value in base 8.
1679  */
1680 IntFormatSpec<int, TypeSpec<'o'> > oct(int value);
1681 
1682 /**
1683   Returns an integer format specifier to format the value in base 16 using
1684   lower-case letters for the digits above 9.
1685  */
1686 IntFormatSpec<int, TypeSpec<'x'> > hex(int value);
1687 
1688 /**
1689   Returns an integer formatter format specifier to format in base 16 using
1690   upper-case letters for the digits above 9.
1691  */
1692 IntFormatSpec<int, TypeSpec<'X'> > hexu(int value);
1693 
1694 /**
1695   \rst
1696   Returns an integer format specifier to pad the formatted argument with the
1697   fill character to the specified width using the default (right) numeric
1698   alignment.
1699 
1700   **Example**::
1701 
1702     MemoryWriter out;
1703     out << pad(hex(0xcafe), 8, '0');
1704     // out.str() == "0000cafe"
1705 
1706   \endrst
1707  */
1708 template <char TYPE_CODE, typename Char>
1709 IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(
1710     int value, unsigned width, Char fill = ' ');
1711 
1712 #define FMT_DEFINE_INT_FORMATTERS(TYPE) \
1713 inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \
1714   return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \
1715 } \
1716  \
1717 inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \
1718   return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \
1719 } \
1720  \
1721 inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \
1722   return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \
1723 } \
1724  \
1725 inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \
1726   return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \
1727 } \
1728  \
1729 template <char TYPE_CODE> \
1730 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \
1731     IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \
1732   return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \
1733       f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \
1734 } \
1735  \
1736 /* For compatibility with older compilers we provide two overloads for pad, */ \
1737 /* one that takes a fill character and one that doesn't. In the future this */ \
1738 /* can be replaced with one overload making the template argument Char      */ \
1739 /* default to char (C++11). */ \
1740 template <char TYPE_CODE, typename Char> \
1741 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \
1742     IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \
1743     unsigned width, Char fill) { \
1744   return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \
1745       f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \
1746 } \
1747  \
1748 inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \
1749     TYPE value, unsigned width) { \
1750   return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \
1751       value, AlignTypeSpec<0>(width, ' ')); \
1752 } \
1753  \
1754 template <typename Char> \
1755 inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \
1756    TYPE value, unsigned width, Char fill) { \
1757  return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \
1758      value, AlignTypeSpec<0>(width, fill)); \
1759 }
1760 
1761 FMT_DEFINE_INT_FORMATTERS(int)
1762 FMT_DEFINE_INT_FORMATTERS(long)
1763 FMT_DEFINE_INT_FORMATTERS(unsigned)
1764 FMT_DEFINE_INT_FORMATTERS(unsigned long)
1765 FMT_DEFINE_INT_FORMATTERS(LongLong)
1766 FMT_DEFINE_INT_FORMATTERS(ULongLong)
1767 
1768 /**
1769   \rst
1770   Returns a string formatter that pads the formatted argument with the fill
1771   character to the specified width using the default (left) string alignment.
1772 
1773   **Example**::
1774 
1775     std::string s = str(MemoryWriter() << pad("abc", 8));
1776     // s == "abc     "
1777 
1778   \endrst
1779  */
1780 template <typename Char>
1781 inline StrFormatSpec<Char> pad(
1782     const Char *str, unsigned width, Char fill = ' ') {
1783   return StrFormatSpec<Char>(str, width, fill);
1784 }
1785 
1786 inline StrFormatSpec<wchar_t> pad(
1787     const wchar_t *str, unsigned width, char fill = ' ') {
1788   return StrFormatSpec<wchar_t>(str, width, fill);
1789 }
1790 
1791 namespace internal {
1792 
1793 template <typename Char>
1794 class ArgMap {
1795  private:
1796   typedef std::vector<
1797     std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType;
1798   typedef typename MapType::value_type Pair;
1799 
1800   MapType map_;
1801 
1802  public:
1803   FMT_API void init(const ArgList &args);
1804 
1805   const internal::Arg* find(const fmt::BasicStringRef<Char> &name) const {
1806     // The list is unsorted, so just return the first matching name.
1807     for (typename MapType::const_iterator it = map_.begin(), end = map_.end();
1808          it != end; ++it) {
1809       if (it->first == name)
1810         return &it->second;
1811     }
1812     return 0;
1813   }
1814 };
1815 
1816 template <typename Impl, typename Char>
1817 class ArgFormatterBase : public ArgVisitor<Impl, void> {
1818  private:
1819   BasicWriter<Char> &writer_;
1820   FormatSpec &spec_;
1821 
1822   FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase);
1823 
1824   void write_pointer(const void *p) {
1825     spec_.flags_ = HASH_FLAG;
1826     spec_.type_ = 'x';
1827     writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_);
1828   }
1829 
1830  protected:
1831   BasicWriter<Char> &writer() { return writer_; }
1832   FormatSpec &spec() { return spec_; }
1833 
1834   void write(bool value) {
1835     const char *str_value = value ? "true" : "false";
1836     Arg::StringValue<char> str = { str_value, std::strlen(str_value) };
1837     writer_.write_str(str, spec_);
1838   }
1839 
1840   void write(const char *value) {
1841     Arg::StringValue<char> str = {value, value != 0 ? std::strlen(value) : 0};
1842     writer_.write_str(str, spec_);
1843   }
1844 
1845  public:
1846   ArgFormatterBase(BasicWriter<Char> &w, FormatSpec &s)
1847   : writer_(w), spec_(s) {}
1848 
1849   template <typename T>
1850   void visit_any_int(T value) { writer_.write_int(value, spec_); }
1851 
1852   template <typename T>
1853   void visit_any_double(T value) { writer_.write_double(value, spec_); }
1854 
1855   void visit_bool(bool value) {
1856     if (spec_.type_)
1857       return visit_any_int(value);
1858     write(value);
1859   }
1860 
1861   void visit_char(int value) {
1862     if (spec_.type_ && spec_.type_ != 'c') {
1863       spec_.flags_ |= CHAR_FLAG;
1864       writer_.write_int(value, spec_);
1865       return;
1866     }
1867     if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0)
1868       FMT_THROW(FormatError("invalid format specifier for char"));
1869     typedef typename BasicWriter<Char>::CharPtr CharPtr;
1870     Char fill = internal::CharTraits<Char>::cast(spec_.fill());
1871     CharPtr out = CharPtr();
1872     const unsigned CHAR_SIZE = 1;
1873     if (spec_.width_ > CHAR_SIZE) {
1874       out = writer_.grow_buffer(spec_.width_);
1875       if (spec_.align_ == ALIGN_RIGHT) {
1876         std::uninitialized_fill_n(out, spec_.width_ - CHAR_SIZE, fill);
1877         out += spec_.width_ - CHAR_SIZE;
1878       } else if (spec_.align_ == ALIGN_CENTER) {
1879         out = writer_.fill_padding(out, spec_.width_,
1880                                    internal::const_check(CHAR_SIZE), fill);
1881       } else {
1882         std::uninitialized_fill_n(out + CHAR_SIZE,
1883                                   spec_.width_ - CHAR_SIZE, fill);
1884       }
1885     } else {
1886       out = writer_.grow_buffer(CHAR_SIZE);
1887     }
1888     *out = internal::CharTraits<Char>::cast(value);
1889   }
1890 
1891   void visit_cstring(const char *value) {
1892     if (spec_.type_ == 'p')
1893       return write_pointer(value);
1894     write(value);
1895   }
1896 
1897   void visit_string(Arg::StringValue<char> value) {
1898     writer_.write_str(value, spec_);
1899   }
1900 
1901   using ArgVisitor<Impl, void>::visit_wstring;
1902 
1903   void visit_wstring(Arg::StringValue<Char> value) {
1904     writer_.write_str(value, spec_);
1905   }
1906 
1907   void visit_pointer(const void *value) {
1908     if (spec_.type_ && spec_.type_ != 'p')
1909       report_unknown_type(spec_.type_, "pointer");
1910     write_pointer(value);
1911   }
1912 };
1913 
1914 class FormatterBase {
1915  private:
1916   ArgList args_;
1917   int next_arg_index_;
1918 
1919   // Returns the argument with specified index.
1920   FMT_API Arg do_get_arg(unsigned arg_index, const char *&error);
1921 
1922  protected:
1923   const ArgList &args() const { return args_; }
1924 
1925   explicit FormatterBase(const ArgList &args) {
1926     args_ = args;
1927     next_arg_index_ = 0;
1928   }
1929 
1930   // Returns the next argument.
1931   Arg next_arg(const char *&error) {
1932     if (next_arg_index_ >= 0)
1933       return do_get_arg(internal::to_unsigned(next_arg_index_++), error);
1934     error = "cannot switch from manual to automatic argument indexing";
1935     return Arg();
1936   }
1937 
1938   // Checks if manual indexing is used and returns the argument with
1939   // specified index.
1940   Arg get_arg(unsigned arg_index, const char *&error) {
1941     return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg();
1942   }
1943 
1944   bool check_no_auto_index(const char *&error) {
1945     if (next_arg_index_ > 0) {
1946       error = "cannot switch from automatic to manual argument indexing";
1947       return false;
1948     }
1949     next_arg_index_ = -1;
1950     return true;
1951   }
1952 
1953   template <typename Char>
1954   void write(BasicWriter<Char> &w, const Char *start, const Char *end) {
1955     if (start != end)
1956       w << BasicStringRef<Char>(start, internal::to_unsigned(end - start));
1957   }
1958 };
1959 
1960 // A printf formatter.
1961 template <typename Char>
1962 class PrintfFormatter : private FormatterBase {
1963  private:
1964   void parse_flags(FormatSpec &spec, const Char *&s);
1965 
1966   // Returns the argument with specified index or, if arg_index is equal
1967   // to the maximum unsigned value, the next argument.
1968   Arg get_arg(const Char *s,
1969       unsigned arg_index = (std::numeric_limits<unsigned>::max)());
1970 
1971   // Parses argument index, flags and width and returns the argument index.
1972   unsigned parse_header(const Char *&s, FormatSpec &spec);
1973 
1974  public:
1975   explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {}
1976   FMT_API void format(BasicWriter<Char> &writer,
1977                       BasicCStringRef<Char> format_str);
1978 };
1979 }  // namespace internal
1980 
1981 /**
1982   \rst
1983   An argument formatter based on the `curiously recurring template pattern
1984   <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
1985 
1986   To use `~fmt::BasicArgFormatter` define a subclass that implements some or
1987   all of the visit methods with the same signatures as the methods in
1988   `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`.
1989   Pass the subclass as the *Impl* template parameter. When a formatting
1990   function processes an argument, it will dispatch to a visit method
1991   specific to the argument type. For example, if the argument type is
1992   ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
1993   will be called. If the subclass doesn't contain a method with this signature,
1994   then a corresponding method of `~fmt::BasicArgFormatter` or its superclass
1995   will be called.
1996   \endrst
1997  */
1998 template <typename Impl, typename Char>
1999 class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char> {
2000  private:
2001   BasicFormatter<Char, Impl> &formatter_;
2002   const Char *format_;
2003 
2004  public:
2005   /**
2006     \rst
2007     Constructs an argument formatter object.
2008     *formatter* is a reference to the main formatter object, *spec* contains
2009     format specifier information for standard argument types, and *fmt* points
2010     to the part of the format string being parsed for custom argument types.
2011     \endrst
2012    */
2013   BasicArgFormatter(BasicFormatter<Char, Impl> &formatter,
2014                     FormatSpec &spec, const Char *fmt)
2015   : internal::ArgFormatterBase<Impl, Char>(formatter.writer(), spec),
2016     formatter_(formatter), format_(fmt) {}
2017 
2018   /** Formats argument of a custom (user-defined) type. */
2019   void visit_custom(internal::Arg::CustomValue c) {
2020     c.format(&formatter_, c.value, &format_);
2021   }
2022 };
2023 
2024 /** The default argument formatter. */
2025 template <typename Char>
2026 class ArgFormatter : public BasicArgFormatter<ArgFormatter<Char>, Char> {
2027  public:
2028   /** Constructs an argument formatter object. */
2029   ArgFormatter(BasicFormatter<Char> &formatter,
2030                FormatSpec &spec, const Char *fmt)
2031   : BasicArgFormatter<ArgFormatter<Char>, Char>(formatter, spec, fmt) {}
2032 };
2033 
2034 /** This template formats data and writes the output to a writer. */
2035 template <typename CharType, typename ArgFormatter>
2036 class BasicFormatter : private internal::FormatterBase {
2037  public:
2038   /** The character type for the output. */
2039   typedef CharType Char;
2040 
2041  private:
2042   BasicWriter<Char> &writer_;
2043   internal::ArgMap<Char> map_;
2044 
2045   FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter);
2046 
2047   using internal::FormatterBase::get_arg;
2048 
2049   // Checks if manual indexing is used and returns the argument with
2050   // specified name.
2051   internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error);
2052 
2053   // Parses argument index and returns corresponding argument.
2054   internal::Arg parse_arg_index(const Char *&s);
2055 
2056   // Parses argument name and returns corresponding argument.
2057   internal::Arg parse_arg_name(const Char *&s);
2058 
2059  public:
2060   /**
2061    \rst
2062    Constructs a ``BasicFormatter`` object. References to the arguments and
2063    the writer are stored in the formatter object so make sure they have
2064    appropriate lifetimes.
2065    \endrst
2066    */
2067   BasicFormatter(const ArgList &args, BasicWriter<Char> &w)
2068     : internal::FormatterBase(args), writer_(w) {}
2069 
2070   /** Returns a reference to the writer associated with this formatter. */
2071   BasicWriter<Char> &writer() { return writer_; }
2072 
2073   /** Formats stored arguments and writes the output to the writer. */
2074   void format(BasicCStringRef<Char> format_str);
2075 
2076   // Formats a single argument and advances format_str, a format string pointer.
2077   const Char *format(const Char *&format_str, const internal::Arg &arg);
2078 };
2079 
2080 // Generates a comma-separated list with results of applying f to
2081 // numbers 0..n-1.
2082 # define FMT_GEN(n, f) FMT_GEN##n(f)
2083 # define FMT_GEN1(f)  f(0)
2084 # define FMT_GEN2(f)  FMT_GEN1(f),  f(1)
2085 # define FMT_GEN3(f)  FMT_GEN2(f),  f(2)
2086 # define FMT_GEN4(f)  FMT_GEN3(f),  f(3)
2087 # define FMT_GEN5(f)  FMT_GEN4(f),  f(4)
2088 # define FMT_GEN6(f)  FMT_GEN5(f),  f(5)
2089 # define FMT_GEN7(f)  FMT_GEN6(f),  f(6)
2090 # define FMT_GEN8(f)  FMT_GEN7(f),  f(7)
2091 # define FMT_GEN9(f)  FMT_GEN8(f),  f(8)
2092 # define FMT_GEN10(f) FMT_GEN9(f),  f(9)
2093 # define FMT_GEN11(f) FMT_GEN10(f), f(10)
2094 # define FMT_GEN12(f) FMT_GEN11(f), f(11)
2095 # define FMT_GEN13(f) FMT_GEN12(f), f(12)
2096 # define FMT_GEN14(f) FMT_GEN13(f), f(13)
2097 # define FMT_GEN15(f) FMT_GEN14(f), f(14)
2098 
2099 namespace internal {
2100 inline uint64_t make_type() { return 0; }
2101 
2102 template <typename T>
2103 inline uint64_t make_type(const T &arg) {
2104   return MakeValue< BasicFormatter<char> >::type(arg);
2105 }
2106 
2107 template <unsigned N, bool/*IsPacked*/= (N < ArgList::MAX_PACKED_ARGS)>
2108 struct ArgArray;
2109 
2110 template <unsigned N>
2111 struct ArgArray<N, true/*IsPacked*/> {
2112   typedef Value Type[N > 0 ? N : 1];
2113 
2114   template <typename Formatter, typename T>
2115   static Value make(const T &value) {
2116 #ifdef __clang__
2117     Value result = MakeValue<Formatter>(value);
2118     // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang:
2119     // https://github.com/fmtlib/fmt/issues/276
2120     (void)result.custom.format;
2121     return result;
2122 #else
2123     return MakeValue<Formatter>(value);
2124 #endif
2125   }
2126 };
2127 
2128 template <unsigned N>
2129 struct ArgArray<N, false/*IsPacked*/> {
2130   typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE
2131 
2132   template <typename Formatter, typename T>
2133   static Arg make(const T &value) { return MakeArg<Formatter>(value); }
2134 };
2135 
2136 #if FMT_USE_VARIADIC_TEMPLATES
2137 template <typename Arg, typename... Args>
2138 inline uint64_t make_type(const Arg &first, const Args & ... tail) {
2139   return make_type(first) | (make_type(tail...) << 4);
2140 }
2141 
2142 #else
2143 
2144 struct ArgType {
2145   uint64_t type;
2146 
2147   ArgType() : type(0) {}
2148 
2149   template <typename T>
2150   ArgType(const T &arg) : type(make_type(arg)) {}
2151 };
2152 
2153 # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType()
2154 
2155 inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) {
2156   return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) |
2157       (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) |
2158       (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) |
2159       (t12.type << 48) | (t13.type << 52) | (t14.type << 56);
2160 }
2161 #endif
2162 }  // namespace internal
2163 
2164 # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n
2165 # define FMT_MAKE_ARG_TYPE(n) T##n
2166 # define FMT_MAKE_ARG(n) const T##n &v##n
2167 # define FMT_ASSIGN_char(n) \
2168   arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<char> >(v##n)
2169 # define FMT_ASSIGN_wchar_t(n) \
2170   arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<wchar_t> >(v##n)
2171 
2172 #if FMT_USE_VARIADIC_TEMPLATES
2173 // Defines a variadic function returning void.
2174 # define FMT_VARIADIC_VOID(func, arg_type) \
2175   template <typename... Args> \
2176   void func(arg_type arg0, const Args & ... args) { \
2177     typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2178     typename ArgArray::Type array{ \
2179       ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2180     func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2181   }
2182 
2183 // Defines a variadic constructor.
2184 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2185   template <typename... Args> \
2186   ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \
2187     typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2188     typename ArgArray::Type array{ \
2189       ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2190     func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2191   }
2192 
2193 #else
2194 
2195 # define FMT_MAKE_REF(n) \
2196   fmt::internal::MakeValue< fmt::BasicFormatter<Char> >(v##n)
2197 # define FMT_MAKE_REF2(n) v##n
2198 
2199 // Defines a wrapper for a function taking one argument of type arg_type
2200 // and n additional arguments of arbitrary types.
2201 # define FMT_WRAP1(func, arg_type, n) \
2202   template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2203   inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2204     const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2205     func(arg1, fmt::ArgList( \
2206       fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2207   }
2208 
2209 // Emulates a variadic function returning void on a pre-C++11 compiler.
2210 # define FMT_VARIADIC_VOID(func, arg_type) \
2211   inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \
2212   FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \
2213   FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \
2214   FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \
2215   FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \
2216   FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10)
2217 
2218 # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \
2219   template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2220   ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2221     const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2222     func(arg0, arg1, fmt::ArgList( \
2223       fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2224   }
2225 
2226 // Emulates a variadic constructor on a pre-C++11 compiler.
2227 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2228   FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \
2229   FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \
2230   FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \
2231   FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \
2232   FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \
2233   FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \
2234   FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \
2235   FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \
2236   FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \
2237   FMT_CTOR(ctor, func, arg0_type, arg1_type, 10)
2238 #endif
2239 
2240 // Generates a comma-separated list with results of applying f to pairs
2241 // (argument, index).
2242 #define FMT_FOR_EACH1(f, x0) f(x0, 0)
2243 #define FMT_FOR_EACH2(f, x0, x1) \
2244   FMT_FOR_EACH1(f, x0), f(x1, 1)
2245 #define FMT_FOR_EACH3(f, x0, x1, x2) \
2246   FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2)
2247 #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \
2248   FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3)
2249 #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \
2250   FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4)
2251 #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \
2252   FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5)
2253 #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \
2254   FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6)
2255 #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \
2256   FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7)
2257 #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \
2258   FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8)
2259 #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \
2260   FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9)
2261 
2262 /**
2263  An error returned by an operating system or a language runtime,
2264  for example a file opening error.
2265 */
2266 class SystemError : public internal::RuntimeError {
2267  private:
2268   void init(int err_code, CStringRef format_str, ArgList args);
2269 
2270  protected:
2271   int error_code_;
2272 
2273   typedef char Char;  // For FMT_VARIADIC_CTOR.
2274 
2275   SystemError() {}
2276 
2277  public:
2278   /**
2279    \rst
2280    Constructs a :class:`fmt::SystemError` object with the description
2281    of the form
2282 
2283    .. parsed-literal::
2284      *<message>*: *<system-message>*
2285 
2286    where *<message>* is the formatted message and *<system-message>* is
2287    the system message corresponding to the error code.
2288    *error_code* is a system error code as given by ``errno``.
2289    If *error_code* is not a valid error code such as -1, the system message
2290    may look like "Unknown error -1" and is platform-dependent.
2291 
2292    **Example**::
2293 
2294      // This throws a SystemError with the description
2295      //   cannot open file 'madeup': No such file or directory
2296      // or similar (system message may vary).
2297      const char *filename = "madeup";
2298      std::FILE *file = std::fopen(filename, "r");
2299      if (!file)
2300        throw fmt::SystemError(errno, "cannot open file '{}'", filename);
2301    \endrst
2302   */
2303   SystemError(int error_code, CStringRef message) {
2304     init(error_code, message, ArgList());
2305   }
2306   FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef)
2307 
2308   ~SystemError() throw();
2309 
2310   int error_code() const { return error_code_; }
2311 };
2312 
2313 /**
2314   \rst
2315   This template provides operations for formatting and writing data into
2316   a character stream. The output is stored in a buffer provided by a subclass
2317   such as :class:`fmt::BasicMemoryWriter`.
2318 
2319   You can use one of the following typedefs for common character types:
2320 
2321   +---------+----------------------+
2322   | Type    | Definition           |
2323   +=========+======================+
2324   | Writer  | BasicWriter<char>    |
2325   +---------+----------------------+
2326   | WWriter | BasicWriter<wchar_t> |
2327   +---------+----------------------+
2328 
2329   \endrst
2330  */
2331 template <typename Char>
2332 class BasicWriter {
2333  private:
2334   // Output buffer.
2335   Buffer<Char> &buffer_;
2336 
2337   FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter);
2338 
2339   typedef typename internal::CharTraits<Char>::CharPtr CharPtr;
2340 
2341 #if FMT_SECURE_SCL
2342   // Returns pointer value.
2343   static Char *get(CharPtr p) { return p.base(); }
2344 #else
2345   static Char *get(Char *p) { return p; }
2346 #endif
2347 
2348   // Fills the padding around the content and returns the pointer to the
2349   // content area.
2350   static CharPtr fill_padding(CharPtr buffer,
2351       unsigned total_size, std::size_t content_size, wchar_t fill);
2352 
2353   // Grows the buffer by n characters and returns a pointer to the newly
2354   // allocated area.
2355   CharPtr grow_buffer(std::size_t n) {
2356     std::size_t size = buffer_.size();
2357     buffer_.resize(size + n);
2358     return internal::make_ptr(&buffer_[size], n);
2359   }
2360 
2361   // Writes an unsigned decimal integer.
2362   template <typename UInt>
2363   Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) {
2364     unsigned num_digits = internal::count_digits(value);
2365     Char *ptr = get(grow_buffer(prefix_size + num_digits));
2366     internal::format_decimal(ptr + prefix_size, value, num_digits);
2367     return ptr;
2368   }
2369 
2370   // Writes a decimal integer.
2371   template <typename Int>
2372   void write_decimal(Int value) {
2373     typedef typename internal::IntTraits<Int>::MainType MainType;
2374     MainType abs_value = static_cast<MainType>(value);
2375     if (internal::is_negative(value)) {
2376       abs_value = 0 - abs_value;
2377       *write_unsigned_decimal(abs_value, 1) = '-';
2378     } else {
2379       write_unsigned_decimal(abs_value, 0);
2380     }
2381   }
2382 
2383   // Prepare a buffer for integer formatting.
2384   CharPtr prepare_int_buffer(unsigned num_digits,
2385       const EmptySpec &, const char *prefix, unsigned prefix_size) {
2386     unsigned size = prefix_size + num_digits;
2387     CharPtr p = grow_buffer(size);
2388     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2389     return p + size - 1;
2390   }
2391 
2392   template <typename Spec>
2393   CharPtr prepare_int_buffer(unsigned num_digits,
2394     const Spec &spec, const char *prefix, unsigned prefix_size);
2395 
2396   // Formats an integer.
2397   template <typename T, typename Spec>
2398   void write_int(T value, Spec spec);
2399 
2400   // Formats a floating-point number (double or long double).
2401   template <typename T>
2402   void write_double(T value, const FormatSpec &spec);
2403 
2404   // Writes a formatted string.
2405   template <typename StrChar>
2406   CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec);
2407 
2408   template <typename StrChar>
2409   void write_str(const internal::Arg::StringValue<StrChar> &str,
2410                  const FormatSpec &spec);
2411 
2412   // This following methods are private to disallow writing wide characters
2413   // and strings to a char stream. If you want to print a wide string as a
2414   // pointer as std::ostream does, cast it to const void*.
2415   // Do not implement!
2416   void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported);
2417   void operator<<(
2418       typename internal::WCharHelper<const wchar_t *, Char>::Unsupported);
2419 
2420   // Appends floating-point length specifier to the format string.
2421   // The second argument is only used for overload resolution.
2422   void append_float_length(Char *&format_ptr, long double) {
2423     *format_ptr++ = 'L';
2424   }
2425 
2426   template<typename T>
2427   void append_float_length(Char *&, T) {}
2428 
2429   template <typename Impl, typename Char_>
2430   friend class internal::ArgFormatterBase;
2431 
2432   friend class internal::PrintfArgFormatter<Char>;
2433 
2434  protected:
2435   /**
2436     Constructs a ``BasicWriter`` object.
2437    */
2438   explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {}
2439 
2440  public:
2441   /**
2442     \rst
2443     Destroys a ``BasicWriter`` object.
2444     \endrst
2445    */
2446   virtual ~BasicWriter() {}
2447 
2448   /**
2449     Returns the total number of characters written.
2450    */
2451   std::size_t size() const { return buffer_.size(); }
2452 
2453   /**
2454     Returns a pointer to the output buffer content. No terminating null
2455     character is appended.
2456    */
2457   const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; }
2458 
2459   /**
2460     Returns a pointer to the output buffer content with terminating null
2461     character appended.
2462    */
2463   const Char *c_str() const {
2464     std::size_t size = buffer_.size();
2465     buffer_.reserve(size + 1);
2466     buffer_[size] = '\0';
2467     return &buffer_[0];
2468   }
2469 
2470   /**
2471     \rst
2472     Returns the content of the output buffer as an `std::string`.
2473     \endrst
2474    */
2475   std::basic_string<Char> str() const {
2476     return std::basic_string<Char>(&buffer_[0], buffer_.size());
2477   }
2478 
2479   /**
2480     \rst
2481     Writes formatted data.
2482 
2483     *args* is an argument list representing arbitrary arguments.
2484 
2485     **Example**::
2486 
2487        MemoryWriter out;
2488        out.write("Current point:\n");
2489        out.write("({:+f}, {:+f})", -3.14, 3.14);
2490 
2491     This will write the following output to the ``out`` object:
2492 
2493     .. code-block:: none
2494 
2495        Current point:
2496        (-3.140000, +3.140000)
2497 
2498     The output can be accessed using :func:`data()`, :func:`c_str` or
2499     :func:`str` methods.
2500 
2501     See also :ref:`syntax`.
2502     \endrst
2503    */
2504   void write(BasicCStringRef<Char> format, ArgList args) {
2505     BasicFormatter<Char>(args, *this).format(format);
2506   }
2507   FMT_VARIADIC_VOID(write, BasicCStringRef<Char>)
2508 
2509   BasicWriter &operator<<(int value) {
2510     write_decimal(value);
2511     return *this;
2512   }
2513   BasicWriter &operator<<(unsigned value) {
2514     return *this << IntFormatSpec<unsigned>(value);
2515   }
2516   BasicWriter &operator<<(long value) {
2517     write_decimal(value);
2518     return *this;
2519   }
2520   BasicWriter &operator<<(unsigned long value) {
2521     return *this << IntFormatSpec<unsigned long>(value);
2522   }
2523   BasicWriter &operator<<(LongLong value) {
2524     write_decimal(value);
2525     return *this;
2526   }
2527 
2528   /**
2529     \rst
2530     Formats *value* and writes it to the stream.
2531     \endrst
2532    */
2533   BasicWriter &operator<<(ULongLong value) {
2534     return *this << IntFormatSpec<ULongLong>(value);
2535   }
2536 
2537   BasicWriter &operator<<(double value) {
2538     write_double(value, FormatSpec());
2539     return *this;
2540   }
2541 
2542   /**
2543     \rst
2544     Formats *value* using the general format for floating-point numbers
2545     (``'g'``) and writes it to the stream.
2546     \endrst
2547    */
2548   BasicWriter &operator<<(long double value) {
2549     write_double(value, FormatSpec());
2550     return *this;
2551   }
2552 
2553   /**
2554     Writes a character to the stream.
2555    */
2556   BasicWriter &operator<<(char value) {
2557     buffer_.push_back(value);
2558     return *this;
2559   }
2560 
2561   BasicWriter &operator<<(
2562       typename internal::WCharHelper<wchar_t, Char>::Supported value) {
2563     buffer_.push_back(value);
2564     return *this;
2565   }
2566 
2567   /**
2568     \rst
2569     Writes *value* to the stream.
2570     \endrst
2571    */
2572   BasicWriter &operator<<(fmt::BasicStringRef<Char> value) {
2573     const Char *str = value.data();
2574     buffer_.append(str, str + value.size());
2575     return *this;
2576   }
2577 
2578   BasicWriter &operator<<(
2579       typename internal::WCharHelper<StringRef, Char>::Supported value) {
2580     const char *str = value.data();
2581     buffer_.append(str, str + value.size());
2582     return *this;
2583   }
2584 
2585   template <typename T, typename Spec, typename FillChar>
2586   BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) {
2587     internal::CharTraits<Char>::convert(FillChar());
2588     write_int(spec.value(), spec);
2589     return *this;
2590   }
2591 
2592   template <typename StrChar>
2593   BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) {
2594     const StrChar *s = spec.str();
2595     write_str(s, std::char_traits<Char>::length(s), spec);
2596     return *this;
2597   }
2598 
2599   void clear() FMT_NOEXCEPT { buffer_.clear(); }
2600 
2601   Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; }
2602 };
2603 
2604 template <typename Char>
2605 template <typename StrChar>
2606 typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str(
2607       const StrChar *s, std::size_t size, const AlignSpec &spec) {
2608   CharPtr out = CharPtr();
2609   if (spec.width() > size) {
2610     out = grow_buffer(spec.width());
2611     Char fill = internal::CharTraits<Char>::cast(spec.fill());
2612     if (spec.align() == ALIGN_RIGHT) {
2613       std::uninitialized_fill_n(out, spec.width() - size, fill);
2614       out += spec.width() - size;
2615     } else if (spec.align() == ALIGN_CENTER) {
2616       out = fill_padding(out, spec.width(), size, fill);
2617     } else {
2618       std::uninitialized_fill_n(out + size, spec.width() - size, fill);
2619     }
2620   } else {
2621     out = grow_buffer(size);
2622   }
2623   std::uninitialized_copy(s, s + size, out);
2624   return out;
2625 }
2626 
2627 template <typename Char>
2628 template <typename StrChar>
2629 void BasicWriter<Char>::write_str(
2630     const internal::Arg::StringValue<StrChar> &s, const FormatSpec &spec) {
2631   // Check if StrChar is convertible to Char.
2632   internal::CharTraits<Char>::convert(StrChar());
2633   if (spec.type_ && spec.type_ != 's')
2634     internal::report_unknown_type(spec.type_, "string");
2635   const StrChar *str_value = s.value;
2636   std::size_t str_size = s.size;
2637   if (str_size == 0) {
2638     if (!str_value) {
2639       FMT_THROW(FormatError("string pointer is null"));
2640     }
2641   }
2642   std::size_t precision = static_cast<std::size_t>(spec.precision_);
2643   if (spec.precision_ >= 0 && precision < str_size)
2644     str_size = precision;
2645   write_str(str_value, str_size, spec);
2646 }
2647 
2648 template <typename Char>
2649 typename BasicWriter<Char>::CharPtr
2650   BasicWriter<Char>::fill_padding(
2651     CharPtr buffer, unsigned total_size,
2652     std::size_t content_size, wchar_t fill) {
2653   std::size_t padding = total_size - content_size;
2654   std::size_t left_padding = padding / 2;
2655   Char fill_char = internal::CharTraits<Char>::cast(fill);
2656   std::uninitialized_fill_n(buffer, left_padding, fill_char);
2657   buffer += left_padding;
2658   CharPtr content = buffer;
2659   std::uninitialized_fill_n(buffer + content_size,
2660                             padding - left_padding, fill_char);
2661   return content;
2662 }
2663 
2664 template <typename Char>
2665 template <typename Spec>
2666 typename BasicWriter<Char>::CharPtr
2667   BasicWriter<Char>::prepare_int_buffer(
2668     unsigned num_digits, const Spec &spec,
2669     const char *prefix, unsigned prefix_size) {
2670   unsigned width = spec.width();
2671   Alignment align = spec.align();
2672   Char fill = internal::CharTraits<Char>::cast(spec.fill());
2673   if (spec.precision() > static_cast<int>(num_digits)) {
2674     // Octal prefix '0' is counted as a digit, so ignore it if precision
2675     // is specified.
2676     if (prefix_size > 0 && prefix[prefix_size - 1] == '0')
2677       --prefix_size;
2678     unsigned number_size =
2679         prefix_size + internal::to_unsigned(spec.precision());
2680     AlignSpec subspec(number_size, '0', ALIGN_NUMERIC);
2681     if (number_size >= width)
2682       return prepare_int_buffer(num_digits, subspec, prefix, prefix_size);
2683     buffer_.reserve(width);
2684     unsigned fill_size = width - number_size;
2685     if (align != ALIGN_LEFT) {
2686       CharPtr p = grow_buffer(fill_size);
2687       std::uninitialized_fill(p, p + fill_size, fill);
2688     }
2689     CharPtr result = prepare_int_buffer(
2690         num_digits, subspec, prefix, prefix_size);
2691     if (align == ALIGN_LEFT) {
2692       CharPtr p = grow_buffer(fill_size);
2693       std::uninitialized_fill(p, p + fill_size, fill);
2694     }
2695     return result;
2696   }
2697   unsigned size = prefix_size + num_digits;
2698   if (width <= size) {
2699     CharPtr p = grow_buffer(size);
2700     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2701     return p + size - 1;
2702   }
2703   CharPtr p = grow_buffer(width);
2704   CharPtr end = p + width;
2705   if (align == ALIGN_LEFT) {
2706     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2707     p += size;
2708     std::uninitialized_fill(p, end, fill);
2709   } else if (align == ALIGN_CENTER) {
2710     p = fill_padding(p, width, size, fill);
2711     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2712     p += size;
2713   } else {
2714     if (align == ALIGN_NUMERIC) {
2715       if (prefix_size != 0) {
2716         p = std::uninitialized_copy(prefix, prefix + prefix_size, p);
2717         size -= prefix_size;
2718       }
2719     } else {
2720       std::uninitialized_copy(prefix, prefix + prefix_size, end - size);
2721     }
2722     std::uninitialized_fill(p, end - size, fill);
2723     p = end;
2724   }
2725   return p - 1;
2726 }
2727 
2728 template <typename Char>
2729 template <typename T, typename Spec>
2730 void BasicWriter<Char>::write_int(T value, Spec spec) {
2731   unsigned prefix_size = 0;
2732   typedef typename internal::IntTraits<T>::MainType UnsignedType;
2733   UnsignedType abs_value = static_cast<UnsignedType>(value);
2734   char prefix[4] = "";
2735   if (internal::is_negative(value)) {
2736     prefix[0] = '-';
2737     ++prefix_size;
2738     abs_value = 0 - abs_value;
2739   } else if (spec.flag(SIGN_FLAG)) {
2740     prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' ';
2741     ++prefix_size;
2742   }
2743   switch (spec.type()) {
2744   case 0: case 'd': {
2745     unsigned num_digits = internal::count_digits(abs_value);
2746     CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1;
2747     internal::format_decimal(get(p), abs_value, 0);
2748     break;
2749   }
2750   case 'x': case 'X': {
2751     UnsignedType n = abs_value;
2752     if (spec.flag(HASH_FLAG)) {
2753       prefix[prefix_size++] = '0';
2754       prefix[prefix_size++] = spec.type();
2755     }
2756     unsigned num_digits = 0;
2757     do {
2758       ++num_digits;
2759     } while ((n >>= 4) != 0);
2760     Char *p = get(prepare_int_buffer(
2761       num_digits, spec, prefix, prefix_size));
2762     n = abs_value;
2763     const char *digits = spec.type() == 'x' ?
2764         "0123456789abcdef" : "0123456789ABCDEF";
2765     do {
2766       *p-- = digits[n & 0xf];
2767     } while ((n >>= 4) != 0);
2768     break;
2769   }
2770   case 'b': case 'B': {
2771     UnsignedType n = abs_value;
2772     if (spec.flag(HASH_FLAG)) {
2773       prefix[prefix_size++] = '0';
2774       prefix[prefix_size++] = spec.type();
2775     }
2776     unsigned num_digits = 0;
2777     do {
2778       ++num_digits;
2779     } while ((n >>= 1) != 0);
2780     Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2781     n = abs_value;
2782     do {
2783       *p-- = static_cast<Char>('0' + (n & 1));
2784     } while ((n >>= 1) != 0);
2785     break;
2786   }
2787   case 'o': {
2788     UnsignedType n = abs_value;
2789     if (spec.flag(HASH_FLAG))
2790       prefix[prefix_size++] = '0';
2791     unsigned num_digits = 0;
2792     do {
2793       ++num_digits;
2794     } while ((n >>= 3) != 0);
2795     Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2796     n = abs_value;
2797     do {
2798       *p-- = static_cast<Char>('0' + (n & 7));
2799     } while ((n >>= 3) != 0);
2800     break;
2801   }
2802   case 'n': {
2803     unsigned num_digits = internal::count_digits(abs_value);
2804     fmt::StringRef sep = "";
2805 #ifndef ANDROID
2806     sep = internal::thousands_sep(std::localeconv());
2807 #endif
2808     unsigned size = static_cast<unsigned>(
2809           num_digits + sep.size() * ((num_digits - 1) / 3));
2810     CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1;
2811     internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep));
2812     break;
2813   }
2814   default:
2815     internal::report_unknown_type(
2816       spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer");
2817     break;
2818   }
2819 }
2820 
2821 template <typename Char>
2822 template <typename T>
2823 void BasicWriter<Char>::write_double(T value, const FormatSpec &spec) {
2824   // Check type.
2825   char type = spec.type();
2826   bool upper = false;
2827   switch (type) {
2828   case 0:
2829     type = 'g';
2830     break;
2831   case 'e': case 'f': case 'g': case 'a':
2832     break;
2833   case 'F':
2834 #if FMT_MSC_VER
2835     // MSVC's printf doesn't support 'F'.
2836     type = 'f';
2837 #endif
2838     // Fall through.
2839   case 'E': case 'G': case 'A':
2840     upper = true;
2841     break;
2842   default:
2843     internal::report_unknown_type(type, "double");
2844     break;
2845   }
2846 
2847   char sign = 0;
2848   // Use isnegative instead of value < 0 because the latter is always
2849   // false for NaN.
2850   if (internal::FPUtil::isnegative(static_cast<double>(value))) {
2851     sign = '-';
2852     value = -value;
2853   } else if (spec.flag(SIGN_FLAG)) {
2854     sign = spec.flag(PLUS_FLAG) ? '+' : ' ';
2855   }
2856 
2857   if (internal::FPUtil::isnotanumber(value)) {
2858     // Format NaN ourselves because sprintf's output is not consistent
2859     // across platforms.
2860     std::size_t nan_size = 4;
2861     const char *nan = upper ? " NAN" : " nan";
2862     if (!sign) {
2863       --nan_size;
2864       ++nan;
2865     }
2866     CharPtr out = write_str(nan, nan_size, spec);
2867     if (sign)
2868       *out = sign;
2869     return;
2870   }
2871 
2872   if (internal::FPUtil::isinfinity(value)) {
2873     // Format infinity ourselves because sprintf's output is not consistent
2874     // across platforms.
2875     std::size_t inf_size = 4;
2876     const char *inf = upper ? " INF" : " inf";
2877     if (!sign) {
2878       --inf_size;
2879       ++inf;
2880     }
2881     CharPtr out = write_str(inf, inf_size, spec);
2882     if (sign)
2883       *out = sign;
2884     return;
2885   }
2886 
2887   std::size_t offset = buffer_.size();
2888   unsigned width = spec.width();
2889   if (sign) {
2890     buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u));
2891     if (width > 0)
2892       --width;
2893     ++offset;
2894   }
2895 
2896   // Build format string.
2897   enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg
2898   Char format[MAX_FORMAT_SIZE];
2899   Char *format_ptr = format;
2900   *format_ptr++ = '%';
2901   unsigned width_for_sprintf = width;
2902   if (spec.flag(HASH_FLAG))
2903     *format_ptr++ = '#';
2904   if (spec.align() == ALIGN_CENTER) {
2905     width_for_sprintf = 0;
2906   } else {
2907     if (spec.align() == ALIGN_LEFT)
2908       *format_ptr++ = '-';
2909     if (width != 0)
2910       *format_ptr++ = '*';
2911   }
2912   if (spec.precision() >= 0) {
2913     *format_ptr++ = '.';
2914     *format_ptr++ = '*';
2915   }
2916 
2917   append_float_length(format_ptr, value);
2918   *format_ptr++ = type;
2919   *format_ptr = '\0';
2920 
2921   // Format using snprintf.
2922   Char fill = internal::CharTraits<Char>::cast(spec.fill());
2923   unsigned n = 0;
2924   Char *start = 0;
2925   for (;;) {
2926     std::size_t buffer_size = buffer_.capacity() - offset;
2927 #if FMT_MSC_VER
2928     // MSVC's vsnprintf_s doesn't work with zero size, so reserve
2929     // space for at least one extra character to make the size non-zero.
2930     // Note that the buffer's capacity will increase by more than 1.
2931     if (buffer_size == 0) {
2932       buffer_.reserve(offset + 1);
2933       buffer_size = buffer_.capacity() - offset;
2934     }
2935 #endif
2936     start = &buffer_[offset];
2937     int result = internal::CharTraits<Char>::format_float(
2938         start, buffer_size, format, width_for_sprintf, spec.precision(), value);
2939     if (result >= 0) {
2940       n = internal::to_unsigned(result);
2941       if (offset + n < buffer_.capacity())
2942         break;  // The buffer is large enough - continue with formatting.
2943       buffer_.reserve(offset + n + 1);
2944     } else {
2945       // If result is negative we ask to increase the capacity by at least 1,
2946       // but as std::vector, the buffer grows exponentially.
2947       buffer_.reserve(buffer_.capacity() + 1);
2948     }
2949   }
2950   if (sign) {
2951     if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) ||
2952         *start != ' ') {
2953       *(start - 1) = sign;
2954       sign = 0;
2955     } else {
2956       *(start - 1) = fill;
2957     }
2958     ++n;
2959   }
2960   if (spec.align() == ALIGN_CENTER && spec.width() > n) {
2961     width = spec.width();
2962     CharPtr p = grow_buffer(width);
2963     std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char));
2964     fill_padding(p, spec.width(), n, fill);
2965     return;
2966   }
2967   if (spec.fill() != ' ' || sign) {
2968     while (*start == ' ')
2969       *start++ = fill;
2970     if (sign)
2971       *(start - 1) = sign;
2972   }
2973   grow_buffer(n);
2974 }
2975 
2976 /**
2977   \rst
2978   This class template provides operations for formatting and writing data
2979   into a character stream. The output is stored in a memory buffer that grows
2980   dynamically.
2981 
2982   You can use one of the following typedefs for common character types
2983   and the standard allocator:
2984 
2985   +---------------+-----------------------------------------------------+
2986   | Type          | Definition                                          |
2987   +===============+=====================================================+
2988   | MemoryWriter  | BasicMemoryWriter<char, std::allocator<char>>       |
2989   +---------------+-----------------------------------------------------+
2990   | WMemoryWriter | BasicMemoryWriter<wchar_t, std::allocator<wchar_t>> |
2991   +---------------+-----------------------------------------------------+
2992 
2993   **Example**::
2994 
2995      MemoryWriter out;
2996      out << "The answer is " << 42 << "\n";
2997      out.write("({:+f}, {:+f})", -3.14, 3.14);
2998 
2999   This will write the following output to the ``out`` object:
3000 
3001   .. code-block:: none
3002 
3003      The answer is 42
3004      (-3.140000, +3.140000)
3005 
3006   The output can be converted to an ``std::string`` with ``out.str()`` or
3007   accessed as a C string with ``out.c_str()``.
3008   \endrst
3009  */
3010 template <typename Char, typename Allocator = std::allocator<Char> >
3011 class BasicMemoryWriter : public BasicWriter<Char> {
3012  private:
3013   internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_;
3014 
3015  public:
3016   explicit BasicMemoryWriter(const Allocator& alloc = Allocator())
3017     : BasicWriter<Char>(buffer_), buffer_(alloc) {}
3018 
3019 #if FMT_USE_RVALUE_REFERENCES
3020   /**
3021     \rst
3022     Constructs a :class:`fmt::BasicMemoryWriter` object moving the content
3023     of the other object to it.
3024     \endrst
3025    */
3026   BasicMemoryWriter(BasicMemoryWriter &&other)
3027     : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) {
3028   }
3029 
3030   /**
3031     \rst
3032     Moves the content of the other ``BasicMemoryWriter`` object to this one.
3033     \endrst
3034    */
3035   BasicMemoryWriter &operator=(BasicMemoryWriter &&other) {
3036     buffer_ = std::move(other.buffer_);
3037     return *this;
3038   }
3039 #endif
3040 };
3041 
3042 typedef BasicMemoryWriter<char> MemoryWriter;
3043 typedef BasicMemoryWriter<wchar_t> WMemoryWriter;
3044 
3045 /**
3046   \rst
3047   This class template provides operations for formatting and writing data
3048   into a fixed-size array. For writing into a dynamically growing buffer
3049   use :class:`fmt::BasicMemoryWriter`.
3050 
3051   Any write method will throw ``std::runtime_error`` if the output doesn't fit
3052   into the array.
3053 
3054   You can use one of the following typedefs for common character types:
3055 
3056   +--------------+---------------------------+
3057   | Type         | Definition                |
3058   +==============+===========================+
3059   | ArrayWriter  | BasicArrayWriter<char>    |
3060   +--------------+---------------------------+
3061   | WArrayWriter | BasicArrayWriter<wchar_t> |
3062   +--------------+---------------------------+
3063   \endrst
3064  */
3065 template <typename Char>
3066 class BasicArrayWriter : public BasicWriter<Char> {
3067  private:
3068   internal::FixedBuffer<Char> buffer_;
3069 
3070  public:
3071   /**
3072    \rst
3073    Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the
3074    given size.
3075    \endrst
3076    */
3077   BasicArrayWriter(Char *array, std::size_t size)
3078     : BasicWriter<Char>(buffer_), buffer_(array, size) {}
3079 
3080   /**
3081    \rst
3082    Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the
3083    size known at compile time.
3084    \endrst
3085    */
3086   template <std::size_t SIZE>
3087   explicit BasicArrayWriter(Char (&array)[SIZE])
3088     : BasicWriter<Char>(buffer_), buffer_(array, SIZE) {}
3089 };
3090 
3091 typedef BasicArrayWriter<char> ArrayWriter;
3092 typedef BasicArrayWriter<wchar_t> WArrayWriter;
3093 
3094 // Reports a system error without throwing an exception.
3095 // Can be used to report errors from destructors.
3096 FMT_API void report_system_error(int error_code,
3097                                  StringRef message) FMT_NOEXCEPT;
3098 
3099 #if FMT_USE_WINDOWS_H
3100 
3101 /** A Windows error. */
3102 class WindowsError : public SystemError {
3103  private:
3104   FMT_API void init(int error_code, CStringRef format_str, ArgList args);
3105 
3106  public:
3107   /**
3108    \rst
3109    Constructs a :class:`fmt::WindowsError` object with the description
3110    of the form
3111 
3112    .. parsed-literal::
3113      *<message>*: *<system-message>*
3114 
3115    where *<message>* is the formatted message and *<system-message>* is the
3116    system message corresponding to the error code.
3117    *error_code* is a Windows error code as given by ``GetLastError``.
3118    If *error_code* is not a valid error code such as -1, the system message
3119    will look like "error -1".
3120 
3121    **Example**::
3122 
3123      // This throws a WindowsError with the description
3124      //   cannot open file 'madeup': The system cannot find the file specified.
3125      // or similar (system message may vary).
3126      const char *filename = "madeup";
3127      LPOFSTRUCT of = LPOFSTRUCT();
3128      HFILE file = OpenFile(filename, &of, OF_READ);
3129      if (file == HFILE_ERROR) {
3130        throw fmt::WindowsError(GetLastError(),
3131                                "cannot open file '{}'", filename);
3132      }
3133    \endrst
3134   */
3135   WindowsError(int error_code, CStringRef message) {
3136     init(error_code, message, ArgList());
3137   }
3138   FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef)
3139 };
3140 
3141 // Reports a Windows error without throwing an exception.
3142 // Can be used to report errors from destructors.
3143 FMT_API void report_windows_error(int error_code,
3144                                   StringRef message) FMT_NOEXCEPT;
3145 
3146 #endif
3147 
3148 enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE };
3149 
3150 /**
3151   Formats a string and prints it to stdout using ANSI escape sequences
3152   to specify color (experimental).
3153   Example:
3154     print_colored(fmt::RED, "Elapsed time: {0:.2f} seconds", 1.23);
3155  */
3156 FMT_API void print_colored(Color c, CStringRef format, ArgList args);
3157 
3158 /**
3159   \rst
3160   Formats arguments and returns the result as a string.
3161 
3162   **Example**::
3163 
3164     std::string message = format("The answer is {}", 42);
3165   \endrst
3166 */
3167 inline std::string format(CStringRef format_str, ArgList args) {
3168   MemoryWriter w;
3169   w.write(format_str, args);
3170   return w.str();
3171 }
3172 
3173 inline std::wstring format(WCStringRef format_str, ArgList args) {
3174   WMemoryWriter w;
3175   w.write(format_str, args);
3176   return w.str();
3177 }
3178 
3179 /**
3180   \rst
3181   Prints formatted data to the file *f*.
3182 
3183   **Example**::
3184 
3185     print(stderr, "Don't {}!", "panic");
3186   \endrst
3187  */
3188 FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args);
3189 
3190 /**
3191   \rst
3192   Prints formatted data to ``stdout``.
3193 
3194   **Example**::
3195 
3196     print("Elapsed time: {0:.2f} seconds", 1.23);
3197   \endrst
3198  */
3199 FMT_API void print(CStringRef format_str, ArgList args);
3200 
3201 template <typename Char>
3202 void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) {
3203   internal::PrintfFormatter<Char>(args).format(w, format);
3204 }
3205 
3206 /**
3207   \rst
3208   Formats arguments and returns the result as a string.
3209 
3210   **Example**::
3211 
3212     std::string message = fmt::sprintf("The answer is %d", 42);
3213   \endrst
3214 */
3215 inline std::string sprintf(CStringRef format, ArgList args) {
3216   MemoryWriter w;
3217   printf(w, format, args);
3218   return w.str();
3219 }
3220 
3221 inline std::wstring sprintf(WCStringRef format, ArgList args) {
3222   WMemoryWriter w;
3223   printf(w, format, args);
3224   return w.str();
3225 }
3226 
3227 /**
3228   \rst
3229   Prints formatted data to the file *f*.
3230 
3231   **Example**::
3232 
3233     fmt::fprintf(stderr, "Don't %s!", "panic");
3234   \endrst
3235  */
3236 FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args);
3237 
3238 /**
3239   \rst
3240   Prints formatted data to ``stdout``.
3241 
3242   **Example**::
3243 
3244     fmt::printf("Elapsed time: %.2f seconds", 1.23);
3245   \endrst
3246  */
3247 inline int printf(CStringRef format, ArgList args) {
3248   return fprintf(stdout, format, args);
3249 }
3250 
3251 /**
3252   Fast integer formatter.
3253  */
3254 class FormatInt {
3255  private:
3256   // Buffer should be large enough to hold all digits (digits10 + 1),
3257   // a sign and a null character.
3258   enum {BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3};
3259   mutable char buffer_[BUFFER_SIZE];
3260   char *str_;
3261 
3262   // Formats value in reverse and returns the number of digits.
3263   char *format_decimal(ULongLong value) {
3264     char *buffer_end = buffer_ + BUFFER_SIZE - 1;
3265     while (value >= 100) {
3266       // Integer division is slow so do it for a group of two digits instead
3267       // of for every digit. The idea comes from the talk by Alexandrescu
3268       // "Three Optimization Tips for C++". See speed-test for a comparison.
3269       unsigned index = static_cast<unsigned>((value % 100) * 2);
3270       value /= 100;
3271       *--buffer_end = internal::Data::DIGITS[index + 1];
3272       *--buffer_end = internal::Data::DIGITS[index];
3273     }
3274     if (value < 10) {
3275       *--buffer_end = static_cast<char>('0' + value);
3276       return buffer_end;
3277     }
3278     unsigned index = static_cast<unsigned>(value * 2);
3279     *--buffer_end = internal::Data::DIGITS[index + 1];
3280     *--buffer_end = internal::Data::DIGITS[index];
3281     return buffer_end;
3282   }
3283 
3284   void FormatSigned(LongLong value) {
3285     ULongLong abs_value = static_cast<ULongLong>(value);
3286     bool negative = value < 0;
3287     if (negative)
3288       abs_value = 0 - abs_value;
3289     str_ = format_decimal(abs_value);
3290     if (negative)
3291       *--str_ = '-';
3292   }
3293 
3294  public:
3295   explicit FormatInt(int value) { FormatSigned(value); }
3296   explicit FormatInt(long value) { FormatSigned(value); }
3297   explicit FormatInt(LongLong value) { FormatSigned(value); }
3298   explicit FormatInt(unsigned value) : str_(format_decimal(value)) {}
3299   explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {}
3300   explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {}
3301 
3302   /** Returns the number of characters written to the output buffer. */
3303   std::size_t size() const {
3304     return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1);
3305   }
3306 
3307   /**
3308     Returns a pointer to the output buffer content. No terminating null
3309     character is appended.
3310    */
3311   const char *data() const { return str_; }
3312 
3313   /**
3314     Returns a pointer to the output buffer content with terminating null
3315     character appended.
3316    */
3317   const char *c_str() const {
3318     buffer_[BUFFER_SIZE - 1] = '\0';
3319     return str_;
3320   }
3321 
3322   /**
3323     \rst
3324     Returns the content of the output buffer as an ``std::string``.
3325     \endrst
3326    */
3327   std::string str() const { return std::string(str_, size()); }
3328 };
3329 
3330 // Formats a decimal integer value writing into buffer and returns
3331 // a pointer to the end of the formatted string. This function doesn't
3332 // write a terminating null character.
3333 template <typename T>
3334 inline void format_decimal(char *&buffer, T value) {
3335   typedef typename internal::IntTraits<T>::MainType MainType;
3336   MainType abs_value = static_cast<MainType>(value);
3337   if (internal::is_negative(value)) {
3338     *buffer++ = '-';
3339     abs_value = 0 - abs_value;
3340   }
3341   if (abs_value < 100) {
3342     if (abs_value < 10) {
3343       *buffer++ = static_cast<char>('0' + abs_value);
3344       return;
3345     }
3346     unsigned index = static_cast<unsigned>(abs_value * 2);
3347     *buffer++ = internal::Data::DIGITS[index];
3348     *buffer++ = internal::Data::DIGITS[index + 1];
3349     return;
3350   }
3351   unsigned num_digits = internal::count_digits(abs_value);
3352   internal::format_decimal(buffer, abs_value, num_digits);
3353   buffer += num_digits;
3354 }
3355 
3356 /**
3357   \rst
3358   Returns a named argument for formatting functions.
3359 
3360   **Example**::
3361 
3362     print("Elapsed time: {s:.2f} seconds", arg("s", 1.23));
3363 
3364   \endrst
3365  */
3366 template <typename T>
3367 inline internal::NamedArg<char> arg(StringRef name, const T &arg) {
3368   return internal::NamedArg<char>(name, arg);
3369 }
3370 
3371 template <typename T>
3372 inline internal::NamedArg<wchar_t> arg(WStringRef name, const T &arg) {
3373   return internal::NamedArg<wchar_t>(name, arg);
3374 }
3375 
3376 // The following two functions are deleted intentionally to disable
3377 // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``.
3378 template <typename Char>
3379 void arg(StringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED;
3380 template <typename Char>
3381 void arg(WStringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED;
3382 }
3383 
3384 #if FMT_GCC_VERSION
3385 // Use the system_header pragma to suppress warnings about variadic macros
3386 // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't
3387 // work. It is used at the end because we want to suppress as little warnings
3388 // as possible.
3389 # pragma GCC system_header
3390 #endif
3391 
3392 // This is used to work around VC++ bugs in handling variadic macros.
3393 #define FMT_EXPAND(args) args
3394 
3395 // Returns the number of arguments.
3396 // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s.
3397 #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N())
3398 #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__))
3399 #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
3400 #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
3401 
3402 #define FMT_CONCAT(a, b) a##b
3403 #define FMT_FOR_EACH_(N, f, ...) \
3404   FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__))
3405 #define FMT_FOR_EACH(f, ...) \
3406   FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__))
3407 
3408 #define FMT_ADD_ARG_NAME(type, index) type arg##index
3409 #define FMT_GET_ARG_NAME(type, index) arg##index
3410 
3411 #if FMT_USE_VARIADIC_TEMPLATES
3412 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
3413   template <typename... Args> \
3414   ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
3415       const Args & ... args) { \
3416     typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
3417     typename ArgArray::Type array{ \
3418       ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
3419     call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \
3420       fmt::ArgList(fmt::internal::make_type(args...), array)); \
3421   }
3422 #else
3423 // Defines a wrapper for a function taking __VA_ARGS__ arguments
3424 // and n additional arguments of arbitrary types.
3425 # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \
3426   template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
3427   inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \
3428       FMT_GEN(n, FMT_MAKE_ARG)) { \
3429     fmt::internal::ArgArray<n>::Type arr; \
3430     FMT_GEN(n, FMT_ASSIGN_##Char); \
3431     call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \
3432       fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \
3433   }
3434 
3435 # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \
3436   inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \
3437     call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \
3438   } \
3439   FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \
3440   FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \
3441   FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \
3442   FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \
3443   FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \
3444   FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \
3445   FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \
3446   FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \
3447   FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \
3448   FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \
3449   FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \
3450   FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \
3451   FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \
3452   FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \
3453   FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__)
3454 #endif  // FMT_USE_VARIADIC_TEMPLATES
3455 
3456 /**
3457   \rst
3458   Defines a variadic function with the specified return type, function name
3459   and argument types passed as variable arguments to this macro.
3460 
3461   **Example**::
3462 
3463     void print_error(const char *file, int line, const char *format,
3464                      fmt::ArgList args) {
3465       fmt::print("{}: {}: ", file, line);
3466       fmt::print(format, args);
3467     }
3468     FMT_VARIADIC(void, print_error, const char *, int, const char *)
3469 
3470   ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that
3471   don't implement variadic templates. You don't have to use this macro if
3472   you don't need legacy compiler support and can use variadic templates
3473   directly::
3474 
3475     template <typename... Args>
3476     void print_error(const char *file, int line, const char *format,
3477                      const Args & ... args) {
3478       fmt::print("{}: {}: ", file, line);
3479       fmt::print(format, args...);
3480     }
3481   \endrst
3482  */
3483 #define FMT_VARIADIC(ReturnType, func, ...) \
3484   FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__)
3485 
3486 #define FMT_VARIADIC_W(ReturnType, func, ...) \
3487   FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__)
3488 
3489 #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id)
3490 
3491 #define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id)
3492 
3493 /**
3494   \rst
3495   Convenient macro to capture the arguments' names and values into several
3496   ``fmt::arg(name, value)``.
3497 
3498   **Example**::
3499 
3500     int x = 1, y = 2;
3501     print("point: ({x}, {y})", FMT_CAPTURE(x, y));
3502     // same as:
3503     // print("point: ({x}, {y})", arg("x", x), arg("y", y));
3504 
3505   \endrst
3506  */
3507 #define FMT_CAPTURE(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_, __VA_ARGS__)
3508 
3509 #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__)
3510 
3511 namespace fmt {
3512 FMT_VARIADIC(std::string, format, CStringRef)
3513 FMT_VARIADIC_W(std::wstring, format, WCStringRef)
3514 FMT_VARIADIC(void, print, CStringRef)
3515 FMT_VARIADIC(void, print, std::FILE *, CStringRef)
3516 
3517 FMT_VARIADIC(void, print_colored, Color, CStringRef)
3518 FMT_VARIADIC(std::string, sprintf, CStringRef)
3519 FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef)
3520 FMT_VARIADIC(int, printf, CStringRef)
3521 FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef)
3522 
3523 namespace internal {
3524 template <typename Char>
3525 inline bool is_name_start(Char c) {
3526   return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
3527 }
3528 
3529 // Parses an unsigned integer advancing s to the end of the parsed input.
3530 // This function assumes that the first character of s is a digit.
3531 template <typename Char>
3532 unsigned parse_nonnegative_int(const Char *&s) {
3533   assert('0' <= *s && *s <= '9');
3534   unsigned value = 0;
3535   do {
3536     unsigned new_value = value * 10 + (*s++ - '0');
3537     // Check if value wrapped around.
3538     if (new_value < value) {
3539       value = (std::numeric_limits<unsigned>::max)();
3540       break;
3541     }
3542     value = new_value;
3543   } while ('0' <= *s && *s <= '9');
3544   // Convert to unsigned to prevent a warning.
3545   unsigned max_int = (std::numeric_limits<int>::max)();
3546   if (value > max_int)
3547     FMT_THROW(FormatError("number is too big"));
3548   return value;
3549 }
3550 
3551 inline void require_numeric_argument(const Arg &arg, char spec) {
3552   if (arg.type > Arg::LAST_NUMERIC_TYPE) {
3553     std::string message =
3554         fmt::format("format specifier '{}' requires numeric argument", spec);
3555     FMT_THROW(fmt::FormatError(message));
3556   }
3557 }
3558 
3559 template <typename Char>
3560 void check_sign(const Char *&s, const Arg &arg) {
3561   char sign = static_cast<char>(*s);
3562   require_numeric_argument(arg, sign);
3563   if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) {
3564     FMT_THROW(FormatError(fmt::format(
3565       "format specifier '{}' requires signed argument", sign)));
3566   }
3567   ++s;
3568 }
3569 }  // namespace internal
3570 
3571 template <typename Char, typename AF>
3572 inline internal::Arg BasicFormatter<Char, AF>::get_arg(
3573     BasicStringRef<Char> arg_name, const char *&error) {
3574   if (check_no_auto_index(error)) {
3575     map_.init(args());
3576     const internal::Arg *arg = map_.find(arg_name);
3577     if (arg)
3578       return *arg;
3579     error = "argument not found";
3580   }
3581   return internal::Arg();
3582 }
3583 
3584 template <typename Char, typename AF>
3585 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) {
3586   const char *error = 0;
3587   internal::Arg arg = *s < '0' || *s > '9' ?
3588         next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error);
3589   if (error) {
3590     FMT_THROW(FormatError(
3591                 *s != '}' && *s != ':' ? "invalid format string" : error));
3592   }
3593   return arg;
3594 }
3595 
3596 template <typename Char, typename AF>
3597 inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) {
3598   assert(internal::is_name_start(*s));
3599   const Char *start = s;
3600   Char c;
3601   do {
3602     c = *++s;
3603   } while (internal::is_name_start(c) || ('0' <= c && c <= '9'));
3604   const char *error = 0;
3605   internal::Arg arg = get_arg(BasicStringRef<Char>(start, s - start), error);
3606   if (error)
3607     FMT_THROW(FormatError(error));
3608   return arg;
3609 }
3610 
3611 template <typename Char, typename ArgFormatter>
3612 const Char *BasicFormatter<Char, ArgFormatter>::format(
3613     const Char *&format_str, const internal::Arg &arg) {
3614   using internal::Arg;
3615   const Char *s = format_str;
3616   FormatSpec spec;
3617   if (*s == ':') {
3618     if (arg.type == Arg::CUSTOM) {
3619       arg.custom.format(this, arg.custom.value, &s);
3620       return s;
3621     }
3622     ++s;
3623     // Parse fill and alignment.
3624     if (Char c = *s) {
3625       const Char *p = s + 1;
3626       spec.align_ = ALIGN_DEFAULT;
3627       do {
3628         switch (*p) {
3629           case '<':
3630             spec.align_ = ALIGN_LEFT;
3631             break;
3632           case '>':
3633             spec.align_ = ALIGN_RIGHT;
3634             break;
3635           case '=':
3636             spec.align_ = ALIGN_NUMERIC;
3637             break;
3638           case '^':
3639             spec.align_ = ALIGN_CENTER;
3640             break;
3641         }
3642         if (spec.align_ != ALIGN_DEFAULT) {
3643           if (p != s) {
3644             if (c == '}') break;
3645             if (c == '{')
3646               FMT_THROW(FormatError("invalid fill character '{'"));
3647             s += 2;
3648             spec.fill_ = c;
3649           } else ++s;
3650           if (spec.align_ == ALIGN_NUMERIC)
3651             require_numeric_argument(arg, '=');
3652           break;
3653         }
3654       } while (--p >= s);
3655     }
3656 
3657     // Parse sign.
3658     switch (*s) {
3659       case '+':
3660         check_sign(s, arg);
3661         spec.flags_ |= SIGN_FLAG | PLUS_FLAG;
3662         break;
3663       case '-':
3664         check_sign(s, arg);
3665         spec.flags_ |= MINUS_FLAG;
3666         break;
3667       case ' ':
3668         check_sign(s, arg);
3669         spec.flags_ |= SIGN_FLAG;
3670         break;
3671     }
3672 
3673     if (*s == '#') {
3674       require_numeric_argument(arg, '#');
3675       spec.flags_ |= HASH_FLAG;
3676       ++s;
3677     }
3678 
3679     // Parse zero flag.
3680     if (*s == '0') {
3681       require_numeric_argument(arg, '0');
3682       spec.align_ = ALIGN_NUMERIC;
3683       spec.fill_ = '0';
3684       ++s;
3685     }
3686 
3687     // Parse width.
3688     if ('0' <= *s && *s <= '9') {
3689       spec.width_ = internal::parse_nonnegative_int(s);
3690     } else if (*s == '{') {
3691       ++s;
3692       Arg width_arg = internal::is_name_start(*s) ?
3693             parse_arg_name(s) : parse_arg_index(s);
3694       if (*s++ != '}')
3695         FMT_THROW(FormatError("invalid format string"));
3696       ULongLong value = 0;
3697       switch (width_arg.type) {
3698       case Arg::INT:
3699         if (width_arg.int_value < 0)
3700           FMT_THROW(FormatError("negative width"));
3701         value = width_arg.int_value;
3702         break;
3703       case Arg::UINT:
3704         value = width_arg.uint_value;
3705         break;
3706       case Arg::LONG_LONG:
3707         if (width_arg.long_long_value < 0)
3708           FMT_THROW(FormatError("negative width"));
3709         value = width_arg.long_long_value;
3710         break;
3711       case Arg::ULONG_LONG:
3712         value = width_arg.ulong_long_value;
3713         break;
3714       default:
3715         FMT_THROW(FormatError("width is not integer"));
3716       }
3717       if (value > (std::numeric_limits<int>::max)())
3718         FMT_THROW(FormatError("number is too big"));
3719       spec.width_ = static_cast<int>(value);
3720     }
3721 
3722     // Parse precision.
3723     if (*s == '.') {
3724       ++s;
3725       spec.precision_ = 0;
3726       if ('0' <= *s && *s <= '9') {
3727         spec.precision_ = internal::parse_nonnegative_int(s);
3728       } else if (*s == '{') {
3729         ++s;
3730         Arg precision_arg = internal::is_name_start(*s) ?
3731               parse_arg_name(s) : parse_arg_index(s);
3732         if (*s++ != '}')
3733           FMT_THROW(FormatError("invalid format string"));
3734         ULongLong value = 0;
3735         switch (precision_arg.type) {
3736           case Arg::INT:
3737             if (precision_arg.int_value < 0)
3738               FMT_THROW(FormatError("negative precision"));
3739             value = precision_arg.int_value;
3740             break;
3741           case Arg::UINT:
3742             value = precision_arg.uint_value;
3743             break;
3744           case Arg::LONG_LONG:
3745             if (precision_arg.long_long_value < 0)
3746               FMT_THROW(FormatError("negative precision"));
3747             value = precision_arg.long_long_value;
3748             break;
3749           case Arg::ULONG_LONG:
3750             value = precision_arg.ulong_long_value;
3751             break;
3752           default:
3753             FMT_THROW(FormatError("precision is not integer"));
3754         }
3755         if (value > (std::numeric_limits<int>::max)())
3756           FMT_THROW(FormatError("number is too big"));
3757         spec.precision_ = static_cast<int>(value);
3758       } else {
3759         FMT_THROW(FormatError("missing precision specifier"));
3760       }
3761       if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) {
3762         FMT_THROW(FormatError(
3763             fmt::format("precision not allowed in {} format specifier",
3764             arg.type == Arg::POINTER ? "pointer" : "integer")));
3765       }
3766     }
3767 
3768     // Parse type.
3769     if (*s != '}' && *s)
3770       spec.type_ = static_cast<char>(*s++);
3771   }
3772 
3773   if (*s++ != '}')
3774     FMT_THROW(FormatError("missing '}' in format string"));
3775 
3776   // Format argument.
3777   ArgFormatter(*this, spec, s - 1).visit(arg);
3778   return s;
3779 }
3780 
3781 template <typename Char, typename AF>
3782 void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) {
3783   const Char *s = format_str.c_str();
3784   const Char *start = s;
3785   while (*s) {
3786     Char c = *s++;
3787     if (c != '{' && c != '}') continue;
3788     if (*s == c) {
3789       write(writer_, start, s);
3790       start = ++s;
3791       continue;
3792     }
3793     if (c == '}')
3794       FMT_THROW(FormatError("unmatched '}' in format string"));
3795     write(writer_, start, s - 1);
3796     internal::Arg arg = internal::is_name_start(*s) ?
3797           parse_arg_name(s) : parse_arg_index(s);
3798     start = s = format(s, arg);
3799   }
3800   write(writer_, start, s);
3801 }
3802 }  // namespace fmt
3803 
3804 #if FMT_USE_USER_DEFINED_LITERALS
3805 namespace fmt {
3806 namespace internal {
3807 
3808 template <typename Char>
3809 struct UdlFormat {
3810   const Char *str;
3811 
3812   template <typename... Args>
3813   auto operator()(Args && ... args) const
3814                   -> decltype(format(str, std::forward<Args>(args)...)) {
3815     return format(str, std::forward<Args>(args)...);
3816   }
3817 };
3818 
3819 template <typename Char>
3820 struct UdlArg {
3821   const Char *str;
3822 
3823   template <typename T>
3824   NamedArg<Char> operator=(T &&value) const {
3825     return {str, std::forward<T>(value)};
3826   }
3827 };
3828 
3829 } // namespace internal
3830 
3831 inline namespace literals {
3832 
3833 /**
3834   \rst
3835   C++11 literal equivalent of :func:`fmt::format`.
3836 
3837   **Example**::
3838 
3839     using namespace fmt::literals;
3840     std::string message = "The answer is {}"_format(42);
3841   \endrst
3842  */
3843 inline internal::UdlFormat<char>
3844 operator"" _format(const char *s, std::size_t) { return {s}; }
3845 inline internal::UdlFormat<wchar_t>
3846 operator"" _format(const wchar_t *s, std::size_t) { return {s}; }
3847 
3848 /**
3849   \rst
3850   C++11 literal equivalent of :func:`fmt::arg`.
3851 
3852   **Example**::
3853 
3854     using namespace fmt::literals;
3855     print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
3856   \endrst
3857  */
3858 inline internal::UdlArg<char>
3859 operator"" _a(const char *s, std::size_t) { return {s}; }
3860 inline internal::UdlArg<wchar_t>
3861 operator"" _a(const wchar_t *s, std::size_t) { return {s}; }
3862 
3863 } // inline namespace literals
3864 } // namespace fmt
3865 #endif // FMT_USE_USER_DEFINED_LITERALS
3866 
3867 // Restore warnings.
3868 #if FMT_GCC_VERSION >= 406
3869 # pragma GCC diagnostic pop
3870 #endif
3871 
3872 #if defined(__clang__) && !defined(FMT_ICC_VERSION)
3873 # pragma clang diagnostic pop
3874 #endif
3875 
3876 #ifdef FMT_HEADER_ONLY
3877 # define FMT_FUNC inline
3878 # include "format.cc"
3879 #else
3880 # define FMT_FUNC
3881 #endif
3882 
3883 #endif  // FMT_FORMAT_H_
3884