1 // Formatting library for C++ - printf tests
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 
8 #include "fmt/printf.h"
9 
10 #include <cctype>
11 #include <climits>
12 #include <cstring>
13 
14 #include "fmt/core.h"
15 #include "gtest-extra.h"
16 #include "util.h"
17 
18 using fmt::format;
19 using fmt::format_error;
20 using fmt::internal::max_value;
21 
22 const unsigned BIG_NUM = INT_MAX + 1u;
23 
24 // Makes format string argument positional.
make_positional(fmt::string_view format)25 static std::string make_positional(fmt::string_view format) {
26   std::string s(format.data(), format.size());
27   s.replace(s.find('%'), 1, "%1$");
28   return s;
29 }
30 
make_positional(fmt::wstring_view format)31 static std::wstring make_positional(fmt::wstring_view format) {
32   std::wstring s(format.data(), format.size());
33   s.replace(s.find(L'%'), 1, L"%1$");
34   return s;
35 }
36 
37 // A wrapper around fmt::sprintf to workaround bogus warnings about invalid
38 // format strings in MSVC.
39 template <typename... Args>
test_sprintf(fmt::string_view format,const Args &...args)40 std::string test_sprintf(fmt::string_view format, const Args&... args) {
41   return fmt::sprintf(format, args...);
42 }
43 template <typename... Args>
test_sprintf(fmt::wstring_view format,const Args &...args)44 std::wstring test_sprintf(fmt::wstring_view format, const Args&... args) {
45   return fmt::sprintf(format, args...);
46 }
47 
48 #define EXPECT_PRINTF(expected_output, format, arg)     \
49   EXPECT_EQ(expected_output, test_sprintf(format, arg)) \
50       << "format: " << format;                          \
51   EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg))
52 
TEST(PrintfTest,NoArgs)53 TEST(PrintfTest, NoArgs) {
54   EXPECT_EQ("test", test_sprintf("test"));
55   EXPECT_EQ(L"test", fmt::sprintf(L"test"));
56 }
57 
TEST(PrintfTest,Escape)58 TEST(PrintfTest, Escape) {
59   EXPECT_EQ("%", test_sprintf("%%"));
60   EXPECT_EQ("before %", test_sprintf("before %%"));
61   EXPECT_EQ("% after", test_sprintf("%% after"));
62   EXPECT_EQ("before % after", test_sprintf("before %% after"));
63   EXPECT_EQ("%s", test_sprintf("%%s"));
64   EXPECT_EQ(L"%", fmt::sprintf(L"%%"));
65   EXPECT_EQ(L"before %", fmt::sprintf(L"before %%"));
66   EXPECT_EQ(L"% after", fmt::sprintf(L"%% after"));
67   EXPECT_EQ(L"before % after", fmt::sprintf(L"before %% after"));
68   EXPECT_EQ(L"%s", fmt::sprintf(L"%%s"));
69 }
70 
TEST(PrintfTest,PositionalArgs)71 TEST(PrintfTest, PositionalArgs) {
72   EXPECT_EQ("42", test_sprintf("%1$d", 42));
73   EXPECT_EQ("before 42", test_sprintf("before %1$d", 42));
74   EXPECT_EQ("42 after", test_sprintf("%1$d after", 42));
75   EXPECT_EQ("before 42 after", test_sprintf("before %1$d after", 42));
76   EXPECT_EQ("answer = 42", test_sprintf("%1$s = %2$d", "answer", 42));
77   EXPECT_EQ("42 is the answer", test_sprintf("%2$d is the %1$s", "answer", 42));
78   EXPECT_EQ("abracadabra", test_sprintf("%1$s%2$s%1$s", "abra", "cad"));
79 }
80 
TEST(PrintfTest,AutomaticArgIndexing)81 TEST(PrintfTest, AutomaticArgIndexing) {
82   EXPECT_EQ("abc", test_sprintf("%c%c%c", 'a', 'b', 'c'));
83 }
84 
TEST(PrintfTest,NumberIsTooBigInArgIndex)85 TEST(PrintfTest, NumberIsTooBigInArgIndex) {
86   EXPECT_THROW_MSG(test_sprintf(format("%{}$", BIG_NUM)), format_error,
87                    "number is too big");
88   EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM)), format_error,
89                    "number is too big");
90 }
91 
TEST(PrintfTest,SwitchArgIndexing)92 TEST(PrintfTest, SwitchArgIndexing) {
93   EXPECT_THROW_MSG(test_sprintf("%1$d%", 1, 2), format_error,
94                    "cannot switch from manual to automatic argument indexing");
95   EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
96                    format_error, "number is too big");
97   EXPECT_THROW_MSG(test_sprintf("%1$d%d", 1, 2), format_error,
98                    "cannot switch from manual to automatic argument indexing");
99 
100   EXPECT_THROW_MSG(test_sprintf("%d%1$", 1, 2), format_error,
101                    "cannot switch from automatic to manual argument indexing");
102   EXPECT_THROW_MSG(test_sprintf(format("%d%{}$d", BIG_NUM), 1, 2), format_error,
103                    "number is too big");
104   EXPECT_THROW_MSG(test_sprintf("%d%1$d", 1, 2), format_error,
105                    "cannot switch from automatic to manual argument indexing");
106 
107   // Indexing errors override width errors.
108   EXPECT_THROW_MSG(test_sprintf(format("%d%1${}d", BIG_NUM), 1, 2),
109                    format_error, "number is too big");
110   EXPECT_THROW_MSG(test_sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
111                    format_error, "number is too big");
112 }
113 
TEST(PrintfTest,InvalidArgIndex)114 TEST(PrintfTest, InvalidArgIndex) {
115   EXPECT_THROW_MSG(test_sprintf("%0$d", 42), format_error,
116                    "argument index out of range");
117   EXPECT_THROW_MSG(test_sprintf("%2$d", 42), format_error,
118                    "argument index out of range");
119   EXPECT_THROW_MSG(test_sprintf(format("%{}$d", INT_MAX), 42), format_error,
120                    "argument index out of range");
121 
122   EXPECT_THROW_MSG(test_sprintf("%2$", 42), format_error,
123                    "argument index out of range");
124   EXPECT_THROW_MSG(test_sprintf(format("%{}$d", BIG_NUM), 42), format_error,
125                    "number is too big");
126 }
127 
TEST(PrintfTest,DefaultAlignRight)128 TEST(PrintfTest, DefaultAlignRight) {
129   EXPECT_PRINTF("   42", "%5d", 42);
130   EXPECT_PRINTF("  abc", "%5s", "abc");
131 }
132 
TEST(PrintfTest,ZeroFlag)133 TEST(PrintfTest, ZeroFlag) {
134   EXPECT_PRINTF("00042", "%05d", 42);
135   EXPECT_PRINTF("-0042", "%05d", -42);
136 
137   EXPECT_PRINTF("00042", "%05d", 42);
138   EXPECT_PRINTF("-0042", "%05d", -42);
139   EXPECT_PRINTF("-004.2", "%06g", -4.2);
140 
141   EXPECT_PRINTF("+00042", "%00+6d", 42);
142 
143   // '0' flag is ignored for non-numeric types.
144   EXPECT_PRINTF("0000x", "%05c", 'x');
145 }
146 
TEST(PrintfTest,PlusFlag)147 TEST(PrintfTest, PlusFlag) {
148   EXPECT_PRINTF("+42", "%+d", 42);
149   EXPECT_PRINTF("-42", "%+d", -42);
150   EXPECT_PRINTF("+0042", "%+05d", 42);
151   EXPECT_PRINTF("+0042", "%0++5d", 42);
152 
153   // '+' flag is ignored for non-numeric types.
154   EXPECT_PRINTF("x", "%+c", 'x');
155 }
156 
TEST(PrintfTest,MinusFlag)157 TEST(PrintfTest, MinusFlag) {
158   EXPECT_PRINTF("abc  ", "%-5s", "abc");
159   EXPECT_PRINTF("abc  ", "%0--5s", "abc");
160 }
161 
TEST(PrintfTest,SpaceFlag)162 TEST(PrintfTest, SpaceFlag) {
163   EXPECT_PRINTF(" 42", "% d", 42);
164   EXPECT_PRINTF("-42", "% d", -42);
165   EXPECT_PRINTF(" 0042", "% 05d", 42);
166   EXPECT_PRINTF(" 0042", "%0  5d", 42);
167 
168   // ' ' flag is ignored for non-numeric types.
169   EXPECT_PRINTF("x", "% c", 'x');
170 }
171 
TEST(PrintfTest,HashFlag)172 TEST(PrintfTest, HashFlag) {
173   EXPECT_PRINTF("042", "%#o", 042);
174   EXPECT_PRINTF(fmt::format("0{:o}", static_cast<unsigned>(-042)), "%#o", -042);
175   EXPECT_PRINTF("0", "%#o", 0);
176 
177   EXPECT_PRINTF("0x42", "%#x", 0x42);
178   EXPECT_PRINTF("0X42", "%#X", 0x42);
179   EXPECT_PRINTF(fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x",
180                 -0x42);
181   EXPECT_PRINTF("0", "%#x", 0);
182 
183   EXPECT_PRINTF("0x0042", "%#06x", 0x42);
184   EXPECT_PRINTF("0x0042", "%0##6x", 0x42);
185 
186   EXPECT_PRINTF("-42.000000", "%#f", -42.0);
187   EXPECT_PRINTF("-42.000000", "%#F", -42.0);
188 
189   char buffer[BUFFER_SIZE];
190   safe_sprintf(buffer, "%#e", -42.0);
191   EXPECT_PRINTF(buffer, "%#e", -42.0);
192   safe_sprintf(buffer, "%#E", -42.0);
193   EXPECT_PRINTF(buffer, "%#E", -42.0);
194 
195   EXPECT_PRINTF("-42.0000", "%#g", -42.0);
196   EXPECT_PRINTF("-42.0000", "%#G", -42.0);
197 
198   safe_sprintf(buffer, "%#a", 16.0);
199   EXPECT_PRINTF(buffer, "%#a", 16.0);
200   safe_sprintf(buffer, "%#A", 16.0);
201   EXPECT_PRINTF(buffer, "%#A", 16.0);
202 
203   // '#' flag is ignored for non-numeric types.
204   EXPECT_PRINTF("x", "%#c", 'x');
205 }
206 
TEST(PrintfTest,Width)207 TEST(PrintfTest, Width) {
208   EXPECT_PRINTF("  abc", "%5s", "abc");
209 
210   // Width cannot be specified twice.
211   EXPECT_THROW_MSG(test_sprintf("%5-5d", 42), format_error,
212                    "invalid type specifier");
213 
214   EXPECT_THROW_MSG(test_sprintf(format("%{}d", BIG_NUM), 42), format_error,
215                    "number is too big");
216   EXPECT_THROW_MSG(test_sprintf(format("%1${}d", BIG_NUM), 42), format_error,
217                    "number is too big");
218 }
219 
TEST(PrintfTest,DynamicWidth)220 TEST(PrintfTest, DynamicWidth) {
221   EXPECT_EQ("   42", test_sprintf("%*d", 5, 42));
222   EXPECT_EQ("42   ", test_sprintf("%*d", -5, 42));
223   EXPECT_THROW_MSG(test_sprintf("%*d", 5.0, 42), format_error,
224                    "width is not integer");
225   EXPECT_THROW_MSG(test_sprintf("%*d"), format_error,
226                    "argument index out of range");
227   EXPECT_THROW_MSG(test_sprintf("%*d", BIG_NUM, 42), format_error,
228                    "number is too big");
229 }
230 
TEST(PrintfTest,IntPrecision)231 TEST(PrintfTest, IntPrecision) {
232   EXPECT_PRINTF("00042", "%.5d", 42);
233   EXPECT_PRINTF("-00042", "%.5d", -42);
234   EXPECT_PRINTF("00042", "%.5x", 0x42);
235   EXPECT_PRINTF("0x00042", "%#.5x", 0x42);
236   EXPECT_PRINTF("00042", "%.5o", 042);
237   EXPECT_PRINTF("00042", "%#.5o", 042);
238 
239   EXPECT_PRINTF("  00042", "%7.5d", 42);
240   EXPECT_PRINTF("  00042", "%7.5x", 0x42);
241   EXPECT_PRINTF("   0x00042", "%#10.5x", 0x42);
242   EXPECT_PRINTF("  00042", "%7.5o", 042);
243   EXPECT_PRINTF("     00042", "%#10.5o", 042);
244 
245   EXPECT_PRINTF("00042  ", "%-7.5d", 42);
246   EXPECT_PRINTF("00042  ", "%-7.5x", 0x42);
247   EXPECT_PRINTF("0x00042   ", "%-#10.5x", 0x42);
248   EXPECT_PRINTF("00042  ", "%-7.5o", 042);
249   EXPECT_PRINTF("00042     ", "%-#10.5o", 042);
250 }
251 
TEST(PrintfTest,FloatPrecision)252 TEST(PrintfTest, FloatPrecision) {
253   char buffer[BUFFER_SIZE];
254   safe_sprintf(buffer, "%.3e", 1234.5678);
255   EXPECT_PRINTF(buffer, "%.3e", 1234.5678);
256   EXPECT_PRINTF("1234.568", "%.3f", 1234.5678);
257   EXPECT_PRINTF("1.23e+03", "%.3g", 1234.5678);
258   safe_sprintf(buffer, "%.3a", 1234.5678);
259   EXPECT_PRINTF(buffer, "%.3a", 1234.5678);
260 }
261 
TEST(PrintfTest,IgnorePrecisionForNonNumericArg)262 TEST(PrintfTest, IgnorePrecisionForNonNumericArg) {
263   EXPECT_PRINTF("abc", "%.5s", "abc");
264 }
265 
TEST(PrintfTest,DynamicPrecision)266 TEST(PrintfTest, DynamicPrecision) {
267   EXPECT_EQ("00042", test_sprintf("%.*d", 5, 42));
268   EXPECT_EQ("42", test_sprintf("%.*d", -5, 42));
269   EXPECT_THROW_MSG(test_sprintf("%.*d", 5.0, 42), format_error,
270                    "precision is not integer");
271   EXPECT_THROW_MSG(test_sprintf("%.*d"), format_error,
272                    "argument index out of range");
273   EXPECT_THROW_MSG(test_sprintf("%.*d", BIG_NUM, 42), format_error,
274                    "number is too big");
275   if (sizeof(long long) != sizeof(int)) {
276     long long prec = static_cast<long long>(INT_MIN) - 1;
277     EXPECT_THROW_MSG(test_sprintf("%.*d", prec, 42), format_error,
278                      "number is too big");
279   }
280 }
281 
282 template <typename T> struct make_signed { typedef T type; };
283 
284 #define SPECIALIZE_MAKE_SIGNED(T, S) \
285   template <> struct make_signed<T> { typedef S type; }
286 
287 SPECIALIZE_MAKE_SIGNED(char, signed char);
288 SPECIALIZE_MAKE_SIGNED(unsigned char, signed char);
289 SPECIALIZE_MAKE_SIGNED(unsigned short, short);
290 SPECIALIZE_MAKE_SIGNED(unsigned, int);
291 SPECIALIZE_MAKE_SIGNED(unsigned long, long);
292 SPECIALIZE_MAKE_SIGNED(unsigned long long, long long);
293 
294 // Test length format specifier ``length_spec``.
295 template <typename T, typename U>
TestLength(const char * length_spec,U value)296 void TestLength(const char* length_spec, U value) {
297   long long signed_value = 0;
298   unsigned long long unsigned_value = 0;
299   // Apply integer promotion to the argument.
300   unsigned long long max = max_value<U>();
301   using fmt::internal::const_check;
302   if (const_check(max <= static_cast<unsigned>(max_value<int>()))) {
303     signed_value = static_cast<int>(value);
304     unsigned_value = static_cast<unsigned long long>(value);
305   } else if (const_check(max <= max_value<unsigned>())) {
306     signed_value = static_cast<unsigned>(value);
307     unsigned_value = static_cast<unsigned long long>(value);
308   }
309   if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) {
310     signed_value = static_cast<long long>(value);
311     unsigned_value = static_cast<unsigned long long>(
312         static_cast<typename std::make_unsigned<unsigned>::type>(value));
313   } else {
314     signed_value = static_cast<typename make_signed<T>::type>(value);
315     unsigned_value = static_cast<typename std::make_unsigned<T>::type>(value);
316   }
317   std::ostringstream os;
318   os << signed_value;
319   EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value);
320   EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value);
321   os.str("");
322   os << unsigned_value;
323   EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value);
324   os.str("");
325   os << std::oct << unsigned_value;
326   EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value);
327   os.str("");
328   os << std::hex << unsigned_value;
329   EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value);
330   os.str("");
331   os << std::hex << std::uppercase << unsigned_value;
332   EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value);
333 }
334 
TestLength(const char * length_spec)335 template <typename T> void TestLength(const char* length_spec) {
336   T min = std::numeric_limits<T>::min(), max = max_value<T>();
337   TestLength<T>(length_spec, 42);
338   TestLength<T>(length_spec, -42);
339   TestLength<T>(length_spec, min);
340   TestLength<T>(length_spec, max);
341   long long long_long_min = std::numeric_limits<long long>::min();
342   if (static_cast<long long>(min) > long_long_min)
343     TestLength<T>(length_spec, static_cast<long long>(min) - 1);
344   unsigned long long long_long_max = max_value<long long>();
345   if (static_cast<unsigned long long>(max) < long_long_max)
346     TestLength<T>(length_spec, static_cast<long long>(max) + 1);
347   TestLength<T>(length_spec, std::numeric_limits<short>::min());
348   TestLength<T>(length_spec, max_value<unsigned short>());
349   TestLength<T>(length_spec, std::numeric_limits<int>::min());
350   TestLength<T>(length_spec, max_value<int>());
351   TestLength<T>(length_spec, std::numeric_limits<unsigned>::min());
352   TestLength<T>(length_spec, max_value<unsigned>());
353   TestLength<T>(length_spec, std::numeric_limits<long long>::min());
354   TestLength<T>(length_spec, max_value<long long>());
355   TestLength<T>(length_spec, std::numeric_limits<unsigned long long>::min());
356   TestLength<T>(length_spec, max_value<unsigned long long>());
357 }
358 
TEST(PrintfTest,Length)359 TEST(PrintfTest, Length) {
360   TestLength<char>("hh");
361   TestLength<signed char>("hh");
362   TestLength<unsigned char>("hh");
363   TestLength<short>("h");
364   TestLength<unsigned short>("h");
365   TestLength<long>("l");
366   TestLength<unsigned long>("l");
367   TestLength<long long>("ll");
368   TestLength<unsigned long long>("ll");
369   TestLength<intmax_t>("j");
370   TestLength<std::size_t>("z");
371   TestLength<std::ptrdiff_t>("t");
372   long double max = max_value<long double>();
373   EXPECT_PRINTF(fmt::format("{:.6}", max), "%g", max);
374   EXPECT_PRINTF(fmt::format("{:.6}", max), "%Lg", max);
375 }
376 
TEST(PrintfTest,Bool)377 TEST(PrintfTest, Bool) {
378   EXPECT_PRINTF("1", "%d", true);
379   EXPECT_PRINTF("true", "%s", true);
380 }
381 
TEST(PrintfTest,Int)382 TEST(PrintfTest, Int) {
383   EXPECT_PRINTF("-42", "%d", -42);
384   EXPECT_PRINTF("-42", "%i", -42);
385   unsigned u = 0 - 42u;
386   EXPECT_PRINTF(fmt::format("{}", u), "%u", -42);
387   EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42);
388   EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42);
389   EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42);
390 }
391 
TEST(PrintfTest,long_long)392 TEST(PrintfTest, long_long) {
393   // fmt::printf allows passing long long arguments to %d without length
394   // specifiers.
395   long long max = max_value<long long>();
396   EXPECT_PRINTF(fmt::format("{}", max), "%d", max);
397 }
398 
TEST(PrintfTest,Float)399 TEST(PrintfTest, Float) {
400   EXPECT_PRINTF("392.650000", "%f", 392.65);
401   EXPECT_PRINTF("392.65", "%.2f", 392.65);
402   EXPECT_PRINTF("392.6", "%.1f", 392.65);
403   EXPECT_PRINTF("393", "%.f", 392.65);
404   EXPECT_PRINTF("392.650000", "%F", 392.65);
405   char buffer[BUFFER_SIZE];
406   safe_sprintf(buffer, "%e", 392.65);
407   EXPECT_PRINTF(buffer, "%e", 392.65);
408   safe_sprintf(buffer, "%E", 392.65);
409   EXPECT_PRINTF(buffer, "%E", 392.65);
410   EXPECT_PRINTF("392.65", "%g", 392.65);
411   EXPECT_PRINTF("392.65", "%G", 392.65);
412   EXPECT_PRINTF("392", "%g", 392.0);
413   EXPECT_PRINTF("392", "%G", 392.0);
414   EXPECT_PRINTF("4.56e-07", "%g", 0.000000456);
415   safe_sprintf(buffer, "%a", -392.65);
416   EXPECT_EQ(buffer, format("{:a}", -392.65));
417   safe_sprintf(buffer, "%A", -392.65);
418   EXPECT_EQ(buffer, format("{:A}", -392.65));
419 }
420 
TEST(PrintfTest,Inf)421 TEST(PrintfTest, Inf) {
422   double inf = std::numeric_limits<double>::infinity();
423   for (const char* type = "fega"; *type; ++type) {
424     EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf);
425     char upper = static_cast<char>(std::toupper(*type));
426     EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf);
427   }
428 }
429 
TEST(PrintfTest,Char)430 TEST(PrintfTest, Char) {
431   EXPECT_PRINTF("x", "%c", 'x');
432   int max = max_value<int>();
433   EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max);
434   // EXPECT_PRINTF("x", "%lc", L'x');
435   EXPECT_PRINTF(L"x", L"%c", L'x');
436   EXPECT_PRINTF(fmt::format(L"{}", static_cast<wchar_t>(max)), L"%c", max);
437 }
438 
TEST(PrintfTest,String)439 TEST(PrintfTest, String) {
440   EXPECT_PRINTF("abc", "%s", "abc");
441   const char* null_str = nullptr;
442   EXPECT_PRINTF("(null)", "%s", null_str);
443   EXPECT_PRINTF("    (null)", "%10s", null_str);
444   EXPECT_PRINTF(L"abc", L"%s", L"abc");
445   const wchar_t* null_wstr = nullptr;
446   EXPECT_PRINTF(L"(null)", L"%s", null_wstr);
447   EXPECT_PRINTF(L"    (null)", L"%10s", null_wstr);
448 }
449 
TEST(PrintfTest,Pointer)450 TEST(PrintfTest, Pointer) {
451   int n;
452   void* p = &n;
453   EXPECT_PRINTF(fmt::format("{}", p), "%p", p);
454   p = nullptr;
455   EXPECT_PRINTF("(nil)", "%p", p);
456   EXPECT_PRINTF("     (nil)", "%10p", p);
457   const char* s = "test";
458   EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s);
459   const char* null_str = nullptr;
460   EXPECT_PRINTF("(nil)", "%p", null_str);
461 
462   p = &n;
463   EXPECT_PRINTF(fmt::format(L"{}", p), L"%p", p);
464   p = nullptr;
465   EXPECT_PRINTF(L"(nil)", L"%p", p);
466   EXPECT_PRINTF(L"     (nil)", L"%10p", p);
467   const wchar_t* w = L"test";
468   EXPECT_PRINTF(fmt::format(L"{:p}", w), L"%p", w);
469   const wchar_t* null_wstr = nullptr;
470   EXPECT_PRINTF(L"(nil)", L"%p", null_wstr);
471 }
472 
TEST(PrintfTest,Location)473 TEST(PrintfTest, Location) {
474   // TODO: test %n
475 }
476 
477 enum test_enum { answer = 42 };
478 
TEST(PrintfTest,Enum)479 TEST(PrintfTest, Enum) {
480   EXPECT_PRINTF("42", "%d", answer);
481   volatile test_enum volatile_enum = answer;
482   EXPECT_PRINTF("42", "%d", volatile_enum);
483 }
484 
485 #if FMT_USE_FCNTL
TEST(PrintfTest,Examples)486 TEST(PrintfTest, Examples) {
487   const char* weekday = "Thursday";
488   const char* month = "August";
489   int day = 21;
490   EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day),
491                "Thursday, 21 August");
492 }
493 
TEST(PrintfTest,PrintfError)494 TEST(PrintfTest, PrintfError) {
495   fmt::file read_end, write_end;
496   fmt::file::pipe(read_end, write_end);
497   int result = fmt::fprintf(read_end.fdopen("r").get(), "test");
498   EXPECT_LT(result, 0);
499 }
500 #endif
501 
TEST(PrintfTest,WideString)502 TEST(PrintfTest, WideString) { EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc")); }
503 
TEST(PrintfTest,PrintfCustom)504 TEST(PrintfTest, PrintfCustom) {
505   // The test is disabled for now because it requires decoupling
506   // fallback_formatter::format from format_context.
507   //EXPECT_EQ("abc", test_sprintf("%s", TestString("abc")));
508 }
509 
TEST(PrintfTest,OStream)510 TEST(PrintfTest, OStream) {
511   std::ostringstream os;
512   int ret = fmt::fprintf(os, "Don't %s!", "panic");
513   EXPECT_EQ("Don't panic!", os.str());
514   EXPECT_EQ(12, ret);
515 }
516 
TEST(PrintfTest,VPrintf)517 TEST(PrintfTest, VPrintf) {
518   fmt::format_arg_store<fmt::printf_context, int> as{42};
519   fmt::basic_format_args<fmt::printf_context> args(as);
520   EXPECT_EQ(fmt::vsprintf("%d", args), "42");
521   EXPECT_WRITE(stdout, fmt::vprintf("%d", args), "42");
522   EXPECT_WRITE(stdout, fmt::vfprintf(stdout, "%d", args), "42");
523   EXPECT_WRITE(stdout, fmt::vfprintf(std::cout, "%d", args), "42");
524 }
525 
526 template <typename... Args>
check_format_string_regression(fmt::string_view s,const Args &...args)527 void check_format_string_regression(fmt::string_view s, const Args&... args) {
528   fmt::sprintf(s, args...);
529 }
530 
TEST(PrintfTest,CheckFormatStringRegression)531 TEST(PrintfTest, CheckFormatStringRegression) {
532   check_format_string_regression("%c%s", 'x', "");
533 }
534 
TEST(PrintfTest,FixedLargeExponent)535 TEST(PrintfTest, FixedLargeExponent) {
536   EXPECT_EQ("1000000000000000000000", fmt::sprintf("%.*f", -13, 1e21));
537 }
538 
TEST(PrintfTest,VSPrintfMakeArgsExample)539 TEST(PrintfTest, VSPrintfMakeArgsExample) {
540   fmt::format_arg_store<fmt::printf_context, int, const char*> as{42,
541                                                                   "something"};
542   fmt::basic_format_args<fmt::printf_context> args(as);
543   EXPECT_EQ("[42] something happened", fmt::vsprintf("[%d] %s happened", args));
544   auto as2 = fmt::make_printf_args(42, "something");
545   fmt::basic_format_args<fmt::printf_context> args2(as2);
546   EXPECT_EQ("[42] something happened",
547             fmt::vsprintf("[%d] %s happened", args2));
548   // The older gcc versions can't cast the return value.
549 #if !defined(__GNUC__) || (__GNUC__ > 4)
550   EXPECT_EQ("[42] something happened",
551             fmt::vsprintf("[%d] %s happened",
552                           {fmt::make_printf_args(42, "something")}));
553 #endif
554 }
555 
TEST(PrintfTest,VSPrintfMakeWArgsExample)556 TEST(PrintfTest, VSPrintfMakeWArgsExample) {
557   fmt::format_arg_store<fmt::wprintf_context, int, const wchar_t*> as{
558       42, L"something"};
559   fmt::basic_format_args<fmt::wprintf_context> args(as);
560   EXPECT_EQ(L"[42] something happened",
561             fmt::vsprintf(L"[%d] %s happened", args));
562   auto as2 = fmt::make_wprintf_args(42, L"something");
563   fmt::basic_format_args<fmt::wprintf_context> args2(as2);
564   EXPECT_EQ(L"[42] something happened",
565             fmt::vsprintf(L"[%d] %s happened", args2));
566   // the older gcc versions can't cast the return value
567 #if !defined(__GNUC__) || (__GNUC__ > 4)
568   EXPECT_EQ(L"[42] something happened",
569             fmt::vsprintf(L"[%d] %s happened",
570                           {fmt::make_wprintf_args(42, L"something")}));
571 #endif
572 }
573 
574 typedef fmt::printf_arg_formatter<fmt::buffer_range<char>> formatter_t;
575 typedef fmt::basic_printf_context<formatter_t::iterator, char> context_t;
576 
577 // A custom printf argument formatter that doesn't print `-` for floating-point
578 // values rounded to 0.
579 class custom_printf_arg_formatter : public formatter_t {
580  public:
581   using formatter_t::iterator;
582 
custom_printf_arg_formatter(formatter_t::iterator iter,formatter_t::format_specs & specs,context_t & ctx)583   custom_printf_arg_formatter(formatter_t::iterator iter,
584                               formatter_t::format_specs& specs, context_t& ctx)
585       : formatter_t(iter, specs, ctx) {}
586 
587   using formatter_t::operator();
588 
589 #if FMT_MSC_VER > 0 && FMT_MSC_VER <= 1804
590   template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
operator ()(T value)591   iterator operator()(T value){
592 #else
593   iterator operator()(double value) {
594 #endif
595       // Comparing a float to 0.0 is safe.
596       if (round(value * pow(10, specs()->precision)) == 0.0) value = 0;
597   return formatter_t::operator()(value);
598 }
599 }
600 ;
601 
602 typedef fmt::basic_format_args<context_t> format_args_t;
603 
custom_vformat(fmt::string_view format_str,format_args_t args)604 std::string custom_vformat(fmt::string_view format_str, format_args_t args) {
605   fmt::memory_buffer buffer;
606   fmt::vprintf<custom_printf_arg_formatter>(buffer, format_str, args);
607   return std::string(buffer.data(), buffer.size());
608 }
609 
610 template <typename... Args>
custom_format(const char * format_str,const Args &...args)611 std::string custom_format(const char* format_str, const Args&... args) {
612   auto va = fmt::make_printf_args(args...);
613   return custom_vformat(format_str, {va});
614 }
615 
TEST(PrintfTest,CustomFormat)616 TEST(PrintfTest, CustomFormat) {
617   EXPECT_EQ("0.00", custom_format("%.2f", -.00001));
618   EXPECT_EQ("0.00", custom_format("%.2f", .00001));
619   EXPECT_EQ("1.00", custom_format("%.2f", 1.00001));
620   EXPECT_EQ("-1.00", custom_format("%.2f", -1.00001));
621 }
622