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