LCOV - code coverage report
Current view: top level - src - tinyformat.h (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 156 254 61.4 %
Date: 2020-09-26 01:30:44 Functions: 1052 2026 51.9 %

          Line data    Source code
       1             : // tinyformat.h
       2             : // Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com]
       3             : //
       4             : // Boost Software License - Version 1.0
       5             : //
       6             : // Permission is hereby granted, free of charge, to any person or organization
       7             : // obtaining a copy of the software and accompanying documentation covered by
       8             : // this license (the "Software") to use, reproduce, display, distribute,
       9             : // execute, and transmit the Software, and to prepare derivative works of the
      10             : // Software, and to permit third-parties to whom the Software is furnished to
      11             : // do so, all subject to the following:
      12             : //
      13             : // The copyright notices in the Software and this entire statement, including
      14             : // the above license grant, this restriction and the following disclaimer,
      15             : // must be included in all copies of the Software, in whole or in part, and
      16             : // all derivative works of the Software, unless such copies or derivative
      17             : // works are solely in the form of machine-executable object code generated by
      18             : // a source language processor.
      19             : //
      20             : // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      21             : // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      22             : // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
      23             : // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
      24             : // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
      25             : // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      26             : // DEALINGS IN THE SOFTWARE.
      27             : 
      28             : //------------------------------------------------------------------------------
      29             : // Tinyformat: A minimal type safe printf replacement
      30             : //
      31             : // tinyformat.h is a type safe printf replacement library in a single C++
      32             : // header file.  Design goals include:
      33             : //
      34             : // * Type safety and extensibility for user defined types.
      35             : // * C99 printf() compatibility, to the extent possible using std::ostream
      36             : // * POSIX extension for positional arguments
      37             : // * Simplicity and minimalism.  A single header file to include and distribute
      38             : //   with your projects.
      39             : // * Augment rather than replace the standard stream formatting mechanism
      40             : // * C++98 support, with optional C++11 niceties
      41             : //
      42             : //
      43             : // Main interface example usage
      44             : // ----------------------------
      45             : //
      46             : // To print a date to std::cout for American usage:
      47             : //
      48             : //   std::string weekday = "Wednesday";
      49             : //   const char* month = "July";
      50             : //   size_t day = 27;
      51             : //   long hour = 14;
      52             : //   int min = 44;
      53             : //
      54             : //   tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);
      55             : //
      56             : // POSIX extension for positional arguments is available.
      57             : // The ability to rearrange formatting arguments is an important feature
      58             : // for localization because the word order may vary in different languages.
      59             : //
      60             : // Previous example for German usage. Arguments are reordered:
      61             : //
      62             : //   tfm::printf("%1$s, %3$d. %2$s, %4$d:%5$.2d\n", weekday, month, day, hour, min);
      63             : //
      64             : // The strange types here emphasize the type safety of the interface; it is
      65             : // possible to print a std::string using the "%s" conversion, and a
      66             : // size_t using the "%d" conversion.  A similar result could be achieved
      67             : // using either of the tfm::format() functions.  One prints on a user provided
      68             : // stream:
      69             : //
      70             : //   tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",
      71             : //               weekday, month, day, hour, min);
      72             : //
      73             : // The other returns a std::string:
      74             : //
      75             : //   std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",
      76             : //                                  weekday, month, day, hour, min);
      77             : //   std::cout << date;
      78             : //
      79             : // These are the three primary interface functions.  There is also a
      80             : // convenience function printfln() which appends a newline to the usual result
      81             : // of printf() for super simple logging.
      82             : //
      83             : //
      84             : // User defined format functions
      85             : // -----------------------------
      86             : //
      87             : // Simulating variadic templates in C++98 is pretty painful since it requires
      88             : // writing out the same function for each desired number of arguments.  To make
      89             : // this bearable tinyformat comes with a set of macros which are used
      90             : // internally to generate the API, but which may also be used in user code.
      91             : //
      92             : // The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and
      93             : // TINYFORMAT_PASSARGS(n) will generate a list of n argument types,
      94             : // type/name pairs and argument names respectively when called with an integer
      95             : // n between 1 and 16.  We can use these to define a macro which generates the
      96             : // desired user defined function with n arguments.  To generate all 16 user
      97             : // defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM.  For an
      98             : // example, see the implementation of printf() at the end of the source file.
      99             : //
     100             : // Sometimes it's useful to be able to pass a list of format arguments through
     101             : // to a non-template function.  The FormatList class is provided as a way to do
     102             : // this by storing the argument list in a type-opaque way.  Continuing the
     103             : // example from above, we construct a FormatList using makeFormatList():
     104             : //
     105             : //   FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min);
     106             : //
     107             : // The format list can now be passed into any non-template function and used
     108             : // via a call to the vformat() function:
     109             : //
     110             : //   tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList);
     111             : //
     112             : //
     113             : // Additional API information
     114             : // --------------------------
     115             : //
     116             : // Error handling: Define TINYFORMAT_ERROR to customize the error handling for
     117             : // format strings which are unsupported or have the wrong number of format
     118             : // specifiers (calls assert() by default).
     119             : //
     120             : // User defined types: Uses operator<< for user defined types by default.
     121             : // Overload formatValue() for more control.
     122             : 
     123             : 
     124             : #ifndef TINYFORMAT_H_INCLUDED
     125             : #define TINYFORMAT_H_INCLUDED
     126             : 
     127             : namespace tinyformat {}
     128             : //------------------------------------------------------------------------------
     129             : // Config section.  Customize to your liking!
     130             : 
     131             : // Namespace alias to encourage brevity
     132             : namespace tfm = tinyformat;
     133             : 
     134             : // Error handling; calls assert() by default.
     135             : #define TINYFORMAT_ERROR(reasonString) throw tinyformat::format_error(reasonString)
     136             : 
     137             : // Define for C++11 variadic templates which make the code shorter & more
     138             : // general.  If you don't define this, C++11 support is autodetected below.
     139             : #define TINYFORMAT_USE_VARIADIC_TEMPLATES
     140             : 
     141             : 
     142             : //------------------------------------------------------------------------------
     143             : // Implementation details.
     144             : #include <algorithm>
     145             : #include <iostream>
     146             : #include <sstream>
     147             : #include <stdexcept> // Added for Bitcoin Core
     148             : 
     149             : #ifndef TINYFORMAT_ASSERT
     150             : #   include <cassert>
     151             : #   define TINYFORMAT_ASSERT(cond) assert(cond)
     152             : #endif
     153             : 
     154             : #ifndef TINYFORMAT_ERROR
     155             : #   include <cassert>
     156             : #   define TINYFORMAT_ERROR(reason) assert(0 && reason)
     157             : #endif
     158             : 
     159             : #if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)
     160             : #   ifdef __GXX_EXPERIMENTAL_CXX0X__
     161             : #       define TINYFORMAT_USE_VARIADIC_TEMPLATES
     162             : #   endif
     163             : #endif
     164             : 
     165             : #if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201
     166             : //  std::showpos is broken on old libstdc++ as provided with macOS.  See
     167             : //  http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html
     168             : #   define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
     169             : #endif
     170             : 
     171             : #ifdef __APPLE__
     172             : // Workaround macOS linker warning: Xcode uses different default symbol
     173             : // visibilities for static libs vs executables (see issue #25)
     174             : #   define TINYFORMAT_HIDDEN __attribute__((visibility("hidden")))
     175             : #else
     176             : #   define TINYFORMAT_HIDDEN
     177             : #endif
     178             : 
     179             : namespace tinyformat {
     180             : 
     181             : // Added for Bitcoin Core
     182           0 : class format_error: public std::runtime_error
     183             : {
     184             : public:
     185           0 :     explicit format_error(const std::string &what): std::runtime_error(what) {
     186           0 :     }
     187             : };
     188             : 
     189             : //------------------------------------------------------------------------------
     190             : namespace detail {
     191             : 
     192             : // Test whether type T1 is convertible to type T2
     193             : template <typename T1, typename T2>
     194             : struct is_convertible
     195             : {
     196             :     private:
     197             :         // two types of different size
     198             :         struct fail { char dummy[2]; };
     199             :         struct succeed { char dummy; };
     200             :         // Try to convert a T1 to a T2 by plugging into tryConvert
     201             :         static fail tryConvert(...);
     202             :         static succeed tryConvert(const T2&);
     203             :         static const T1& makeT1();
     204             :     public:
     205             : #       ifdef _MSC_VER
     206             :         // Disable spurious loss of precision warnings in tryConvert(makeT1())
     207             : #       pragma warning(push)
     208             : #       pragma warning(disable:4244)
     209             : #       pragma warning(disable:4267)
     210             : #       endif
     211             :         // Standard trick: the (...) version of tryConvert will be chosen from
     212             :         // the overload set only if the version taking a T2 doesn't match.
     213             :         // Then we compare the sizes of the return types to check which
     214             :         // function matched.  Very neat, in a disgusting kind of way :)
     215             :         static const bool value =
     216             :             sizeof(tryConvert(makeT1())) == sizeof(succeed);
     217             : #       ifdef _MSC_VER
     218             : #       pragma warning(pop)
     219             : #       endif
     220             : };
     221             : 
     222             : 
     223             : // Detect when a type is not a wchar_t string
     224             : template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };
     225             : template<> struct is_wchar<wchar_t*> {};
     226             : template<> struct is_wchar<const wchar_t*> {};
     227             : template<int n> struct is_wchar<const wchar_t[n]> {};
     228             : template<int n> struct is_wchar<wchar_t[n]> {};
     229             : 
     230             : 
     231             : // Format the value by casting to type fmtT.  This default implementation
     232             : // should never be called.
     233             : template<typename T, typename fmtT, bool convertible = is_convertible<T, fmtT>::value>
     234             : struct formatValueAsType
     235             : {
     236             :     static void invoke(std::ostream& /*out*/, const T& /*value*/) { TINYFORMAT_ASSERT(0); }
     237             : };
     238             : // Specialized version for types that can actually be converted to fmtT, as
     239             : // indicated by the "convertible" template parameter.
     240             : template<typename T, typename fmtT>
     241             : struct formatValueAsType<T,fmtT,true>
     242             : {
     243           0 :     static void invoke(std::ostream& out, const T& value)
     244           0 :         { out << static_cast<fmtT>(value); }
     245             : };
     246             : 
     247             : #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
     248             : template<typename T, bool convertible = is_convertible<T, int>::value>
     249             : struct formatZeroIntegerWorkaround
     250             : {
     251             :     static bool invoke(std::ostream& /**/, const T& /**/) { return false; }
     252             : };
     253             : template<typename T>
     254             : struct formatZeroIntegerWorkaround<T,true>
     255             : {
     256             :     static bool invoke(std::ostream& out, const T& value)
     257             :     {
     258             :         if (static_cast<int>(value) == 0 && out.flags() & std::ios::showpos) {
     259             :             out << "+0";
     260             :             return true;
     261             :         }
     262             :         return false;
     263             :     }
     264             : };
     265             : #endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
     266             : 
     267             : // Convert an arbitrary type to integer.  The version with convertible=false
     268             : // throws an error.
     269             : template<typename T, bool convertible = is_convertible<T,int>::value>
     270             : struct convertToInt
     271             : {
     272           0 :     static int invoke(const T& /*value*/)
     273             :     {
     274           0 :         TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to "
     275             :                          "integer for use as variable width or precision");
     276             :         return 0;
     277           0 :     }
     278             : };
     279             : // Specialization for convertToInt when conversion is possible
     280             : template<typename T>
     281             : struct convertToInt<T,true>
     282             : {
     283           0 :     static int invoke(const T& value) { return static_cast<int>(value); }
     284             : };
     285             : 
     286             : // Format at most ntrunc characters to the given stream.
     287             : template<typename T>
     288           0 : inline void formatTruncated(std::ostream& out, const T& value, int ntrunc)
     289             : {
     290           0 :     std::ostringstream tmp;
     291           0 :     tmp << value;
     292           0 :     std::string result = tmp.str();
     293           0 :     out.write(result.c_str(), (std::min)(ntrunc, static_cast<int>(result.size())));
     294           0 : }
     295             : #define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type)       \
     296             : inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \
     297             : {                                                           \
     298             :     std::streamsize len = 0;                                \
     299             :     while (len < ntrunc && value[len] != 0)                 \
     300             :         ++len;                                              \
     301             :     out.write(value, len);                                  \
     302             : }
     303             : // Overload for const char* and char*.  Could overload for signed & unsigned
     304             : // char too, but these are technically unneeded for printf compatibility.
     305           0 : TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char)
     306           0 : TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char)
     307             : #undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR
     308             : 
     309             : } // namespace detail
     310             : 
     311             : 
     312             : //------------------------------------------------------------------------------
     313             : // Variable formatting functions.  May be overridden for user-defined types if
     314             : // desired.
     315             : 
     316             : 
     317             : /// Format a value into a stream, delegating to operator<< by default.
     318             : ///
     319             : /// Users may override this for their own types.  When this function is called,
     320             : /// the stream flags will have been modified according to the format string.
     321             : /// The format specification is provided in the range [fmtBegin, fmtEnd).  For
     322             : /// truncating conversions, ntrunc is set to the desired maximum number of
     323             : /// characters, for example "%.7s" calls formatValue with ntrunc = 7.
     324             : ///
     325             : /// By default, formatValue() uses the usual stream insertion operator
     326             : /// operator<< to format the type T, with special cases for the %c and %p
     327             : /// conversions.
     328             : template<typename T>
     329    29184052 : inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,
     330             :                         const char* fmtEnd, int ntrunc, const T& value)
     331             : {
     332             : #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS
     333             :     // Since we don't support printing of wchar_t using "%ls", make it fail at
     334             :     // compile time in preference to printing as a void* at runtime.
     335             :     typedef typename detail::is_wchar<T>::tinyformat_wchar_is_not_supported DummyType;
     336             :     (void) DummyType(); // avoid unused type warning with gcc-4.8
     337             : #endif
     338             :     // The mess here is to support the %c and %p conversions: if these
     339             :     // conversions are active we try to convert the type to a char or const
     340             :     // void* respectively and format that instead of the value itself.  For the
     341             :     // %p conversion it's important to avoid dereferencing the pointer, which
     342             :     // could otherwise lead to a crash when printing a dangling (const char*).
     343             :     const bool canConvertToChar = detail::is_convertible<T,char>::value;
     344             :     const bool canConvertToVoidPtr = detail::is_convertible<T, const void*>::value;
     345    25083615 :     if (canConvertToChar && *(fmtEnd-1) == 'c')
     346           0 :         detail::formatValueAsType<T, char>::invoke(out, value);
     347     1611762 :     else if (canConvertToVoidPtr && *(fmtEnd-1) == 'p')
     348           0 :         detail::formatValueAsType<T, const void*>::invoke(out, value);
     349             : #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
     350             :     else if (detail::formatZeroIntegerWorkaround<T>::invoke(out, value)) /**/;
     351             : #endif
     352    29184054 :     else if (ntrunc >= 0) {
     353             :         // Take care not to overread C strings in truncating conversions like
     354             :         // "%.4s" where at most 4 characters may be read.
     355           0 :         detail::formatTruncated(out, value, ntrunc);
     356           0 :     }
     357             :     else
     358    29184051 :         out << value;
     359    29184046 : }
     360             : 
     361             : 
     362             : // Overloaded version for char types to support printing as an integer
     363             : #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType)                  \
     364             : inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,  \
     365             :                         const char* fmtEnd, int /**/, charType value) \
     366             : {                                                                     \
     367             :     switch (*(fmtEnd-1)) {                                            \
     368             :         case 'u': case 'd': case 'i': case 'o': case 'X': case 'x':   \
     369             :             out << static_cast<int>(value); break;                    \
     370             :         default:                                                      \
     371             :             out << value;                   break;                    \
     372             :     }                                                                 \
     373             : }
     374             : // per 3.9.1: char, signed char and unsigned char are all distinct types
     375           2 : TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char)
     376             : TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char)
     377        3329 : TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char)
     378             : #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR
     379             : 
     380             : 
     381             : //------------------------------------------------------------------------------
     382             : // Tools for emulating variadic templates in C++98.  The basic idea here is
     383             : // stolen from the boost preprocessor metaprogramming library and cut down to
     384             : // be just general enough for what we need.
     385             : 
     386             : #define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n
     387             : #define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n
     388             : #define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n
     389             : #define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n
     390             : 
     391             : // To keep it as transparent as possible, the macros below have been generated
     392             : // using python via the excellent cog.py code generation script.  This avoids
     393             : // the need for a bunch of complex (but more general) preprocessor tricks as
     394             : // used in boost.preprocessor.
     395             : //
     396             : // To rerun the code generation in place, use `cog.py -r tinyformat.h`
     397             : // (see http://nedbatchelder.com/code/cog).  Alternatively you can just create
     398             : // extra versions by hand.
     399             : 
     400             : /*[[[cog
     401             : maxParams = 16
     402             : 
     403             : def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1):
     404             :     for j in range(startInd,maxParams+1):
     405             :         list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)])
     406             :         cog.outl(lineTemplate % {'j':j, 'list':list})
     407             : 
     408             : makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s',
     409             :                   'class T%(i)d')
     410             : 
     411             : cog.outl()
     412             : makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s',
     413             :                   'const T%(i)d& v%(i)d')
     414             : 
     415             : cog.outl()
     416             : makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d')
     417             : 
     418             : cog.outl()
     419             : cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1')
     420             : makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s',
     421             :                   'v%(i)d', startInd = 2)
     422             : 
     423             : cog.outl()
     424             : cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n    ' +
     425             :          ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)]))
     426             : ]]]*/
     427             : #define TINYFORMAT_ARGTYPES_1 class T1
     428             : #define TINYFORMAT_ARGTYPES_2 class T1, class T2
     429             : #define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3
     430             : #define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4
     431             : #define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5
     432             : #define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6
     433             : #define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7
     434             : #define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8
     435             : #define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9
     436             : #define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10
     437             : #define TINYFORMAT_ARGTYPES_11 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11
     438             : #define TINYFORMAT_ARGTYPES_12 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12
     439             : #define TINYFORMAT_ARGTYPES_13 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13
     440             : #define TINYFORMAT_ARGTYPES_14 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14
     441             : #define TINYFORMAT_ARGTYPES_15 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15
     442             : #define TINYFORMAT_ARGTYPES_16 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16
     443             : 
     444             : #define TINYFORMAT_VARARGS_1 const T1& v1
     445             : #define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2
     446             : #define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3
     447             : #define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4
     448             : #define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5
     449             : #define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6
     450             : #define TINYFORMAT_VARARGS_7 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7
     451             : #define TINYFORMAT_VARARGS_8 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8
     452             : #define TINYFORMAT_VARARGS_9 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9
     453             : #define TINYFORMAT_VARARGS_10 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10
     454             : #define TINYFORMAT_VARARGS_11 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11
     455             : #define TINYFORMAT_VARARGS_12 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12
     456             : #define TINYFORMAT_VARARGS_13 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13
     457             : #define TINYFORMAT_VARARGS_14 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14
     458             : #define TINYFORMAT_VARARGS_15 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15
     459             : #define TINYFORMAT_VARARGS_16 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15, const T16& v16
     460             : 
     461             : #define TINYFORMAT_PASSARGS_1 v1
     462             : #define TINYFORMAT_PASSARGS_2 v1, v2
     463             : #define TINYFORMAT_PASSARGS_3 v1, v2, v3
     464             : #define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4
     465             : #define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5
     466             : #define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6
     467             : #define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7
     468             : #define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8
     469             : #define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9
     470             : #define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10
     471             : #define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
     472             : #define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
     473             : #define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
     474             : #define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
     475             : #define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
     476             : #define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
     477             : 
     478             : #define TINYFORMAT_PASSARGS_TAIL_1
     479             : #define TINYFORMAT_PASSARGS_TAIL_2 , v2
     480             : #define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3
     481             : #define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4
     482             : #define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5
     483             : #define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6
     484             : #define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7
     485             : #define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8
     486             : #define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9
     487             : #define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10
     488             : #define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
     489             : #define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
     490             : #define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
     491             : #define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
     492             : #define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
     493             : #define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
     494             : 
     495             : #define TINYFORMAT_FOREACH_ARGNUM(m) \
     496             :     m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) m(15) m(16)
     497             : //[[[end]]]
     498             : 
     499             : 
     500             : 
     501             : namespace detail {
     502             : 
     503             : // Type-opaque holder for an argument to format(), with associated actions on
     504             : // the type held as explicit function pointers.  This allows FormatArg's for
     505             : // each argument to be allocated as a homogeneous array inside FormatList
     506             : // whereas a naive implementation based on inheritance does not.
     507             : class FormatArg
     508             : {
     509             :     public:
     510             :         FormatArg()
     511             :             : m_value(NULL),
     512             :             m_formatImpl(NULL),
     513             :             m_toIntImpl(NULL)
     514             :         { }
     515             : 
     516             :         template<typename T>
     517    58374778 :         FormatArg(const T& value)
     518    29187394 :             : m_value(static_cast<const void*>(&value)),
     519    29187394 :             m_formatImpl(&formatImpl<T>),
     520    29187394 :             m_toIntImpl(&toIntImpl<T>)
     521    58374778 :         { }
     522             : 
     523    29186974 :         void format(std::ostream& out, const char* fmtBegin,
     524             :                     const char* fmtEnd, int ntrunc) const
     525             :         {
     526    29186974 :             TINYFORMAT_ASSERT(m_value);
     527    29187017 :             TINYFORMAT_ASSERT(m_formatImpl);
     528    29187046 :             m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value);
     529    29187046 :         }
     530             : 
     531           0 :         int toInt() const
     532             :         {
     533           0 :             TINYFORMAT_ASSERT(m_value);
     534           0 :             TINYFORMAT_ASSERT(m_toIntImpl);
     535           0 :             return m_toIntImpl(m_value);
     536             :         }
     537             : 
     538             :     private:
     539             :         template<typename T>
     540    29187393 :         TINYFORMAT_HIDDEN static void formatImpl(std::ostream& out, const char* fmtBegin,
     541             :                         const char* fmtEnd, int ntrunc, const void* value)
     542             :         {
     543    29187393 :             formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast<const T*>(value));
     544    29187393 :         }
     545             : 
     546             :         template<typename T>
     547           0 :         TINYFORMAT_HIDDEN static int toIntImpl(const void* value)
     548             :         {
     549           0 :             return convertToInt<T>::invoke(*static_cast<const T*>(value));
     550             :         }
     551             : 
     552             :         const void* m_value;
     553             :         void (*m_formatImpl)(std::ostream& out, const char* fmtBegin,
     554             :                              const char* fmtEnd, int ntrunc, const void* value);
     555             :         int (*m_toIntImpl)(const void* value);
     556             : };
     557             : 
     558             : 
     559             : // Parse and return an integer from the string c, as atoi()
     560             : // On return, c is set to one past the end of the integer.
     561    20670671 : inline int parseIntAndAdvance(const char*& c)
     562             : {
     563             :     int i = 0;
     564    58335928 :     for (;*c >= '0' && *c <= '9'; ++c)
     565    37665258 :         i = 10*i + (*c - '0');
     566    20670672 :     return i;
     567             : }
     568             : 
     569             : // Parse width or precision `n` from format string pointer `c`, and advance it
     570             : // to the next character. If an indirection is requested with `*`, the argument
     571             : // is read from `args[argIndex]` and `argIndex` is incremented (or read
     572             : // from `args[n]` in positional mode). Returns true if one or more
     573             : // characters were read.
     574    15885988 : inline bool parseWidthOrPrecision(int& n, const char*& c, bool positionalMode,
     575             :                                   const detail::FormatArg* args,
     576             :                                   int& argIndex, int numArgs)
     577             : {
     578    15885988 :     if (*c >= '0' && *c <= '9') {
     579     3684782 :         n = parseIntAndAdvance(c);
     580     3684782 :     }
     581    12201347 :     else if (*c == '*') {
     582           0 :         ++c;
     583           0 :         n = 0;
     584           0 :         if (positionalMode) {
     585           0 :             int pos = parseIntAndAdvance(c) - 1;
     586           0 :             if (*c != '$')
     587           0 :                 TINYFORMAT_ERROR("tinyformat: Non-positional argument used after a positional one");
     588           0 :             if (pos >= 0 && pos < numArgs)
     589           0 :                 n = args[pos].toInt();
     590             :             else
     591           0 :                 TINYFORMAT_ERROR("tinyformat: Positional argument out of range");
     592           0 :             ++c;
     593           0 :         }
     594             :         else {
     595           0 :             if (argIndex < numArgs)
     596           0 :                 n = args[argIndex++].toInt();
     597             :             else
     598           0 :                 TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width or precision");
     599             :         }
     600             :     }
     601             :     else {
     602    12201315 :         return false;
     603             :     }
     604     3684782 :     return true;
     605    15886060 : }
     606             : 
     607             : // Print literal part of format string and return next format spec position.
     608             : //
     609             : // Skips over any occurrences of '%%', printing a literal '%' to the output.
     610             : // The position of the first % character of the next nontrivial format spec is
     611             : // returned, or the end of string.
     612    37888039 : inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt)
     613             : {
     614             :     const char* c = fmt;
     615   158618333 :     for (;; ++c) {
     616   158618476 :         if (*c == '\0') {
     617     8701210 :             out.write(fmt, c - fmt);
     618     8701210 :             return c;
     619             :         }
     620   149916742 :         else if (*c == '%') {
     621    29647185 :             out.write(fmt, c - fmt);
     622    29647185 :             if (*(c+1) != '%')
     623    29187111 :                 return c;
     624             :             // for "%%", tack trailing % onto next literal section.
     625      460152 :             fmt = ++c;
     626      460152 :         }
     627             :     }
     628    37888367 : }
     629             : 
     630             : 
     631             : // Parse a format string and set the stream state accordingly.
     632             : //
     633             : // The format mini-language recognized here is meant to be the one from C99,
     634             : // with the form "%[flags][width][.precision][length]type" with POSIX
     635             : // positional arguments extension.
     636             : //
     637             : // POSIX positional arguments extension:
     638             : // Conversions can be applied to the nth argument after the format in
     639             : // the argument list, rather than to the next unused argument. In this case,
     640             : // the conversion specifier character % (see below) is replaced by the sequence
     641             : // "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}],
     642             : // giving the position of the argument in the argument list. This feature
     643             : // provides for the definition of format strings that select arguments
     644             : // in an order appropriate to specific languages.
     645             : //
     646             : // The format can contain either numbered argument conversion specifications
     647             : // (that is, "%n$" and "*m$"), or unnumbered argument conversion specifications
     648             : // (that is, % and * ), but not both. The only exception to this is that %%
     649             : // can be mixed with the "%n$" form. The results of mixing numbered and
     650             : // unnumbered argument specifications in a format string are undefined.
     651             : // When numbered argument specifications are used, specifying the Nth argument
     652             : // requires that all the leading arguments, from the first to the (N-1)th,
     653             : // are specified in the format string.
     654             : //
     655             : // In format strings containing the "%n$" form of conversion specification,
     656             : // numbered arguments in the argument list can be referenced from the format
     657             : // string as many times as required.
     658             : //
     659             : // Formatting options which can't be natively represented using the ostream
     660             : // state are returned in spacePadPositive (for space padded positive numbers)
     661             : // and ntrunc (for truncating conversions).  argIndex is incremented if
     662             : // necessary to pull out variable width and precision.  The function returns a
     663             : // pointer to the character after the end of the current format spec.
     664    29187161 : inline const char* streamStateFromFormat(std::ostream& out, bool& positionalMode,
     665             :                                          bool& spacePadPositive,
     666             :                                          int& ntrunc, const char* fmtStart,
     667             :                                          const detail::FormatArg* args,
     668             :                                          int& argIndex, int numArgs)
     669             : {
     670    29187161 :     TINYFORMAT_ASSERT(*fmtStart == '%');
     671             :     // Reset stream state to defaults.
     672    29187159 :     out.width(0);
     673    29187159 :     out.precision(6);
     674    29187159 :     out.fill(' ');
     675             :     // Reset most flags; ignore irrelevant unitbuf & skipws.
     676    29187159 :     out.unsetf(std::ios::adjustfield | std::ios::basefield |
     677             :                std::ios::floatfield | std::ios::showbase | std::ios::boolalpha |
     678             :                std::ios::showpoint | std::ios::showpos | std::ios::uppercase);
     679             :     bool precisionSet = false;
     680    29187198 :     bool widthSet = false;
     681    29187190 :     int widthExtra = 0;
     682    29187159 :     const char* c = fmtStart + 1;
     683             : 
     684             :     // 1) Parse an argument index (if followed by '$') or a width possibly
     685             :     // preceded with '0' flag.
     686    29187159 :     if (*c >= '0' && *c <= '9') {
     687             :         const char tmpc = *c;
     688    16985910 :         int value = parseIntAndAdvance(c);
     689    16985910 :         if (*c == '$') {
     690             :             // value is an argument index
     691           0 :             if (value > 0 && value <= numArgs)
     692           0 :                 argIndex = value - 1;
     693             :             else
     694           0 :                 TINYFORMAT_ERROR("tinyformat: Positional argument out of range");
     695           0 :             ++c;
     696           0 :             positionalMode = true;
     697           0 :         }
     698    16985908 :         else if (positionalMode) {
     699           0 :             TINYFORMAT_ERROR("tinyformat: Non-positional argument used after a positional one");
     700             :         }
     701             :         else {
     702    16985908 :             if (tmpc == '0') {
     703             :                 // Use internal padding so that numeric values are
     704             :                 // formatted correctly, eg -00010 rather than 000-10
     705    16982836 :                 out.fill('0');
     706    16982836 :                 out.setf(std::ios::internal, std::ios::adjustfield);
     707    16982836 :             }
     708    16985907 :             if (value != 0) {
     709             :                 // Nonzero value means that we parsed width.
     710             :                 widthSet = true;
     711    16985908 :                 out.width(value);
     712    16985908 :             }
     713             :         }
     714    16985909 :     }
     715    12201382 :     else if (positionalMode) {
     716           0 :         TINYFORMAT_ERROR("tinyformat: Non-positional argument used after a positional one");
     717             :     }
     718             :     // 2) Parse flags and width if we did not do it in previous step.
     719    29187198 :     if (!widthSet) {
     720             :         // Parse flags
     721       11192 :         for (;; ++c) {
     722    12212469 :             switch (*c) {
     723             :                 case '#':
     724           0 :                     out.setf(std::ios::showpoint | std::ios::showbase);
     725           0 :                     continue;
     726             :                 case '0':
     727             :                     // overridden by left alignment ('-' flag)
     728           0 :                     if (!(out.flags() & std::ios::left)) {
     729             :                         // Use internal padding so that numeric values are
     730             :                         // formatted correctly, eg -00010 rather than 000-10
     731           0 :                         out.fill('0');
     732           0 :                         out.setf(std::ios::internal, std::ios::adjustfield);
     733           0 :                     }
     734             :                     continue;
     735             :                 case '-':
     736           0 :                     out.fill(' ');
     737           0 :                     out.setf(std::ios::left, std::ios::adjustfield);
     738           0 :                     continue;
     739             :                 case ' ':
     740             :                     // overridden by show positive sign, '+' flag.
     741           0 :                     if (!(out.flags() & std::ios::showpos))
     742           0 :                         spacePadPositive = true;
     743             :                     continue;
     744             :                 case '+':
     745       11192 :                     out.setf(std::ios::showpos);
     746       11192 :                     spacePadPositive = false;
     747             :                     widthExtra = 1;
     748       11192 :                     continue;
     749             :                 default:
     750             :                     break;
     751             :             }
     752             :             break;
     753             :         }
     754             :         // Parse width
     755    12201294 :         int width = 0;
     756    12201294 :         widthSet = parseWidthOrPrecision(width, c, positionalMode,
     757             :                                          args, argIndex, numArgs);
     758    12201294 :         if (widthSet) {
     759           0 :             if (width < 0) {
     760             :                 // negative widths correspond to '-' flag set
     761           0 :                 out.fill(' ');
     762           0 :                 out.setf(std::ios::left, std::ios::adjustfield);
     763           0 :                 width = -width;
     764           0 :             }
     765           0 :             out.width(width);
     766           0 :         }
     767    12201274 :     }
     768             :     // 3) Parse precision
     769    29187190 :     if (*c == '.') {
     770     3684782 :         ++c;
     771     3684782 :         int precision = 0;
     772     3684782 :         parseWidthOrPrecision(precision, c, positionalMode,
     773             :                               args, argIndex, numArgs);
     774             :         // Presence of `.` indicates precision set, unless the inferred value
     775             :         // was negative in which case the default is used.
     776     3684782 :         precisionSet = precision >= 0;
     777     3684782 :         if (precisionSet)
     778     3684782 :             out.precision(precision);
     779     3684782 :     }
     780             :     // 4) Ignore any C99 length modifier
     781    58504510 :     while (*c == 'l' || *c == 'h' || *c == 'L' ||
     782    29192899 :            *c == 'j' || *c == 'z' || *c == 't') {
     783      130396 :         ++c;
     784             :     }
     785             :     // 5) We're up to the conversion specifier character.
     786             :     // Set stream flags based on conversion specifier (thanks to the
     787             :     // boost::format class for forging the way here).
     788             :     bool intConversion = false;
     789    29187028 :     switch (*c) {
     790             :         case 'u': case 'd': case 'i':
     791    20364528 :             out.setf(std::ios::dec, std::ios::basefield);
     792             :             intConversion = true;
     793    20364528 :             break;
     794             :         case 'o':
     795           0 :             out.setf(std::ios::oct, std::ios::basefield);
     796             :             intConversion = true;
     797           0 :             break;
     798             :         case 'X':
     799           0 :             out.setf(std::ios::uppercase);
     800             :             // Falls through
     801             :         case 'x': case 'p':
     802       93473 :             out.setf(std::ios::hex, std::ios::basefield);
     803             :             intConversion = true;
     804       93473 :             break;
     805             :         case 'E':
     806           0 :             out.setf(std::ios::uppercase);
     807             :             // Falls through
     808             :         case 'e':
     809           0 :             out.setf(std::ios::scientific, std::ios::floatfield);
     810           0 :             out.setf(std::ios::dec, std::ios::basefield);
     811           0 :             break;
     812             :         case 'F':
     813           0 :             out.setf(std::ios::uppercase);
     814             :             // Falls through
     815             :         case 'f':
     816     3783555 :             out.setf(std::ios::fixed, std::ios::floatfield);
     817     3783555 :             break;
     818             :         case 'A':
     819           0 :             out.setf(std::ios::uppercase);
     820             :             // Falls through
     821             :         case 'a':
     822             : #           ifdef _MSC_VER
     823             :             // Workaround https://developercommunity.visualstudio.com/content/problem/520472/hexfloat-stream-output-does-not-ignore-precision-a.html
     824             :             // by always setting maximum precision on MSVC to avoid precision
     825             :             // loss for doubles.
     826             :             out.precision(13);
     827             : #           endif
     828           0 :             out.setf(std::ios::fixed | std::ios::scientific, std::ios::floatfield);
     829           0 :             break;
     830             :         case 'G':
     831           0 :             out.setf(std::ios::uppercase);
     832             :             // Falls through
     833             :         case 'g':
     834      766527 :             out.setf(std::ios::dec, std::ios::basefield);
     835             :             // As in boost::format, let stream decide float format.
     836      766527 :             out.flags(out.flags() & ~std::ios::floatfield);
     837      766527 :             break;
     838             :         case 'c':
     839             :             // Handled as special case inside formatValue()
     840             :             break;
     841             :         case 's':
     842     4179191 :             if (precisionSet)
     843           0 :                 ntrunc = static_cast<int>(out.precision());
     844             :             // Make %s print Booleans as "true" and "false"
     845     4179185 :             out.setf(std::ios::boolalpha);
     846     4179185 :             break;
     847             :         case 'n':
     848             :             // Not supported - will cause problems!
     849           0 :             TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported");
     850             :             break;
     851             :         case '\0':
     852           0 :             TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly "
     853             :                              "terminated by end of string");
     854             :             return c;
     855             :         default:
     856             :             break;
     857             :     }
     858    29187303 :     if (intConversion && precisionSet && !widthSet) {
     859             :         // "precision" for integers gives the minimum number of digits (to be
     860             :         // padded with zeros on the left).  This isn't really supported by the
     861             :         // iostreams, but we can approximately simulate it with the width if
     862             :         // the width isn't otherwise used.
     863           0 :         out.width(out.precision() + widthExtra);
     864           0 :         out.setf(std::ios::internal, std::ios::adjustfield);
     865           0 :         out.fill('0');
     866           0 :     }
     867    58374430 :     return c+1;
     868    29187215 : }
     869             : 
     870             : 
     871             : //------------------------------------------------------------------------------
     872     8701161 : inline void formatImpl(std::ostream& out, const char* fmt,
     873             :                        const detail::FormatArg* args,
     874             :                        int numArgs)
     875             : {
     876             :     // Saved stream state
     877     8701161 :     std::streamsize origWidth = out.width();
     878     8701161 :     std::streamsize origPrecision = out.precision();
     879     8701161 :     std::ios::fmtflags origFlags = out.flags();
     880     8701161 :     char origFill = out.fill();
     881             : 
     882             :     // "Positional mode" means all format specs should be of the form "%n$..."
     883             :     // with `n` an integer. We detect this in `streamStateFromFormat`.
     884     8701161 :     bool positionalMode = false;
     885     8701161 :     int argIndex = 0;
     886    37888289 :     while (true) {
     887    37888364 :         fmt = printFormatStringLiteral(out, fmt);
     888    37888364 :         if (*fmt == '\0') {
     889     8701223 :             if (!positionalMode && argIndex < numArgs) {
     890           0 :                 TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string");
     891             :             }
     892             :             break;
     893             :         }
     894    29187161 :         bool spacePadPositive = false;
     895    29187161 :         int ntrunc = -1;
     896    29187161 :         const char* fmtEnd = streamStateFromFormat(out, positionalMode, spacePadPositive, ntrunc, fmt,
     897             :                                                    args, argIndex, numArgs);
     898             :         // NB: argIndex may be incremented by reading variable width/precision
     899             :         // in `streamStateFromFormat`, so do the bounds check here.
     900    29187161 :         if (argIndex >= numArgs) {
     901           0 :             TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string");
     902             :             return;
     903             :         }
     904    29187035 :         const FormatArg& arg = args[argIndex];
     905             :         // Format the arg into the stream.
     906    29187035 :         if (!spacePadPositive) {
     907    29186979 :             arg.format(out, fmt, fmtEnd, ntrunc);
     908    29186979 :         }
     909             :         else {
     910             :             // The following is a special case with no direct correspondence
     911             :             // between stream formatting and the printf() behaviour.  Simulate
     912             :             // it crudely by formatting into a temporary string stream and
     913             :             // munging the resulting string.
     914           0 :             std::ostringstream tmpStream;
     915           0 :             tmpStream.copyfmt(out);
     916           0 :             tmpStream.setf(std::ios::showpos);
     917           0 :             arg.format(tmpStream, fmt, fmtEnd, ntrunc);
     918           0 :             std::string result = tmpStream.str(); // allocates... yuck.
     919           0 :             for (size_t i = 0, iend = result.size(); i < iend; ++i) {
     920           0 :                 if (result[i] == '+')
     921           0 :                     result[i] = ' ';
     922             :             }
     923           0 :             out << result;
     924           0 :         }
     925    29187118 :         if (!positionalMode)
     926    29187102 :             ++argIndex;
     927             :         fmt = fmtEnd;
     928    29187128 :     }
     929             : 
     930             :     // Restore stream state
     931     8701223 :     out.width(origWidth);
     932     8701223 :     out.precision(origPrecision);
     933     8701223 :     out.flags(origFlags);
     934     8701223 :     out.fill(origFill);
     935     8701223 : }
     936             : 
     937             : } // namespace detail
     938             : 
     939             : 
     940             : /// List of template arguments format(), held in a type-opaque way.
     941             : ///
     942             : /// A const reference to FormatList (typedef'd as FormatListRef) may be
     943             : /// conveniently used to pass arguments to non-template functions: All type
     944             : /// information has been stripped from the arguments, leaving just enough of a
     945             : /// common interface to perform formatting as required.
     946             : class FormatList
     947             : {
     948             :     public:
     949     8701186 :         FormatList(detail::FormatArg* args, int N)
     950     8701186 :             : m_args(args), m_N(N) { }
     951             : 
     952             :         friend void vformat(std::ostream& out, const char* fmt,
     953             :                             const FormatList& list);
     954             : 
     955             :     private:
     956             :         const detail::FormatArg* m_args;
     957             :         int m_N;
     958             : };
     959             : 
     960             : /// Reference to type-opaque format list for passing to vformat()
     961             : typedef const FormatList& FormatListRef;
     962             : 
     963             : 
     964             : namespace detail {
     965             : 
     966             : // Format list subclass with fixed storage to avoid dynamic allocation
     967             : template<int N>
     968             : class FormatListN : public FormatList
     969             : {
     970             :     public:
     971             : #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
     972             :         template<typename... Args>
     973    17364152 :         FormatListN(const Args&... args)
     974     8682076 :             : FormatList(&m_formatterStore[0], N),
     975     8682076 :             m_formatterStore { FormatArg(args)... }
     976    17364152 :         { static_assert(sizeof...(args) == N, "Number of args must be N"); }
     977             : #else // C++98 version
     978             :         void init(int) {}
     979             : #       define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n)                \
     980             :                                                                         \
     981             :         template<TINYFORMAT_ARGTYPES(n)>                                \
     982             :         FormatListN(TINYFORMAT_VARARGS(n))                              \
     983             :             : FormatList(&m_formatterStore[0], n)                       \
     984             :         { TINYFORMAT_ASSERT(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \
     985             :                                                                         \
     986             :         template<TINYFORMAT_ARGTYPES(n)>                                \
     987             :         void init(int i, TINYFORMAT_VARARGS(n))                         \
     988             :         {                                                               \
     989             :             m_formatterStore[i] = FormatArg(v1);                        \
     990             :             init(i+1 TINYFORMAT_PASSARGS_TAIL(n));                      \
     991             :         }
     992             : 
     993             :         TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR)
     994             : #       undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR
     995             : #endif
     996             :         FormatListN(const FormatListN& other)
     997             :             : FormatList(&m_formatterStore[0], N)
     998             :         { std::copy(&other.m_formatterStore[0], &other.m_formatterStore[N],
     999             :                     &m_formatterStore[0]); }
    1000             : 
    1001             :     private:
    1002             :         FormatArg m_formatterStore[N];
    1003             : };
    1004             : 
    1005             : // Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard
    1006             : template<> class FormatListN<0> : public FormatList
    1007             : {
    1008       38362 :     public: FormatListN() : FormatList(0, 0) {}
    1009             : };
    1010             : 
    1011             : } // namespace detail
    1012             : 
    1013             : 
    1014             : //------------------------------------------------------------------------------
    1015             : // Primary API functions
    1016             : 
    1017             : #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
    1018             : 
    1019             : /// Make type-agnostic format list from list of template arguments.
    1020             : ///
    1021             : /// The exact return type of this function is an implementation detail and
    1022             : /// shouldn't be relied upon.  Instead it should be stored as a FormatListRef:
    1023             : ///
    1024             : ///   FormatListRef formatList = makeFormatList( /*...*/ );
    1025             : template<typename... Args>
    1026     8701254 : detail::FormatListN<sizeof...(Args)> makeFormatList(const Args&... args)
    1027             : {
    1028     8701254 :     return detail::FormatListN<sizeof...(args)>(args...);
    1029             : }
    1030             : 
    1031             : #else // C++98 version
    1032             : 
    1033             : inline detail::FormatListN<0> makeFormatList()
    1034             : {
    1035             :     return detail::FormatListN<0>();
    1036             : }
    1037             : #define TINYFORMAT_MAKE_MAKEFORMATLIST(n)                     \
    1038             : template<TINYFORMAT_ARGTYPES(n)>                              \
    1039             : detail::FormatListN<n> makeFormatList(TINYFORMAT_VARARGS(n))  \
    1040             : {                                                             \
    1041             :     return detail::FormatListN<n>(TINYFORMAT_PASSARGS(n));    \
    1042             : }
    1043             : TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST)
    1044             : #undef TINYFORMAT_MAKE_MAKEFORMATLIST
    1045             : 
    1046             : #endif
    1047             : 
    1048             : /// Format list of arguments to the stream according to the given format string.
    1049             : ///
    1050             : /// The name vformat() is chosen for the semantic similarity to vprintf(): the
    1051             : /// list of format arguments is held in a single function argument.
    1052     8701171 : inline void vformat(std::ostream& out, const char* fmt, FormatListRef list)
    1053             : {
    1054     8701171 :     detail::formatImpl(out, fmt, list.m_args, list.m_N);
    1055     8701171 : }
    1056             : 
    1057             : 
    1058             : #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
    1059             : 
    1060             : /// Format list of arguments to the stream according to given format string.
    1061             : template<typename... Args>
    1062     8701252 : void format(std::ostream& out, const char* fmt, const Args&... args)
    1063             : {
    1064     8701252 :     vformat(out, fmt, makeFormatList(args...));
    1065     8701252 : }
    1066             : 
    1067             : /// Format list of arguments according to the given format string and return
    1068             : /// the result as a string.
    1069             : template<typename... Args>
    1070     8695893 : std::string format(const char* fmt, const Args&... args)
    1071             : {
    1072     8695893 :     std::ostringstream oss;
    1073     8695893 :     format(oss, fmt, args...);
    1074     8695878 :     return oss.str();
    1075     8695896 : }
    1076             : 
    1077             : /// Format list of arguments to std::cout, according to the given format string
    1078             : template<typename... Args>
    1079             : void printf(const char* fmt, const Args&... args)
    1080             : {
    1081             :     format(std::cout, fmt, args...);
    1082             : }
    1083             : 
    1084             : template<typename... Args>
    1085             : void printfln(const char* fmt, const Args&... args)
    1086             : {
    1087             :     format(std::cout, fmt, args...);
    1088             :     std::cout << '\n';
    1089             : }
    1090             : 
    1091             : 
    1092             : #else // C++98 version
    1093             : 
    1094             : inline void format(std::ostream& out, const char* fmt)
    1095             : {
    1096             :     vformat(out, fmt, makeFormatList());
    1097             : }
    1098             : 
    1099             : inline std::string format(const char* fmt)
    1100             : {
    1101             :     std::ostringstream oss;
    1102             :     format(oss, fmt);
    1103             :     return oss.str();
    1104             : }
    1105             : 
    1106             : inline void printf(const char* fmt)
    1107             : {
    1108             :     format(std::cout, fmt);
    1109             : }
    1110             : 
    1111             : inline void printfln(const char* fmt)
    1112             : {
    1113             :     format(std::cout, fmt);
    1114             :     std::cout << '\n';
    1115             : }
    1116             : 
    1117             : #define TINYFORMAT_MAKE_FORMAT_FUNCS(n)                                   \
    1118             :                                                                           \
    1119             : template<TINYFORMAT_ARGTYPES(n)>                                          \
    1120             : void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n))    \
    1121             : {                                                                         \
    1122             :     vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n)));            \
    1123             : }                                                                         \
    1124             :                                                                           \
    1125             : template<TINYFORMAT_ARGTYPES(n)>                                          \
    1126             : std::string format(const char* fmt, TINYFORMAT_VARARGS(n))                \
    1127             : {                                                                         \
    1128             :     std::ostringstream oss;                                               \
    1129             :     format(oss, fmt, TINYFORMAT_PASSARGS(n));                             \
    1130             :     return oss.str();                                                     \
    1131             : }                                                                         \
    1132             :                                                                           \
    1133             : template<TINYFORMAT_ARGTYPES(n)>                                          \
    1134             : void printf(const char* fmt, TINYFORMAT_VARARGS(n))                       \
    1135             : {                                                                         \
    1136             :     format(std::cout, fmt, TINYFORMAT_PASSARGS(n));                       \
    1137             : }                                                                         \
    1138             :                                                                           \
    1139             : template<TINYFORMAT_ARGTYPES(n)>                                          \
    1140             : void printfln(const char* fmt, TINYFORMAT_VARARGS(n))                     \
    1141             : {                                                                         \
    1142             :     format(std::cout, fmt, TINYFORMAT_PASSARGS(n));                       \
    1143             :     std::cout << '\n';                                                    \
    1144             : }
    1145             : 
    1146             : TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS)
    1147             : #undef TINYFORMAT_MAKE_FORMAT_FUNCS
    1148             : 
    1149             : #endif
    1150             : 
    1151             : // Added for Bitcoin Core
    1152             : template<typename... Args>
    1153        4285 : std::string format(const std::string &fmt, const Args&... args)
    1154             : {
    1155        4285 :     std::ostringstream oss;
    1156        4285 :     format(oss, fmt.c_str(), args...);
    1157        4285 :     return oss.str();
    1158        4285 : }
    1159             : 
    1160             : } // namespace tinyformat
    1161             : 
    1162             : // Added for Bitcoin Core:
    1163             : /** Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for details) */
    1164             : #define strprintf tfm::format
    1165             : 
    1166             : #endif // TINYFORMAT_H_INCLUDED

Generated by: LCOV version 1.15