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