1 /*
2  Formatting library for C++
3 
4  Copyright (c) 2012 - 2016, Victor Zverovich
5  All rights reserved.
6 
7  Redistribution and use in source and binary forms, with or without
8  modification, are permitted provided that the following conditions are met:
9 
10  1. Redistributions of source code must retain the above copyright notice, this
11     list of conditions and the following disclaimer.
12  2. Redistributions in binary form must reproduce the above copyright notice,
13     this list of conditions and the following disclaimer in the documentation
14     and/or other materials provided with the distribution.
15 
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifndef FMT_FORMAT_H_
29 #define FMT_FORMAT_H_
30 
31 #include <cassert>
32 #include <clocale>
33 #include <cmath>
34 #include <cstdio>
35 #include <cstring>
36 #include <limits>
37 #include <memory>
38 #include <stdexcept>
39 #include <string>
40 #include <vector>
41 #include <utility>  // for std::pair
42 
43 // The fmt library version in the form major * 10000 + minor * 100 + patch.
44 #define FMT_VERSION 40000
45 
46 #ifdef _SECURE_SCL
47 # define FMT_SECURE_SCL _SECURE_SCL
48 #else
49 # define FMT_SECURE_SCL 0
50 #endif
51 
52 #if FMT_SECURE_SCL
53 # include <iterator>
54 #endif
55 
56 #ifdef _MSC_VER
57 # define FMT_MSC_VER _MSC_VER
58 #else
59 # define FMT_MSC_VER 0
60 #endif
61 
62 #if FMT_MSC_VER && FMT_MSC_VER <= 1500
63 typedef unsigned __int32 uint32_t;
64 typedef unsigned __int64 uint64_t;
65 typedef __int64          intmax_t;
66 #else
67 #include <stdint.h>
68 #endif
69 
70 #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
71 # ifdef FMT_EXPORT
72 #  define FMT_API __declspec(dllexport)
73 # elif defined(FMT_SHARED)
74 #  define FMT_API __declspec(dllimport)
75 # endif
76 #endif
77 #ifndef FMT_API
78 # define FMT_API
79 #endif
80 
81 #ifdef __GNUC__
82 # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
83 # define FMT_GCC_EXTENSION __extension__
84 # if FMT_GCC_VERSION >= 406
85 #  pragma GCC diagnostic push
86 // Disable the warning about "long long" which is sometimes reported even
87 // when using __extension__.
88 #  pragma GCC diagnostic ignored "-Wlong-long"
89 // Disable the warning about declaration shadowing because it affects too
90 // many valid cases.
91 #  pragma GCC diagnostic ignored "-Wshadow"
92 // Disable the warning about implicit conversions that may change the sign of
93 // an integer; silencing it otherwise would require many explicit casts.
94 #  pragma GCC diagnostic ignored "-Wsign-conversion"
95 # endif
96 # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__
97 #  define FMT_HAS_GXX_CXX11 1
98 # endif
99 #else
100 # define FMT_GCC_EXTENSION
101 #endif
102 
103 #if defined(__INTEL_COMPILER)
104 # define FMT_ICC_VERSION __INTEL_COMPILER
105 #elif defined(__ICL)
106 # define FMT_ICC_VERSION __ICL
107 #endif
108 
109 #if defined(__clang__) && !defined(FMT_ICC_VERSION)
110 # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
111 # pragma clang diagnostic push
112 # pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
113 # pragma clang diagnostic ignored "-Wpadded"
114 #endif
115 
116 #ifdef __GNUC_LIBSTD__
117 # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__)
118 #endif
119 
120 #ifdef __has_feature
121 # define FMT_HAS_FEATURE(x) __has_feature(x)
122 #else
123 # define FMT_HAS_FEATURE(x) 0
124 #endif
125 
126 #ifdef __has_builtin
127 # define FMT_HAS_BUILTIN(x) __has_builtin(x)
128 #else
129 # define FMT_HAS_BUILTIN(x) 0
130 #endif
131 
132 #ifdef __has_cpp_attribute
133 # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
134 #else
135 # define FMT_HAS_CPP_ATTRIBUTE(x) 0
136 #endif
137 
138 #ifndef FMT_USE_VARIADIC_TEMPLATES
139 // Variadic templates are available in GCC since version 4.4
140 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++
141 // since version 2013.
142 # define FMT_USE_VARIADIC_TEMPLATES \
143    (FMT_HAS_FEATURE(cxx_variadic_templates) || \
144        (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800)
145 #endif
146 
147 #ifndef FMT_USE_RVALUE_REFERENCES
148 // Don't use rvalue references when compiling with clang and an old libstdc++
149 // as the latter doesn't provide std::move.
150 # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402
151 #  define FMT_USE_RVALUE_REFERENCES 0
152 # else
153 #  define FMT_USE_RVALUE_REFERENCES \
154     (FMT_HAS_FEATURE(cxx_rvalue_references) || \
155         (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1600)
156 # endif
157 #endif
158 
159 // Check if exceptions are disabled.
160 #if defined(__GNUC__) && !defined(__EXCEPTIONS)
161 # define FMT_EXCEPTIONS 0
162 #endif
163 #if FMT_MSC_VER && !_HAS_EXCEPTIONS
164 # define FMT_EXCEPTIONS 0
165 #endif
166 #ifndef FMT_EXCEPTIONS
167 # define FMT_EXCEPTIONS 1
168 #endif
169 
170 #ifndef FMT_THROW
171 # if FMT_EXCEPTIONS
172 #  define FMT_THROW(x) throw x
173 # else
174 #  define FMT_THROW(x) assert(false)
175 # endif
176 #endif
177 
178 // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
179 #ifndef FMT_USE_NOEXCEPT
180 # define FMT_USE_NOEXCEPT 0
181 #endif
182 
183 #if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
184     (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
185     FMT_MSC_VER >= 1900
186 # define FMT_DETECTED_NOEXCEPT noexcept
187 #else
188 # define FMT_DETECTED_NOEXCEPT throw()
189 #endif
190 
191 #ifndef FMT_NOEXCEPT
192 # if FMT_EXCEPTIONS
193 #  define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
194 # else
195 #  define FMT_NOEXCEPT
196 # endif
197 #endif
198 
199 // This is needed because GCC still uses throw() in its headers when exceptions
200 // are disabled.
201 #if FMT_GCC_VERSION
202 # define FMT_DTOR_NOEXCEPT FMT_DETECTED_NOEXCEPT
203 #else
204 # define FMT_DTOR_NOEXCEPT FMT_NOEXCEPT
205 #endif
206 
207 #ifndef FMT_OVERRIDE
208 # if (defined(FMT_USE_OVERRIDE) && FMT_USE_OVERRIDE) || FMT_HAS_FEATURE(cxx_override) || \
209    (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
210    FMT_MSC_VER >= 1900
211 #  define FMT_OVERRIDE override
212 # else
213 #  define FMT_OVERRIDE
214 # endif
215 #endif
216 
217 #ifndef FMT_NULL
218 # if FMT_HAS_FEATURE(cxx_nullptr) || \
219    (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \
220    FMT_MSC_VER >= 1600
221 #  define FMT_NULL nullptr
222 # else
223 #  define FMT_NULL NULL
224 # endif
225 #endif
226 
227 // A macro to disallow the copy constructor and operator= functions
228 // This should be used in the private: declarations for a class
229 #ifndef FMT_USE_DELETED_FUNCTIONS
230 # define FMT_USE_DELETED_FUNCTIONS 0
231 #endif
232 
233 #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \
234   (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800
235 # define FMT_DELETED_OR_UNDEFINED  = delete
236 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
237     TypeName(const TypeName&) = delete; \
238     TypeName& operator=(const TypeName&) = delete
239 #else
240 # define FMT_DELETED_OR_UNDEFINED
241 # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \
242     TypeName(const TypeName&); \
243     TypeName& operator=(const TypeName&)
244 #endif
245 
246 #ifndef FMT_USE_DEFAULTED_FUNCTIONS
247 # define FMT_USE_DEFAULTED_FUNCTIONS 0
248 #endif
249 
250 #ifndef FMT_DEFAULTED_COPY_CTOR
251 # if FMT_USE_DEFAULTED_FUNCTIONS || FMT_HAS_FEATURE(cxx_defaulted_functions) || \
252    (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1800
253 #  define FMT_DEFAULTED_COPY_CTOR(TypeName) \
254     TypeName(const TypeName&) = default;
255 # else
256 #  define FMT_DEFAULTED_COPY_CTOR(TypeName)
257 # endif
258 #endif
259 
260 #ifndef FMT_USE_USER_DEFINED_LITERALS
261 // All compilers which support UDLs also support variadic templates. This
262 // makes the fmt::literals implementation easier. However, an explicit check
263 // for variadic templates is added here just in case.
264 // For Intel's compiler both it and the system gcc/msc must support UDLs.
265 # define FMT_USE_USER_DEFINED_LITERALS \
266    FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \
267    (FMT_HAS_FEATURE(cxx_user_literals) || \
268      (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900) && \
269    (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500)
270 #endif
271 
272 #ifndef FMT_USE_EXTERN_TEMPLATES
273 # define FMT_USE_EXTERN_TEMPLATES \
274     (FMT_CLANG_VERSION >= 209 || (FMT_GCC_VERSION >= 303 && FMT_HAS_GXX_CXX11))
275 #endif
276 
277 #ifdef FMT_HEADER_ONLY
278 // If header only do not use extern templates.
279 # undef FMT_USE_EXTERN_TEMPLATES
280 # define FMT_USE_EXTERN_TEMPLATES 0
281 #endif
282 
283 #ifndef FMT_ASSERT
284 # define FMT_ASSERT(condition, message) assert((condition) && message)
285 #endif
286 
287 // __builtin_clz is broken in clang with Microsoft CodeGen:
288 // https://github.com/fmtlib/fmt/issues/519
289 #ifndef _MSC_VER
290 # if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz)
291 #  define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
292 # endif
293 
294 # if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll)
295 #  define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
296 # endif
297 #endif
298 
299 // Some compilers masquerade as both MSVC and GCC-likes or
300 // otherwise support __builtin_clz and __builtin_clzll, so
301 // only define FMT_BUILTIN_CLZ using the MSVC intrinsics
302 // if the clz and clzll builtins are not available.
303 #if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && !defined(_MANAGED)
304 # include <intrin.h>  // _BitScanReverse, _BitScanReverse64
305 
306 namespace fmt {
307 namespace internal {
308 # pragma intrinsic(_BitScanReverse)
clz(uint32_t x)309 inline uint32_t clz(uint32_t x) {
310   unsigned long r = 0;
311   _BitScanReverse(&r, x);
312 
313   assert(x != 0);
314   // Static analysis complains about using uninitialized data
315   // "r", but the only way that can happen is if "x" is 0,
316   // which the callers guarantee to not happen.
317 # pragma warning(suppress: 6102)
318   return 31 - r;
319 }
320 # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n)
321 
322 # ifdef _WIN64
323 #  pragma intrinsic(_BitScanReverse64)
324 # endif
325 
clzll(uint64_t x)326 inline uint32_t clzll(uint64_t x) {
327   unsigned long r = 0;
328 # ifdef _WIN64
329   _BitScanReverse64(&r, x);
330 # else
331   // Scan the high 32 bits.
332   if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
333     return 63 - (r + 32);
334 
335   // Scan the low 32 bits.
336   _BitScanReverse(&r, static_cast<uint32_t>(x));
337 # endif
338 
339   assert(x != 0);
340   // Static analysis complains about using uninitialized data
341   // "r", but the only way that can happen is if "x" is 0,
342   // which the callers guarantee to not happen.
343 # pragma warning(suppress: 6102)
344   return 63 - r;
345 }
346 # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n)
347 }
348 }
349 #endif
350 
351 namespace fmt {
352 namespace internal {
353 struct DummyInt {
354   int data[2];
operator intfmt::internal::DummyInt355   operator int() const { return 0; }
356 };
357 typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil;
358 
359 // Dummy implementations of system functions such as signbit and ecvt called
360 // if the latter are not available.
signbit(....)361 inline DummyInt signbit(...) { return DummyInt(); }
_ecvt_s(....)362 inline DummyInt _ecvt_s(...) { return DummyInt(); }
isinf(....)363 inline DummyInt isinf(...) { return DummyInt(); }
_finite(....)364 inline DummyInt _finite(...) { return DummyInt(); }
isnan(....)365 inline DummyInt isnan(...) { return DummyInt(); }
_isnan(....)366 inline DummyInt _isnan(...) { return DummyInt(); }
367 
368 // A helper function to suppress bogus "conditional expression is constant"
369 // warnings.
370 template <typename T>
const_check(T value)371 inline T const_check(T value) { return value; }
372 }
373 }  // namespace fmt
374 
375 namespace std {
376 // Standard permits specialization of std::numeric_limits. This specialization
377 // is used to resolve ambiguity between isinf and std::isinf in glibc:
378 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891
379 // and the same for isnan and signbit.
380 template <>
381 class numeric_limits<fmt::internal::DummyInt> :
382     public std::numeric_limits<int> {
383  public:
384   // Portable version of isinf.
385   template <typename T>
isinfinity(T x)386   static bool isinfinity(T x) {
387     using namespace fmt::internal;
388     // The resolution "priority" is:
389     // isinf macro > std::isinf > ::isinf > fmt::internal::isinf
390     if (const_check(sizeof(isinf(x)) == sizeof(bool) ||
391                     sizeof(isinf(x)) == sizeof(int))) {
392       return isinf(x) != 0;
393     }
394     return !_finite(static_cast<double>(x));
395   }
396 
397   // Portable version of isnan.
398   template <typename T>
isnotanumber(T x)399   static bool isnotanumber(T x) {
400     using namespace fmt::internal;
401     if (const_check(sizeof(isnan(x)) == sizeof(bool) ||
402                     sizeof(isnan(x)) == sizeof(int))) {
403       return isnan(x) != 0;
404     }
405     return _isnan(static_cast<double>(x)) != 0;
406   }
407 
408   // Portable version of signbit.
isnegative(double x)409   static bool isnegative(double x) {
410     using namespace fmt::internal;
411     if (const_check(sizeof(signbit(x)) == sizeof(bool) ||
412                     sizeof(signbit(x)) == sizeof(int))) {
413       return signbit(x) != 0;
414     }
415     if (x < 0) return true;
416     if (!isnotanumber(x)) return false;
417     int dec = 0, sign = 0;
418     char buffer[2];  // The buffer size must be >= 2 or _ecvt_s will fail.
419     _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign);
420     return sign != 0;
421   }
422 };
423 }  // namespace std
424 
425 namespace fmt {
426 
427 // Fix the warning about long long on older versions of GCC
428 // that don't support the diagnostic pragma.
429 FMT_GCC_EXTENSION typedef long long LongLong;
430 FMT_GCC_EXTENSION typedef unsigned long long ULongLong;
431 
432 #if FMT_USE_RVALUE_REFERENCES
433 using std::move;
434 #endif
435 
436 template <typename Char>
437 class BasicWriter;
438 
439 typedef BasicWriter<char> Writer;
440 typedef BasicWriter<wchar_t> WWriter;
441 
442 template <typename Char>
443 class ArgFormatter;
444 
445 struct FormatSpec;
446 
447 template <typename Impl, typename Char, typename Spec = fmt::FormatSpec>
448 class BasicPrintfArgFormatter;
449 
450 template <typename CharType,
451           typename ArgFormatter = fmt::ArgFormatter<CharType> >
452 class BasicFormatter;
453 
454 /**
455   \rst
456   A string reference. It can be constructed from a C string or
457   ``std::basic_string``.
458 
459   You can use one of the following typedefs for common character types:
460 
461   +------------+-------------------------+
462   | Type       | Definition              |
463   +============+=========================+
464   | StringRef  | BasicStringRef<char>    |
465   +------------+-------------------------+
466   | WStringRef | BasicStringRef<wchar_t> |
467   +------------+-------------------------+
468 
469   This class is most useful as a parameter type to allow passing
470   different types of strings to a function, for example::
471 
472     template <typename... Args>
473     std::string format(StringRef format_str, const Args & ... args);
474 
475     format("{}", 42);
476     format(std::string("{}"), 42);
477   \endrst
478  */
479 template <typename Char>
480 class BasicStringRef {
481  private:
482   const Char *data_;
483   std::size_t size_;
484 
485  public:
486   /** Constructs a string reference object from a C string and a size. */
BasicStringRef(const Char *s, std::size_t size)487   BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {}
488 
489   /**
490     \rst
491     Constructs a string reference object from a C string computing
492     the size with ``std::char_traits<Char>::length``.
493     \endrst
494    */
BasicStringRef(const Char *s)495   BasicStringRef(const Char *s)
496     : data_(s), size_(std::char_traits<Char>::length(s)) {}
497 
498   /**
499     \rst
500     Constructs a string reference from a ``std::basic_string`` object.
501     \endrst
502    */
503   template <typename Allocator>
BasicStringRef( const std::basic_string<Char, std::char_traits<Char>, Allocator> &s)504   BasicStringRef(
505       const std::basic_string<Char, std::char_traits<Char>, Allocator> &s)
506   : data_(s.c_str()), size_(s.size()) {}
507 
508   /**
509     \rst
510     Converts a string reference to an ``std::string`` object.
511     \endrst
512    */
to_string() const513   std::basic_string<Char> to_string() const {
514     return std::basic_string<Char>(data_, size_);
515   }
516 
517   /** Returns a pointer to the string data. */
data() const518   const Char *data() const { return data_; }
519 
520   /** Returns the string size. */
size() const521   std::size_t size() const { return size_; }
522 
523   // Lexicographically compare this string reference to other.
compare(BasicStringRef other) const524   int compare(BasicStringRef other) const {
525     std::size_t size = size_ < other.size_ ? size_ : other.size_;
526     int result = std::char_traits<Char>::compare(data_, other.data_, size);
527     if (result == 0)
528       result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
529     return result;
530   }
531 
532   friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) {
533     return lhs.compare(rhs) == 0;
534   }
535   friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) {
536     return lhs.compare(rhs) != 0;
537   }
538   friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) {
539     return lhs.compare(rhs) < 0;
540   }
541   friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) {
542     return lhs.compare(rhs) <= 0;
543   }
544   friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) {
545     return lhs.compare(rhs) > 0;
546   }
547   friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) {
548     return lhs.compare(rhs) >= 0;
549   }
550 };
551 
552 typedef BasicStringRef<char> StringRef;
553 typedef BasicStringRef<wchar_t> WStringRef;
554 
555 /**
556   \rst
557   A reference to a null terminated string. It can be constructed from a C
558   string or ``std::basic_string``.
559 
560   You can use one of the following typedefs for common character types:
561 
562   +-------------+--------------------------+
563   | Type        | Definition               |
564   +=============+==========================+
565   | CStringRef  | BasicCStringRef<char>    |
566   +-------------+--------------------------+
567   | WCStringRef | BasicCStringRef<wchar_t> |
568   +-------------+--------------------------+
569 
570   This class is most useful as a parameter type to allow passing
571   different types of strings to a function, for example::
572 
573     template <typename... Args>
574     std::string format(CStringRef format_str, const Args & ... args);
575 
576     format("{}", 42);
577     format(std::string("{}"), 42);
578   \endrst
579  */
580 template <typename Char>
581 class BasicCStringRef {
582  private:
583   const Char *data_;
584 
585  public:
586   /** Constructs a string reference object from a C string. */
587   BasicCStringRef(const Char *s) : data_(s) {}
588 
589   /**
590     \rst
591     Constructs a string reference from a ``std::basic_string`` object.
592     \endrst
593    */
594   template <typename Allocator>
595   BasicCStringRef(
596       const std::basic_string<Char, std::char_traits<Char>, Allocator> &s)
597   : data_(s.c_str()) {}
598 
599   /** Returns the pointer to a C string. */
600   const Char *c_str() const { return data_; }
601 };
602 
603 typedef BasicCStringRef<char> CStringRef;
604 typedef BasicCStringRef<wchar_t> WCStringRef;
605 
606 /** A formatting error such as invalid format string. */
607 class FormatError : public std::runtime_error {
608  public:
609   explicit FormatError(CStringRef message)
610   : std::runtime_error(message.c_str()) {}
611   FormatError(const FormatError &ferr) : std::runtime_error(ferr) {}
612   FMT_API ~FormatError() FMT_DTOR_NOEXCEPT;
613 };
614 
615 namespace internal {
616 
617 // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T.
618 template <typename T>
619 struct MakeUnsigned { typedef T Type; };
620 
621 #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \
622   template <> \
623   struct MakeUnsigned<T> { typedef U Type; }
624 
625 FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char);
626 FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char);
627 FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short);
628 FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned);
629 FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long);
630 FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong);
631 
632 // Casts nonnegative integer to unsigned.
633 template <typename Int>
634 inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) {
635   FMT_ASSERT(value >= 0, "negative value");
636   return static_cast<typename MakeUnsigned<Int>::Type>(value);
637 }
638 
639 // The number of characters to store in the MemoryBuffer object itself
640 // to avoid dynamic memory allocation.
641 enum { INLINE_BUFFER_SIZE = 500 };
642 
643 #if FMT_SECURE_SCL
644 // Use checked iterator to avoid warnings on MSVC.
645 template <typename T>
646 inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) {
647   return stdext::checked_array_iterator<T*>(ptr, size);
648 }
649 #else
650 template <typename T>
651 inline T *make_ptr(T *ptr, std::size_t) { return ptr; }
652 #endif
653 }  // namespace internal
654 
655 /**
656   \rst
657   A buffer supporting a subset of ``std::vector``'s operations.
658   \endrst
659  */
660 template <typename T>
661 class Buffer {
662  private:
663   FMT_DISALLOW_COPY_AND_ASSIGN(Buffer);
664 
665  protected:
666   T *ptr_;
667   std::size_t size_;
668   std::size_t capacity_;
669 
670   Buffer(T *ptr = FMT_NULL, std::size_t capacity = 0)
671     : ptr_(ptr), size_(0), capacity_(capacity) {}
672 
673   /**
674     \rst
675     Increases the buffer capacity to hold at least *size* elements updating
676     ``ptr_`` and ``capacity_``.
677     \endrst
678    */
679   virtual void grow(std::size_t size) = 0;
680 
681  public:
682   virtual ~Buffer() {}
683 
684   /** Returns the size of this buffer. */
685   std::size_t size() const { return size_; }
686 
687   /** Returns the capacity of this buffer. */
688   std::size_t capacity() const { return capacity_; }
689 
690   /**
691     Resizes the buffer. If T is a POD type new elements may not be initialized.
692    */
693   void resize(std::size_t new_size) {
694     if (new_size > capacity_)
695       grow(new_size);
696     size_ = new_size;
697   }
698 
699   /**
700     \rst
701     Reserves space to store at least *capacity* elements.
702     \endrst
703    */
reserve(std::size_t capacity)704   void reserve(std::size_t capacity) {
705     if (capacity > capacity_)
706       grow(capacity);
707   }
708 
709   void clear() FMT_NOEXCEPT { size_ = 0; }
710 
push_back(const T &value)711   void push_back(const T &value) {
712     if (size_ == capacity_)
713       grow(size_ + 1);
714     ptr_[size_++] = value;
715   }
716 
717   /** Appends data to the end of the buffer. */
718   template <typename U>
719   void append(const U *begin, const U *end);
720 
operator [](std::size_t index)721   T &operator[](std::size_t index) { return ptr_[index]; }
operator [](std::size_t index) const722   const T &operator[](std::size_t index) const { return ptr_[index]; }
723 };
724 
725 template <typename T>
726 template <typename U>
append(const U *begin, const U *end)727 void Buffer<T>::append(const U *begin, const U *end) {
728   FMT_ASSERT(end >= begin, "negative value");
729   std::size_t new_size = size_ + (end - begin);
730   if (new_size > capacity_)
731     grow(new_size);
732   std::uninitialized_copy(begin, end,
733                           internal::make_ptr(ptr_, capacity_) + size_);
734   size_ = new_size;
735 }
736 
737 namespace internal {
738 
739 // A memory buffer for trivially copyable/constructible types with the first
740 // SIZE elements stored in the object itself.
741 template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> >
742 class MemoryBuffer : private Allocator, public Buffer<T> {
743  private:
744   T data_[SIZE];
745 
746   // Deallocate memory allocated by the buffer.
deallocate()747   void deallocate() {
748     if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_);
749   }
750 
751  protected:
752   void grow(std::size_t size) FMT_OVERRIDE;
753 
754  public:
MemoryBuffer(const Allocator &alloc = Allocator())755   explicit MemoryBuffer(const Allocator &alloc = Allocator())
756       : Allocator(alloc), Buffer<T>(data_, SIZE) {}
~MemoryBuffer()757   ~MemoryBuffer() { deallocate(); }
758 
759 #if FMT_USE_RVALUE_REFERENCES
760  private:
761   // Move data from other to this buffer.
move(MemoryBuffer &other)762   void move(MemoryBuffer &other) {
763     Allocator &this_alloc = *this, &other_alloc = other;
764     this_alloc = std::move(other_alloc);
765     this->size_ = other.size_;
766     this->capacity_ = other.capacity_;
767     if (other.ptr_ == other.data_) {
768       this->ptr_ = data_;
769       std::uninitialized_copy(other.data_, other.data_ + this->size_,
770                               make_ptr(data_, this->capacity_));
771     } else {
772       this->ptr_ = other.ptr_;
773       // Set pointer to the inline array so that delete is not called
774       // when deallocating.
775       other.ptr_ = other.data_;
776     }
777   }
778 
779  public:
MemoryBuffer(MemoryBuffer &&other)780   MemoryBuffer(MemoryBuffer &&other) {
781     move(other);
782   }
783 
operator =(MemoryBuffer &&other)784   MemoryBuffer &operator=(MemoryBuffer &&other) {
785     assert(this != &other);
786     deallocate();
787     move(other);
788     return *this;
789   }
790 #endif
791 
792   // Returns a copy of the allocator associated with this buffer.
get_allocator() const793   Allocator get_allocator() const { return *this; }
794 };
795 
796 template <typename T, std::size_t SIZE, typename Allocator>
grow(std::size_t size)797 void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) {
798   std::size_t new_capacity = this->capacity_ + this->capacity_ / 2;
799   if (size > new_capacity)
800       new_capacity = size;
801   T *new_ptr = this->allocate(new_capacity, FMT_NULL);
802   // The following code doesn't throw, so the raw pointer above doesn't leak.
803   std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_,
804                           make_ptr(new_ptr, new_capacity));
805   std::size_t old_capacity = this->capacity_;
806   T *old_ptr = this->ptr_;
807   this->capacity_ = new_capacity;
808   this->ptr_ = new_ptr;
809   // deallocate may throw (at least in principle), but it doesn't matter since
810   // the buffer already uses the new storage and will deallocate it in case
811   // of exception.
812   if (old_ptr != data_)
813     Allocator::deallocate(old_ptr, old_capacity);
814 }
815 
816 // A fixed-size buffer.
817 template <typename Char>
818 class FixedBuffer : public fmt::Buffer<Char> {
819  public:
FixedBuffer(Char *array, std::size_t size)820   FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {}
821 
822  protected:
823   FMT_API void grow(std::size_t size) FMT_OVERRIDE;
824 };
825 
826 template <typename Char>
827 class BasicCharTraits {
828  public:
829 #if FMT_SECURE_SCL
830   typedef stdext::checked_array_iterator<Char*> CharPtr;
831 #else
832   typedef Char *CharPtr;
833 #endif
cast(int value)834   static Char cast(int value) { return static_cast<Char>(value); }
835 };
836 
837 template <typename Char>
838 class CharTraits;
839 
840 template <>
841 class CharTraits<char> : public BasicCharTraits<char> {
842  private:
843   // Conversion from wchar_t to char is not allowed.
844   static char convert(wchar_t);
845 
846  public:
convert(char value)847   static char convert(char value) { return value; }
848 
849   // Formats a floating-point number.
850   template <typename T>
851   FMT_API static int format_float(char *buffer, std::size_t size,
852       const char *format, unsigned width, int precision, T value);
853 };
854 
855 #if FMT_USE_EXTERN_TEMPLATES
856 extern template int CharTraits<char>::format_float<double>
857         (char *buffer, std::size_t size,
858          const char* format, unsigned width, int precision, double value);
859 extern template int CharTraits<char>::format_float<long double>
860         (char *buffer, std::size_t size,
861          const char* format, unsigned width, int precision, long double value);
862 #endif
863 
864 template <>
865 class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> {
866  public:
convert(char value)867   static wchar_t convert(char value) { return value; }
convert(wchar_t value)868   static wchar_t convert(wchar_t value) { return value; }
869 
870   template <typename T>
871   FMT_API static int format_float(wchar_t *buffer, std::size_t size,
872       const wchar_t *format, unsigned width, int precision, T value);
873 };
874 
875 #if FMT_USE_EXTERN_TEMPLATES
876 extern template int CharTraits<wchar_t>::format_float<double>
877         (wchar_t *buffer, std::size_t size,
878          const wchar_t* format, unsigned width, int precision, double value);
879 extern template int CharTraits<wchar_t>::format_float<long double>
880         (wchar_t *buffer, std::size_t size,
881          const wchar_t* format, unsigned width, int precision, long double value);
882 #endif
883 
884 // Checks if a number is negative - used to avoid warnings.
885 template <bool IsSigned>
886 struct SignChecker {
887   template <typename T>
is_negativefmt::internal::SignChecker888   static bool is_negative(T value) { return value < 0; }
889 };
890 
891 template <>
892 struct SignChecker<false> {
893   template <typename T>
is_negativefmt::internal::SignChecker894   static bool is_negative(T) { return false; }
895 };
896 
897 // Returns true if value is negative, false otherwise.
898 // Same as (value < 0) but doesn't produce warnings if T is an unsigned type.
899 template <typename T>
is_negative(T value)900 inline bool is_negative(T value) {
901   return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value);
902 }
903 
904 // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise.
905 template <bool FitsIn32Bits>
906 struct TypeSelector { typedef uint32_t Type; };
907 
908 template <>
909 struct TypeSelector<false> { typedef uint64_t Type; };
910 
911 template <typename T>
912 struct IntTraits {
913   // Smallest of uint32_t and uint64_t that is large enough to represent
914   // all values of T.
915   typedef typename
916     TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType;
917 };
918 
919 FMT_API void report_unknown_type(char code, const char *type);
920 
921 // Static data is placed in this class template to allow header-only
922 // configuration.
923 template <typename T = void>
924 struct FMT_API BasicData {
925   static const uint32_t POWERS_OF_10_32[];
926   static const uint64_t POWERS_OF_10_64[];
927   static const char DIGITS[];
928 };
929 
930 #if FMT_USE_EXTERN_TEMPLATES
931 extern template struct BasicData<void>;
932 #endif
933 
934 typedef BasicData<> Data;
935 
936 #ifdef FMT_BUILTIN_CLZLL
937 // Returns the number of decimal digits in n. Leading zeros are not counted
938 // except for n == 0 in which case count_digits returns 1.
939 inline unsigned count_digits(uint64_t n) {
940   // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
941   // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits.
942   int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12;
943   return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1;
944 }
945 #else
946 // Fallback version of count_digits used when __builtin_clz is not available.
947 inline unsigned count_digits(uint64_t n) {
948   unsigned count = 1;
949   for (;;) {
950     // Integer division is slow so do it for a group of four digits instead
951     // of for every digit. The idea comes from the talk by Alexandrescu
952     // "Three Optimization Tips for C++". See speed-test for a comparison.
953     if (n < 10) return count;
954     if (n < 100) return count + 1;
955     if (n < 1000) return count + 2;
956     if (n < 10000) return count + 3;
957     n /= 10000u;
958     count += 4;
959   }
960 }
961 #endif
962 
963 #ifdef FMT_BUILTIN_CLZ
964 // Optional version of count_digits for better performance on 32-bit platforms.
count_digits(uint32_t n)965 inline unsigned count_digits(uint32_t n) {
966   int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12;
967   return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1;
968 }
969 #endif
970 
971 // A functor that doesn't add a thousands separator.
972 struct NoThousandsSep {
973   template <typename Char>
operator ()fmt::internal::NoThousandsSep974   void operator()(Char *) {}
975 };
976 
977 // A functor that adds a thousands separator.
978 class ThousandsSep {
979  private:
980   fmt::StringRef sep_;
981 
982   // Index of a decimal digit with the least significant digit having index 0.
983   unsigned digit_index_;
984 
985  public:
ThousandsSep(fmt::StringRef sep)986   explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {}
987 
988   template <typename Char>
operator ()(Char *&buffer)989   void operator()(Char *&buffer) {
990     if (++digit_index_ % 3 != 0)
991       return;
992     buffer -= sep_.size();
993     std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(),
994                             internal::make_ptr(buffer, sep_.size()));
995   }
996 };
997 
998 // Formats a decimal unsigned integer value writing into buffer.
999 // thousands_sep is a functor that is called after writing each char to
1000 // add a thousands separator if necessary.
1001 template <typename UInt, typename Char, typename ThousandsSep>
format_decimal(Char *buffer, UInt value, unsigned num_digits, ThousandsSep thousands_sep)1002 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits,
1003                            ThousandsSep thousands_sep) {
1004   buffer += num_digits;
1005   while (value >= 100) {
1006     // Integer division is slow so do it for a group of two digits instead
1007     // of for every digit. The idea comes from the talk by Alexandrescu
1008     // "Three Optimization Tips for C++". See speed-test for a comparison.
1009     unsigned index = static_cast<unsigned>((value % 100) * 2);
1010     value /= 100;
1011     *--buffer = Data::DIGITS[index + 1];
1012     thousands_sep(buffer);
1013     *--buffer = Data::DIGITS[index];
1014     thousands_sep(buffer);
1015   }
1016   if (value < 10) {
1017     *--buffer = static_cast<char>('0' + value);
1018     return;
1019   }
1020   unsigned index = static_cast<unsigned>(value * 2);
1021   *--buffer = Data::DIGITS[index + 1];
1022   thousands_sep(buffer);
1023   *--buffer = Data::DIGITS[index];
1024 }
1025 
1026 template <typename UInt, typename Char>
format_decimal(Char *buffer, UInt value, unsigned num_digits)1027 inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) {
1028   format_decimal(buffer, value, num_digits, NoThousandsSep());
1029   return;
1030 }
1031 
1032 #ifndef _WIN32
1033 # define FMT_USE_WINDOWS_H 0
1034 #elif !defined(FMT_USE_WINDOWS_H)
1035 # define FMT_USE_WINDOWS_H 1
1036 #endif
1037 
1038 // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h.
1039 // All the functionality that relies on it will be disabled too.
1040 #if FMT_USE_WINDOWS_H
1041 // A converter from UTF-8 to UTF-16.
1042 // It is only provided for Windows since other systems support UTF-8 natively.
1043 class UTF8ToUTF16 {
1044  private:
1045   MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_;
1046 
1047  public:
1048   FMT_API explicit UTF8ToUTF16(StringRef s);
operator WStringRef() const1049   operator WStringRef() const { return WStringRef(&buffer_[0], size()); }
size() const1050   size_t size() const { return buffer_.size() - 1; }
c_str() const1051   const wchar_t *c_str() const { return &buffer_[0]; }
str() const1052   std::wstring str() const { return std::wstring(&buffer_[0], size()); }
1053 };
1054 
1055 // A converter from UTF-16 to UTF-8.
1056 // It is only provided for Windows since other systems support UTF-8 natively.
1057 class UTF16ToUTF8 {
1058  private:
1059   MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_;
1060 
1061  public:
UTF16ToUTF8()1062   UTF16ToUTF8() {}
1063   FMT_API explicit UTF16ToUTF8(WStringRef s);
operator StringRef() const1064   operator StringRef() const { return StringRef(&buffer_[0], size()); }
size() const1065   size_t size() const { return buffer_.size() - 1; }
c_str() const1066   const char *c_str() const { return &buffer_[0]; }
str() const1067   std::string str() const { return std::string(&buffer_[0], size()); }
1068 
1069   // Performs conversion returning a system error code instead of
1070   // throwing exception on conversion error. This method may still throw
1071   // in case of memory allocation error.
1072   FMT_API int convert(WStringRef s);
1073 };
1074 
1075 FMT_API void format_windows_error(fmt::Writer &out, int error_code,
1076                                   fmt::StringRef message) FMT_NOEXCEPT;
1077 #endif
1078 
1079 // A formatting argument value.
1080 struct Value {
1081   template <typename Char>
1082   struct StringValue {
1083     const Char *value;
1084     std::size_t size;
1085   };
1086 
1087   typedef void (*FormatFunc)(
1088       void *formatter, const void *arg, void *format_str_ptr);
1089 
1090   struct CustomValue {
1091     const void *value;
1092     FormatFunc format;
1093   };
1094 
1095   union {
1096     int int_value;
1097     unsigned uint_value;
1098     LongLong long_long_value;
1099     ULongLong ulong_long_value;
1100     double double_value;
1101     long double long_double_value;
1102     const void *pointer;
1103     StringValue<char> string;
1104     StringValue<signed char> sstring;
1105     StringValue<unsigned char> ustring;
1106     StringValue<wchar_t> wstring;
1107     CustomValue custom;
1108   };
1109 
1110   enum Type {
1111     NONE, NAMED_ARG,
1112     // Integer types should go first,
1113     INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR,
1114     // followed by floating-point types.
1115     DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE,
1116     CSTRING, STRING, WSTRING, POINTER, CUSTOM
1117   };
1118 };
1119 
1120 // A formatting argument. It is a trivially copyable/constructible type to
1121 // allow storage in internal::MemoryBuffer.
1122 struct Arg : Value {
1123   Type type;
1124 };
1125 
1126 template <typename Char>
1127 struct NamedArg;
1128 template <typename Char, typename T>
1129 struct NamedArgWithType;
1130 
1131 template <typename T = void>
1132 struct Null {};
1133 
1134 // A helper class template to enable or disable overloads taking wide
1135 // characters and strings in MakeValue.
1136 template <typename T, typename Char>
1137 struct WCharHelper {
1138   typedef Null<T> Supported;
1139   typedef T Unsupported;
1140 };
1141 
1142 template <typename T>
1143 struct WCharHelper<T, wchar_t> {
1144   typedef T Supported;
1145   typedef Null<T> Unsupported;
1146 };
1147 
1148 typedef char Yes[1];
1149 typedef char No[2];
1150 
1151 template <typename T>
1152 T &get();
1153 
1154 // These are non-members to workaround an overload resolution bug in bcc32.
1155 Yes &convert(fmt::ULongLong);
1156 No &convert(...);
1157 
1158 template<typename T, bool ENABLE_CONVERSION>
1159 struct ConvertToIntImpl {
1160   enum { value = ENABLE_CONVERSION };
1161 };
1162 
1163 template<typename T, bool ENABLE_CONVERSION>
1164 struct ConvertToIntImpl2 {
1165   enum { value = false };
1166 };
1167 
1168 template<typename T>
1169 struct ConvertToIntImpl2<T, true> {
1170   enum {
1171     // Don't convert numeric types.
1172     value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value
1173   };
1174 };
1175 
1176 template<typename T>
1177 struct ConvertToInt {
1178   enum {
1179     enable_conversion = sizeof(fmt::internal::convert(get<T>())) == sizeof(Yes)
1180   };
1181   enum { value = ConvertToIntImpl2<T, enable_conversion>::value };
1182 };
1183 
1184 #define FMT_DISABLE_CONVERSION_TO_INT(Type) \
1185   template <> \
1186   struct ConvertToInt<Type> {  enum { value = 0 }; }
1187 
1188 // Silence warnings about convering float to int.
1189 FMT_DISABLE_CONVERSION_TO_INT(float);
1190 FMT_DISABLE_CONVERSION_TO_INT(double);
1191 FMT_DISABLE_CONVERSION_TO_INT(long double);
1192 
1193 template<bool B, class T = void>
1194 struct EnableIf {};
1195 
1196 template<class T>
1197 struct EnableIf<true, T> { typedef T type; };
1198 
1199 template<bool B, class T, class F>
1200 struct Conditional { typedef T type; };
1201 
1202 template<class T, class F>
1203 struct Conditional<false, T, F> { typedef F type; };
1204 
1205 // For bcc32 which doesn't understand ! in template arguments.
1206 template <bool>
1207 struct Not { enum { value = 0 }; };
1208 
1209 template <>
1210 struct Not<false> { enum { value = 1 }; };
1211 
1212 template <typename T>
1213 struct FalseType { enum { value = 0 }; };
1214 
1215 template <typename T, T> struct LConvCheck {
LConvCheckfmt::internal::LConvCheck1216   LConvCheck(int) {}
1217 };
1218 
1219 // Returns the thousands separator for the current locale.
1220 // We check if ``lconv`` contains ``thousands_sep`` because on Android
1221 // ``lconv`` is stubbed as an empty struct.
1222 template <typename LConv>
thousands_sep( LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0)1223 inline StringRef thousands_sep(
1224     LConv *lc, LConvCheck<char *LConv::*, &LConv::thousands_sep> = 0) {
1225   return lc->thousands_sep;
1226 }
1227 
thousands_sep(....)1228 inline fmt::StringRef thousands_sep(...) { return ""; }
1229 
1230 #define FMT_CONCAT(a, b) a##b
1231 
1232 #if FMT_GCC_VERSION >= 303
1233 # define FMT_UNUSED __attribute__((unused))
1234 #else
1235 # define FMT_UNUSED
1236 #endif
1237 
1238 #ifndef FMT_USE_STATIC_ASSERT
1239 # define FMT_USE_STATIC_ASSERT 0
1240 #endif
1241 
1242 #if FMT_USE_STATIC_ASSERT || FMT_HAS_FEATURE(cxx_static_assert) || \
1243   (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600
1244 # define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message)
1245 #else
1246 # define FMT_CONCAT_(a, b) FMT_CONCAT(a, b)
1247 # define FMT_STATIC_ASSERT(cond, message) \
1248   typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED
1249 #endif
1250 
1251 template <typename Formatter, typename Char, typename T>
format_arg(Formatter &, const Char *, const T &)1252 void format_arg(Formatter &, const Char *, const T &) {
1253   FMT_STATIC_ASSERT(FalseType<T>::value,
1254                     "Cannot format argument. To enable the use of ostream "
1255                     "operator<< include fmt/ostream.h. Otherwise provide "
1256                     "an overload of format_arg.");
1257 }
1258 
1259 // Makes an Arg object from any type.
1260 template <typename Formatter>
1261 class MakeValue : public Arg {
1262  public:
1263   typedef typename Formatter::Char Char;
1264 
1265  private:
1266   // The following two methods are private to disallow formatting of
1267   // arbitrary pointers. If you want to output a pointer cast it to
1268   // "void *" or "const void *". In particular, this forbids formatting
1269   // of "[const] volatile char *" which is printed as bool by iostreams.
1270   // Do not implement!
1271   template <typename T>
1272   MakeValue(const T *value);
1273   template <typename T>
1274   MakeValue(T *value);
1275 
1276   // The following methods are private to disallow formatting of wide
1277   // characters and strings into narrow strings as in
1278   //   fmt::format("{}", L"test");
1279   // To fix this, use a wide format string: fmt::format(L"{}", L"test").
1280 #if !FMT_MSC_VER || defined(_NATIVE_WCHAR_T_DEFINED)
1281   MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported);
1282 #endif
1283   MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported);
1284   MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported);
1285   MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported);
1286   MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported);
1287 
set_string(StringRef str)1288   void set_string(StringRef str) {
1289     string.value = str.data();
1290     string.size = str.size();
1291   }
1292 
set_string(WStringRef str)1293   void set_string(WStringRef str) {
1294     wstring.value = str.data();
1295     wstring.size = str.size();
1296   }
1297 
1298   // Formats an argument of a custom type, such as a user-defined class.
1299   template <typename T>
format_custom_arg( void *formatter, const void *arg, void *format_str_ptr)1300   static void format_custom_arg(
1301       void *formatter, const void *arg, void *format_str_ptr) {
1302     format_arg(*static_cast<Formatter*>(formatter),
1303                *static_cast<const Char**>(format_str_ptr),
1304                *static_cast<const T*>(arg));
1305   }
1306 
1307  public:
MakeValue()1308   MakeValue() {}
1309 
1310 #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \
1311   MakeValue(Type value) { field = rhs; } \
1312   static uint64_t type(Type) { return Arg::TYPE; }
1313 
1314 #define FMT_MAKE_VALUE(Type, field, TYPE) \
1315   FMT_MAKE_VALUE_(Type, field, TYPE, value)
1316 
1317   FMT_MAKE_VALUE(bool, int_value, BOOL)
1318   FMT_MAKE_VALUE(short, int_value, INT)
1319   FMT_MAKE_VALUE(unsigned short, uint_value, UINT)
1320   FMT_MAKE_VALUE(int, int_value, INT)
1321   FMT_MAKE_VALUE(unsigned, uint_value, UINT)
1322 
MakeValue(long value)1323   MakeValue(long value) {
1324     // To minimize the number of types we need to deal with, long is
1325     // translated either to int or to long long depending on its size.
1326     if (const_check(sizeof(long) == sizeof(int)))
1327       int_value = static_cast<int>(value);
1328     else
1329       long_long_value = value;
1330   }
type(long)1331   static uint64_t type(long) {
1332     return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG;
1333   }
1334 
MakeValue(unsigned long value)1335   MakeValue(unsigned long value) {
1336     if (const_check(sizeof(unsigned long) == sizeof(unsigned)))
1337       uint_value = static_cast<unsigned>(value);
1338     else
1339       ulong_long_value = value;
1340   }
type(unsigned long)1341   static uint64_t type(unsigned long) {
1342     return sizeof(unsigned long) == sizeof(unsigned) ?
1343           Arg::UINT : Arg::ULONG_LONG;
1344   }
1345 
1346   FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG)
1347   FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG)
1348   FMT_MAKE_VALUE(float, double_value, DOUBLE)
1349   FMT_MAKE_VALUE(double, double_value, DOUBLE)
1350   FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE)
1351   FMT_MAKE_VALUE(signed char, int_value, INT)
1352   FMT_MAKE_VALUE(unsigned char, uint_value, UINT)
1353   FMT_MAKE_VALUE(char, int_value, CHAR)
1354 
1355 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
MakeValue(typename WCharHelper<wchar_t, Char>::Supported value)1356   MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) {
1357     int_value = value;
1358   }
type(wchar_t)1359   static uint64_t type(wchar_t) { return Arg::CHAR; }
1360 #endif
1361 
1362 #define FMT_MAKE_STR_VALUE(Type, TYPE) \
1363   MakeValue(Type value) { set_string(value); } \
1364   static uint64_t type(Type) { return Arg::TYPE; }
1365 
1366   FMT_MAKE_VALUE(char *, string.value, CSTRING)
1367   FMT_MAKE_VALUE(const char *, string.value, CSTRING)
1368   FMT_MAKE_VALUE(signed char *, sstring.value, CSTRING)
1369   FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING)
1370   FMT_MAKE_VALUE(unsigned char *, ustring.value, CSTRING)
1371   FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING)
1372   FMT_MAKE_STR_VALUE(const std::string &, STRING)
1373   FMT_MAKE_STR_VALUE(StringRef, STRING)
1374   FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str())
1375 
1376 #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \
1377   MakeValue(typename WCharHelper<Type, Char>::Supported value) { \
1378     set_string(value); \
1379   } \
1380   static uint64_t type(Type) { return Arg::TYPE; }
1381 
1382   FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING)
1383   FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING)
1384   FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING)
1385   FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING)
1386 
1387   FMT_MAKE_VALUE(void *, pointer, POINTER)
1388   FMT_MAKE_VALUE(const void *, pointer, POINTER)
1389 
1390   template <typename T>
MakeValue(const T &value, typename EnableIf<Not< ConvertToInt<T>::value>::value, int>::type = 0)1391   MakeValue(const T &value,
1392             typename EnableIf<Not<
1393               ConvertToInt<T>::value>::value, int>::type = 0) {
1394     custom.value = &value;
1395     custom.format = &format_custom_arg<T>;
1396   }
1397 
1398   template <typename T>
1399   static typename EnableIf<Not<ConvertToInt<T>::value>::value, uint64_t>::type
type(const T &)1400       type(const T &) {
1401     return Arg::CUSTOM;
1402   }
1403 
1404   // Additional template param `Char_` is needed here because make_type always
1405   // uses char.
1406   template <typename Char_>
MakeValue(const NamedArg<Char_> &value)1407   MakeValue(const NamedArg<Char_> &value) { pointer = &value; }
1408   template <typename Char_, typename T>
MakeValue(const NamedArgWithType<Char_, T> &value)1409   MakeValue(const NamedArgWithType<Char_, T> &value) { pointer = &value; }
1410 
1411   template <typename Char_>
type(const NamedArg<Char_> &)1412   static uint64_t type(const NamedArg<Char_> &) { return Arg::NAMED_ARG; }
1413   template <typename Char_, typename T>
type(const NamedArgWithType<Char_, T> &)1414   static uint64_t type(const NamedArgWithType<Char_, T> &) { return Arg::NAMED_ARG; }
1415 };
1416 
1417 template <typename Formatter>
1418 class MakeArg : public Arg {
1419 public:
MakeArg()1420   MakeArg() {
1421     type = Arg::NONE;
1422   }
1423 
1424   template <typename T>
MakeArg(const T &value)1425   MakeArg(const T &value)
1426   : Arg(MakeValue<Formatter>(value)) {
1427     type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value));
1428   }
1429 };
1430 
1431 template <typename Char>
1432 struct NamedArg : Arg {
1433   BasicStringRef<Char> name;
1434 
1435   template <typename T>
NamedArgfmt::internal::NamedArg1436   NamedArg(BasicStringRef<Char> argname, const T &value)
1437   : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {}
1438 };
1439 
1440 template <typename Char, typename T>
1441 struct NamedArgWithType : NamedArg<Char> {
NamedArgWithTypefmt::internal::NamedArgWithType1442   NamedArgWithType(BasicStringRef<Char> argname, const T &value)
1443   : NamedArg<Char>(argname, value) {}
1444 };
1445 
1446 class RuntimeError : public std::runtime_error {
1447  protected:
RuntimeError()1448   RuntimeError() : std::runtime_error("") {}
RuntimeError(const RuntimeError &rerr)1449   RuntimeError(const RuntimeError &rerr) : std::runtime_error(rerr) {}
1450   FMT_API ~RuntimeError() FMT_DTOR_NOEXCEPT;
1451 };
1452 
1453 template <typename Char>
1454 class ArgMap;
1455 }  // namespace internal
1456 
1457 /** An argument list. */
1458 class ArgList {
1459  private:
1460   // To reduce compiled code size per formatting function call, types of first
1461   // MAX_PACKED_ARGS arguments are passed in the types_ field.
1462   uint64_t types_;
1463   union {
1464     // If the number of arguments is less than MAX_PACKED_ARGS, the argument
1465     // values are stored in values_, otherwise they are stored in args_.
1466     // This is done to reduce compiled code size as storing larger objects
1467     // may require more code (at least on x86-64) even if the same amount of
1468     // data is actually copied to stack. It saves ~10% on the bloat test.
1469     const internal::Value *values_;
1470     const internal::Arg *args_;
1471   };
1472 
type(unsigned index) const1473   internal::Arg::Type type(unsigned index) const {
1474     return type(types_, index);
1475   }
1476 
1477   template <typename Char>
1478   friend class internal::ArgMap;
1479 
1480  public:
1481   // Maximum number of arguments with packed types.
1482   enum { MAX_PACKED_ARGS = 16 };
1483 
ArgList()1484   ArgList() : types_(0) {}
1485 
ArgList(ULongLong types, const internal::Value *values)1486   ArgList(ULongLong types, const internal::Value *values)
1487   : types_(types), values_(values) {}
ArgList(ULongLong types, const internal::Arg *args)1488   ArgList(ULongLong types, const internal::Arg *args)
1489   : types_(types), args_(args) {}
1490 
types() const1491   uint64_t types() const { return types_; }
1492 
1493   /** Returns the argument at specified index. */
operator [](unsigned index) const1494   internal::Arg operator[](unsigned index) const {
1495     using internal::Arg;
1496     Arg arg;
1497     bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE;
1498     if (index < MAX_PACKED_ARGS) {
1499       Arg::Type arg_type = type(index);
1500       internal::Value &val = arg;
1501       if (arg_type != Arg::NONE)
1502         val = use_values ? values_[index] : args_[index];
1503       arg.type = arg_type;
1504       return arg;
1505     }
1506     if (use_values) {
1507       // The index is greater than the number of arguments that can be stored
1508       // in values, so return a "none" argument.
1509       arg.type = Arg::NONE;
1510       return arg;
1511     }
1512     for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) {
1513       if (args_[i].type == Arg::NONE)
1514         return args_[i];
1515     }
1516     return args_[index];
1517   }
1518 
type(uint64_t types, unsigned index)1519   static internal::Arg::Type type(uint64_t types, unsigned index) {
1520     unsigned shift = index * 4;
1521     uint64_t mask = 0xf;
1522     return static_cast<internal::Arg::Type>(
1523           (types & (mask << shift)) >> shift);
1524   }
1525 };
1526 
1527 #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call
1528 
1529 /**
1530   \rst
1531   An argument visitor based on the `curiously recurring template pattern
1532   <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
1533 
1534   To use `~fmt::ArgVisitor` define a subclass that implements some or all of the
1535   visit methods with the same signatures as the methods in `~fmt::ArgVisitor`,
1536   for example, `~fmt::ArgVisitor::visit_int()`.
1537   Pass the subclass as the *Impl* template parameter. Then calling
1538   `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method
1539   specific to the argument type. For example, if the argument type is
1540   ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
1541   will be called. If the subclass doesn't contain a method with this signature,
1542   then a corresponding method of `~fmt::ArgVisitor` will be called.
1543 
1544   **Example**::
1545 
1546     class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> {
1547      public:
1548       void visit_int(int value) { fmt::print("{}", value); }
1549       void visit_double(double value) { fmt::print("{}", value ); }
1550     };
1551   \endrst
1552  */
1553 template <typename Impl, typename Result>
1554 class ArgVisitor {
1555  private:
1556   typedef internal::Arg Arg;
1557 
1558  public:
report_unhandled_arg()1559   void report_unhandled_arg() {}
1560 
visit_unhandled_arg()1561   Result visit_unhandled_arg() {
1562     FMT_DISPATCH(report_unhandled_arg());
1563     return Result();
1564   }
1565 
1566   /** Visits an ``int`` argument. **/
visit_int(int value)1567   Result visit_int(int value) {
1568     return FMT_DISPATCH(visit_any_int(value));
1569   }
1570 
1571   /** Visits a ``long long`` argument. **/
visit_long_long(LongLong value)1572   Result visit_long_long(LongLong value) {
1573     return FMT_DISPATCH(visit_any_int(value));
1574   }
1575 
1576   /** Visits an ``unsigned`` argument. **/
visit_uint(unsigned value)1577   Result visit_uint(unsigned value) {
1578     return FMT_DISPATCH(visit_any_int(value));
1579   }
1580 
1581   /** Visits an ``unsigned long long`` argument. **/
visit_ulong_long(ULongLong value)1582   Result visit_ulong_long(ULongLong value) {
1583     return FMT_DISPATCH(visit_any_int(value));
1584   }
1585 
1586   /** Visits a ``bool`` argument. **/
visit_bool(bool value)1587   Result visit_bool(bool value) {
1588     return FMT_DISPATCH(visit_any_int(value));
1589   }
1590 
1591   /** Visits a ``char`` or ``wchar_t`` argument. **/
visit_char(int value)1592   Result visit_char(int value) {
1593     return FMT_DISPATCH(visit_any_int(value));
1594   }
1595 
1596   /** Visits an argument of any integral type. **/
1597   template <typename T>
visit_any_int(T)1598   Result visit_any_int(T) {
1599     return FMT_DISPATCH(visit_unhandled_arg());
1600   }
1601 
1602   /** Visits a ``double`` argument. **/
visit_double(double value)1603   Result visit_double(double value) {
1604     return FMT_DISPATCH(visit_any_double(value));
1605   }
1606 
1607   /** Visits a ``long double`` argument. **/
visit_long_double(long double value)1608   Result visit_long_double(long double value) {
1609     return FMT_DISPATCH(visit_any_double(value));
1610   }
1611 
1612   /** Visits a ``double`` or ``long double`` argument. **/
1613   template <typename T>
visit_any_double(T)1614   Result visit_any_double(T) {
1615     return FMT_DISPATCH(visit_unhandled_arg());
1616   }
1617 
1618   /** Visits a null-terminated C string (``const char *``) argument. **/
visit_cstring(const char *)1619   Result visit_cstring(const char *) {
1620     return FMT_DISPATCH(visit_unhandled_arg());
1621   }
1622 
1623   /** Visits a string argument. **/
visit_string(Arg::StringValue<char>)1624   Result visit_string(Arg::StringValue<char>) {
1625     return FMT_DISPATCH(visit_unhandled_arg());
1626   }
1627 
1628   /** Visits a wide string argument. **/
visit_wstring(Arg::StringValue<wchar_t>)1629   Result visit_wstring(Arg::StringValue<wchar_t>) {
1630     return FMT_DISPATCH(visit_unhandled_arg());
1631   }
1632 
1633   /** Visits a pointer argument. **/
visit_pointer(const void *)1634   Result visit_pointer(const void *) {
1635     return FMT_DISPATCH(visit_unhandled_arg());
1636   }
1637 
1638   /** Visits an argument of a custom (user-defined) type. **/
visit_custom(Arg::CustomValue)1639   Result visit_custom(Arg::CustomValue) {
1640     return FMT_DISPATCH(visit_unhandled_arg());
1641   }
1642 
1643   /**
1644     \rst
1645     Visits an argument dispatching to the appropriate visit method based on
1646     the argument type. For example, if the argument type is ``double`` then
1647     the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be
1648     called.
1649     \endrst
1650    */
visit(const Arg &arg)1651   Result visit(const Arg &arg) {
1652     switch (arg.type) {
1653     case Arg::NONE:
1654     case Arg::NAMED_ARG:
1655       FMT_ASSERT(false, "invalid argument type");
1656       break;
1657     case Arg::INT:
1658       return FMT_DISPATCH(visit_int(arg.int_value));
1659     case Arg::UINT:
1660       return FMT_DISPATCH(visit_uint(arg.uint_value));
1661     case Arg::LONG_LONG:
1662       return FMT_DISPATCH(visit_long_long(arg.long_long_value));
1663     case Arg::ULONG_LONG:
1664       return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value));
1665     case Arg::BOOL:
1666       return FMT_DISPATCH(visit_bool(arg.int_value != 0));
1667     case Arg::CHAR:
1668       return FMT_DISPATCH(visit_char(arg.int_value));
1669     case Arg::DOUBLE:
1670       return FMT_DISPATCH(visit_double(arg.double_value));
1671     case Arg::LONG_DOUBLE:
1672       return FMT_DISPATCH(visit_long_double(arg.long_double_value));
1673     case Arg::CSTRING:
1674       return FMT_DISPATCH(visit_cstring(arg.string.value));
1675     case Arg::STRING:
1676       return FMT_DISPATCH(visit_string(arg.string));
1677     case Arg::WSTRING:
1678       return FMT_DISPATCH(visit_wstring(arg.wstring));
1679     case Arg::POINTER:
1680       return FMT_DISPATCH(visit_pointer(arg.pointer));
1681     case Arg::CUSTOM:
1682       return FMT_DISPATCH(visit_custom(arg.custom));
1683     }
1684     return Result();
1685   }
1686 };
1687 
1688 enum Alignment {
1689   ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC
1690 };
1691 
1692 // Flags.
1693 enum {
1694   SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8,
1695   CHAR_FLAG = 0x10  // Argument has char type - used in error reporting.
1696 };
1697 
1698 // An empty format specifier.
1699 struct EmptySpec {};
1700 
1701 // A type specifier.
1702 template <char TYPE>
1703 struct TypeSpec : EmptySpec {
alignfmt::TypeSpec1704   Alignment align() const { return ALIGN_DEFAULT; }
widthfmt::TypeSpec1705   unsigned width() const { return 0; }
precisionfmt::TypeSpec1706   int precision() const { return -1; }
flagfmt::TypeSpec1707   bool flag(unsigned) const { return false; }
typefmt::TypeSpec1708   char type() const { return TYPE; }
type_prefixfmt::TypeSpec1709   char type_prefix() const { return TYPE; }
fillfmt::TypeSpec1710   char fill() const { return ' '; }
1711 };
1712 
1713 // A width specifier.
1714 struct WidthSpec {
1715   unsigned width_;
1716   // Fill is always wchar_t and cast to char if necessary to avoid having
1717   // two specialization of WidthSpec and its subclasses.
1718   wchar_t fill_;
1719 
WidthSpecfmt::WidthSpec1720   WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {}
1721 
widthfmt::WidthSpec1722   unsigned width() const { return width_; }
fillfmt::WidthSpec1723   wchar_t fill() const { return fill_; }
1724 };
1725 
1726 // An alignment specifier.
1727 struct AlignSpec : WidthSpec {
1728   Alignment align_;
1729 
AlignSpecfmt::AlignSpec1730   AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT)
1731   : WidthSpec(width, fill), align_(align) {}
1732 
alignfmt::AlignSpec1733   Alignment align() const { return align_; }
1734 
precisionfmt::AlignSpec1735   int precision() const { return -1; }
1736 };
1737 
1738 // An alignment and type specifier.
1739 template <char TYPE>
1740 struct AlignTypeSpec : AlignSpec {
AlignTypeSpecfmt::AlignTypeSpec1741   AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {}
1742 
flagfmt::AlignTypeSpec1743   bool flag(unsigned) const { return false; }
typefmt::AlignTypeSpec1744   char type() const { return TYPE; }
type_prefixfmt::AlignTypeSpec1745   char type_prefix() const { return TYPE; }
1746 };
1747 
1748 // A full format specifier.
1749 struct FormatSpec : AlignSpec {
1750   unsigned flags_;
1751   int precision_;
1752   char type_;
1753 
FormatSpecfmt::FormatSpec1754   FormatSpec(
1755     unsigned width = 0, char type = 0, wchar_t fill = ' ')
1756   : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {}
1757 
flagfmt::FormatSpec1758   bool flag(unsigned f) const { return (flags_ & f) != 0; }
precisionfmt::FormatSpec1759   int precision() const { return precision_; }
typefmt::FormatSpec1760   char type() const { return type_; }
type_prefixfmt::FormatSpec1761   char type_prefix() const { return type_; }
1762 };
1763 
1764 // An integer format specifier.
1765 template <typename T, typename SpecT = TypeSpec<0>, typename Char = char>
1766 class IntFormatSpec : public SpecT {
1767  private:
1768   T value_;
1769 
1770  public:
IntFormatSpec(T val, const SpecT &spec = SpecT())1771   IntFormatSpec(T val, const SpecT &spec = SpecT())
1772   : SpecT(spec), value_(val) {}
1773 
value() const1774   T value() const { return value_; }
1775 };
1776 
1777 // A string format specifier.
1778 template <typename Char>
1779 class StrFormatSpec : public AlignSpec {
1780  private:
1781   const Char *str_;
1782 
1783  public:
1784   template <typename FillChar>
StrFormatSpec(const Char *str, unsigned width, FillChar fill)1785   StrFormatSpec(const Char *str, unsigned width, FillChar fill)
1786   : AlignSpec(width, fill), str_(str) {
1787     internal::CharTraits<Char>::convert(FillChar());
1788   }
1789 
str() const1790   const Char *str() const { return str_; }
1791 };
1792 
1793 /**
1794   Returns an integer format specifier to format the value in base 2.
1795  */
1796 IntFormatSpec<int, TypeSpec<'b'> > bin(int value);
1797 
1798 /**
1799   Returns an integer format specifier to format the value in base 8.
1800  */
1801 IntFormatSpec<int, TypeSpec<'o'> > oct(int value);
1802 
1803 /**
1804   Returns an integer format specifier to format the value in base 16 using
1805   lower-case letters for the digits above 9.
1806  */
1807 IntFormatSpec<int, TypeSpec<'x'> > hex(int value);
1808 
1809 /**
1810   Returns an integer formatter format specifier to format in base 16 using
1811   upper-case letters for the digits above 9.
1812  */
1813 IntFormatSpec<int, TypeSpec<'X'> > hexu(int value);
1814 
1815 /**
1816   \rst
1817   Returns an integer format specifier to pad the formatted argument with the
1818   fill character to the specified width using the default (right) numeric
1819   alignment.
1820 
1821   **Example**::
1822 
1823     MemoryWriter out;
1824     out << pad(hex(0xcafe), 8, '0');
1825     // out.str() == "0000cafe"
1826 
1827   \endrst
1828  */
1829 template <char TYPE_CODE, typename Char>
1830 IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(
1831     int value, unsigned width, Char fill = ' ');
1832 
1833 #define FMT_DEFINE_INT_FORMATTERS(TYPE) \
1834 inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \
1835   return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \
1836 } \
1837  \
1838 inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \
1839   return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \
1840 } \
1841  \
1842 inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \
1843   return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \
1844 } \
1845  \
1846 inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \
1847   return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \
1848 } \
1849  \
1850 template <char TYPE_CODE> \
1851 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \
1852     IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \
1853   return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \
1854       f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \
1855 } \
1856  \
1857 /* For compatibility with older compilers we provide two overloads for pad, */ \
1858 /* one that takes a fill character and one that doesn't. In the future this */ \
1859 /* can be replaced with one overload making the template argument Char      */ \
1860 /* default to char (C++11). */ \
1861 template <char TYPE_CODE, typename Char> \
1862 inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \
1863     IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \
1864     unsigned width, Char fill) { \
1865   return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \
1866       f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \
1867 } \
1868  \
1869 inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \
1870     TYPE value, unsigned width) { \
1871   return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \
1872       value, AlignTypeSpec<0>(width, ' ')); \
1873 } \
1874  \
1875 template <typename Char> \
1876 inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \
1877    TYPE value, unsigned width, Char fill) { \
1878  return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \
1879      value, AlignTypeSpec<0>(width, fill)); \
1880 }
1881 
1882 FMT_DEFINE_INT_FORMATTERS(int)
1883 FMT_DEFINE_INT_FORMATTERS(long)
1884 FMT_DEFINE_INT_FORMATTERS(unsigned)
1885 FMT_DEFINE_INT_FORMATTERS(unsigned long)
1886 FMT_DEFINE_INT_FORMATTERS(LongLong)
1887 FMT_DEFINE_INT_FORMATTERS(ULongLong)
1888 
1889 /**
1890   \rst
1891   Returns a string formatter that pads the formatted argument with the fill
1892   character to the specified width using the default (left) string alignment.
1893 
1894   **Example**::
1895 
1896     std::string s = str(MemoryWriter() << pad("abc", 8));
1897     // s == "abc     "
1898 
1899   \endrst
1900  */
1901 template <typename Char>
pad( const Char *str, unsigned width, Char fill = �)1902 inline StrFormatSpec<Char> pad(
1903     const Char *str, unsigned width, Char fill = ' ') {
1904   return StrFormatSpec<Char>(str, width, fill);
1905 }
1906 
pad( const wchar_t *str, unsigned width, char fill = �)1907 inline StrFormatSpec<wchar_t> pad(
1908     const wchar_t *str, unsigned width, char fill = ' ') {
1909   return StrFormatSpec<wchar_t>(str, width, fill);
1910 }
1911 
1912 namespace internal {
1913 
1914 template <typename Char>
1915 class ArgMap {
1916  private:
1917   typedef std::vector<
1918     std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType;
1919   typedef typename MapType::value_type Pair;
1920 
1921   MapType map_;
1922 
1923  public:
1924   FMT_API void init(const ArgList &args);
1925 
find(const fmt::BasicStringRef<Char> &name) const1926   const internal::Arg *find(const fmt::BasicStringRef<Char> &name) const {
1927     // The list is unsorted, so just return the first matching name.
1928     for (typename MapType::const_iterator it = map_.begin(), end = map_.end();
1929          it != end; ++it) {
1930       if (it->first == name)
1931         return &it->second;
1932     }
1933     return FMT_NULL;
1934   }
1935 };
1936 
1937 template <typename Impl, typename Char, typename Spec = fmt::FormatSpec>
1938 class ArgFormatterBase : public ArgVisitor<Impl, void> {
1939  private:
1940   BasicWriter<Char> &writer_;
1941   Spec &spec_;
1942 
1943   FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase);
1944 
write_pointer(const void *p)1945   void write_pointer(const void *p) {
1946     spec_.flags_ = HASH_FLAG;
1947     spec_.type_ = 'x';
1948     writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_);
1949   }
1950 
1951   // workaround MSVC two-phase lookup issue
1952   typedef internal::Arg Arg;
1953 
1954  protected:
writer()1955   BasicWriter<Char> &writer() { return writer_; }
spec()1956   Spec &spec() { return spec_; }
1957 
write(bool value)1958   void write(bool value) {
1959     const char *str_value = value ? "true" : "false";
1960     Arg::StringValue<char> str = { str_value, std::strlen(str_value) };
1961     writer_.write_str(str, spec_);
1962   }
1963 
write(const char *value)1964   void write(const char *value) {
1965     Arg::StringValue<char> str = {value, value ? std::strlen(value) : 0};
1966     writer_.write_str(str, spec_);
1967   }
1968 
1969  public:
1970   typedef Spec SpecType;
1971 
ArgFormatterBase(BasicWriter<Char> &w, Spec &s)1972   ArgFormatterBase(BasicWriter<Char> &w, Spec &s)
1973   : writer_(w), spec_(s) {}
1974 
1975   template <typename T>
visit_any_int(T value)1976   void visit_any_int(T value) { writer_.write_int(value, spec_); }
1977 
1978   template <typename T>
visit_any_double(T value)1979   void visit_any_double(T value) { writer_.write_double(value, spec_); }
1980 
visit_bool(bool value)1981   void visit_bool(bool value) {
1982     if (spec_.type_) {
1983       visit_any_int(value);
1984       return;
1985     }
1986     write(value);
1987   }
1988 
visit_char(int value)1989   void visit_char(int value) {
1990     if (spec_.type_ && spec_.type_ != 'c') {
1991       spec_.flags_ |= CHAR_FLAG;
1992       writer_.write_int(value, spec_);
1993       return;
1994     }
1995     if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0)
1996       FMT_THROW(FormatError("invalid format specifier for char"));
1997     typedef typename BasicWriter<Char>::CharPtr CharPtr;
1998     Char fill = internal::CharTraits<Char>::cast(spec_.fill());
1999     CharPtr out = CharPtr();
2000     const unsigned CHAR_SIZE = 1;
2001     if (spec_.width_ > CHAR_SIZE) {
2002       out = writer_.grow_buffer(spec_.width_);
2003       if (spec_.align_ == ALIGN_RIGHT) {
2004         std::uninitialized_fill_n(out, spec_.width_ - CHAR_SIZE, fill);
2005         out += spec_.width_ - CHAR_SIZE;
2006       } else if (spec_.align_ == ALIGN_CENTER) {
2007         out = writer_.fill_padding(out, spec_.width_,
2008                                    internal::const_check(CHAR_SIZE), fill);
2009       } else {
2010         std::uninitialized_fill_n(out + CHAR_SIZE,
2011                                   spec_.width_ - CHAR_SIZE, fill);
2012       }
2013     } else {
2014       out = writer_.grow_buffer(CHAR_SIZE);
2015     }
2016     *out = internal::CharTraits<Char>::cast(value);
2017   }
2018 
visit_cstring(const char *value)2019   void visit_cstring(const char *value) {
2020     if (spec_.type_ == 'p')
2021       return write_pointer(value);
2022     write(value);
2023   }
2024 
2025   // Qualification with "internal" here and below is a workaround for nvcc.
visit_string(internal::Arg::StringValue<char> value)2026   void visit_string(internal::Arg::StringValue<char> value) {
2027     writer_.write_str(value, spec_);
2028   }
2029 
2030   using ArgVisitor<Impl, void>::visit_wstring;
2031 
visit_wstring(internal::Arg::StringValue<Char> value)2032   void visit_wstring(internal::Arg::StringValue<Char> value) {
2033     writer_.write_str(value, spec_);
2034   }
2035 
visit_pointer(const void *value)2036   void visit_pointer(const void *value) {
2037     if (spec_.type_ && spec_.type_ != 'p')
2038       report_unknown_type(spec_.type_, "pointer");
2039     write_pointer(value);
2040   }
2041 };
2042 
2043 class FormatterBase {
2044  private:
2045   ArgList args_;
2046   int next_arg_index_;
2047 
2048   // Returns the argument with specified index.
2049   FMT_API Arg do_get_arg(unsigned arg_index, const char *&error);
2050 
2051  protected:
args() const2052   const ArgList &args() const { return args_; }
2053 
FormatterBase(const ArgList &args)2054   explicit FormatterBase(const ArgList &args) {
2055     args_ = args;
2056     next_arg_index_ = 0;
2057   }
2058 
2059   // Returns the next argument.
next_arg(const char *&error)2060   Arg next_arg(const char *&error) {
2061     if (next_arg_index_ >= 0)
2062       return do_get_arg(internal::to_unsigned(next_arg_index_++), error);
2063     error = "cannot switch from manual to automatic argument indexing";
2064     return Arg();
2065   }
2066 
2067   // Checks if manual indexing is used and returns the argument with
2068   // specified index.
get_arg(unsigned arg_index, const char *&error)2069   Arg get_arg(unsigned arg_index, const char *&error) {
2070     return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg();
2071   }
2072 
check_no_auto_index(const char *&error)2073   bool check_no_auto_index(const char *&error) {
2074     if (next_arg_index_ > 0) {
2075       error = "cannot switch from automatic to manual argument indexing";
2076       return false;
2077     }
2078     next_arg_index_ = -1;
2079     return true;
2080   }
2081 
2082   template <typename Char>
write(BasicWriter<Char> &w, const Char *start, const Char *end)2083   void write(BasicWriter<Char> &w, const Char *start, const Char *end) {
2084     if (start != end)
2085       w << BasicStringRef<Char>(start, internal::to_unsigned(end - start));
2086   }
2087 };
2088 }  // namespace internal
2089 
2090 /**
2091   \rst
2092   An argument formatter based on the `curiously recurring template pattern
2093   <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_.
2094 
2095   To use `~fmt::BasicArgFormatter` define a subclass that implements some or
2096   all of the visit methods with the same signatures as the methods in
2097   `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`.
2098   Pass the subclass as the *Impl* template parameter. When a formatting
2099   function processes an argument, it will dispatch to a visit method
2100   specific to the argument type. For example, if the argument type is
2101   ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass
2102   will be called. If the subclass doesn't contain a method with this signature,
2103   then a corresponding method of `~fmt::BasicArgFormatter` or its superclass
2104   will be called.
2105   \endrst
2106  */
2107 template <typename Impl, typename Char, typename Spec = fmt::FormatSpec>
2108 class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char, Spec> {
2109  private:
2110   BasicFormatter<Char, Impl> &formatter_;
2111   const Char *format_;
2112 
2113  public:
2114   /**
2115     \rst
2116     Constructs an argument formatter object.
2117     *formatter* is a reference to the main formatter object, *spec* contains
2118     format specifier information for standard argument types, and *fmt* points
2119     to the part of the format string being parsed for custom argument types.
2120     \endrst
2121    */
BasicArgFormatter(BasicFormatter<Char, Impl> &formatter, Spec &spec, const Char *fmt)2122   BasicArgFormatter(BasicFormatter<Char, Impl> &formatter,
2123                     Spec &spec, const Char *fmt)
2124   : internal::ArgFormatterBase<Impl, Char, Spec>(formatter.writer(), spec),
2125     formatter_(formatter), format_(fmt) {}
2126 
2127   /** Formats an argument of a custom (user-defined) type. */
visit_custom(internal::Arg::CustomValue c)2128   void visit_custom(internal::Arg::CustomValue c) {
2129     c.format(&formatter_, c.value, &format_);
2130   }
2131 };
2132 
2133 /** The default argument formatter. */
2134 template <typename Char>
2135 class ArgFormatter :
2136     public BasicArgFormatter<ArgFormatter<Char>, Char, FormatSpec> {
2137  public:
2138   /** Constructs an argument formatter object. */
ArgFormatter(BasicFormatter<Char> &formatter, FormatSpec &spec, const Char *fmt)2139   ArgFormatter(BasicFormatter<Char> &formatter,
2140                FormatSpec &spec, const Char *fmt)
2141   : BasicArgFormatter<ArgFormatter<Char>,
2142                       Char, FormatSpec>(formatter, spec, fmt) {}
2143 };
2144 
2145 /** This template formats data and writes the output to a writer. */
2146 template <typename CharType, typename ArgFormatter>
2147 class BasicFormatter : private internal::FormatterBase {
2148  public:
2149   /** The character type for the output. */
2150   typedef CharType Char;
2151 
2152  private:
2153   BasicWriter<Char> &writer_;
2154   internal::ArgMap<Char> map_;
2155 
2156   FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter);
2157 
2158   using internal::FormatterBase::get_arg;
2159 
2160   // Checks if manual indexing is used and returns the argument with
2161   // specified name.
2162   internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error);
2163 
2164   // Parses argument index and returns corresponding argument.
2165   internal::Arg parse_arg_index(const Char *&s);
2166 
2167   // Parses argument name and returns corresponding argument.
2168   internal::Arg parse_arg_name(const Char *&s);
2169 
2170  public:
2171   /**
2172    \rst
2173    Constructs a ``BasicFormatter`` object. References to the arguments and
2174    the writer are stored in the formatter object so make sure they have
2175    appropriate lifetimes.
2176    \endrst
2177    */
BasicFormatter(const ArgList &args, BasicWriter<Char> &w)2178   BasicFormatter(const ArgList &args, BasicWriter<Char> &w)
2179     : internal::FormatterBase(args), writer_(w) {}
2180 
2181   /** Returns a reference to the writer associated with this formatter. */
writer()2182   BasicWriter<Char> &writer() { return writer_; }
2183 
2184   /** Formats stored arguments and writes the output to the writer. */
2185   void format(BasicCStringRef<Char> format_str);
2186 
2187   // Formats a single argument and advances format_str, a format string pointer.
2188   const Char *format(const Char *&format_str, const internal::Arg &arg);
2189 };
2190 
2191 // Generates a comma-separated list with results of applying f to
2192 // numbers 0..n-1.
2193 # define FMT_GEN(n, f) FMT_GEN##n(f)
2194 # define FMT_GEN1(f)  f(0)
2195 # define FMT_GEN2(f)  FMT_GEN1(f),  f(1)
2196 # define FMT_GEN3(f)  FMT_GEN2(f),  f(2)
2197 # define FMT_GEN4(f)  FMT_GEN3(f),  f(3)
2198 # define FMT_GEN5(f)  FMT_GEN4(f),  f(4)
2199 # define FMT_GEN6(f)  FMT_GEN5(f),  f(5)
2200 # define FMT_GEN7(f)  FMT_GEN6(f),  f(6)
2201 # define FMT_GEN8(f)  FMT_GEN7(f),  f(7)
2202 # define FMT_GEN9(f)  FMT_GEN8(f),  f(8)
2203 # define FMT_GEN10(f) FMT_GEN9(f),  f(9)
2204 # define FMT_GEN11(f) FMT_GEN10(f), f(10)
2205 # define FMT_GEN12(f) FMT_GEN11(f), f(11)
2206 # define FMT_GEN13(f) FMT_GEN12(f), f(12)
2207 # define FMT_GEN14(f) FMT_GEN13(f), f(13)
2208 # define FMT_GEN15(f) FMT_GEN14(f), f(14)
2209 
2210 namespace internal {
make_type()2211 inline uint64_t make_type() { return 0; }
2212 
2213 template <typename T>
make_type(const T &arg)2214 inline uint64_t make_type(const T &arg) {
2215   return MakeValue< BasicFormatter<char> >::type(arg);
2216 }
2217 
2218 template <std::size_t N, bool/*IsPacked*/= (N < ArgList::MAX_PACKED_ARGS)>
2219 struct ArgArray;
2220 
2221 template <std::size_t N>
2222 struct ArgArray<N, true/*IsPacked*/> {
2223   typedef Value Type[N > 0 ? N : 1];
2224 
2225   template <typename Formatter, typename T>
make(const T &value)2226   static Value make(const T &value) {
2227 #ifdef __clang__
2228     Value result = MakeValue<Formatter>(value);
2229     // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang:
2230     // https://github.com/fmtlib/fmt/issues/276
2231     (void)result.custom.format;
2232     return result;
2233 #else
2234     return MakeValue<Formatter>(value);
2235 #endif
2236   }
2237 };
2238 
2239 template <std::size_t N>
2240 struct ArgArray<N, false/*IsPacked*/> {
2241   typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE
2242 
2243   template <typename Formatter, typename T>
makefmt::ArgArray2244   static Arg make(const T &value) { return MakeArg<Formatter>(value); }
2245 };
2246 
2247 #if FMT_USE_VARIADIC_TEMPLATES
2248 template <typename Arg, typename... Args>
make_type(const Arg &first, const Args & ... tail)2249 inline uint64_t make_type(const Arg &first, const Args & ... tail) {
2250   return make_type(first) | (make_type(tail...) << 4);
2251 }
2252 
2253 #else
2254 
2255 struct ArgType {
2256   uint64_t type;
2257 
ArgTypefmt::ArgType2258   ArgType() : type(0) {}
2259 
2260   template <typename T>
ArgTypefmt::ArgType2261   ArgType(const T &arg) : type(make_type(arg)) {}
2262 };
2263 
2264 # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType()
2265 
FMT_GEN15(FMT_ARG_TYPE_DEFAULT)2266 inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) {
2267   return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) |
2268       (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) |
2269       (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) |
2270       (t12.type << 48) | (t13.type << 52) | (t14.type << 56);
2271 }
2272 #endif
2273 }  // namespace internal
2274 
2275 # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n
2276 # define FMT_MAKE_ARG_TYPE(n) T##n
2277 # define FMT_MAKE_ARG(n) const T##n &v##n
2278 # define FMT_ASSIGN_char(n) \
2279   arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<char> >(v##n)
2280 # define FMT_ASSIGN_wchar_t(n) \
2281   arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<wchar_t> >(v##n)
2282 
2283 #if FMT_USE_VARIADIC_TEMPLATES
2284 // Defines a variadic function returning void.
2285 # define FMT_VARIADIC_VOID(func, arg_type) \
2286   template <typename... Args> \
2287   void func(arg_type arg0, const Args & ... args) { \
2288     typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2289     typename ArgArray::Type array{ \
2290       ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2291     func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2292   }
2293 
2294 // Defines a variadic constructor.
2295 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2296   template <typename... Args> \
2297   ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \
2298     typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \
2299     typename ArgArray::Type array{ \
2300       ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \
2301     func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \
2302   }
2303 
2304 #else
2305 
2306 # define FMT_MAKE_REF(n) \
2307   fmt::internal::MakeValue< fmt::BasicFormatter<Char> >(v##n)
2308 # define FMT_MAKE_REF2(n) v##n
2309 
2310 // Defines a wrapper for a function taking one argument of type arg_type
2311 // and n additional arguments of arbitrary types.
2312 # define FMT_WRAP1(func, arg_type, n) \
2313   template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2314   inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2315     const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2316     func(arg1, fmt::ArgList( \
2317       fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2318   }
2319 
2320 // Emulates a variadic function returning void on a pre-C++11 compiler.
2321 # define FMT_VARIADIC_VOID(func, arg_type) \
2322   inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \
2323   FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \
2324   FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \
2325   FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \
2326   FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \
2327   FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10)
2328 
2329 # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \
2330   template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \
2331   ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \
2332     const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \
2333     func(arg0, arg1, fmt::ArgList( \
2334       fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \
2335   }
2336 
2337 // Emulates a variadic constructor on a pre-C++11 compiler.
2338 # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \
2339   FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \
2340   FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \
2341   FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \
2342   FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \
2343   FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \
2344   FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \
2345   FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \
2346   FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \
2347   FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \
2348   FMT_CTOR(ctor, func, arg0_type, arg1_type, 10)
2349 #endif
2350 
2351 // Generates a comma-separated list with results of applying f to pairs
2352 // (argument, index).
2353 #define FMT_FOR_EACH1(f, x0) f(x0, 0)
2354 #define FMT_FOR_EACH2(f, x0, x1) \
2355   FMT_FOR_EACH1(f, x0), f(x1, 1)
2356 #define FMT_FOR_EACH3(f, x0, x1, x2) \
2357   FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2)
2358 #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \
2359   FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3)
2360 #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \
2361   FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4)
2362 #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \
2363   FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5)
2364 #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \
2365   FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6)
2366 #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \
2367   FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7)
2368 #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \
2369   FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8)
2370 #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \
2371   FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9)
2372 
2373 /**
2374  An error returned by an operating system or a language runtime,
2375  for example a file opening error.
2376 */
2377 class SystemError : public internal::RuntimeError {
2378  private:
2379   FMT_API void init(int err_code, CStringRef format_str, ArgList args);
2380 
2381  protected:
2382   int error_code_;
2383 
2384   typedef char Char;  // For FMT_VARIADIC_CTOR.
2385 
SystemError()2386   SystemError() {}
2387 
2388  public:
2389   /**
2390    \rst
2391    Constructs a :class:`fmt::SystemError` object with a description
2392    formatted with `fmt::format_system_error`. *message* and additional
2393    arguments passed into the constructor are formatted similarly to
2394    `fmt::format`.
2395 
2396    **Example**::
2397 
2398      // This throws a SystemError with the description
2399      //   cannot open file 'madeup': No such file or directory
2400      // or similar (system message may vary).
2401      const char *filename = "madeup";
2402      std::FILE *file = std::fopen(filename, "r");
2403      if (!file)
2404        throw fmt::SystemError(errno, "cannot open file '{}'", filename);
2405    \endrst
2406   */
SystemError(int error_code, CStringRef message)2407   SystemError(int error_code, CStringRef message) {
2408     init(error_code, message, ArgList());
2409   }
2410   FMT_DEFAULTED_COPY_CTOR(SystemError)
2411   FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef)
2412 
2413   FMT_API ~SystemError() FMT_DTOR_NOEXCEPT;
2414 
error_code() const2415   int error_code() const { return error_code_; }
2416 };
2417 
2418 /**
2419   \rst
2420   Formats an error returned by an operating system or a language runtime,
2421   for example a file opening error, and writes it to *out* in the following
2422   form:
2423 
2424   .. parsed-literal::
2425      *<message>*: *<system-message>*
2426 
2427   where *<message>* is the passed message and *<system-message>* is
2428   the system message corresponding to the error code.
2429   *error_code* is a system error code as given by ``errno``.
2430   If *error_code* is not a valid error code such as -1, the system message
2431   may look like "Unknown error -1" and is platform-dependent.
2432   \endrst
2433  */
2434 FMT_API void format_system_error(fmt::Writer &out, int error_code,
2435                                  fmt::StringRef message) FMT_NOEXCEPT;
2436 
2437 /**
2438   \rst
2439   This template provides operations for formatting and writing data into
2440   a character stream. The output is stored in a buffer provided by a subclass
2441   such as :class:`fmt::BasicMemoryWriter`.
2442 
2443   You can use one of the following typedefs for common character types:
2444 
2445   +---------+----------------------+
2446   | Type    | Definition           |
2447   +=========+======================+
2448   | Writer  | BasicWriter<char>    |
2449   +---------+----------------------+
2450   | WWriter | BasicWriter<wchar_t> |
2451   +---------+----------------------+
2452 
2453   \endrst
2454  */
2455 template <typename Char>
2456 class BasicWriter {
2457  private:
2458   // Output buffer.
2459   Buffer<Char> &buffer_;
2460 
2461   FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter);
2462 
2463   typedef typename internal::CharTraits<Char>::CharPtr CharPtr;
2464 
2465 #if FMT_SECURE_SCL
2466   // Returns pointer value.
get(CharPtr p)2467   static Char *get(CharPtr p) { return p.base(); }
2468 #else
get(Char *p)2469   static Char *get(Char *p) { return p; }
2470 #endif
2471 
2472   // Fills the padding around the content and returns the pointer to the
2473   // content area.
2474   static CharPtr fill_padding(CharPtr buffer,
2475       unsigned total_size, std::size_t content_size, wchar_t fill);
2476 
2477   // Grows the buffer by n characters and returns a pointer to the newly
2478   // allocated area.
grow_buffer(std::size_t n)2479   CharPtr grow_buffer(std::size_t n) {
2480     std::size_t size = buffer_.size();
2481     buffer_.resize(size + n);
2482     return internal::make_ptr(&buffer_[size], n);
2483   }
2484 
2485   // Writes an unsigned decimal integer.
2486   template <typename UInt>
write_unsigned_decimal(UInt value, unsigned prefix_size = 0)2487   Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) {
2488     unsigned num_digits = internal::count_digits(value);
2489     Char *ptr = get(grow_buffer(prefix_size + num_digits));
2490     internal::format_decimal(ptr + prefix_size, value, num_digits);
2491     return ptr;
2492   }
2493 
2494   // Writes a decimal integer.
2495   template <typename Int>
write_decimal(Int value)2496   void write_decimal(Int value) {
2497     typedef typename internal::IntTraits<Int>::MainType MainType;
2498     MainType abs_value = static_cast<MainType>(value);
2499     if (internal::is_negative(value)) {
2500       abs_value = 0 - abs_value;
2501       *write_unsigned_decimal(abs_value, 1) = '-';
2502     } else {
2503       write_unsigned_decimal(abs_value, 0);
2504     }
2505   }
2506 
2507   // Prepare a buffer for integer formatting.
prepare_int_buffer(unsigned num_digits, const EmptySpec &, const char *prefix, unsigned prefix_size)2508   CharPtr prepare_int_buffer(unsigned num_digits,
2509       const EmptySpec &, const char *prefix, unsigned prefix_size) {
2510     unsigned size = prefix_size + num_digits;
2511     CharPtr p = grow_buffer(size);
2512     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2513     return p + size - 1;
2514   }
2515 
2516   template <typename Spec>
2517   CharPtr prepare_int_buffer(unsigned num_digits,
2518     const Spec &spec, const char *prefix, unsigned prefix_size);
2519 
2520   // Formats an integer.
2521   template <typename T, typename Spec>
2522   void write_int(T value, Spec spec);
2523 
2524   // Formats a floating-point number (double or long double).
2525   template <typename T, typename Spec>
2526   void write_double(T value, const Spec &spec);
2527 
2528   // Writes a formatted string.
2529   template <typename StrChar>
2530   CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec);
2531 
2532   template <typename StrChar, typename Spec>
2533   void write_str(const internal::Arg::StringValue<StrChar> &str,
2534                  const Spec &spec);
2535 
2536   // This following methods are private to disallow writing wide characters
2537   // and strings to a char stream. If you want to print a wide string as a
2538   // pointer as std::ostream does, cast it to const void*.
2539   // Do not implement!
2540   void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported);
2541   void operator<<(
2542       typename internal::WCharHelper<const wchar_t *, Char>::Unsupported);
2543 
2544   // Appends floating-point length specifier to the format string.
2545   // The second argument is only used for overload resolution.
append_float_length(Char *&format_ptr, long double)2546   void append_float_length(Char *&format_ptr, long double) {
2547     *format_ptr++ = 'L';
2548   }
2549 
2550   template<typename T>
append_float_length(Char *&, T)2551   void append_float_length(Char *&, T) {}
2552 
2553   template <typename Impl, typename Char_, typename Spec_>
2554   friend class internal::ArgFormatterBase;
2555 
2556   template <typename Impl, typename Char_, typename Spec_>
2557   friend class BasicPrintfArgFormatter;
2558 
2559  protected:
2560   /**
2561     Constructs a ``BasicWriter`` object.
2562    */
BasicWriter(Buffer<Char> &b)2563   explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {}
2564 
2565  public:
2566   /**
2567     \rst
2568     Destroys a ``BasicWriter`` object.
2569     \endrst
2570    */
~BasicWriter()2571   virtual ~BasicWriter() {}
2572 
2573   /**
2574     Returns the total number of characters written.
2575    */
size() const2576   std::size_t size() const { return buffer_.size(); }
2577 
2578   /**
2579     Returns a pointer to the output buffer content. No terminating null
2580     character is appended.
2581    */
2582   const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; }
2583 
2584   /**
2585     Returns a pointer to the output buffer content with terminating null
2586     character appended.
2587    */
c_str() const2588   const Char *c_str() const {
2589     std::size_t size = buffer_.size();
2590     buffer_.reserve(size + 1);
2591     buffer_[size] = '\0';
2592     return &buffer_[0];
2593   }
2594 
2595   /**
2596     \rst
2597     Returns the content of the output buffer as an `std::string`.
2598     \endrst
2599    */
str() const2600   std::basic_string<Char> str() const {
2601     return std::basic_string<Char>(&buffer_[0], buffer_.size());
2602   }
2603 
2604   /**
2605     \rst
2606     Writes formatted data.
2607 
2608     *args* is an argument list representing arbitrary arguments.
2609 
2610     **Example**::
2611 
2612        MemoryWriter out;
2613        out.write("Current point:\n");
2614        out.write("({:+f}, {:+f})", -3.14, 3.14);
2615 
2616     This will write the following output to the ``out`` object:
2617 
2618     .. code-block:: none
2619 
2620        Current point:
2621        (-3.140000, +3.140000)
2622 
2623     The output can be accessed using :func:`data()`, :func:`c_str` or
2624     :func:`str` methods.
2625 
2626     See also :ref:`syntax`.
2627     \endrst
2628    */
write(BasicCStringRef<Char> format, ArgList args)2629   void write(BasicCStringRef<Char> format, ArgList args) {
2630     BasicFormatter<Char>(args, *this).format(format);
2631   }
2632   FMT_VARIADIC_VOID(write, BasicCStringRef<Char>)
2633 
operator <<(int value)2634   BasicWriter &operator<<(int value) {
2635     write_decimal(value);
2636     return *this;
2637   }
operator <<(unsigned value)2638   BasicWriter &operator<<(unsigned value) {
2639     return *this << IntFormatSpec<unsigned>(value);
2640   }
operator <<(long value)2641   BasicWriter &operator<<(long value) {
2642     write_decimal(value);
2643     return *this;
2644   }
operator <<(unsigned long value)2645   BasicWriter &operator<<(unsigned long value) {
2646     return *this << IntFormatSpec<unsigned long>(value);
2647   }
operator <<(LongLong value)2648   BasicWriter &operator<<(LongLong value) {
2649     write_decimal(value);
2650     return *this;
2651   }
2652 
2653   /**
2654     \rst
2655     Formats *value* and writes it to the stream.
2656     \endrst
2657    */
operator <<(ULongLong value)2658   BasicWriter &operator<<(ULongLong value) {
2659     return *this << IntFormatSpec<ULongLong>(value);
2660   }
2661 
operator <<(double value)2662   BasicWriter &operator<<(double value) {
2663     write_double(value, FormatSpec());
2664     return *this;
2665   }
2666 
2667   /**
2668     \rst
2669     Formats *value* using the general format for floating-point numbers
2670     (``'g'``) and writes it to the stream.
2671     \endrst
2672    */
operator <<(long double value)2673   BasicWriter &operator<<(long double value) {
2674     write_double(value, FormatSpec());
2675     return *this;
2676   }
2677 
2678   /**
2679     Writes a character to the stream.
2680    */
operator <<(char value)2681   BasicWriter &operator<<(char value) {
2682     buffer_.push_back(value);
2683     return *this;
2684   }
2685 
operator <<( typename internal::WCharHelper<wchar_t, Char>::Supported value)2686   BasicWriter &operator<<(
2687       typename internal::WCharHelper<wchar_t, Char>::Supported value) {
2688     buffer_.push_back(value);
2689     return *this;
2690   }
2691 
2692   /**
2693     \rst
2694     Writes *value* to the stream.
2695     \endrst
2696    */
operator <<(fmt::BasicStringRef<Char> value)2697   BasicWriter &operator<<(fmt::BasicStringRef<Char> value) {
2698     const Char *str = value.data();
2699     buffer_.append(str, str + value.size());
2700     return *this;
2701   }
2702 
operator <<( typename internal::WCharHelper<StringRef, Char>::Supported value)2703   BasicWriter &operator<<(
2704       typename internal::WCharHelper<StringRef, Char>::Supported value) {
2705     const char *str = value.data();
2706     buffer_.append(str, str + value.size());
2707     return *this;
2708   }
2709 
2710   template <typename T, typename Spec, typename FillChar>
operator <<(IntFormatSpec<T, Spec, FillChar> spec)2711   BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) {
2712     internal::CharTraits<Char>::convert(FillChar());
2713     write_int(spec.value(), spec);
2714     return *this;
2715   }
2716 
2717   template <typename StrChar>
operator <<(const StrFormatSpec<StrChar> &spec)2718   BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) {
2719     const StrChar *s = spec.str();
2720     write_str(s, std::char_traits<Char>::length(s), spec);
2721     return *this;
2722   }
2723 
2724   void clear() FMT_NOEXCEPT { buffer_.clear(); }
2725 
2726   Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; }
2727 };
2728 
2729 template <typename Char>
2730 template <typename StrChar>
write_str( const StrChar *s, std::size_t size, const AlignSpec &spec)2731 typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str(
2732       const StrChar *s, std::size_t size, const AlignSpec &spec) {
2733   CharPtr out = CharPtr();
2734   if (spec.width() > size) {
2735     out = grow_buffer(spec.width());
2736     Char fill = internal::CharTraits<Char>::cast(spec.fill());
2737     if (spec.align() == ALIGN_RIGHT) {
2738       std::uninitialized_fill_n(out, spec.width() - size, fill);
2739       out += spec.width() - size;
2740     } else if (spec.align() == ALIGN_CENTER) {
2741       out = fill_padding(out, spec.width(), size, fill);
2742     } else {
2743       std::uninitialized_fill_n(out + size, spec.width() - size, fill);
2744     }
2745   } else {
2746     out = grow_buffer(size);
2747   }
2748   std::uninitialized_copy(s, s + size, out);
2749   return out;
2750 }
2751 
2752 template <typename Char>
2753 template <typename StrChar, typename Spec>
write_str( const internal::Arg::StringValue<StrChar> &s, const Spec &spec)2754 void BasicWriter<Char>::write_str(
2755     const internal::Arg::StringValue<StrChar> &s, const Spec &spec) {
2756   // Check if StrChar is convertible to Char.
2757   internal::CharTraits<Char>::convert(StrChar());
2758   if (spec.type_ && spec.type_ != 's')
2759     internal::report_unknown_type(spec.type_, "string");
2760   const StrChar *str_value = s.value;
2761   std::size_t str_size = s.size;
2762   if (str_size == 0) {
2763     if (!str_value) {
2764       FMT_THROW(FormatError("string pointer is null"));
2765     }
2766   }
2767   std::size_t precision = static_cast<std::size_t>(spec.precision_);
2768   if (spec.precision_ >= 0 && precision < str_size)
2769     str_size = precision;
2770   write_str(str_value, str_size, spec);
2771 }
2772 
2773 template <typename Char>
2774 typename BasicWriter<Char>::CharPtr
fill_padding( CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill)2775   BasicWriter<Char>::fill_padding(
2776     CharPtr buffer, unsigned total_size,
2777     std::size_t content_size, wchar_t fill) {
2778   std::size_t padding = total_size - content_size;
2779   std::size_t left_padding = padding / 2;
2780   Char fill_char = internal::CharTraits<Char>::cast(fill);
2781   std::uninitialized_fill_n(buffer, left_padding, fill_char);
2782   buffer += left_padding;
2783   CharPtr content = buffer;
2784   std::uninitialized_fill_n(buffer + content_size,
2785                             padding - left_padding, fill_char);
2786   return content;
2787 }
2788 
2789 template <typename Char>
2790 template <typename Spec>
2791 typename BasicWriter<Char>::CharPtr
prepare_int_buffer( unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size)2792   BasicWriter<Char>::prepare_int_buffer(
2793     unsigned num_digits, const Spec &spec,
2794     const char *prefix, unsigned prefix_size) {
2795   unsigned width = spec.width();
2796   Alignment align = spec.align();
2797   Char fill = internal::CharTraits<Char>::cast(spec.fill());
2798   if (spec.precision() > static_cast<int>(num_digits)) {
2799     // Octal prefix '0' is counted as a digit, so ignore it if precision
2800     // is specified.
2801     if (prefix_size > 0 && prefix[prefix_size - 1] == '0')
2802       --prefix_size;
2803     unsigned number_size =
2804         prefix_size + internal::to_unsigned(spec.precision());
2805     AlignSpec subspec(number_size, '0', ALIGN_NUMERIC);
2806     if (number_size >= width)
2807       return prepare_int_buffer(num_digits, subspec, prefix, prefix_size);
2808     buffer_.reserve(width);
2809     unsigned fill_size = width - number_size;
2810     if (align != ALIGN_LEFT) {
2811       CharPtr p = grow_buffer(fill_size);
2812       std::uninitialized_fill(p, p + fill_size, fill);
2813     }
2814     CharPtr result = prepare_int_buffer(
2815         num_digits, subspec, prefix, prefix_size);
2816     if (align == ALIGN_LEFT) {
2817       CharPtr p = grow_buffer(fill_size);
2818       std::uninitialized_fill(p, p + fill_size, fill);
2819     }
2820     return result;
2821   }
2822   unsigned size = prefix_size + num_digits;
2823   if (width <= size) {
2824     CharPtr p = grow_buffer(size);
2825     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2826     return p + size - 1;
2827   }
2828   CharPtr p = grow_buffer(width);
2829   CharPtr end = p + width;
2830   if (align == ALIGN_LEFT) {
2831     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2832     p += size;
2833     std::uninitialized_fill(p, end, fill);
2834   } else if (align == ALIGN_CENTER) {
2835     p = fill_padding(p, width, size, fill);
2836     std::uninitialized_copy(prefix, prefix + prefix_size, p);
2837     p += size;
2838   } else {
2839     if (align == ALIGN_NUMERIC) {
2840       if (prefix_size != 0) {
2841         p = std::uninitialized_copy(prefix, prefix + prefix_size, p);
2842         size -= prefix_size;
2843       }
2844     } else {
2845       std::uninitialized_copy(prefix, prefix + prefix_size, end - size);
2846     }
2847     std::uninitialized_fill(p, end - size, fill);
2848     p = end;
2849   }
2850   return p - 1;
2851 }
2852 
2853 template <typename Char>
2854 template <typename T, typename Spec>
write_int(T value, Spec spec)2855 void BasicWriter<Char>::write_int(T value, Spec spec) {
2856   unsigned prefix_size = 0;
2857   typedef typename internal::IntTraits<T>::MainType UnsignedType;
2858   UnsignedType abs_value = static_cast<UnsignedType>(value);
2859   char prefix[4] = "";
2860   if (internal::is_negative(value)) {
2861     prefix[0] = '-';
2862     ++prefix_size;
2863     abs_value = 0 - abs_value;
2864   } else if (spec.flag(SIGN_FLAG)) {
2865     prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' ';
2866     ++prefix_size;
2867   }
2868   switch (spec.type()) {
2869   case 0: case 'd': {
2870     unsigned num_digits = internal::count_digits(abs_value);
2871     CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1;
2872     internal::format_decimal(get(p), abs_value, 0);
2873     break;
2874   }
2875   case 'x': case 'X': {
2876     UnsignedType n = abs_value;
2877     if (spec.flag(HASH_FLAG)) {
2878       prefix[prefix_size++] = '0';
2879       prefix[prefix_size++] = spec.type_prefix();
2880     }
2881     unsigned num_digits = 0;
2882     do {
2883       ++num_digits;
2884     } while ((n >>= 4) != 0);
2885     Char *p = get(prepare_int_buffer(
2886       num_digits, spec, prefix, prefix_size));
2887     n = abs_value;
2888     const char *digits = spec.type() == 'x' ?
2889         "0123456789abcdef" : "0123456789ABCDEF";
2890     do {
2891       *p-- = digits[n & 0xf];
2892     } while ((n >>= 4) != 0);
2893     break;
2894   }
2895   case 'b': case 'B': {
2896     UnsignedType n = abs_value;
2897     if (spec.flag(HASH_FLAG)) {
2898       prefix[prefix_size++] = '0';
2899       prefix[prefix_size++] = spec.type_prefix();
2900     }
2901     unsigned num_digits = 0;
2902     do {
2903       ++num_digits;
2904     } while ((n >>= 1) != 0);
2905     Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2906     n = abs_value;
2907     do {
2908       *p-- = static_cast<Char>('0' + (n & 1));
2909     } while ((n >>= 1) != 0);
2910     break;
2911   }
2912   case 'o': {
2913     UnsignedType n = abs_value;
2914     if (spec.flag(HASH_FLAG))
2915       prefix[prefix_size++] = '0';
2916     unsigned num_digits = 0;
2917     do {
2918       ++num_digits;
2919     } while ((n >>= 3) != 0);
2920     Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size));
2921     n = abs_value;
2922     do {
2923       *p-- = static_cast<Char>('0' + (n & 7));
2924     } while ((n >>= 3) != 0);
2925     break;
2926   }
2927   case 'n': {
2928     unsigned num_digits = internal::count_digits(abs_value);
2929     fmt::StringRef sep = "";
2930 #if !(defined(ANDROID) || defined(__ANDROID__))
2931     sep = internal::thousands_sep(std::localeconv());
2932 #endif
2933     unsigned size = static_cast<unsigned>(
2934           num_digits + sep.size() * ((num_digits - 1) / 3));
2935     CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1;
2936     internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep));
2937     break;
2938   }
2939   default:
2940     internal::report_unknown_type(
2941       spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer");
2942     break;
2943   }
2944 }
2945 
2946 template <typename Char>
2947 template <typename T, typename Spec>
write_double(T value, const Spec &spec)2948 void BasicWriter<Char>::write_double(T value, const Spec &spec) {
2949   // Check type.
2950   char type = spec.type();
2951   bool upper = false;
2952   switch (type) {
2953   case 0:
2954     type = 'g';
2955     break;
2956   case 'e': case 'f': case 'g': case 'a':
2957     break;
2958   case 'F':
2959 #if FMT_MSC_VER
2960     // MSVC's printf doesn't support 'F'.
2961     type = 'f';
2962 #endif
2963     // Fall through.
2964   case 'E': case 'G': case 'A':
2965     upper = true;
2966     break;
2967   default:
2968     internal::report_unknown_type(type, "double");
2969     break;
2970   }
2971 
2972   char sign = 0;
2973   // Use isnegative instead of value < 0 because the latter is always
2974   // false for NaN.
2975   if (internal::FPUtil::isnegative(static_cast<double>(value))) {
2976     sign = '-';
2977     value = -value;
2978   } else if (spec.flag(SIGN_FLAG)) {
2979     sign = spec.flag(PLUS_FLAG) ? '+' : ' ';
2980   }
2981 
2982   if (internal::FPUtil::isnotanumber(value)) {
2983     // Format NaN ourselves because sprintf's output is not consistent
2984     // across platforms.
2985     std::size_t nan_size = 4;
2986     const char *nan = upper ? " NAN" : " nan";
2987     if (!sign) {
2988       --nan_size;
2989       ++nan;
2990     }
2991     CharPtr out = write_str(nan, nan_size, spec);
2992     if (sign)
2993       *out = sign;
2994