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