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