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