Debian Codegraph @

progs/tinyformat.h

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