2 // Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com]
4 // Boost Software License - Version 1.0
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:
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.
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.
28 //------------------------------------------------------------------------------
29 // Tinyformat: A minimal type safe printf replacement
31 // tinyformat.h is a type safe printf replacement library in a single C++
32 // header file. Design goals include:
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
42 // Main interface example usage
43 // ----------------------------
45 // To print a date to std::cout:
47 // std::string weekday = "Wednesday";
48 // const char* month = "July";
53 // tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);
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
61 // tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",
62 // weekday, month, day, hour, min);
64 // The other returns a std::string:
66 // std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",
67 // weekday, month, day, hour, min);
70 // These are the three primary interface functions.
73 // User defined format functions
74 // -----------------------------
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.
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.
90 // Additional API information
91 // --------------------------
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).
97 // User defined types: Uses operator<< for user defined types by default.
98 // Overload formatValue() for more control.
101 #ifndef TINYFORMAT_H_INCLUDED
102 #define TINYFORMAT_H_INCLUDED
104 namespace tinyformat {}
105 //------------------------------------------------------------------------------
106 // Config section. Customize to your liking!
108 // Namespace alias to encourage brevity
109 namespace tfm = tinyformat;
111 // Error handling; calls assert() by default.
112 // #define TINYFORMAT_ERROR(reasonString) your_error_handler(reasonString)
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
119 //------------------------------------------------------------------------------
120 // Implementation details.
125 #ifndef TINYFORMAT_ERROR
126 # define TINYFORMAT_ERROR(reason) assert(0 && reason)
129 #if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)
130 # ifdef __GXX_EXPERIMENTAL_CXX0X__
131 # define TINYFORMAT_USE_VARIADIC_TEMPLATES
136 # define TINYFORMAT_NOINLINE __attribute__((noinline))
137 #elif defined(_MSC_VER)
138 # define TINYFORMAT_NOINLINE __declspec(noinline)
140 # define TINYFORMAT_NOINLINE
143 #if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201
144 // std::showpos is broken on old libstdc++ as provided with OSX. See
145 // http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html
146 # define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
149 namespace tinyformat {
151 //------------------------------------------------------------------------------
154 // Test whether type T1 is convertible to type T2
155 template <typename T1, typename T2>
156 struct is_convertible
159 // two types of different size
160 struct fail { char dummy[2]; };
161 struct succeed { char dummy; };
162 // Try to convert a T1 to a T2 by plugging into tryConvert
163 static fail tryConvert(...);
164 static succeed tryConvert(const T2&);
165 static const T1& makeT1();
168 // Disable spurious loss of precision warnings in tryConvert(makeT1())
169 # pragma warning(push)
170 # pragma warning(disable:4244)
171 # pragma warning(disable:4267)
173 // Standard trick: the (...) version of tryConvert will be chosen from
174 // the overload set only if the version taking a T2 doesn't match.
175 // Then we compare the sizes of the return types to check which
176 // function matched. Very neat, in a disgusting kind of way :)
177 static const bool value =
178 sizeof(tryConvert(makeT1())) == sizeof(succeed);
180 # pragma warning(pop)
185 // Detect when a type is not a wchar_t string
186 template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };
187 template<> struct is_wchar<wchar_t*> {};
188 template<> struct is_wchar<const wchar_t*> {};
189 template<int n> struct is_wchar<const wchar_t[n]> {};
190 template<int n> struct is_wchar<wchar_t[n]> {};
193 // Format the value by casting to type fmtT. This default implementation
194 // should never be called.
195 template<typename T, typename fmtT, bool convertible = is_convertible<T, fmtT>::value>
196 struct formatValueAsType
198 static void invoke(std::ostream& /*out*/, const T& /*value*/) { assert(0); }
200 // Specialized version for types that can actually be converted to fmtT, as
201 // indicated by the "convertible" template parameter.
202 template<typename T, typename fmtT>
203 struct formatValueAsType<T,fmtT,true>
205 static void invoke(std::ostream& out, const T& value)
206 { out << static_cast<fmtT>(value); }
209 #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
210 template<typename T, bool convertible = is_convertible<T, int>::value>
211 struct formatZeroIntegerWorkaround
213 static bool invoke(std::ostream& /**/, const T& /**/) { return false; }
216 struct formatZeroIntegerWorkaround<T,true>
218 static bool invoke(std::ostream& out, const T& value)
220 if (static_cast<int>(value) == 0 && out.flags() & std::ios::showpos)
228 #endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
230 // Convert an arbitrary type to integer. The version with convertible=false
232 template<typename T, bool convertible = is_convertible<T,int>::value>
235 static int invoke(const T& /*value*/)
237 TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to "
238 "integer for use as variable width or precision");
242 // Specialization for convertToInt when conversion is possible
244 struct convertToInt<T,true>
246 static int invoke(const T& value) { return static_cast<int>(value); }
249 } // namespace detail
252 //------------------------------------------------------------------------------
253 // Variable formatting functions. May be overridden for user-defined types if
257 // Format a value into a stream. Called from format() for all types by default.
259 // Users may override this for their own types. When this function is called,
260 // the stream flags will have been modified according to the format string.
261 // The format specification is provided in the range [fmtBegin, fmtEnd).
263 // By default, formatValue() uses the usual stream insertion operator
264 // operator<< to format the type T, with special cases for the %c and %p
267 inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,
268 const char* fmtEnd, const T& value)
270 #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS
271 // Since we don't support printing of wchar_t using "%ls", make it fail at
272 // compile time in preference to printing as a void* at runtime.
273 typedef typename detail::is_wchar<T>::tinyformat_wchar_is_not_supported DummyType;
274 (void) DummyType(); // avoid unused type warning with gcc-4.8
276 // The mess here is to support the %c and %p conversions: if these
277 // conversions are active we try to convert the type to a char or const
278 // void* respectively and format that instead of the value itself. For the
279 // %p conversion it's important to avoid dereferencing the pointer, which
280 // could otherwise lead to a crash when printing a dangling (const char*).
281 const bool canConvertToChar = detail::is_convertible<T,char>::value;
282 const bool canConvertToVoidPtr = detail::is_convertible<T, const void*>::value;
283 if(canConvertToChar && *(fmtEnd-1) == 'c')
284 detail::formatValueAsType<T, char>::invoke(out, value);
285 else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p')
286 detail::formatValueAsType<T, const void*>::invoke(out, value);
287 #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
288 else if(detail::formatZeroIntegerWorkaround<T>::invoke(out, value)) /**/;
295 // Overloaded version for char types to support printing as an integer
296 #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \
297 inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \
298 const char* fmtEnd, charType value) \
300 switch(*(fmtEnd-1)) \
302 case 'u': case 'd': case 'i': case 'o': case 'X': case 'x': \
303 out << static_cast<int>(value); break; \
305 out << value; break; \
308 // per 3.9.1: char, signed char and unsigned char are all distinct types
309 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char)
310 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char)
311 TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char)
312 #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR
315 //------------------------------------------------------------------------------
316 // Tools for emulating variadic templates in C++98. The basic idea here is
317 // stolen from the boost preprocessor metaprogramming library and cut down to
318 // be just general enough for what we need.
320 #define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n
321 #define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n
322 #define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n
323 #define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n
325 // To keep it as transparent as possible, the macros below have been generated
326 // using python via the excellent cog.py code generation script. This avoids
327 // the need for a bunch of complex (but more general) preprocessor tricks as
328 // used in boost.preprocessor.
330 // To rerun the code generation in place, use `cog.py -r tinyformat.h`
331 // (see http://nedbatchelder.com/code/cog). Alternatively you can just create
332 // extra versions by hand.
337 def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1):
338 for j in range(startInd,maxParams+1):
339 list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)])
340 cog.outl(lineTemplate % {'j':j, 'list':list})
342 makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s',
346 makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s',
347 'const T%(i)d& v%(i)d')
350 makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d')
353 cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1')
354 makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s',
355 'v%(i)d', startInd = 2)
358 cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' +
359 ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)]))
361 #define TINYFORMAT_ARGTYPES_1 class T1
362 #define TINYFORMAT_ARGTYPES_2 class T1, class T2
363 #define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3
364 #define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4
365 #define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5
366 #define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6
367 #define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7
368 #define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8
369 #define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9
370 #define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10
371 #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
372 #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
373 #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
374 #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
375 #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
376 #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 #define TINYFORMAT_VARARGS_1 const T1& v1
379 #define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2
380 #define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3
381 #define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4
382 #define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5
383 #define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6
384 #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
385 #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
386 #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
387 #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
388 #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
389 #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
390 #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
391 #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
392 #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
393 #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 #define TINYFORMAT_PASSARGS_1 v1
396 #define TINYFORMAT_PASSARGS_2 v1, v2
397 #define TINYFORMAT_PASSARGS_3 v1, v2, v3
398 #define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4
399 #define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5
400 #define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6
401 #define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7
402 #define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8
403 #define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9
404 #define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10
405 #define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
406 #define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
407 #define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
408 #define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
409 #define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
410 #define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
412 #define TINYFORMAT_PASSARGS_TAIL_1
413 #define TINYFORMAT_PASSARGS_TAIL_2 , v2
414 #define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3
415 #define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4
416 #define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5
417 #define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6
418 #define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7
419 #define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8
420 #define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9
421 #define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10
422 #define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
423 #define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
424 #define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
425 #define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
426 #define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
427 #define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
429 #define TINYFORMAT_FOREACH_ARGNUM(m) \
430 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)
437 // Class holding current position in format string and an output stream into
438 // which arguments are formatted.
442 // Flags for features not representable with standard stream state
443 enum ExtraFormatFlags
446 Flag_TruncateToPrecision = 1<<0, // truncate length to stream precision()
447 Flag_SpacePadPositive = 1<<1, // pad positive values with spaces
448 Flag_VariableWidth = 1<<2, // variable field width in arg list
449 Flag_VariablePrecision = 1<<3 // variable field precision in arg list
452 // out is the output stream, fmt is the full format string
453 FormatIterator(std::ostream& out, const char* fmt)
456 m_extraFlags(Flag_None),
458 m_wantPrecision(false),
460 m_variablePrecision(0),
461 m_origWidth(out.width()),
462 m_origPrecision(out.precision()),
463 m_origFlags(out.flags()),
464 m_origFill(out.fill())
467 // Print remaining part of format string.
470 // It would be nice if we could do this from the destructor, but we
471 // can't if TINFORMAT_ERROR is used to throw an exception!
472 m_fmt = printFormatStringLiteral(m_out, m_fmt);
474 TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string");
479 // Restore stream state
480 m_out.width(m_origWidth);
481 m_out.precision(m_origPrecision);
482 m_out.flags(m_origFlags);
483 m_out.fill(m_origFill);
487 void accept(const T& value);
490 // Parse and return an integer from the string c, as atoi()
491 // On return, c is set to one past the end of the integer.
492 static int parseIntAndAdvance(const char*& c)
495 for(;*c >= '0' && *c <= '9'; ++c)
496 i = 10*i + (*c - '0');
500 // Format at most truncLen characters of a C string to the given
501 // stream. Return true if formatting proceeded (generic version always
504 static bool formatCStringTruncate(std::ostream& /*out*/, const T& /*value*/,
505 std::streamsize /*truncLen*/)
509 # define TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(type) \
510 static bool formatCStringTruncate(std::ostream& out, type* value, \
511 std::streamsize truncLen) \
513 std::streamsize len = 0; \
514 while(len < truncLen && value[len] != 0) \
516 out.write(value, len); \
519 // Overload for const char* and char*. Could overload for signed &
520 // unsigned char too, but these are technically unneeded for printf
522 TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(const char)
523 TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(char)
524 # undef TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE
526 // Print literal part of format string and return next format spec
529 // Skips over any occurrences of '%%', printing a literal '%' to the
530 // output. The position of the first % character of the next
531 // nontrivial format spec is returned, or the end of string.
532 static const char* printFormatStringLiteral(std::ostream& out,
541 out.write(fmt, static_cast<std::streamsize>(c - fmt));
544 out.write(fmt, static_cast<std::streamsize>(c - fmt));
547 // for "%%", tack trailing % onto next literal section.
554 static const char* streamStateFromFormat(std::ostream& out,
555 unsigned int& extraFlags,
556 const char* fmtStart,
558 int variablePrecision);
560 // Private copy & assign: Kill gcc warnings with -Weffc++
561 FormatIterator(const FormatIterator&);
562 FormatIterator& operator=(const FormatIterator&);
564 // Stream, current format string & state
567 unsigned int m_extraFlags;
568 // State machine info for handling of variable width & precision
570 bool m_wantPrecision;
572 int m_variablePrecision;
573 // Saved stream state
574 std::streamsize m_origWidth;
575 std::streamsize m_origPrecision;
576 std::ios::fmtflags m_origFlags;
581 // Accept a value for formatting into the internal stream.
583 TINYFORMAT_NOINLINE // < greatly reduces bloat in optimized builds
584 void FormatIterator::accept(const T& value)
586 // Parse the format string
587 const char* fmtEnd = 0;
588 if(m_extraFlags == Flag_None && !m_wantWidth && !m_wantPrecision)
590 m_fmt = printFormatStringLiteral(m_out, m_fmt);
591 fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt, 0, 0);
592 m_wantWidth = (m_extraFlags & Flag_VariableWidth) != 0;
593 m_wantPrecision = (m_extraFlags & Flag_VariablePrecision) != 0;
595 // Consume value as variable width and precision specifier if necessary
596 if(m_extraFlags & (Flag_VariableWidth | Flag_VariablePrecision))
598 if(m_wantWidth || m_wantPrecision)
600 int v = convertToInt<T>::invoke(value);
606 else if(m_wantPrecision)
608 m_variablePrecision = v;
609 m_wantPrecision = false;
613 // If we get here, we've set both the variable precision and width as
614 // required and we need to rerun the stream state setup to insert these.
615 fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt,
616 m_variableWidth, m_variablePrecision);
619 // Format the value into the stream.
620 if(!(m_extraFlags & (Flag_SpacePadPositive | Flag_TruncateToPrecision)))
621 formatValue(m_out, m_fmt, fmtEnd, value);
624 // The following are special cases where there's no direct
625 // correspondence between stream formatting and the printf() behaviour.
626 // Instead, we simulate the behaviour crudely by formatting into a
627 // temporary string stream and munging the resulting string.
628 std::ostringstream tmpStream;
629 tmpStream.copyfmt(m_out);
630 if(m_extraFlags & Flag_SpacePadPositive)
631 tmpStream.setf(std::ios::showpos);
632 // formatCStringTruncate is required for truncating conversions like
633 // "%.4s" where at most 4 characters of the c-string should be read.
634 // If we didn't include this special case, we might read off the end.
635 if(!( (m_extraFlags & Flag_TruncateToPrecision) &&
636 formatCStringTruncate(tmpStream, value, m_out.precision()) ))
638 // Not a truncated c-string; just format normally.
639 formatValue(tmpStream, m_fmt, fmtEnd, value);
641 std::string result = tmpStream.str(); // allocates... yuck.
642 if(m_extraFlags & Flag_SpacePadPositive)
644 for(size_t i = 0, iend = result.size(); i < iend; ++i)
648 if((m_extraFlags & Flag_TruncateToPrecision) &&
649 (int)result.size() > (int)m_out.precision())
650 m_out.write(result.c_str(), m_out.precision());
654 m_extraFlags = Flag_None;
659 // Parse a format string and set the stream state accordingly.
661 // The format mini-language recognized here is meant to be the one from C99,
662 // with the form "%[flags][width][.precision][length]type".
664 // Formatting options which can't be natively represented using the ostream
665 // state are returned in the extraFlags parameter which is a bitwise
666 // combination of values from the ExtraFormatFlags enum.
667 inline const char* FormatIterator::streamStateFromFormat(std::ostream& out,
668 unsigned int& extraFlags,
669 const char* fmtStart,
671 int variablePrecision)
675 TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string");
678 // Reset stream state to defaults.
682 // Reset most flags; ignore irrelevant unitbuf & skipws.
683 out.unsetf(std::ios::adjustfield | std::ios::basefield |
684 std::ios::floatfield | std::ios::showbase | std::ios::boolalpha |
685 std::ios::showpoint | std::ios::showpos | std::ios::uppercase);
686 extraFlags = Flag_None;
687 bool precisionSet = false;
688 bool widthSet = false;
689 const char* c = fmtStart + 1;
696 out.setf(std::ios::showpoint | std::ios::showbase);
699 // overridden by left alignment ('-' flag)
700 if(!(out.flags() & std::ios::left))
702 // Use internal padding so that numeric values are
703 // formatted correctly, eg -00010 rather than 000-10
705 out.setf(std::ios::internal, std::ios::adjustfield);
710 out.setf(std::ios::left, std::ios::adjustfield);
713 // overridden by show positive sign, '+' flag.
714 if(!(out.flags() & std::ios::showpos))
715 extraFlags |= Flag_SpacePadPositive;
718 out.setf(std::ios::showpos);
719 extraFlags &= ~Flag_SpacePadPositive;
725 if(*c >= '0' && *c <= '9')
728 out.width(parseIntAndAdvance(c));
733 if(variableWidth < 0)
735 // negative widths correspond to '-' flag set
737 out.setf(std::ios::left, std::ios::adjustfield);
738 variableWidth = -variableWidth;
740 out.width(variableWidth);
741 extraFlags |= Flag_VariableWidth;
744 // 3) Parse precision
752 extraFlags |= Flag_VariablePrecision;
753 precision = variablePrecision;
757 if(*c >= '0' && *c <= '9')
758 precision = parseIntAndAdvance(c);
759 else if(*c == '-') // negative precisions ignored, treated as zero.
760 parseIntAndAdvance(++c);
762 out.precision(precision);
765 // 4) Ignore any C99 length modifier
766 while(*c == 'l' || *c == 'h' || *c == 'L' ||
767 *c == 'j' || *c == 'z' || *c == 't')
769 // 5) We're up to the conversion specifier character.
770 // Set stream flags based on conversion specifier (thanks to the
771 // boost::format class for forging the way here).
772 bool intConversion = false;
775 case 'u': case 'd': case 'i':
776 out.setf(std::ios::dec, std::ios::basefield);
777 intConversion = true;
780 out.setf(std::ios::oct, std::ios::basefield);
781 intConversion = true;
784 out.setf(std::ios::uppercase);
786 out.setf(std::ios::hex, std::ios::basefield);
787 intConversion = true;
790 out.setf(std::ios::uppercase);
792 out.setf(std::ios::scientific, std::ios::floatfield);
793 out.setf(std::ios::dec, std::ios::basefield);
796 out.setf(std::ios::uppercase);
798 out.setf(std::ios::fixed, std::ios::floatfield);
801 out.setf(std::ios::uppercase);
803 out.setf(std::ios::dec, std::ios::basefield);
804 // As in boost::format, let stream decide float format.
805 out.flags(out.flags() & ~std::ios::floatfield);
808 TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs "
809 "are not supported");
812 // Handled as special case inside formatValue()
816 extraFlags |= Flag_TruncateToPrecision;
817 // Make %s print booleans as "true" and "false"
818 out.setf(std::ios::boolalpha);
821 // Not supported - will cause problems!
822 TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported");
825 TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly "
826 "terminated by end of string");
829 if(intConversion && precisionSet && !widthSet)
831 // "precision" for integers gives the minimum number of digits (to be
832 // padded with zeros on the left). This isn't really supported by the
833 // iostreams, but we can approximately simulate it with the width if
834 // the width isn't otherwise used.
835 out.width(out.precision());
836 out.setf(std::ios::internal, std::ios::adjustfield);
844 //------------------------------------------------------------------------------
845 // Private format function on top of which the public interface is implemented.
846 // We enforce a mimimum of one value to be formatted to prevent bugs looking like
848 // const char* myStr = "100% broken";
849 // printf(myStr); // Parses % as a format specifier
850 #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
852 template<typename T1>
853 void format(FormatIterator& fmtIter, const T1& value1)
855 fmtIter.accept(value1);
859 // General version for C++11
860 template<typename T1, typename... Args>
861 void format(FormatIterator& fmtIter, const T1& value1, const Args&... args)
863 fmtIter.accept(value1);
864 format(fmtIter, args...);
869 inline void format(FormatIterator& fmtIter)
874 // General version for C++98
875 #define TINYFORMAT_MAKE_FORMAT_DETAIL(n) \
876 template<TINYFORMAT_ARGTYPES(n)> \
877 void format(detail::FormatIterator& fmtIter, TINYFORMAT_VARARGS(n)) \
879 fmtIter.accept(v1); \
880 format(fmtIter TINYFORMAT_PASSARGS_TAIL(n)); \
883 TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_DETAIL)
884 #undef TINYFORMAT_MAKE_FORMAT_DETAIL
886 #endif // End C++98 variadic template emulation for format()
888 } // namespace detail
891 //------------------------------------------------------------------------------
892 // Implement all the main interface functions here in terms of detail::format()
894 #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
896 // C++11 - the simple case
897 template<typename T1, typename... Args>
898 void format(std::ostream& out, const char* fmt, const T1& v1, const Args&... args)
900 detail::FormatIterator fmtIter(out, fmt);
901 format(fmtIter, v1, args...);
904 template<typename T1, typename... Args>
905 std::string format(const char* fmt, const T1& v1, const Args&... args)
907 std::ostringstream oss;
908 format(oss, fmt, v1, args...);
912 template<typename T1, typename... Args>
913 std::string format(const std::string &fmt, const T1& v1, const Args&... args)
915 std::ostringstream oss;
916 format(oss, fmt.c_str(), v1, args...);
920 template<typename T1, typename... Args>
921 void printf(const char* fmt, const T1& v1, const Args&... args)
923 format(std::cout, fmt, v1, args...);
928 // C++98 - define the interface functions using the wrapping macros
929 #define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \
931 template<TINYFORMAT_ARGTYPES(n)> \
932 void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \
934 tinyformat::detail::FormatIterator fmtIter(out, fmt); \
935 tinyformat::detail::format(fmtIter, TINYFORMAT_PASSARGS(n)); \
938 template<TINYFORMAT_ARGTYPES(n)> \
939 std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \
941 std::ostringstream oss; \
942 tinyformat::format(oss, fmt, TINYFORMAT_PASSARGS(n)); \
946 template<TINYFORMAT_ARGTYPES(n)> \
947 std::string format(const std::string &fmt, TINYFORMAT_VARARGS(n)) \
949 std::ostringstream oss; \
950 tinyformat::format(oss, fmt.c_str(), TINYFORMAT_PASSARGS(n)); \
954 template<TINYFORMAT_ARGTYPES(n)> \
955 void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \
957 tinyformat::format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \
960 TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS)
961 #undef TINYFORMAT_MAKE_FORMAT_FUNCS
965 //------------------------------------------------------------------------------
966 // Define deprecated wrapping macro for backward compatibility in tinyformat
967 // 1.x. Will be removed in version 2!
968 #define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS
969 #define TINYFORMAT_WRAP_FORMAT_N(n, returnType, funcName, funcDeclSuffix, \
970 bodyPrefix, streamName, bodySuffix) \
971 template<TINYFORMAT_ARGTYPES(n)> \
972 returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt, \
973 TINYFORMAT_VARARGS(n)) funcDeclSuffix \
976 tinyformat::format(streamName, fmt, TINYFORMAT_PASSARGS(n)); \
980 #define TINYFORMAT_WRAP_FORMAT(returnType, funcName, funcDeclSuffix, \
981 bodyPrefix, streamName, bodySuffix) \
983 returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \
987 tinyformat::detail::FormatIterator(streamName, fmt).finish(); \
990 TINYFORMAT_WRAP_FORMAT_N(1 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
991 TINYFORMAT_WRAP_FORMAT_N(2 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
992 TINYFORMAT_WRAP_FORMAT_N(3 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
993 TINYFORMAT_WRAP_FORMAT_N(4 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
994 TINYFORMAT_WRAP_FORMAT_N(5 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
995 TINYFORMAT_WRAP_FORMAT_N(6 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
996 TINYFORMAT_WRAP_FORMAT_N(7 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
997 TINYFORMAT_WRAP_FORMAT_N(8 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
998 TINYFORMAT_WRAP_FORMAT_N(9 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
999 TINYFORMAT_WRAP_FORMAT_N(10, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1000 TINYFORMAT_WRAP_FORMAT_N(11, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1001 TINYFORMAT_WRAP_FORMAT_N(12, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1002 TINYFORMAT_WRAP_FORMAT_N(13, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1003 TINYFORMAT_WRAP_FORMAT_N(14, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1004 TINYFORMAT_WRAP_FORMAT_N(15, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1005 TINYFORMAT_WRAP_FORMAT_N(16, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
1008 } // namespace tinyformat
1010 #endif // TINYFORMAT_H_INCLUDED