]> Git Repo - VerusCoin.git/blob - src/tinyformat.h
Merge commit '77404203ee87992f34ff57c2e8a6f0c85717318f' into 2333-validation-speed
[VerusCoin.git] / src / tinyformat.h
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 // * Simplicity and minimalism.  A single header file to include and distribute
37 //   with your projects.
38 // * Augment rather than replace the standard stream formatting mechanism
39 // * C++98 support, with optional C++11 niceties
40 //
41 //
42 // Main interface example usage
43 // ----------------------------
44 //
45 // To print a date to std::cout:
46 //
47 //   std::string weekday = "Wednesday";
48 //   const char* month = "July";
49 //   size_t day = 27;
50 //   long hour = 14;
51 //   int min = 44;
52 //
53 //   tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);
54 //
55 // The strange types here emphasize the type safety of the interface; it is
56 // possible to print a std::string using the "%s" conversion, and a
57 // size_t using the "%d" conversion.  A similar result could be achieved
58 // using either of the tfm::format() functions.  One prints on a user provided
59 // stream:
60 //
61 //   tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",
62 //               weekday, month, day, hour, min);
63 //
64 // The other returns a std::string:
65 //
66 //   std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",
67 //                                  weekday, month, day, hour, min);
68 //   std::cout << date;
69 //
70 // These are the three primary interface functions.  There is also a
71 // convenience function printfln() which appends a newline to the usual result
72 // of printf() for super simple logging.
73 //
74 //
75 // User defined format functions
76 // -----------------------------
77 //
78 // Simulating variadic templates in C++98 is pretty painful since it requires
79 // writing out the same function for each desired number of arguments.  To make
80 // this bearable tinyformat comes with a set of macros which are used
81 // internally to generate the API, but which may also be used in user code.
82 //
83 // The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and
84 // TINYFORMAT_PASSARGS(n) will generate a list of n argument types,
85 // type/name pairs and argument names respectively when called with an integer
86 // n between 1 and 16.  We can use these to define a macro which generates the
87 // desired user defined function with n arguments.  To generate all 16 user
88 // defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM.  For an
89 // example, see the implementation of printf() at the end of the source file.
90 //
91 // Sometimes it's useful to be able to pass a list of format arguments through
92 // to a non-template function.  The FormatList class is provided as a way to do
93 // this by storing the argument list in a type-opaque way.  Continuing the
94 // example from above, we construct a FormatList using makeFormatList():
95 //
96 //   FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min);
97 //
98 // The format list can now be passed into any non-template function and used
99 // via a call to the vformat() function:
100 //
101 //   tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList);
102 //
103 //
104 // Additional API information
105 // --------------------------
106 //
107 // Error handling: Define TINYFORMAT_ERROR to customize the error handling for
108 // format strings which are unsupported or have the wrong number of format
109 // specifiers (calls assert() by default).
110 //
111 // User defined types: Uses operator<< for user defined types by default.
112 // Overload formatValue() for more control.
113
114
115 #ifndef TINYFORMAT_H_INCLUDED
116 #define TINYFORMAT_H_INCLUDED
117
118 namespace tinyformat {}
119 //------------------------------------------------------------------------------
120 // Config section.  Customize to your liking!
121
122 // Namespace alias to encourage brevity
123 namespace tfm = tinyformat;
124
125 // Error handling; calls assert() by default.
126 #define TINYFORMAT_ERROR(reasonString) throw std::runtime_error(reasonString)
127
128 // Define for C++11 variadic templates which make the code shorter & more
129 // general.  If you don't define this, C++11 support is autodetected below.
130 // #define TINYFORMAT_USE_VARIADIC_TEMPLATES
131
132
133 //------------------------------------------------------------------------------
134 // Implementation details.
135 #include <algorithm>
136 #include <cassert>
137 #include <iostream>
138 #include <sstream>
139 #include <stdexcept>
140
141 #ifndef TINYFORMAT_ERROR
142 #   define TINYFORMAT_ERROR(reason) assert(0 && reason)
143 #endif
144
145 #if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)
146 #   ifdef __GXX_EXPERIMENTAL_CXX0X__
147 #       define TINYFORMAT_USE_VARIADIC_TEMPLATES
148 #   endif
149 #endif
150
151 #if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201
152 //  std::showpos is broken on old libstdc++ as provided with OSX.  See
153 //  http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html
154 #   define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
155 #endif
156
157 #ifdef __APPLE__
158 // Workaround OSX linker warning: xcode uses different default symbol
159 // visibilities for static libs vs executables (see issue #25)
160 #   define TINYFORMAT_HIDDEN __attribute__((visibility("hidden")))
161 #else
162 #   define TINYFORMAT_HIDDEN
163 #endif
164
165 namespace tinyformat {
166
167 //------------------------------------------------------------------------------
168 namespace detail {
169
170 // Test whether type T1 is convertible to type T2
171 template <typename T1, typename T2>
172 struct is_convertible
173 {
174     private:
175         // two types of different size
176         struct fail { char dummy[2]; };
177         struct succeed { char dummy; };
178         // Try to convert a T1 to a T2 by plugging into tryConvert
179         static fail tryConvert(...);
180         static succeed tryConvert(const T2&);
181         static const T1& makeT1();
182     public:
183 #       ifdef _MSC_VER
184         // Disable spurious loss of precision warnings in tryConvert(makeT1())
185 #       pragma warning(push)
186 #       pragma warning(disable:4244)
187 #       pragma warning(disable:4267)
188 #       endif
189         // Standard trick: the (...) version of tryConvert will be chosen from
190         // the overload set only if the version taking a T2 doesn't match.
191         // Then we compare the sizes of the return types to check which
192         // function matched.  Very neat, in a disgusting kind of way :)
193         static const bool value =
194             sizeof(tryConvert(makeT1())) == sizeof(succeed);
195 #       ifdef _MSC_VER
196 #       pragma warning(pop)
197 #       endif
198 };
199
200
201 // Detect when a type is not a wchar_t string
202 template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };
203 template<> struct is_wchar<wchar_t*> {};
204 template<> struct is_wchar<const wchar_t*> {};
205 template<int n> struct is_wchar<const wchar_t[n]> {};
206 template<int n> struct is_wchar<wchar_t[n]> {};
207
208
209 // Format the value by casting to type fmtT.  This default implementation
210 // should never be called.
211 template<typename T, typename fmtT, bool convertible = is_convertible<T, fmtT>::value>
212 struct formatValueAsType
213 {
214     static void invoke(std::ostream& /*out*/, const T& /*value*/) { assert(0); }
215 };
216 // Specialized version for types that can actually be converted to fmtT, as
217 // indicated by the "convertible" template parameter.
218 template<typename T, typename fmtT>
219 struct formatValueAsType<T,fmtT,true>
220 {
221     static void invoke(std::ostream& out, const T& value)
222         { out << static_cast<fmtT>(value); }
223 };
224
225 #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
226 template<typename T, bool convertible = is_convertible<T, int>::value>
227 struct formatZeroIntegerWorkaround
228 {
229     static bool invoke(std::ostream& /**/, const T& /**/) { return false; }
230 };
231 template<typename T>
232 struct formatZeroIntegerWorkaround<T,true>
233 {
234     static bool invoke(std::ostream& out, const T& value)
235     {
236         if (static_cast<int>(value) == 0 && out.flags() & std::ios::showpos)
237         {
238             out << "+0";
239             return true;
240         }
241         return false;
242     }
243 };
244 #endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
245
246 // Convert an arbitrary type to integer.  The version with convertible=false
247 // throws an error.
248 template<typename T, bool convertible = is_convertible<T,int>::value>
249 struct convertToInt
250 {
251     static int invoke(const T& /*value*/)
252     {
253         TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to "
254                          "integer for use as variable width or precision");
255         return 0;
256     }
257 };
258 // Specialization for convertToInt when conversion is possible
259 template<typename T>
260 struct convertToInt<T,true>
261 {
262     static int invoke(const T& value) { return static_cast<int>(value); }
263 };
264
265 // Format at most ntrunc characters to the given stream.
266 template<typename T>
267 inline void formatTruncated(std::ostream& out, const T& value, int ntrunc)
268 {
269     std::ostringstream tmp;
270     tmp << value;
271     std::string result = tmp.str();
272     out.write(result.c_str(), (std::min)(ntrunc, static_cast<int>(result.size())));
273 }
274 #define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type)       \
275 inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \
276 {                                                           \
277     std::streamsize len = 0;                                \
278     while(len < ntrunc && value[len] != 0)                  \
279         ++len;                                              \
280     out.write(value, len);                                  \
281 }
282 // Overload for const char* and char*.  Could overload for signed & unsigned
283 // char too, but these are technically unneeded for printf compatibility.
284 TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char)
285 TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char)
286 #undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR
287
288 } // namespace detail
289
290
291 //------------------------------------------------------------------------------
292 // Variable formatting functions.  May be overridden for user-defined types if
293 // desired.
294
295
296 /// Format a value into a stream, delegating to operator<< by default.
297 ///
298 /// Users may override this for their own types.  When this function is called,
299 /// the stream flags will have been modified according to the format string.
300 /// The format specification is provided in the range [fmtBegin, fmtEnd).  For
301 /// truncating conversions, ntrunc is set to the desired maximum number of
302 /// characters, for example "%.7s" calls formatValue with ntrunc = 7.
303 ///
304 /// By default, formatValue() uses the usual stream insertion operator
305 /// operator<< to format the type T, with special cases for the %c and %p
306 /// conversions.
307 template<typename T>
308 inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,
309                         const char* fmtEnd, int ntrunc, const T& value)
310 {
311 #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS
312     // Since we don't support printing of wchar_t using "%ls", make it fail at
313     // compile time in preference to printing as a void* at runtime.
314     typedef typename detail::is_wchar<T>::tinyformat_wchar_is_not_supported DummyType;
315     (void) DummyType(); // avoid unused type warning with gcc-4.8
316 #endif
317     // The mess here is to support the %c and %p conversions: if these
318     // conversions are active we try to convert the type to a char or const
319     // void* respectively and format that instead of the value itself.  For the
320     // %p conversion it's important to avoid dereferencing the pointer, which
321     // could otherwise lead to a crash when printing a dangling (const char*).
322     const bool canConvertToChar = detail::is_convertible<T,char>::value;
323     const bool canConvertToVoidPtr = detail::is_convertible<T, const void*>::value;
324     if(canConvertToChar && *(fmtEnd-1) == 'c')
325         detail::formatValueAsType<T, char>::invoke(out, value);
326     else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p')
327         detail::formatValueAsType<T, const void*>::invoke(out, value);
328 #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
329     else if(detail::formatZeroIntegerWorkaround<T>::invoke(out, value)) /**/;
330 #endif
331     else if(ntrunc >= 0)
332     {
333         // Take care not to overread C strings in truncating conversions like
334         // "%.4s" where at most 4 characters may be read.
335         detail::formatTruncated(out, value, ntrunc);
336     }
337     else
338         out << value;
339 }
340
341
342 // Overloaded version for char types to support printing as an integer
343 #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType)                  \
344 inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,  \
345                         const char* fmtEnd, int /**/, charType value) \
346 {                                                                     \
347     switch(*(fmtEnd-1))                                               \
348     {                                                                 \
349         case 'u': case 'd': case 'i': case 'o': case 'X': case 'x':   \
350             out << static_cast<int>(value); break;                    \
351         default:                                                      \
352             out << value;                   break;                    \
353     }                                                                 \
354 }
355 // per 3.9.1: char, signed char and unsigned char are all distinct types
356 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char)
357 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char)
358 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char)
359 #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR
360
361
362 //------------------------------------------------------------------------------
363 // Tools for emulating variadic templates in C++98.  The basic idea here is
364 // stolen from the boost preprocessor metaprogramming library and cut down to
365 // be just general enough for what we need.
366
367 #define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n
368 #define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n
369 #define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n
370 #define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n
371
372 // To keep it as transparent as possible, the macros below have been generated
373 // using python via the excellent cog.py code generation script.  This avoids
374 // the need for a bunch of complex (but more general) preprocessor tricks as
375 // used in boost.preprocessor.
376 //
377 // To rerun the code generation in place, use `cog.py -r tinyformat.h`
378 // (see http://nedbatchelder.com/code/cog).  Alternatively you can just create
379 // extra versions by hand.
380
381 /*[[[cog
382 maxParams = 16
383
384 def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1):
385     for j in range(startInd,maxParams+1):
386         list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)])
387         cog.outl(lineTemplate % {'j':j, 'list':list})
388
389 makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s',
390                   'class T%(i)d')
391
392 cog.outl()
393 makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s',
394                   'const T%(i)d& v%(i)d')
395
396 cog.outl()
397 makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d')
398
399 cog.outl()
400 cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1')
401 makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s',
402                   'v%(i)d', startInd = 2)
403
404 cog.outl()
405 cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n    ' +
406          ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)]))
407 ]]]*/
408 #define TINYFORMAT_ARGTYPES_1 class T1
409 #define TINYFORMAT_ARGTYPES_2 class T1, class T2
410 #define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3
411 #define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4
412 #define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5
413 #define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6
414 #define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7
415 #define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8
416 #define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9
417 #define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10
418 #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
419 #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
420 #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
421 #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
422 #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
423 #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
424
425 #define TINYFORMAT_VARARGS_1 const T1& v1
426 #define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2
427 #define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3
428 #define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4
429 #define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5
430 #define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6
431 #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
432 #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
433 #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
434 #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
435 #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
436 #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
437 #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
438 #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
439 #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
440 #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
441
442 #define TINYFORMAT_PASSARGS_1 v1
443 #define TINYFORMAT_PASSARGS_2 v1, v2
444 #define TINYFORMAT_PASSARGS_3 v1, v2, v3
445 #define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4
446 #define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5
447 #define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6
448 #define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7
449 #define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8
450 #define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9
451 #define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10
452 #define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
453 #define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
454 #define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
455 #define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
456 #define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
457 #define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
458
459 #define TINYFORMAT_PASSARGS_TAIL_1
460 #define TINYFORMAT_PASSARGS_TAIL_2 , v2
461 #define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3
462 #define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4
463 #define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5
464 #define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6
465 #define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7
466 #define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8
467 #define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9
468 #define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10
469 #define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
470 #define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
471 #define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
472 #define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
473 #define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
474 #define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
475
476 #define TINYFORMAT_FOREACH_ARGNUM(m) \
477     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)
478 //[[[end]]]
479
480
481
482 namespace detail {
483
484 // Type-opaque holder for an argument to format(), with associated actions on
485 // the type held as explicit function pointers.  This allows FormatArg's for
486 // each argument to be allocated as a homogenous array inside FormatList
487 // whereas a naive implementation based on inheritance does not.
488 class FormatArg
489 {
490     public:
491         FormatArg() {}
492
493         template<typename T>
494         FormatArg(const T& value)
495             : m_value(static_cast<const void*>(&value)),
496             m_formatImpl(&formatImpl<T>),
497             m_toIntImpl(&toIntImpl<T>)
498         { }
499
500         void format(std::ostream& out, const char* fmtBegin,
501                     const char* fmtEnd, int ntrunc) const
502         {
503             m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value);
504         }
505
506         int toInt() const
507         {
508             return m_toIntImpl(m_value);
509         }
510
511     private:
512         template<typename T>
513         TINYFORMAT_HIDDEN static void formatImpl(std::ostream& out, const char* fmtBegin,
514                         const char* fmtEnd, int ntrunc, const void* value)
515         {
516             formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast<const T*>(value));
517         }
518
519         template<typename T>
520         TINYFORMAT_HIDDEN static int toIntImpl(const void* value)
521         {
522             return convertToInt<T>::invoke(*static_cast<const T*>(value));
523         }
524
525         const void* m_value;
526         void (*m_formatImpl)(std::ostream& out, const char* fmtBegin,
527                              const char* fmtEnd, int ntrunc, const void* value);
528         int (*m_toIntImpl)(const void* value);
529 };
530
531
532 // Parse and return an integer from the string c, as atoi()
533 // On return, c is set to one past the end of the integer.
534 inline int parseIntAndAdvance(const char*& c)
535 {
536     int i = 0;
537     for(;*c >= '0' && *c <= '9'; ++c)
538         i = 10*i + (*c - '0');
539     return i;
540 }
541
542 // Print literal part of format string and return next format spec
543 // position.
544 //
545 // Skips over any occurrences of '%%', printing a literal '%' to the
546 // output.  The position of the first % character of the next
547 // nontrivial format spec is returned, or the end of string.
548 inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt)
549 {
550     const char* c = fmt;
551     for(;; ++c)
552     {
553         switch(*c)
554         {
555             case '\0':
556                 out.write(fmt, c - fmt);
557                 return c;
558             case '%':
559                 out.write(fmt, c - fmt);
560                 if(*(c+1) != '%')
561                     return c;
562                 // for "%%", tack trailing % onto next literal section.
563                 fmt = ++c;
564                 break;
565             default:
566                 break;
567         }
568     }
569 }
570
571
572 // Parse a format string and set the stream state accordingly.
573 //
574 // The format mini-language recognized here is meant to be the one from C99,
575 // with the form "%[flags][width][.precision][length]type".
576 //
577 // Formatting options which can't be natively represented using the ostream
578 // state are returned in spacePadPositive (for space padded positive numbers)
579 // and ntrunc (for truncating conversions).  argIndex is incremented if
580 // necessary to pull out variable width and precision .  The function returns a
581 // pointer to the character after the end of the current format spec.
582 inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive,
583                                          int& ntrunc, const char* fmtStart,
584                                          const detail::FormatArg* formatters,
585                                          int& argIndex, int numFormatters)
586 {
587     if(*fmtStart != '%')
588     {
589         TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string");
590         return fmtStart;
591     }
592     // Reset stream state to defaults.
593     out.width(0);
594     out.precision(6);
595     out.fill(' ');
596     // Reset most flags; ignore irrelevant unitbuf & skipws.
597     out.unsetf(std::ios::adjustfield | std::ios::basefield |
598                std::ios::floatfield | std::ios::showbase | std::ios::boolalpha |
599                std::ios::showpoint | std::ios::showpos | std::ios::uppercase);
600     bool precisionSet = false;
601     bool widthSet = false;
602     int widthExtra = 0;
603     const char* c = fmtStart + 1;
604     // 1) Parse flags
605     for(;; ++c)
606     {
607         switch(*c)
608         {
609             case '#':
610                 out.setf(std::ios::showpoint | std::ios::showbase);
611                 continue;
612             case '0':
613                 // overridden by left alignment ('-' flag)
614                 if(!(out.flags() & std::ios::left))
615                 {
616                     // Use internal padding so that numeric values are
617                     // formatted correctly, eg -00010 rather than 000-10
618                     out.fill('0');
619                     out.setf(std::ios::internal, std::ios::adjustfield);
620                 }
621                 continue;
622             case '-':
623                 out.fill(' ');
624                 out.setf(std::ios::left, std::ios::adjustfield);
625                 continue;
626             case ' ':
627                 // overridden by show positive sign, '+' flag.
628                 if(!(out.flags() & std::ios::showpos))
629                     spacePadPositive = true;
630                 continue;
631             case '+':
632                 out.setf(std::ios::showpos);
633                 spacePadPositive = false;
634                 widthExtra = 1;
635                 continue;
636             default:
637                 break;
638         }
639         break;
640     }
641     // 2) Parse width
642     if(*c >= '0' && *c <= '9')
643     {
644         widthSet = true;
645         out.width(parseIntAndAdvance(c));
646     }
647     if(*c == '*')
648     {
649         widthSet = true;
650         int width = 0;
651         if(argIndex < numFormatters)
652             width = formatters[argIndex++].toInt();
653         else
654             TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width");
655         if(width < 0)
656         {
657             // negative widths correspond to '-' flag set
658             out.fill(' ');
659             out.setf(std::ios::left, std::ios::adjustfield);
660             width = -width;
661         }
662         out.width(width);
663         ++c;
664     }
665     // 3) Parse precision
666     if(*c == '.')
667     {
668         ++c;
669         int precision = 0;
670         if(*c == '*')
671         {
672             ++c;
673             if(argIndex < numFormatters)
674                 precision = formatters[argIndex++].toInt();
675             else
676                 TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable precision");
677         }
678         else
679         {
680             if(*c >= '0' && *c <= '9')
681                 precision = parseIntAndAdvance(c);
682             else if(*c == '-') // negative precisions ignored, treated as zero.
683                 parseIntAndAdvance(++c);
684         }
685         out.precision(precision);
686         precisionSet = true;
687     }
688     // 4) Ignore any C99 length modifier
689     while(*c == 'l' || *c == 'h' || *c == 'L' ||
690           *c == 'j' || *c == 'z' || *c == 't')
691         ++c;
692     // 5) We're up to the conversion specifier character.
693     // Set stream flags based on conversion specifier (thanks to the
694     // boost::format class for forging the way here).
695     bool intConversion = false;
696     switch(*c)
697     {
698         case 'u': case 'd': case 'i':
699             out.setf(std::ios::dec, std::ios::basefield);
700             intConversion = true;
701             break;
702         case 'o':
703             out.setf(std::ios::oct, std::ios::basefield);
704             intConversion = true;
705             break;
706         case 'X':
707             out.setf(std::ios::uppercase);
708         case 'x': case 'p':
709             out.setf(std::ios::hex, std::ios::basefield);
710             intConversion = true;
711             break;
712         case 'E':
713             out.setf(std::ios::uppercase);
714         case 'e':
715             out.setf(std::ios::scientific, std::ios::floatfield);
716             out.setf(std::ios::dec, std::ios::basefield);
717             break;
718         case 'F':
719             out.setf(std::ios::uppercase);
720         case 'f':
721             out.setf(std::ios::fixed, std::ios::floatfield);
722             break;
723         case 'G':
724             out.setf(std::ios::uppercase);
725         case 'g':
726             out.setf(std::ios::dec, std::ios::basefield);
727             // As in boost::format, let stream decide float format.
728             out.flags(out.flags() & ~std::ios::floatfield);
729             break;
730         case 'a': case 'A':
731             TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs "
732                              "are not supported");
733             break;
734         case 'c':
735             // Handled as special case inside formatValue()
736             break;
737         case 's':
738             if(precisionSet)
739                 ntrunc = static_cast<int>(out.precision());
740             // Make %s print booleans as "true" and "false"
741             out.setf(std::ios::boolalpha);
742             break;
743         case 'n':
744             // Not supported - will cause problems!
745             TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported");
746             break;
747         case '\0':
748             TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly "
749                              "terminated by end of string");
750             return c;
751         default:
752             break;
753     }
754     if(intConversion && precisionSet && !widthSet)
755     {
756         // "precision" for integers gives the minimum number of digits (to be
757         // padded with zeros on the left).  This isn't really supported by the
758         // iostreams, but we can approximately simulate it with the width if
759         // the width isn't otherwise used.
760         out.width(out.precision() + widthExtra);
761         out.setf(std::ios::internal, std::ios::adjustfield);
762         out.fill('0');
763     }
764     return c+1;
765 }
766
767
768 //------------------------------------------------------------------------------
769 inline void formatImpl(std::ostream& out, const char* fmt,
770                        const detail::FormatArg* formatters,
771                        int numFormatters)
772 {
773     // Saved stream state
774     std::streamsize origWidth = out.width();
775     std::streamsize origPrecision = out.precision();
776     std::ios::fmtflags origFlags = out.flags();
777     char origFill = out.fill();
778
779     for (int argIndex = 0; argIndex < numFormatters; ++argIndex)
780     {
781         // Parse the format string
782         fmt = printFormatStringLiteral(out, fmt);
783         bool spacePadPositive = false;
784         int ntrunc = -1;
785         const char* fmtEnd = streamStateFromFormat(out, spacePadPositive, ntrunc, fmt,
786                                                    formatters, argIndex, numFormatters);
787         if (argIndex >= numFormatters)
788         {
789             // Check args remain after reading any variable width/precision
790             TINYFORMAT_ERROR("tinyformat: Not enough format arguments");
791             return;
792         }
793         const FormatArg& arg = formatters[argIndex];
794         // Format the arg into the stream.
795         if(!spacePadPositive)
796             arg.format(out, fmt, fmtEnd, ntrunc);
797         else
798         {
799             // The following is a special case with no direct correspondence
800             // between stream formatting and the printf() behaviour.  Simulate
801             // it crudely by formatting into a temporary string stream and
802             // munging the resulting string.
803             std::ostringstream tmpStream;
804             tmpStream.copyfmt(out);
805             tmpStream.setf(std::ios::showpos);
806             arg.format(tmpStream, fmt, fmtEnd, ntrunc);
807             std::string result = tmpStream.str(); // allocates... yuck.
808             for(size_t i = 0, iend = result.size(); i < iend; ++i)
809                 if(result[i] == '+') result[i] = ' ';
810             out << result;
811         }
812         fmt = fmtEnd;
813     }
814
815     // Print remaining part of format string.
816     fmt = printFormatStringLiteral(out, fmt);
817     if(*fmt != '\0')
818         TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string");
819
820     // Restore stream state
821     out.width(origWidth);
822     out.precision(origPrecision);
823     out.flags(origFlags);
824     out.fill(origFill);
825 }
826
827 } // namespace detail
828
829
830 /// List of template arguments format(), held in a type-opaque way.
831 ///
832 /// A const reference to FormatList (typedef'd as FormatListRef) may be
833 /// conveniently used to pass arguments to non-template functions: All type
834 /// information has been stripped from the arguments, leaving just enough of a
835 /// common interface to perform formatting as required.
836 class FormatList
837 {
838     public:
839         FormatList(detail::FormatArg* formatters, int N)
840             : m_formatters(formatters), m_N(N) { }
841
842         friend void vformat(std::ostream& out, const char* fmt,
843                             const FormatList& list);
844
845     private:
846         const detail::FormatArg* m_formatters;
847         int m_N;
848 };
849
850 /// Reference to type-opaque format list for passing to vformat()
851 typedef const FormatList& FormatListRef;
852
853
854 namespace detail {
855
856 // Format list subclass with fixed storage to avoid dynamic allocation
857 template<int N>
858 class FormatListN : public FormatList
859 {
860     public:
861 #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
862         template<typename... Args>
863         FormatListN(const Args&... args)
864             : FormatList(&m_formatterStore[0], N),
865             m_formatterStore { FormatArg(args)... }
866         { static_assert(sizeof...(args) == N, "Number of args must be N"); }
867 #else // C++98 version
868         void init(int) {}
869 #       define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n)       \
870                                                                \
871         template<TINYFORMAT_ARGTYPES(n)>                       \
872         FormatListN(TINYFORMAT_VARARGS(n))                     \
873             : FormatList(&m_formatterStore[0], n)              \
874         { assert(n == N); init(0, TINYFORMAT_PASSARGS(n)); }   \
875                                                                \
876         template<TINYFORMAT_ARGTYPES(n)>                       \
877         void init(int i, TINYFORMAT_VARARGS(n))                \
878         {                                                      \
879             m_formatterStore[i] = FormatArg(v1);               \
880             init(i+1 TINYFORMAT_PASSARGS_TAIL(n));             \
881         }
882
883         TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR)
884 #       undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR
885 #endif
886
887     private:
888         FormatArg m_formatterStore[N];
889 };
890
891 // Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard
892 template<> class FormatListN<0> : public FormatList
893 {
894     public: FormatListN() : FormatList(0, 0) {}
895 };
896
897 } // namespace detail
898
899
900 //------------------------------------------------------------------------------
901 // Primary API functions
902
903 #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
904
905 /// Make type-agnostic format list from list of template arguments.
906 ///
907 /// The exact return type of this function is an implementation detail and
908 /// shouldn't be relied upon.  Instead it should be stored as a FormatListRef:
909 ///
910 ///   FormatListRef formatList = makeFormatList( /*...*/ );
911 template<typename... Args>
912 detail::FormatListN<sizeof...(Args)> makeFormatList(const Args&... args)
913 {
914     return detail::FormatListN<sizeof...(args)>(args...);
915 }
916
917 #else // C++98 version
918
919 inline detail::FormatListN<0> makeFormatList()
920 {
921     return detail::FormatListN<0>();
922 }
923 #define TINYFORMAT_MAKE_MAKEFORMATLIST(n)                     \
924 template<TINYFORMAT_ARGTYPES(n)>                              \
925 detail::FormatListN<n> makeFormatList(TINYFORMAT_VARARGS(n))  \
926 {                                                             \
927     return detail::FormatListN<n>(TINYFORMAT_PASSARGS(n));    \
928 }
929 TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST)
930 #undef TINYFORMAT_MAKE_MAKEFORMATLIST
931
932 #endif
933
934 /// Format list of arguments to the stream according to the given format string.
935 ///
936 /// The name vformat() is chosen for the semantic similarity to vprintf(): the
937 /// list of format arguments is held in a single function argument.
938 inline void vformat(std::ostream& out, const char* fmt, FormatListRef list)
939 {
940     detail::formatImpl(out, fmt, list.m_formatters, list.m_N);
941 }
942
943
944 #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
945
946 /// Format list of arguments to the stream according to given format string.
947 template<typename... Args>
948 void format(std::ostream& out, const char* fmt, const Args&... args)
949 {
950     vformat(out, fmt, makeFormatList(args...));
951 }
952
953 /// Format list of arguments according to the given format string and return
954 /// the result as a string.
955 template<typename... Args>
956 std::string format(const char* fmt, const Args&... args)
957 {
958     std::ostringstream oss;
959     format(oss, fmt, args...);
960     return oss.str();
961 }
962
963 /// Format list of arguments to std::cout, according to the given format string
964 template<typename... Args>
965 void printf(const char* fmt, const Args&... args)
966 {
967     format(std::cout, fmt, args...);
968 }
969
970 template<typename... Args>
971 void printfln(const char* fmt, const Args&... args)
972 {
973     format(std::cout, fmt, args...);
974     std::cout << '\n';
975 }
976
977 #else // C++98 version
978
979 inline void format(std::ostream& out, const char* fmt)
980 {
981     vformat(out, fmt, makeFormatList());
982 }
983
984 inline std::string format(const char* fmt)
985 {
986     std::ostringstream oss;
987     format(oss, fmt);
988     return oss.str();
989 }
990
991 inline void printf(const char* fmt)
992 {
993     format(std::cout, fmt);
994 }
995
996 inline void printfln(const char* fmt)
997 {
998     format(std::cout, fmt);
999     std::cout << '\n';
1000 }
1001
1002 #define TINYFORMAT_MAKE_FORMAT_FUNCS(n)                                   \
1003                                                                           \
1004 template<TINYFORMAT_ARGTYPES(n)>                                          \
1005 void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n))    \
1006 {                                                                         \
1007     vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n)));            \
1008 }                                                                         \
1009                                                                           \
1010 template<TINYFORMAT_ARGTYPES(n)>                                          \
1011 std::string format(const char* fmt, TINYFORMAT_VARARGS(n))                \
1012 {                                                                         \
1013     std::ostringstream oss;                                               \
1014     format(oss, fmt, TINYFORMAT_PASSARGS(n));                             \
1015     return oss.str();                                                     \
1016 }                                                                         \
1017                                                                           \
1018 template<TINYFORMAT_ARGTYPES(n)>                                          \
1019 void printf(const char* fmt, TINYFORMAT_VARARGS(n))                       \
1020 {                                                                         \
1021     format(std::cout, fmt, TINYFORMAT_PASSARGS(n));                       \
1022 }                                                                         \
1023                                                                           \
1024 template<TINYFORMAT_ARGTYPES(n)>                                          \
1025 void printfln(const char* fmt, TINYFORMAT_VARARGS(n))                     \
1026 {                                                                         \
1027     format(std::cout, fmt, TINYFORMAT_PASSARGS(n));                       \
1028     std::cout << '\n';                                                    \
1029 }
1030
1031 TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS)
1032 #undef TINYFORMAT_MAKE_FORMAT_FUNCS
1033
1034 #endif
1035
1036 // Added for Bitcoin Core
1037 template<typename... Args>
1038 std::string format(const std::string &fmt, const Args&... args)
1039 {
1040     std::ostringstream oss;
1041     format(oss, fmt.c_str(), args...);
1042     return oss.str();
1043 }
1044
1045 } // namespace tinyformat
1046
1047 #define strprintf tfm::format
1048
1049 #endif // TINYFORMAT_H_INCLUDED
This page took 0.082469 seconds and 4 git commands to generate.