From 4e4e182679118580ec66068288100c57f971fbc6 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Tue, 10 Feb 2015 19:13:51 -0800 Subject: [PATCH] Update tinyformat to version 2.0.1 And remove its unit tests from tinyformat_test as we are only interested in speed test. --- tinyformat.h | 1066 +++++++++++++++++++++---------------------- tinyformat_test.cpp | 156 ------- 2 files changed, 524 insertions(+), 698 deletions(-) diff --git a/tinyformat.h b/tinyformat.h index eaefe10..1194d75 100644 --- a/tinyformat.h +++ b/tinyformat.h @@ -26,70 +26,81 @@ // DEALINGS IN THE SOFTWARE. //------------------------------------------------------------------------------ -// Tinyformat: A minimal type safe printf-replacement library for C++ +// Tinyformat: A minimal type safe printf replacement // -// This library aims to support 95% of casual C++ string formatting needs with -// a single lightweight header file. Anything you can do with this library -// can also be done with the standard C++ streams, but probably with -// considerably more typing :) +// tinyformat.h is a type safe printf replacement library in a single C++ +// header file. Design goals include: // -// Design goals: -// -// * Simplicity and minimalism. A single header file to include and distribute -// with your own projects. // * Type safety and extensibility for user defined types. -// * Parse standard C99 format strings, and support most features. -// * Support as many commonly used ``printf()`` features as practical without -// compromising on simplicity. +// * C99 printf() compatibility, to the extent possible using std::ostream +// * Simplicity and minimalism. A single header file to include and distribute +// with your projects. +// * Augment rather than replace the standard stream formatting mechanism +// * C++98 support, with optional C++11 niceties // // -// Example usage -// ------------- +// Main interface example usage +// ---------------------------- // -// To print the date, we might have +// To print a date to std::cout: // -// std::string weekday = "Wednesday"; -// const char* month = "July"; -// long day = 27; -// int hour = 14; -// int min = 44; +// std::string weekday = "Wednesday"; +// const char* month = "July"; +// size_t day = 27; +// long hour = 14; +// int min = 44; // -// tfm::format(std::cout, "%s, %s %d, %.2d:%.2d\n", -// weekday, month, day, hour, min); +// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); // -// (The types here are intentionally odd to emphasize the type safety of the -// interface.) The same thing could be achieved using either of the two -// convenience functions. One returns a std::string: +// The strange types here emphasize the type safety of the interface; it is +// possible to print a std::string using the "%s" conversion, and a +// size_t using the "%d" conversion. A similar result could be achieved +// using either of the tfm::format() functions. One prints on a user provided +// stream: // -// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n", -// weekday, month, day, hour, min); -// std::cout << date; +// tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); // -// The other prints to the std::cout stream: +// The other returns a std::string: // -// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); +// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); +// std::cout << date; // +// These are the three primary interface functions. // -// Brief outline of functionality -// ------------------------------ // -// (For full docs, see the accompanying README) +// User defined format functions +// ----------------------------- // +// Simulating variadic templates in C++98 is pretty painful since it requires +// writing out the same function for each desired number of arguments. To make +// this bearable tinyformat comes with a set of macros which are used +// internally to generate the API, but which may also be used in user code. // -// Interface functions: +// The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and +// TINYFORMAT_PASSARGS(n) will generate a list of n argument types, +// type/name pairs and argument names respectively when called with an integer +// n between 1 and 16. We can use these to define a macro which generates the +// desired user defined function with n arguments. To generate all 16 user +// defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an +// example, see the implementation of printf() at the end of the source file. // -// template -// void format(std::ostream& stream, const char* formatString, -// const T1& value1, const T2& value1, ...) +// Sometimes it's useful to be able to pass a list of format arguments through +// to a non-template function. The FormatList class is provided as a way to do +// this by storing the argument list in a type-opaque way. Continuing the +// example from above, we construct a FormatList using makeFormatList(): // -// template -// std::string format(const char* formatString, -// const T1& value1, const T2& value1, ...) +// FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min); // -// template -// void printf(const char* formatString, -// const T1& value1, const T2& value1, ...) +// The format list can now be passed into any non-template function and used +// via a call to the vformat() function: // +// tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList); +// +// +// Additional API information +// -------------------------- // // Error handling: Define TINYFORMAT_ERROR to customize the error handling for // format strings which are unsupported or have the wrong number of format @@ -97,10 +108,6 @@ // // User defined types: Uses operator<< for user defined types by default. // Overload formatValue() for more control. -// -// Wrapping tfm::format inside a user defined format function: See the macros -// TINYFORMAT_WRAP_FORMAT and TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS. - #ifndef TINYFORMAT_H_INCLUDED @@ -116,13 +123,14 @@ namespace tfm = tinyformat; // Error handling; calls assert() by default. // #define TINYFORMAT_ERROR(reasonString) your_error_handler(reasonString) -// Define for C++0x variadic templates which make the code shorter & more -// general. If you don't define this, C++0x support is autodetected below. +// Define for C++11 variadic templates which make the code shorter & more +// general. If you don't define this, C++11 support is autodetected below. // #define TINYFORMAT_USE_VARIADIC_TEMPLATES //------------------------------------------------------------------------------ // Implementation details. +#include #include #include #include @@ -137,15 +145,12 @@ namespace tfm = tinyformat; # endif #endif -#ifdef __GNUC__ -# define TINYFORMAT_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) -# define TINYFORMAT_NOINLINE __declspec(noinline) -#else -# define TINYFORMAT_NOINLINE +#if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201 +// std::showpos is broken on old libstdc++ as provided with OSX. See +// http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html +# define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND #endif - namespace tinyformat { //------------------------------------------------------------------------------ @@ -206,6 +211,26 @@ struct formatValueAsType { out << static_cast(value); } }; +#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND +template::value> +struct formatZeroIntegerWorkaround +{ + static bool invoke(std::ostream& /**/, const T& /**/) { return false; } +}; +template +struct formatZeroIntegerWorkaround +{ + static bool invoke(std::ostream& out, const T& value) + { + if (static_cast(value) == 0 && out.flags() & std::ios::showpos) + { + out << "+0"; + return true; + } + return false; + } +}; +#endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND // Convert an arbitrary type to integer. The version with convertible=false // throws an error. @@ -226,6 +251,29 @@ struct convertToInt static int invoke(const T& value) { return static_cast(value); } }; +// Format at most ntrunc characters to the given stream. +template +inline void formatTruncated(std::ostream& out, const T& value, int ntrunc) +{ + std::ostringstream tmp; + tmp << value; + std::string result = tmp.str(); + out.write(result.c_str(), std::min(ntrunc, static_cast(result.size()))); +} +#define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type) \ +inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \ +{ \ + std::streamsize len = 0; \ + while(len < ntrunc && value[len] != 0) \ + ++len; \ + out.write(value, len); \ +} +// Overload for const char* and char*. Could overload for signed & unsigned +// char too, but these are technically unneeded for printf compatibility. +TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char) +TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char) +#undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR + } // namespace detail @@ -234,23 +282,26 @@ struct convertToInt // desired. -// Format a value into a stream. Called from format() for all types by default. -// -// Users may override this for their own types. When this function is called, -// the stream flags will have been modified according to the format string. -// The format specification is provided in the range [fmtBegin, fmtEnd). -// -// By default, formatValue() uses the usual stream insertion operator -// operator<< to format the type T, with special cases for the %c and %p -// conversions. +/// Format a value into a stream, delegating to operator<< by default. +/// +/// Users may override this for their own types. When this function is called, +/// the stream flags will have been modified according to the format string. +/// The format specification is provided in the range [fmtBegin, fmtEnd). For +/// truncating conversions, ntrunc is set to the desired maximum number of +/// characters, for example "%.7s" calls formatValue with ntrunc = 7. +/// +/// By default, formatValue() uses the usual stream insertion operator +/// operator<< to format the type T, with special cases for the %c and %p +/// conversions. template inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, - const char* fmtEnd, const T& value) + const char* fmtEnd, int ntrunc, const T& value) { #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS // Since we don't support printing of wchar_t using "%ls", make it fail at // compile time in preference to printing as a void* at runtime. typedef typename detail::is_wchar::tinyformat_wchar_is_not_supported DummyType; + (void) DummyType(); // avoid unused type warning with gcc-4.8 #endif // The mess here is to support the %c and %p conversions: if these // conversions are active we try to convert the type to a char or const @@ -263,6 +314,15 @@ inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, detail::formatValueAsType::invoke(out, value); else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p') detail::formatValueAsType::invoke(out, value); +#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND + else if(detail::formatZeroIntegerWorkaround::invoke(out, value)) /**/; +#endif + else if(ntrunc >= 0) + { + // Take care not to overread C strings in truncating conversions like + // "%.4s" where at most 4 characters may be read. + detail::formatTruncated(out, value, ntrunc); + } else out << value; } @@ -271,7 +331,7 @@ inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, // Overloaded version for char types to support printing as an integer #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \ inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \ - const char* fmtEnd, charType value) \ + const char* fmtEnd, int /**/, charType value) \ { \ switch(*(fmtEnd-1)) \ { \ @@ -288,223 +348,211 @@ TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char) #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR +//------------------------------------------------------------------------------ +// Tools for emulating variadic templates in C++98. The basic idea here is +// stolen from the boost preprocessor metaprogramming library and cut down to +// be just general enough for what we need. + +#define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n +#define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n +#define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n +#define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n + +// To keep it as transparent as possible, the macros below have been generated +// using python via the excellent cog.py code generation script. This avoids +// the need for a bunch of complex (but more general) preprocessor tricks as +// used in boost.preprocessor. +// +// To rerun the code generation in place, use `cog.py -r tinyformat.h` +// (see http://nedbatchelder.com/code/cog). Alternatively you can just create +// extra versions by hand. + +/*[[[cog +maxParams = 16 + +def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1): + for j in range(startInd,maxParams+1): + list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) + cog.outl(lineTemplate % {'j':j, 'list':list}) + +makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s', + 'class T%(i)d') + +cog.outl() +makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s', + 'const T%(i)d& v%(i)d') + +cog.outl() +makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d') + +cog.outl() +cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1') +makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s', + 'v%(i)d', startInd = 2) + +cog.outl() +cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' + + ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)])) +]]]*/ +#define TINYFORMAT_ARGTYPES_1 class T1 +#define TINYFORMAT_ARGTYPES_2 class T1, class T2 +#define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3 +#define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4 +#define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5 +#define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6 +#define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7 +#define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8 +#define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9 +#define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10 +#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 +#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 +#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 +#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 +#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 +#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 + +#define TINYFORMAT_VARARGS_1 const T1& v1 +#define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2 +#define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3 +#define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4 +#define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5 +#define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 +#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 + +#define TINYFORMAT_PASSARGS_1 v1 +#define TINYFORMAT_PASSARGS_2 v1, v2 +#define TINYFORMAT_PASSARGS_3 v1, v2, v3 +#define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4 +#define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5 +#define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6 +#define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7 +#define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8 +#define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9 +#define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 +#define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 +#define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 +#define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 +#define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 +#define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 +#define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 + +#define TINYFORMAT_PASSARGS_TAIL_1 +#define TINYFORMAT_PASSARGS_TAIL_2 , v2 +#define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3 +#define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4 +#define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5 +#define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6 +#define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7 +#define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8 +#define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9 +#define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10 +#define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 +#define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 +#define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 +#define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 +#define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 +#define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 + +#define TINYFORMAT_FOREACH_ARGNUM(m) \ + 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) +//[[[end]]] + + + namespace detail { -// Class holding current position in format string and an output stream into -// which arguments are formatted. -class FormatIterator +// Type-opaque holder for an argument to format(), with associated actions on +// the type held as explicit function pointers. This allows FormatArg's for +// each argument to be allocated as a homogenous array inside FormatList +// whereas a naive implementation based on inheritance does not. +class FormatArg { public: - // Flags for features not representable with standard stream state - enum ExtraFormatFlags - { - Flag_None = 0, - Flag_TruncateToPrecision = 1<<0, // truncate length to stream precision() - Flag_SpacePadPositive = 1<<1, // pad positive values with spaces - Flag_VariableWidth = 1<<2, // variable field width in arg list - Flag_VariablePrecision = 1<<3 // variable field precision in arg list - }; - - // out is the output stream, fmt is the full format string - FormatIterator(std::ostream& out, const char* fmt) - : m_out(out), - m_fmt(fmt), - m_extraFlags(Flag_None), - m_wantWidth(false), - m_wantPrecision(false), - m_variableWidth(0), - m_variablePrecision(0), - m_origWidth(out.width()), - m_origPrecision(out.precision()), - m_origFlags(out.flags()), - m_origFill(out.fill()) + FormatArg() {} + + template + FormatArg(const T& value) + : m_value(static_cast(&value)), + m_formatImpl(&formatImpl), + m_toIntImpl(&toIntImpl) { } - // Print remaining part of format string. - void finish() + void format(std::ostream& out, const char* fmtBegin, + const char* fmtEnd, int ntrunc) const { - // It would be nice if we could do this from the destructor, but we - // can't if TINFORMAT_ERROR is used to throw an exception! - m_fmt = printFormatStringLiteral(m_out, m_fmt); - if(*m_fmt != '\0') - TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string"); + m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value); } - ~FormatIterator() + int toInt() const { - // Restore stream state - m_out.width(m_origWidth); - m_out.precision(m_origPrecision); - m_out.flags(m_origFlags); - m_out.fill(m_origFill); + return m_toIntImpl(m_value); } - template - void accept(const T& value); - private: - // Parse and return an integer from the string c, as atoi() - // On return, c is set to one past the end of the integer. - static int parseIntAndAdvance(const char*& c) + template + static void formatImpl(std::ostream& out, const char* fmtBegin, + const char* fmtEnd, int ntrunc, const void* value) { - int i = 0; - for(;*c >= '0' && *c <= '9'; ++c) - i = 10*i + (*c - '0'); - return i; + formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast(value)); } - // Format at most truncLen characters of a C string to the given - // stream. Return true if formatting proceeded (generic version always - // returns false) template - static bool formatCStringTruncate(std::ostream& /*out*/, const T& /*value*/, - std::streamsize /*truncLen*/) - { - return false; - } -# define TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(type) \ - static bool formatCStringTruncate(std::ostream& out, type* value, \ - std::streamsize truncLen) \ - { \ - std::streamsize len = 0; \ - while(len < truncLen && value[len] != 0) \ - ++len; \ - out.write(value, len); \ - return true; \ - } - // Overload for const char* and char*. Could overload for signed & - // unsigned char too, but these are technically unneeded for printf - // compatibility. - TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(const char) - TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(char) -# undef TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE - - // Print literal part of format string and return next format spec - // position. - // - // Skips over any occurrences of '%%', printing a literal '%' to the - // output. The position of the first % character of the next - // nontrivial format spec is returned, or the end of string. - static const char* printFormatStringLiteral(std::ostream& out, - const char* fmt) + static int toIntImpl(const void* value) { - const char* c = fmt; - for(; true; ++c) - { - switch(*c) - { - case '\0': - out.write(fmt, static_cast(c - fmt)); - return c; - case '%': - out.write(fmt, static_cast(c - fmt)); - if(*(c+1) != '%') - return c; - // for "%%", tack trailing % onto next literal section. - fmt = ++c; - break; - } - } + return convertToInt::invoke(*static_cast(value)); } - static const char* streamStateFromFormat(std::ostream& out, - unsigned int& extraFlags, - const char* fmtStart, - int variableWidth, - int variablePrecision); - - // Stream, current format string & state - std::ostream& m_out; - const char* m_fmt; - unsigned int m_extraFlags; - // State machine info for handling of variable width & precision - bool m_wantWidth; - bool m_wantPrecision; - int m_variableWidth; - int m_variablePrecision; - // Saved stream state - std::streamsize m_origWidth; - std::streamsize m_origPrecision; - std::ios::fmtflags m_origFlags; - char m_origFill; + const void* m_value; + void (*m_formatImpl)(std::ostream& out, const char* fmtBegin, + const char* fmtEnd, int ntrunc, const void* value); + int (*m_toIntImpl)(const void* value); }; -// Accept a value for formatting into the internal stream. -template -TINYFORMAT_NOINLINE // < greatly reduces bloat in optimized builds -void FormatIterator::accept(const T& value) +// Parse and return an integer from the string c, as atoi() +// On return, c is set to one past the end of the integer. +inline int parseIntAndAdvance(const char*& c) { - // Parse the format string - const char* fmtEnd = 0; - if(m_extraFlags == Flag_None && !m_wantWidth && !m_wantPrecision) - { - m_fmt = printFormatStringLiteral(m_out, m_fmt); - fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt, 0, 0); - m_wantWidth = (m_extraFlags & Flag_VariableWidth) != 0; - m_wantPrecision = (m_extraFlags & Flag_VariablePrecision) != 0; - } - // Consume value as variable width and precision specifier if necessary - if(m_extraFlags & (Flag_VariableWidth | Flag_VariablePrecision)) - { - if(m_wantWidth || m_wantPrecision) - { - int v = convertToInt::invoke(value); - if(m_wantWidth) - { - m_variableWidth = v; - m_wantWidth = false; - } - else if(m_wantPrecision) - { - m_variablePrecision = v; - m_wantPrecision = false; - } - return; - } - // If we get here, we've set both the variable precision and width as - // required and we need to rerun the stream state setup to insert these. - fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt, - m_variableWidth, m_variablePrecision); - } + int i = 0; + for(;*c >= '0' && *c <= '9'; ++c) + i = 10*i + (*c - '0'); + return i; +} - // Format the value into the stream. - if(!(m_extraFlags & (Flag_SpacePadPositive | Flag_TruncateToPrecision))) - formatValue(m_out, m_fmt, fmtEnd, value); - else +// Print literal part of format string and return next format spec +// position. +// +// Skips over any occurrences of '%%', printing a literal '%' to the +// output. The position of the first % character of the next +// nontrivial format spec is returned, or the end of string. +inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt) +{ + const char* c = fmt; + for(; true; ++c) { - // The following are special cases where there's no direct - // correspondence between stream formatting and the printf() behaviour. - // Instead, we simulate the behaviour crudely by formatting into a - // temporary string stream and munging the resulting string. - std::ostringstream tmpStream; - tmpStream.copyfmt(m_out); - if(m_extraFlags & Flag_SpacePadPositive) - tmpStream.setf(std::ios::showpos); - // formatCStringTruncate is required for truncating conversions like - // "%.4s" where at most 4 characters of the c-string should be read. - // If we didn't include this special case, we might read off the end. - if(!( (m_extraFlags & Flag_TruncateToPrecision) && - formatCStringTruncate(tmpStream, value, m_out.precision()) )) + switch(*c) { - // Not a truncated c-string; just format normally. - formatValue(tmpStream, m_fmt, fmtEnd, value); + case '\0': + out.write(fmt, static_cast(c - fmt)); + return c; + case '%': + out.write(fmt, static_cast(c - fmt)); + if(*(c+1) != '%') + return c; + // for "%%", tack trailing % onto next literal section. + fmt = ++c; + break; } - std::string result = tmpStream.str(); // allocates... yuck. - if(m_extraFlags & Flag_SpacePadPositive) - { - for(size_t i = 0, iend = result.size(); i < iend; ++i) - if(result[i] == '+') - result[i] = ' '; - } - if((m_extraFlags & Flag_TruncateToPrecision) && - (int)result.size() > (int)m_out.precision()) - m_out.write(result.c_str(), m_out.precision()); - else - m_out << result; } - m_extraFlags = Flag_None; - m_fmt = fmtEnd; } @@ -514,13 +562,14 @@ void FormatIterator::accept(const T& value) // with the form "%[flags][width][.precision][length]type". // // Formatting options which can't be natively represented using the ostream -// state are returned in the extraFlags parameter which is a bitwise -// combination of values from the ExtraFormatFlags enum. -inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, - unsigned int& extraFlags, - const char* fmtStart, - int variableWidth, - int variablePrecision) +// state are returned in spacePadPositive (for space padded positive numbers) +// and ntrunc (for truncating conversions). argIndex is incremented if +// necessary to pull out variable width and precision . The function returns a +// pointer to the character after the end of the current format spec. +inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive, + int& ntrunc, const char* fmtStart, + const detail::FormatArg* formatters, + int& argIndex, int numFormatters) { if(*fmtStart != '%') { @@ -535,9 +584,9 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, 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); - extraFlags = Flag_None; bool precisionSet = false; bool widthSet = false; + int widthExtra = 0; const char* c = fmtStart + 1; // 1) Parse flags for(;; ++c) @@ -564,11 +613,12 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, case ' ': // overridden by show positive sign, '+' flag. if(!(out.flags() & std::ios::showpos)) - extraFlags |= Flag_SpacePadPositive; + spacePadPositive = true; continue; case '+': out.setf(std::ios::showpos); - extraFlags &= ~Flag_SpacePadPositive; + spacePadPositive = false; + widthExtra = 1; continue; } break; @@ -582,15 +632,19 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, if(*c == '*') { widthSet = true; - if(variableWidth < 0) + int width = 0; + if(argIndex < numFormatters) + width = formatters[argIndex++].toInt(); + else + TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width"); + if(width < 0) { // negative widths correspond to '-' flag set out.fill(' '); out.setf(std::ios::left, std::ios::adjustfield); - variableWidth = -variableWidth; + width = -width; } - out.width(variableWidth); - extraFlags |= Flag_VariableWidth; + out.width(width); ++c; } // 3) Parse precision @@ -601,8 +655,10 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, if(*c == '*') { ++c; - extraFlags |= Flag_VariablePrecision; - precision = variablePrecision; + if(argIndex < numFormatters) + precision = formatters[argIndex++].toInt(); + else + TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable precision"); } else { @@ -665,7 +721,7 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, break; case 's': if(precisionSet) - extraFlags |= Flag_TruncateToPrecision; + ntrunc = static_cast(out.precision()); // Make %s print booleans as "true" and "false" out.setf(std::ios::boolalpha); break; @@ -684,7 +740,7 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, // padded with zeros on the left). This isn't really supported by the // iostreams, but we can approximately simulate it with the width if // the width isn't otherwise used. - out.width(out.precision()); + out.width(out.precision() + widthExtra); out.setf(std::ios::internal, std::ios::adjustfield); out.fill('0'); } @@ -692,290 +748,193 @@ inline const char* FormatIterator::streamStateFromFormat(std::ostream& out, } - //------------------------------------------------------------------------------ -// Private format function on top of which the public interface is implemented -inline void format(FormatIterator& fmtIter) +inline void formatImpl(std::ostream& out, const char* fmt, + const detail::FormatArg* formatters, + int numFormatters) { - fmtIter.finish(); + // Saved stream state + std::streamsize origWidth = out.width(); + std::streamsize origPrecision = out.precision(); + std::ios::fmtflags origFlags = out.flags(); + char origFill = out.fill(); + + for (int argIndex = 0; argIndex < numFormatters; ++argIndex) + { + // Parse the format string + fmt = printFormatStringLiteral(out, fmt); + bool spacePadPositive = false; + int ntrunc = -1; + const char* fmtEnd = streamStateFromFormat(out, spacePadPositive, ntrunc, fmt, + formatters, argIndex, numFormatters); + if (argIndex >= numFormatters) + { + // Check args remain after reading any variable width/precision + TINYFORMAT_ERROR("tinyformat: Not enough format arguments"); + return; + } + const FormatArg& arg = formatters[argIndex]; + // Format the arg into the stream. + if(!spacePadPositive) + arg.format(out, fmt, fmtEnd, ntrunc); + else + { + // The following is a special case with no direct correspondence + // between stream formatting and the printf() behaviour. Simulate + // it crudely by formatting into a temporary string stream and + // munging the resulting string. + std::ostringstream tmpStream; + tmpStream.copyfmt(out); + tmpStream.setf(std::ios::showpos); + arg.format(tmpStream, fmt, fmtEnd, ntrunc); + std::string result = tmpStream.str(); // allocates... yuck. + for(size_t i = 0, iend = result.size(); i < iend; ++i) + if(result[i] == '+') result[i] = ' '; + out << result; + } + fmt = fmtEnd; + } + + // Print remaining part of format string. + fmt = printFormatStringLiteral(out, fmt); + if(*fmt != '\0') + TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string"); + + // Restore stream state + out.width(origWidth); + out.precision(origPrecision); + out.flags(origFlags); + out.fill(origFill); } -// Define N-argument format function. -// -// There's two cases here: c++0x and c++98. -#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES +} // namespace detail + -// First, the simple definition for C++0x: -template -void format(FormatIterator& fmtIter, const T1& value1, const Args&... args) +/// List of template arguments format(), held in a type-opaque way. +/// +/// A const reference to FormatList (typedef'd as FormatListRef) may be +/// conveniently used to pass arguments to non-template functions: All type +/// information has been stripped from the arguments, leaving just enough of a +/// common interface to perform formatting as required. +class FormatList { - fmtIter.accept(value1); - format(fmtIter, args...); -} + public: + FormatList(detail::FormatArg* formatters, int N) + : m_formatters(formatters), m_N(N) { } -#else + friend void vformat(std::ostream& out, const char* fmt, + const FormatList& list); -// For C++98 we don't have variadic templates so we need to generate code -// outside the language. We could do this with some ugly macros but instead -// let's use a short snippet of python code with the help of the excellent cog -// code generation script ( http://nedbatchelder.com/code/cog/ ) + private: + const detail::FormatArg* m_formatters; + int m_N; +}; -/*[[[cog +/// Reference to type-opaque format list for passing to vformat() +typedef const FormatList& FormatListRef; -maxParams = 10 - -# prepend a comma if the string isn't empty. -def prependComma(str): - return '' if str == '' else ', ' + str - -# Append backslashes to lines so they appear as a macro in C++ -# lineLen is the desired padding before the backslash -def formatAsMacro(str, lineLen=75): - lines = str.splitlines() - lines = [l+' '*max(1, lineLen-len(l)) for l in lines] - return '\\\n'.join(lines) + '\\' - -# Fill out the given string template. -def fillTemplate(template, minParams=0, formatFunc=lambda s: s): - for i in range(minParams,maxParams+1): - paramRange = range(1,i+1) - templateSpec = ', '.join(['typename T%d' % (j,) for j in paramRange]) - if templateSpec == '': - templateSpec = 'inline' - else: - templateSpec = 'template<%s>' % (templateSpec,) - paramList = prependComma(', '.join(['const T%d& v%d' % (j,j) - for j in paramRange])) - argList = prependComma(', '.join(['v%d' % (j,) for j in paramRange])) - argListNoHead = prependComma(', '.join(['v%d' % (j,) - for j in paramRange[1:]])) - cog.outl(formatFunc(template % locals())) - -fillTemplate( -'''%(templateSpec)s -void format(FormatIterator& fmtIter %(paramList)s) -{ - fmtIter.accept(v1); - format(fmtIter%(argListNoHead)s); -}''', minParams=1) -]]]*/ -template -void format(FormatIterator& fmtIter , const T1& v1) -{ - fmtIter.accept(v1); - format(fmtIter); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2) -{ - fmtIter.accept(v1); - format(fmtIter, v2); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3, const T4& v4) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5, v6); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5, v6, v7); -} -template -void format(FormatIterator& fmtIter , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5, v6, v7, v8); -} -template -void format(FormatIterator& fmtIter , 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) -{ - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5, v6, v7, v8, v9); -} -template -void format(FormatIterator& fmtIter , 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) +namespace detail { + +// Format list subclass with fixed storage to avoid dynamic allocation +template +class FormatListN : public FormatList { - fmtIter.accept(v1); - format(fmtIter, v2, v3, v4, v5, v6, v7, v8, v9, v10); -} -//[[[end]]] + public: +#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES + template + FormatListN(const Args&... args) + : FormatList(&m_formatterStore[0], N), + m_formatterStore{FormatArg(args)...} + { static_assert(sizeof...(args) == N, "Number of args must be N"); } +#else // C++98 version + void init(int) {} +# define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n) \ + \ + template \ + FormatListN(TINYFORMAT_VARARGS(n)) \ + : FormatList(&m_formatterStore[0], n) \ + { assert(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \ + \ + template \ + void init(int i, TINYFORMAT_VARARGS(n)) \ + { \ + m_formatterStore[i] = FormatArg(v1); \ + init(i+1 TINYFORMAT_PASSARGS_TAIL(n)); \ + } + + TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR) +# undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR +#endif + + private: + FormatArg m_formatterStore[N]; +}; -#endif // End C++98 variadic template emulation for format() +// Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard +template<> class FormatListN<0> : public FormatList +{ + public: FormatListN() : FormatList(0, 0) {} +}; } // namespace detail //------------------------------------------------------------------------------ -// Define the macro TINYFORMAT_WRAP_FORMAT, which can be used to wrap a call -// to tfm::format for C++98 support. -// -// We make this available in both C++0x and C++98 mode for convenience so that -// users can choose not to write out the C++0x version if they're primarily -// interested in C++98 support, but still have things work with C++0x. -// -// Note that TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS cannot be a macro parameter -// because it must expand to a comma separated list (or nothing, as used for -// printf below) +// Primary API functions -/*[[[cog -cog.outl(formatAsMacro( -'''#define TINYFORMAT_WRAP_FORMAT(returnType, funcName, funcDeclSuffix, - bodyPrefix, streamName, bodySuffix)''')) - -fillTemplate( -r'''%(templateSpec)s -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt - %(paramList)s) funcDeclSuffix +#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES + +/// Make type-agnostic format list from list of template arguments. +/// +/// The exact return type of this function is an implementation detail and +/// shouldn't be relied upon. Instead it should be stored as a FormatListRef: +/// +/// FormatListRef formatList = makeFormatList( /*...*/ ); +template +detail::FormatListN makeFormatList(const Args&... args) { - bodyPrefix - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); - tinyformat::detail::format(fmtIter%(argList)s); - bodySuffix -}''', minParams=0, formatFunc=formatAsMacro) -cog.outl() + return detail::FormatListN(args...); +} -]]]*/ -#define TINYFORMAT_WRAP_FORMAT(returnType, funcName, funcDeclSuffix, \ - bodyPrefix, streamName, bodySuffix) \ -inline \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - ) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3, const T4& v4) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5, v6); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5, v6, v7); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5, v6, v7, v8); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , 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) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5, v6, v7, v8, v9); \ - bodySuffix \ -} \ -template \ -returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \ - , 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) funcDeclSuffix \ -{ \ - bodyPrefix \ - tinyformat::detail::FormatIterator fmtIter(streamName, fmt); \ - tinyformat::detail::format(fmtIter, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); \ - bodySuffix \ -} \ +#else // C++98 version -//[[[end]]] +inline detail::FormatListN<0> makeFormatList() +{ + return detail::FormatListN<0>(); +} +#define TINYFORMAT_MAKE_MAKEFORMATLIST(n) \ +template \ +detail::FormatListN makeFormatList(TINYFORMAT_VARARGS(n)) \ +{ \ + return detail::FormatListN(TINYFORMAT_PASSARGS(n)); \ +} +TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST) +#undef TINYFORMAT_MAKE_MAKEFORMATLIST +#endif + +/// Format list of arguments to the stream according to the given format string. +/// +/// The name vformat() is chosen for the semantic similarity to vprintf(): the +/// list of format arguments is held in a single function argument. +inline void vformat(std::ostream& out, const char* fmt, FormatListRef list) +{ + detail::formatImpl(out, fmt, list.m_formatters, list.m_N); +} -//------------------------------------------------------------------------------ -// Implement all the main interface functions here in terms of detail::format() -// Again, there's two cases. #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES -// C++0x - the simple case +/// Format list of arguments to the stream according to given format string. template void format(std::ostream& out, const char* fmt, const Args&... args) { - detail::FormatIterator fmtIter(out, fmt); - format(fmtIter, args...); + vformat(out, fmt, makeFormatList(args...)); } +/// Format list of arguments according to the given format string and return +/// the result as a string. template std::string format(const char* fmt, const Args&... args) { @@ -984,38 +943,61 @@ std::string format(const char* fmt, const Args&... args) return oss.str(); } +/// Format list of arguments to std::cout, according to the given format string template void printf(const char* fmt, const Args&... args) { format(std::cout, fmt, args...); } -// Define for consistency with C++98 mode -#define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS -#else +#else // C++98 version -// C++98 - define the convenience functions using the wrapping macros +inline void format(std::ostream& out, const char* fmt) +{ + vformat(out, fmt, makeFormatList()); +} -// template -// void format(std::ostream& out, const char* fmt, const Args&... args) -#define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS std::ostream& out, -TINYFORMAT_WRAP_FORMAT(void, format, /*empty*/, /*empty*/, out, /*empty*/) -#undef TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS +inline std::string format(const char* fmt) +{ + std::ostringstream oss; + format(oss, fmt); + return oss.str(); +} -// Define to nothing for format & printf; leave defined for convenience. -#define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS +inline void printf(const char* fmt) +{ + format(std::cout, fmt); +} -// std::string format(const char* fmt, const Args&... args); -TINYFORMAT_WRAP_FORMAT(std::string, format, /*empty*/, - std::ostringstream oss;, oss, - return oss.str();) +#define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \ + \ +template \ +void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \ +{ \ + vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n))); \ +} \ + \ +template \ +std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \ +{ \ + std::ostringstream oss; \ + format(oss, fmt, TINYFORMAT_PASSARGS(n)); \ + return oss.str(); \ +} \ + \ +template \ +void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \ +{ \ + format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \ +} -// void printf(const char* fmt, const Args&... args) -TINYFORMAT_WRAP_FORMAT(void, printf, /*empty*/, /*empty*/, std::cout, /*empty*/) +TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS) +#undef TINYFORMAT_MAKE_FORMAT_FUNCS #endif + } // namespace tinyformat #endif // TINYFORMAT_H_INCLUDED diff --git a/tinyformat_test.cpp b/tinyformat_test.cpp index cd62f02..c1f53ea 100644 --- a/tinyformat_test.cpp +++ b/tinyformat_test.cpp @@ -61,162 +61,6 @@ if(!((a) == (b))) \ ++nfailed; \ } - -// Test wrapping to create our own function which calls through to tfm::format -struct TestWrap -{ - std::ostringstream m_oss; -# undef TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS -# define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS int code, - // std::string error(int code, const char* fmt, const Args&... args); - TINYFORMAT_WRAP_FORMAT(std::string, error, /**/, - m_oss.clear(); m_oss << code << ": ";, - m_oss, - return m_oss.str();) -# undef TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS -# define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS -}; - - -int unitTests() -{ - int nfailed = 0; -# ifdef _MSC_VER - // floats are printed with three digit exponents on windows, which messes - // up the tests. Turn this off for consistency: - _set_output_format(_TWO_DIGIT_EXPONENT); -# endif - // Test various basic format specs against results of sprintf - CHECK_EQUAL(tfm::format("%s", "asdf"), "asdf"); - CHECK_EQUAL(tfm::format("%d", 1234), "1234"); - CHECK_EQUAL(tfm::format("%i", -5678), "-5678"); - CHECK_EQUAL(tfm::format("%o", 012), "12"); - CHECK_EQUAL(tfm::format("%u", 123456u), "123456"); - CHECK_EQUAL(tfm::format("%x", 0xdeadbeef), "deadbeef"); - CHECK_EQUAL(tfm::format("%X", 0xDEADBEEF), "DEADBEEF"); - CHECK_EQUAL(tfm::format("%e", 1.23456e10), "1.234560e+10"); - CHECK_EQUAL(tfm::format("%E", -1.23456E10), "-1.234560E+10"); - CHECK_EQUAL(tfm::format("%f", -9.8765), "-9.876500"); - CHECK_EQUAL(tfm::format("%F", 9.8765), "9.876500"); - CHECK_EQUAL(tfm::format("%g", 10), "10"); - CHECK_EQUAL(tfm::format("%G", 100), "100"); - CHECK_EQUAL(tfm::format("%c", 65), "A"); - CHECK_EQUAL(tfm::format("%hc", (short)65), "A"); - CHECK_EQUAL(tfm::format("%lc", (long)65), "A"); - CHECK_EQUAL(tfm::format("%s", "asdf_123098"), "asdf_123098"); - // Note: All tests printing pointers are different on windows, since - // there's no standard numerical representation. -# ifdef _MSC_VER - CHECK_EQUAL(tfm::format("%p", (void*)0x12345), "00012345"); -# else - CHECK_EQUAL(tfm::format("%p", (void*)0x12345), "0x12345"); -# endif - CHECK_EQUAL(tfm::format("%%%s", "asdf"), "%asdf"); // note: plain "%%" format gives warning with gcc - // chars with int format specs are printed as ints: - CHECK_EQUAL(tfm::format("%hhd", (char)65), "65"); - CHECK_EQUAL(tfm::format("%hhu", (unsigned char)65), "65"); - CHECK_EQUAL(tfm::format("%hhd", (signed char)65), "65"); -# ifdef _MSC_VER - CHECK_EQUAL(tfm::format("%p", (const char*)0x10), "00000010"); -# else - CHECK_EQUAL(tfm::format("%p", (const char*)0x10), "0x10"); // should print address, not string. -# endif - // bools with string format spec are printed as "true" or "false" - CHECK_EQUAL(tfm::format("%s", true), "true"); - CHECK_EQUAL(tfm::format("%d", true), "1"); - - // Test precision & width - CHECK_EQUAL(tfm::format("%10d", -10), " -10"); - CHECK_EQUAL(tfm::format("%.4d", 10), "0010"); - CHECK_EQUAL(tfm::format("%10.4f", 1234.1234567890), " 1234.1235"); - CHECK_EQUAL(tfm::format("%.f", 10.1), "10"); - CHECK_EQUAL(tfm::format("%.2s", "asdf"), "as"); // strings truncate to precision -// // Test variable precision & width - CHECK_EQUAL(tfm::format("%*.4f", 10, 1234.1234567890), " 1234.1235"); - CHECK_EQUAL(tfm::format("%10.*f", 4, 1234.1234567890), " 1234.1235"); - CHECK_EQUAL(tfm::format("%*.*f", 10, 4, 1234.1234567890), " 1234.1235"); - CHECK_EQUAL(tfm::format("%*.*f", -10, 4, 1234.1234567890), "1234.1235 "); - - // Test flags - CHECK_EQUAL(tfm::format("%#x", 0x271828), "0x271828"); - CHECK_EQUAL(tfm::format("%#o", 0x271828), "011614050"); - CHECK_EQUAL(tfm::format("%#f", 3.0), "3.000000"); - CHECK_EQUAL(tfm::format("%010d", 100), "0000000100"); - CHECK_EQUAL(tfm::format("%010d", -10), "-000000010"); // sign should extend - CHECK_EQUAL(tfm::format("%#010X", 0xBEEF), "0X0000BEEF"); - // flag override precedence - CHECK_EQUAL(tfm::format("%+ 10d", 10), " +10"); // '+' overrides ' ' - CHECK_EQUAL(tfm::format("% +10d", 10), " +10"); - CHECK_EQUAL(tfm::format("%-010d", 10), "10 "); // '-' overrides '0' - CHECK_EQUAL(tfm::format("%0-10d", 10), "10 "); - - // Check that length modifiers are ignored - CHECK_EQUAL(tfm::format("%hd", (short)1000), "1000"); - CHECK_EQUAL(tfm::format("%ld", (long)100000), "100000"); - CHECK_EQUAL(tfm::format("%lld", (long long)100000), "100000"); - CHECK_EQUAL(tfm::format("%zd", (size_t)100000), "100000"); - CHECK_EQUAL(tfm::format("%td", (ptrdiff_t)100000), "100000"); - CHECK_EQUAL(tfm::format("%jd", 100000), "100000"); - - // printf incompatibilities: - // compareSprintf("%6.4x", 10); // precision & width can't be supported independently - // compareSprintf("%.4d", -10); // negative numbers + precision don't quite work. - - // General "complicated" format spec test - CHECK_EQUAL(tfm::format("%0.10f:%04d:%+g:%s:%#X:%c:%%:%%asdf", - 1.234, 42, 3.13, "str", 0XDEAD, (int)'X'), - "1.2340000000:0042:+3.13:str:0XDEAD:X:%:%asdf"); - // Test wrong number of args - EXPECT_ERROR( - tfm::format("%d", 5, 10) - ) - EXPECT_ERROR( - tfm::format("%d") - ) - // Unterminated format spec - EXPECT_ERROR( - tfm::format("%123", 10) - ) - // Types used to specify variable width/precision must be convertible to int. - EXPECT_ERROR( - tfm::format("%0*d", "thing that can't convert to int", 42) - ) - EXPECT_ERROR( - tfm::format("%0.*d", "thing that can't convert to int", 42) - ) - - // Unhandled C99 format spec - EXPECT_ERROR( - tfm::format("%n", 10) - ) - EXPECT_ERROR( - tfm::format("%a", 10) - ) - EXPECT_ERROR( - tfm::format("%A", 10) - ) - -#ifdef TEST_WCHAR_T_COMPILE - // Test wchar_t handling - should fail to compile! - tfm::format("%ls", L"blah"); -#endif - - // Test that formatting is independent of underlying stream state. - std::ostringstream oss; - oss.width(20); - oss.precision(10); - oss.fill('*'); - oss.setf(std::ios::scientific); - tfm::format(oss, "%f", 10.1234123412341234); - assert(oss.str() == "10.123412"); - - // Test that interface wrapping works correctly - TestWrap wrap; - assert(wrap.error(10, "someformat %s:%d:%d", "asdf", 2, 4) == - "10: someformat asdf:2:4"); - return nfailed; -} - #ifdef FMT_PROFILE # include // Make sure the profiler library is linked in.