• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  Formatting library tests.
3 
4  Copyright (c) 2012-2014, Victor Zverovich
5  All rights reserved.
6 
7  Redistribution and use in source and binary forms, with or without
8  modification, are permitted provided that the following conditions are met:
9 
10  1. Redistributions of source code must retain the above copyright notice, this
11     list of conditions and the following disclaimer.
12  2. Redistributions in binary form must reproduce the above copyright notice,
13     this list of conditions and the following disclaimer in the documentation
14     and/or other materials provided with the distribution.
15 
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <cctype>
29 #include <cfloat>
30 #include <climits>
31 #include <clocale>
32 #include <cmath>
33 #include <cstring>
34 #include <memory>
35 #include <stdint.h>
36 
37 #if FMT_USE_TYPE_TRAITS
38 # include <type_traits>
39 #endif
40 
41 #include "gmock/gmock.h"
42 
43 // Test that the library compiles if None is defined to 0 as done by xlib.h.
44 #define None 0
45 
46 struct LocaleMock {
47   static LocaleMock *instance;
48 
49   MOCK_METHOD0(localeconv, lconv *());
50 } *LocaleMock::instance;
51 
52 namespace fmt {
53 namespace std {
54 using namespace ::std;
localeconv()55 lconv *localeconv() {
56   return LocaleMock::instance ?
57         LocaleMock::instance->localeconv() : ::std::localeconv();
58 }
59 }
60 }
61 
62 #include "fmt/format.h"
63 
64 #include "util.h"
65 #include "mock-allocator.h"
66 #include "gtest-extra.h"
67 
68 #undef min
69 #undef max
70 
71 using std::size_t;
72 
73 using fmt::BasicWriter;
74 using fmt::format;
75 using fmt::FormatError;
76 using fmt::StringRef;
77 using fmt::CStringRef;
78 using fmt::MemoryWriter;
79 using fmt::WMemoryWriter;
80 using fmt::pad;
81 
82 namespace {
83 
84 // Format value using the standard library.
85 template <typename Char, typename T>
std_format(const T & value,std::basic_string<Char> & result)86 void std_format(const T &value, std::basic_string<Char> &result) {
87   std::basic_ostringstream<Char> os;
88   os << value;
89   result = os.str();
90 }
91 
92 #ifdef __MINGW32__
93 // Workaround a bug in formatting long double in MinGW.
std_format(long double value,std::string & result)94 void std_format(long double value, std::string &result) {
95   char buffer[100];
96   safe_sprintf(buffer, "%Lg", value);
97   result = buffer;
98 }
std_format(long double value,std::wstring & result)99 void std_format(long double value, std::wstring &result) {
100   wchar_t buffer[100];
101   swprintf(buffer, L"%Lg", value);
102   result = buffer;
103 }
104 #endif
105 
106 // Checks if writing value to BasicWriter<Char> produces the same result
107 // as writing it to std::basic_ostringstream<Char>.
108 template <typename Char, typename T>
check_write(const T & value,const char * type)109 ::testing::AssertionResult check_write(const T &value, const char *type) {
110   std::basic_string<Char> actual =
111       (fmt::BasicMemoryWriter<Char>() << value).str();
112   std::basic_string<Char> expected;
113   std_format(value, expected);
114   if (expected == actual)
115     return ::testing::AssertionSuccess();
116   return ::testing::AssertionFailure()
117       << "Value of: (Writer<" << type << ">() << value).str()\n"
118       << "  Actual: " << actual << "\n"
119       << "Expected: " << expected << "\n";
120 }
121 
122 struct AnyWriteChecker {
123   template <typename T>
operator ()__anon757f6cb70111::AnyWriteChecker124   ::testing::AssertionResult operator()(const char *, const T &value) const {
125     ::testing::AssertionResult result = check_write<char>(value, "char");
126     return result ? check_write<wchar_t>(value, "wchar_t") : result;
127   }
128 };
129 
130 template <typename Char>
131 struct WriteChecker {
132   template <typename T>
operator ()__anon757f6cb70111::WriteChecker133   ::testing::AssertionResult operator()(const char *, const T &value) const {
134     return check_write<Char>(value, "char");
135   }
136 };
137 
138 // Checks if writing value to BasicWriter produces the same result
139 // as writing it to std::ostringstream both for char and wchar_t.
140 #define CHECK_WRITE(value) EXPECT_PRED_FORMAT1(AnyWriteChecker(), value)
141 
142 #define CHECK_WRITE_CHAR(value) \
143   EXPECT_PRED_FORMAT1(WriteChecker<char>(), value)
144 #define CHECK_WRITE_WCHAR(value) \
145   EXPECT_PRED_FORMAT1(WriteChecker<wchar_t>(), value)
146 }  // namespace
147 
TEST(StringRefTest,Ctor)148 TEST(StringRefTest, Ctor) {
149   EXPECT_STREQ("abc", StringRef("abc").data());
150   EXPECT_EQ(3u, StringRef("abc").size());
151 
152   EXPECT_STREQ("defg", StringRef(std::string("defg")).data());
153   EXPECT_EQ(4u, StringRef(std::string("defg")).size());
154 }
155 
TEST(StringRefTest,ConvertToString)156 TEST(StringRefTest, ConvertToString) {
157   std::string s = StringRef("abc").to_string();
158   EXPECT_EQ("abc", s);
159 }
160 
TEST(CStringRefTest,Ctor)161 TEST(CStringRefTest, Ctor) {
162   EXPECT_STREQ("abc", CStringRef("abc").c_str());
163   EXPECT_STREQ("defg", CStringRef(std::string("defg")).c_str());
164 }
165 
166 #if FMT_USE_TYPE_TRAITS
TEST(WriterTest,NotCopyConstructible)167 TEST(WriterTest, NotCopyConstructible) {
168   EXPECT_FALSE(std::is_copy_constructible<BasicWriter<char> >::value);
169 }
170 
TEST(WriterTest,NotCopyAssignable)171 TEST(WriterTest, NotCopyAssignable) {
172   EXPECT_FALSE(std::is_copy_assignable<BasicWriter<char> >::value);
173 }
174 #endif
175 
TEST(WriterTest,Ctor)176 TEST(WriterTest, Ctor) {
177   MemoryWriter w;
178   EXPECT_EQ(0u, w.size());
179   EXPECT_STREQ("", w.c_str());
180   EXPECT_EQ("", w.str());
181 }
182 
183 #if FMT_USE_RVALUE_REFERENCES
184 
check_move_writer(const std::string & str,MemoryWriter & w)185 void check_move_writer(const std::string &str, MemoryWriter &w) {
186   MemoryWriter w2(std::move(w));
187   // Move shouldn't destroy the inline content of the first writer.
188   EXPECT_EQ(str, w.str());
189   EXPECT_EQ(str, w2.str());
190 }
191 
TEST(WriterTest,MoveCtor)192 TEST(WriterTest, MoveCtor) {
193   MemoryWriter w;
194   w << "test";
195   check_move_writer("test", w);
196   // This fills the inline buffer, but doesn't cause dynamic allocation.
197   std::string s;
198   for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i)
199     s += '*';
200   w.clear();
201   w << s;
202   check_move_writer(s, w);
203   const char *inline_buffer_ptr = w.data();
204   // Adding one more character causes the content to move from the inline to
205   // a dynamically allocated buffer.
206   w << '*';
207   MemoryWriter w2(std::move(w));
208   // Move should rip the guts of the first writer.
209   EXPECT_EQ(inline_buffer_ptr, w.data());
210   EXPECT_EQ(s + '*', w2.str());
211 }
212 
CheckMoveAssignWriter(const std::string & str,MemoryWriter & w)213 void CheckMoveAssignWriter(const std::string &str, MemoryWriter &w) {
214   MemoryWriter w2;
215   w2 = std::move(w);
216   // Move shouldn't destroy the inline content of the first writer.
217   EXPECT_EQ(str, w.str());
218   EXPECT_EQ(str, w2.str());
219 }
220 
TEST(WriterTest,MoveAssignment)221 TEST(WriterTest, MoveAssignment) {
222   MemoryWriter w;
223   w << "test";
224   CheckMoveAssignWriter("test", w);
225   // This fills the inline buffer, but doesn't cause dynamic allocation.
226   std::string s;
227   for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i)
228     s += '*';
229   w.clear();
230   w << s;
231   CheckMoveAssignWriter(s, w);
232   const char *inline_buffer_ptr = w.data();
233   // Adding one more character causes the content to move from the inline to
234   // a dynamically allocated buffer.
235   w << '*';
236   MemoryWriter w2;
237   w2 = std::move(w);
238   // Move should rip the guts of the first writer.
239   EXPECT_EQ(inline_buffer_ptr, w.data());
240   EXPECT_EQ(s + '*', w2.str());
241 }
242 
243 #endif  // FMT_USE_RVALUE_REFERENCES
244 
TEST(WriterTest,Allocator)245 TEST(WriterTest, Allocator) {
246   typedef testing::StrictMock< MockAllocator<char> > MockAllocator;
247   typedef AllocatorRef<MockAllocator> TestAllocator;
248   MockAllocator alloc;
249   fmt::BasicMemoryWriter<char, TestAllocator> w((TestAllocator(&alloc)));
250   std::size_t size =
251       static_cast<std::size_t>(1.5 * fmt::internal::INLINE_BUFFER_SIZE);
252   std::vector<char> mem(size);
253   EXPECT_CALL(alloc, allocate(size, 0)).WillOnce(testing::Return(&mem[0]));
254   for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE + 1; ++i)
255     w << '*';
256   EXPECT_CALL(alloc, deallocate(&mem[0], size));
257 }
258 
TEST(WriterTest,Data)259 TEST(WriterTest, Data) {
260   MemoryWriter w;
261   w << 42;
262   EXPECT_EQ("42", std::string(w.data(), w.size()));
263 }
264 
TEST(WriterTest,WriteWithoutArgs)265 TEST(WriterTest, WriteWithoutArgs) {
266   MemoryWriter w;
267   w.write("test");
268   EXPECT_EQ("test", std::string(w.data(), w.size()));
269 }
270 
TEST(WriterTest,WriteInt)271 TEST(WriterTest, WriteInt) {
272   CHECK_WRITE(42);
273   CHECK_WRITE(-42);
274   CHECK_WRITE(static_cast<short>(12));
275   CHECK_WRITE(34u);
276   CHECK_WRITE(std::numeric_limits<int>::min());
277   CHECK_WRITE(std::numeric_limits<int>::max());
278   CHECK_WRITE(std::numeric_limits<unsigned>::max());
279 }
280 
TEST(WriterTest,WriteLong)281 TEST(WriterTest, WriteLong) {
282   CHECK_WRITE(56l);
283   CHECK_WRITE(78ul);
284   CHECK_WRITE(std::numeric_limits<long>::min());
285   CHECK_WRITE(std::numeric_limits<long>::max());
286   CHECK_WRITE(std::numeric_limits<unsigned long>::max());
287 }
288 
TEST(WriterTest,WriteLongLong)289 TEST(WriterTest, WriteLongLong) {
290   CHECK_WRITE(56ll);
291   CHECK_WRITE(78ull);
292   CHECK_WRITE(std::numeric_limits<long long>::min());
293   CHECK_WRITE(std::numeric_limits<long long>::max());
294   CHECK_WRITE(std::numeric_limits<unsigned long long>::max());
295 }
296 
TEST(WriterTest,WriteDouble)297 TEST(WriterTest, WriteDouble) {
298   CHECK_WRITE(4.2);
299   CHECK_WRITE(-4.2);
300   CHECK_WRITE(std::numeric_limits<double>::min());
301   CHECK_WRITE(std::numeric_limits<double>::max());
302 }
303 
TEST(WriterTest,WriteLongDouble)304 TEST(WriterTest, WriteLongDouble) {
305   CHECK_WRITE(4.2l);
306   CHECK_WRITE_CHAR(-4.2l);
307   std::wstring str;
308   std_format(4.2l, str);
309   if (str[0] != '-')
310     CHECK_WRITE_WCHAR(-4.2l);
311   else
312     fmt::print("warning: long double formatting with std::swprintf is broken");
313   CHECK_WRITE(std::numeric_limits<long double>::min());
314   CHECK_WRITE(std::numeric_limits<long double>::max());
315 }
316 
TEST(WriterTest,WriteDoubleAtBufferBoundary)317 TEST(WriterTest, WriteDoubleAtBufferBoundary) {
318   MemoryWriter writer;
319   for (int i = 0; i < 100; ++i)
320     writer << 1.23456789;
321 }
322 
TEST(WriterTest,WriteDoubleWithFilledBuffer)323 TEST(WriterTest, WriteDoubleWithFilledBuffer) {
324   MemoryWriter writer;
325   // Fill the buffer.
326   for (int i = 0; i < fmt::internal::INLINE_BUFFER_SIZE; ++i)
327     writer << ' ';
328   writer << 1.2;
329   EXPECT_STREQ("1.2", writer.c_str() + fmt::internal::INLINE_BUFFER_SIZE);
330 }
331 
TEST(WriterTest,WriteChar)332 TEST(WriterTest, WriteChar) {
333   CHECK_WRITE('a');
334 }
335 
TEST(WriterTest,WriteWideChar)336 TEST(WriterTest, WriteWideChar) {
337   CHECK_WRITE_WCHAR(L'a');
338 }
339 
TEST(WriterTest,WriteString)340 TEST(WriterTest, WriteString) {
341   CHECK_WRITE_CHAR("abc");
342   CHECK_WRITE_WCHAR("abc");
343   // The following line shouldn't compile:
344   //MemoryWriter() << L"abc";
345 }
346 
TEST(WriterTest,WriteWideString)347 TEST(WriterTest, WriteWideString) {
348   CHECK_WRITE_WCHAR(L"abc");
349   // The following line shouldn't compile:
350   //fmt::WMemoryWriter() << "abc";
351 }
352 
TEST(WriterTest,bin)353 TEST(WriterTest, bin) {
354   using fmt::bin;
355   EXPECT_EQ("1100101011111110", (MemoryWriter() << bin(0xcafe)).str());
356   EXPECT_EQ("1011101010111110", (MemoryWriter() << bin(0xbabeu)).str());
357   EXPECT_EQ("1101111010101101", (MemoryWriter() << bin(0xdeadl)).str());
358   EXPECT_EQ("1011111011101111", (MemoryWriter() << bin(0xbeeful)).str());
359   EXPECT_EQ("11001010111111101011101010111110",
360             (MemoryWriter() << bin(0xcafebabell)).str());
361   EXPECT_EQ("11011110101011011011111011101111",
362             (MemoryWriter() << bin(0xdeadbeefull)).str());
363 }
364 
TEST(WriterTest,oct)365 TEST(WriterTest, oct) {
366   using fmt::oct;
367   EXPECT_EQ("12", (MemoryWriter() << oct(static_cast<short>(012))).str());
368   EXPECT_EQ("12", (MemoryWriter() << oct(012)).str());
369   EXPECT_EQ("34", (MemoryWriter() << oct(034u)).str());
370   EXPECT_EQ("56", (MemoryWriter() << oct(056l)).str());
371   EXPECT_EQ("70", (MemoryWriter() << oct(070ul)).str());
372   EXPECT_EQ("1234", (MemoryWriter() << oct(01234ll)).str());
373   EXPECT_EQ("5670", (MemoryWriter() << oct(05670ull)).str());
374 }
375 
TEST(WriterTest,hex)376 TEST(WriterTest, hex) {
377   using fmt::hex;
378   fmt::IntFormatSpec<int, fmt::TypeSpec<'x'> > (*phex)(int value) = hex;
379   phex(42);
380   // This shouldn't compile:
381   //fmt::IntFormatSpec<short, fmt::TypeSpec<'x'> > (*phex2)(short value) = hex;
382 
383   EXPECT_EQ("cafe", (MemoryWriter() << hex(0xcafe)).str());
384   EXPECT_EQ("babe", (MemoryWriter() << hex(0xbabeu)).str());
385   EXPECT_EQ("dead", (MemoryWriter() << hex(0xdeadl)).str());
386   EXPECT_EQ("beef", (MemoryWriter() << hex(0xbeeful)).str());
387   EXPECT_EQ("cafebabe", (MemoryWriter() << hex(0xcafebabell)).str());
388   EXPECT_EQ("deadbeef", (MemoryWriter() << hex(0xdeadbeefull)).str());
389 }
390 
TEST(WriterTest,hexu)391 TEST(WriterTest, hexu) {
392   using fmt::hexu;
393   EXPECT_EQ("CAFE", (MemoryWriter() << hexu(0xcafe)).str());
394   EXPECT_EQ("BABE", (MemoryWriter() << hexu(0xbabeu)).str());
395   EXPECT_EQ("DEAD", (MemoryWriter() << hexu(0xdeadl)).str());
396   EXPECT_EQ("BEEF", (MemoryWriter() << hexu(0xbeeful)).str());
397   EXPECT_EQ("CAFEBABE", (MemoryWriter() << hexu(0xcafebabell)).str());
398   EXPECT_EQ("DEADBEEF", (MemoryWriter() << hexu(0xdeadbeefull)).str());
399 }
400 
401 template <typename Char>
operator <<(BasicWriter<Char> & f,const Date & d)402 BasicWriter<Char> &operator<<(BasicWriter<Char> &f, const Date &d) {
403   return f << d.year() << '-' << d.month() << '-' << d.day();
404 }
405 
406 class ISO8601DateFormatter {
407  const Date *date_;
408 
409 public:
ISO8601DateFormatter(const Date & d)410   ISO8601DateFormatter(const Date &d) : date_(&d) {}
411 
412   template <typename Char>
operator <<(BasicWriter<Char> & w,const ISO8601DateFormatter & d)413   friend BasicWriter<Char> &operator<<(
414       BasicWriter<Char> &w, const ISO8601DateFormatter &d) {
415     return w << pad(d.date_->year(), 4, '0') << '-'
416         << pad(d.date_->month(), 2, '0') << '-' << pad(d.date_->day(), 2, '0');
417   }
418 };
419 
iso8601(const Date & d)420 ISO8601DateFormatter iso8601(const Date &d) { return ISO8601DateFormatter(d); }
421 
TEST(WriterTest,pad)422 TEST(WriterTest, pad) {
423   using fmt::hex;
424   EXPECT_EQ("    cafe", (MemoryWriter() << pad(hex(0xcafe), 8)).str());
425   EXPECT_EQ("    babe", (MemoryWriter() << pad(hex(0xbabeu), 8)).str());
426   EXPECT_EQ("    dead", (MemoryWriter() << pad(hex(0xdeadl), 8)).str());
427   EXPECT_EQ("    beef", (MemoryWriter() << pad(hex(0xbeeful), 8)).str());
428   EXPECT_EQ("    dead", (MemoryWriter() << pad(hex(0xdeadll), 8)).str());
429   EXPECT_EQ("    beef", (MemoryWriter() << pad(hex(0xbeefull), 8)).str());
430 
431   EXPECT_EQ("     11", (MemoryWriter() << pad(11, 7)).str());
432   EXPECT_EQ("     22", (MemoryWriter() << pad(22u, 7)).str());
433   EXPECT_EQ("     33", (MemoryWriter() << pad(33l, 7)).str());
434   EXPECT_EQ("     44", (MemoryWriter() << pad(44ul, 7)).str());
435   EXPECT_EQ("     33", (MemoryWriter() << pad(33ll, 7)).str());
436   EXPECT_EQ("     44", (MemoryWriter() << pad(44ull, 7)).str());
437 
438   MemoryWriter w;
439   w.clear();
440   w << pad(42, 5, '0');
441   EXPECT_EQ("00042", w.str());
442   w.clear();
443   w << Date(2012, 12, 9);
444   EXPECT_EQ("2012-12-9", w.str());
445   w.clear();
446   w << iso8601(Date(2012, 1, 9));
447   EXPECT_EQ("2012-01-09", w.str());
448 }
449 
TEST(WriterTest,PadString)450 TEST(WriterTest, PadString) {
451   EXPECT_EQ("test    ", (MemoryWriter() << pad("test", 8)).str());
452   EXPECT_EQ("test******", (MemoryWriter() << pad("test", 10, '*')).str());
453 }
454 
TEST(WriterTest,PadWString)455 TEST(WriterTest, PadWString) {
456   EXPECT_EQ(L"test    ", (WMemoryWriter() << pad(L"test", 8)).str());
457   EXPECT_EQ(L"test******", (WMemoryWriter() << pad(L"test", 10, '*')).str());
458   EXPECT_EQ(L"test******", (WMemoryWriter() << pad(L"test", 10, L'*')).str());
459 }
460 
TEST(WriterTest,NoConflictWithIOManip)461 TEST(WriterTest, NoConflictWithIOManip) {
462   using namespace std;
463   using namespace fmt;
464   EXPECT_EQ("cafe", (MemoryWriter() << hex(0xcafe)).str());
465   EXPECT_EQ("12", (MemoryWriter() << oct(012)).str());
466 }
467 
TEST(WriterTest,Format)468 TEST(WriterTest, Format) {
469   MemoryWriter w;
470   w.write("part{0}", 1);
471   EXPECT_EQ(strlen("part1"), w.size());
472   EXPECT_STREQ("part1", w.c_str());
473   EXPECT_STREQ("part1", w.data());
474   EXPECT_EQ("part1", w.str());
475   w.write("part{0}", 2);
476   EXPECT_EQ(strlen("part1part2"), w.size());
477   EXPECT_STREQ("part1part2", w.c_str());
478   EXPECT_STREQ("part1part2", w.data());
479   EXPECT_EQ("part1part2", w.str());
480 }
481 
TEST(WriterTest,WWriter)482 TEST(WriterTest, WWriter) {
483   EXPECT_EQ(L"cafe", (fmt::WMemoryWriter() << fmt::hex(0xcafe)).str());
484 }
485 
TEST(ArrayWriterTest,Ctor)486 TEST(ArrayWriterTest, Ctor) {
487   char array[10] = "garbage";
488   fmt::ArrayWriter w(array, sizeof(array));
489   EXPECT_EQ(0u, w.size());
490   EXPECT_STREQ("", w.c_str());
491 }
492 
TEST(ArrayWriterTest,CompileTimeSizeCtor)493 TEST(ArrayWriterTest, CompileTimeSizeCtor) {
494   char array[10] = "garbage";
495   fmt::ArrayWriter w(array);
496   EXPECT_EQ(0u, w.size());
497   EXPECT_STREQ("", w.c_str());
498   w.write("{:10}", 1);
499 }
500 
TEST(ArrayWriterTest,Write)501 TEST(ArrayWriterTest, Write) {
502   char array[10];
503   fmt::ArrayWriter w(array, sizeof(array));
504   w.write("{}", 42);
505   EXPECT_EQ("42", w.str());
506 }
507 
TEST(ArrayWriterTest,BufferOverflow)508 TEST(ArrayWriterTest, BufferOverflow) {
509   char array[10];
510   fmt::ArrayWriter w(array, sizeof(array));
511   w.write("{:10}", 1);
512   EXPECT_THROW_MSG(w.write("{}", 1), std::runtime_error, "buffer overflow");
513 }
514 
TEST(ArrayWriterTest,WChar)515 TEST(ArrayWriterTest, WChar) {
516   wchar_t array[10];
517   fmt::WArrayWriter w(array);
518   w.write(L"{}", 42);
519   EXPECT_EQ(L"42", w.str());
520 }
521 
TEST(FormatterTest,Escape)522 TEST(FormatterTest, Escape) {
523   EXPECT_EQ("{", format("{{"));
524   EXPECT_EQ("before {", format("before {{"));
525   EXPECT_EQ("{ after", format("{{ after"));
526   EXPECT_EQ("before { after", format("before {{ after"));
527 
528   EXPECT_EQ("}", format("}}"));
529   EXPECT_EQ("before }", format("before }}"));
530   EXPECT_EQ("} after", format("}} after"));
531   EXPECT_EQ("before } after", format("before }} after"));
532 
533   EXPECT_EQ("{}", format("{{}}"));
534   EXPECT_EQ("{42}", format("{{{0}}}", 42));
535 }
536 
TEST(FormatterTest,UnmatchedBraces)537 TEST(FormatterTest, UnmatchedBraces) {
538   EXPECT_THROW_MSG(format("{"), FormatError, "invalid format string");
539   EXPECT_THROW_MSG(format("}"), FormatError, "unmatched '}' in format string");
540   EXPECT_THROW_MSG(format("{0{}"), FormatError, "invalid format string");
541 }
542 
TEST(FormatterTest,NoArgs)543 TEST(FormatterTest, NoArgs) {
544   EXPECT_EQ("test", format("test"));
545 }
546 
TEST(FormatterTest,ArgsInDifferentPositions)547 TEST(FormatterTest, ArgsInDifferentPositions) {
548   EXPECT_EQ("42", format("{0}", 42));
549   EXPECT_EQ("before 42", format("before {0}", 42));
550   EXPECT_EQ("42 after", format("{0} after", 42));
551   EXPECT_EQ("before 42 after", format("before {0} after", 42));
552   EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42));
553   EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42));
554   EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
555 }
556 
TEST(FormatterTest,ArgErrors)557 TEST(FormatterTest, ArgErrors) {
558   EXPECT_THROW_MSG(format("{"), FormatError, "invalid format string");
559   EXPECT_THROW_MSG(format("{?}"), FormatError, "invalid format string");
560   EXPECT_THROW_MSG(format("{0"), FormatError, "invalid format string");
561   EXPECT_THROW_MSG(format("{0}"), FormatError, "argument index out of range");
562 
563   char format_str[BUFFER_SIZE];
564   safe_sprintf(format_str, "{%u", INT_MAX);
565   EXPECT_THROW_MSG(format(format_str), FormatError, "invalid format string");
566   safe_sprintf(format_str, "{%u}", INT_MAX);
567   EXPECT_THROW_MSG(format(format_str), FormatError,
568       "argument index out of range");
569 
570   safe_sprintf(format_str, "{%u", INT_MAX + 1u);
571   EXPECT_THROW_MSG(format(format_str), FormatError, "number is too big");
572   safe_sprintf(format_str, "{%u}", INT_MAX + 1u);
573   EXPECT_THROW_MSG(format(format_str), FormatError, "number is too big");
574 }
575 
576 #if FMT_USE_VARIADIC_TEMPLATES
577 template <int N>
578 struct TestFormat {
579   template <typename... Args>
formatTestFormat580   static std::string format(fmt::CStringRef format_str, const Args & ... args) {
581     return TestFormat<N - 1>::format(format_str, N - 1, args...);
582   }
583 };
584 
585 template <>
586 struct TestFormat<0> {
587   template <typename... Args>
formatTestFormat588   static std::string format(fmt::CStringRef format_str, const Args & ... args) {
589     return fmt::format(format_str, args...);
590   }
591 };
592 
TEST(FormatterTest,ManyArgs)593 TEST(FormatterTest, ManyArgs) {
594   EXPECT_EQ("19", TestFormat<20>::format("{19}"));
595   EXPECT_THROW_MSG(TestFormat<20>::format("{20}"),
596                    FormatError, "argument index out of range");
597   EXPECT_THROW_MSG(TestFormat<21>::format("{21}"),
598                    FormatError, "argument index out of range");
599   enum { MAX_PACKED_ARGS = fmt::ArgList::MAX_PACKED_ARGS };
600   std::string format_str = fmt::format("{{{}}}", MAX_PACKED_ARGS + 1);
601   EXPECT_THROW_MSG(TestFormat<MAX_PACKED_ARGS>::format(format_str),
602                    FormatError, "argument index out of range");
603 }
604 #endif
605 
TEST(FormatterTest,NamedArg)606 TEST(FormatterTest, NamedArg) {
607   EXPECT_EQ("1/a/A", format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
608                             fmt::arg("A_", "A"), fmt::arg("_1", 1)));
609   char a = 'A', b = 'B', c = 'C';
610   EXPECT_EQ("BB/AA/CC", format("{1}{b}/{0}{a}/{2}{c}", FMT_CAPTURE(a, b, c)));
611   EXPECT_EQ(" A", format("{a:>2}", FMT_CAPTURE(a)));
612   EXPECT_THROW_MSG(format("{a+}", FMT_CAPTURE(a)), FormatError,
613                    "missing '}' in format string");
614   EXPECT_THROW_MSG(format("{a}"), FormatError, "argument not found");
615   EXPECT_THROW_MSG(format("{d}", FMT_CAPTURE(a, b, c)), FormatError,
616                    "argument not found");
617   EXPECT_THROW_MSG(format("{a}{}", FMT_CAPTURE(a)),
618     FormatError, "cannot switch from manual to automatic argument indexing");
619   EXPECT_THROW_MSG(format("{}{a}", FMT_CAPTURE(a)),
620     FormatError, "cannot switch from automatic to manual argument indexing");
621   EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4)));
622   EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
623   int n = 100;
624   EXPECT_EQ(L"n=100", format(L"n={n}", FMT_CAPTURE_W(n)));
625 }
626 
TEST(FormatterTest,AutoArgIndex)627 TEST(FormatterTest, AutoArgIndex) {
628   EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c'));
629   EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'),
630       FormatError, "cannot switch from manual to automatic argument indexing");
631   EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'),
632       FormatError, "cannot switch from automatic to manual argument indexing");
633   EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2));
634   EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2),
635       FormatError, "cannot switch from manual to automatic argument indexing");
636   EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2),
637       FormatError, "cannot switch from automatic to manual argument indexing");
638   EXPECT_THROW_MSG(format("{}"), FormatError, "argument index out of range");
639 }
640 
TEST(FormatterTest,EmptySpecs)641 TEST(FormatterTest, EmptySpecs) {
642   EXPECT_EQ("42", format("{0:}", 42));
643 }
644 
TEST(FormatterTest,LeftAlign)645 TEST(FormatterTest, LeftAlign) {
646   EXPECT_EQ("42  ", format("{0:<4}", 42));
647   EXPECT_EQ("42  ", format("{0:<4o}", 042));
648   EXPECT_EQ("42  ", format("{0:<4x}", 0x42));
649   EXPECT_EQ("-42  ", format("{0:<5}", -42));
650   EXPECT_EQ("42   ", format("{0:<5}", 42u));
651   EXPECT_EQ("-42  ", format("{0:<5}", -42l));
652   EXPECT_EQ("42   ", format("{0:<5}", 42ul));
653   EXPECT_EQ("-42  ", format("{0:<5}", -42ll));
654   EXPECT_EQ("42   ", format("{0:<5}", 42ull));
655   EXPECT_EQ("-42  ", format("{0:<5}", -42.0));
656   EXPECT_EQ("-42  ", format("{0:<5}", -42.0l));
657   EXPECT_EQ("c    ", format("{0:<5}", 'c'));
658   EXPECT_EQ("abc  ", format("{0:<5}", "abc"));
659   EXPECT_EQ("0xface  ", format("{0:<8}", reinterpret_cast<void*>(0xface)));
660 }
661 
TEST(FormatterTest,RightAlign)662 TEST(FormatterTest, RightAlign) {
663   EXPECT_EQ("  42", format("{0:>4}", 42));
664   EXPECT_EQ("  42", format("{0:>4o}", 042));
665   EXPECT_EQ("  42", format("{0:>4x}", 0x42));
666   EXPECT_EQ("  -42", format("{0:>5}", -42));
667   EXPECT_EQ("   42", format("{0:>5}", 42u));
668   EXPECT_EQ("  -42", format("{0:>5}", -42l));
669   EXPECT_EQ("   42", format("{0:>5}", 42ul));
670   EXPECT_EQ("  -42", format("{0:>5}", -42ll));
671   EXPECT_EQ("   42", format("{0:>5}", 42ull));
672   EXPECT_EQ("  -42", format("{0:>5}", -42.0));
673   EXPECT_EQ("  -42", format("{0:>5}", -42.0l));
674   EXPECT_EQ("    c", format("{0:>5}", 'c'));
675   EXPECT_EQ("  abc", format("{0:>5}", "abc"));
676   EXPECT_EQ("  0xface", format("{0:>8}", reinterpret_cast<void*>(0xface)));
677 }
678 
TEST(FormatterTest,NumericAlign)679 TEST(FormatterTest, NumericAlign) {
680   EXPECT_EQ("  42", format("{0:=4}", 42));
681   EXPECT_EQ("+ 42", format("{0:=+4}", 42));
682   EXPECT_EQ("  42", format("{0:=4o}", 042));
683   EXPECT_EQ("+ 42", format("{0:=+4o}", 042));
684   EXPECT_EQ("  42", format("{0:=4x}", 0x42));
685   EXPECT_EQ("+ 42", format("{0:=+4x}", 0x42));
686   EXPECT_EQ("-  42", format("{0:=5}", -42));
687   EXPECT_EQ("   42", format("{0:=5}", 42u));
688   EXPECT_EQ("-  42", format("{0:=5}", -42l));
689   EXPECT_EQ("   42", format("{0:=5}", 42ul));
690   EXPECT_EQ("-  42", format("{0:=5}", -42ll));
691   EXPECT_EQ("   42", format("{0:=5}", 42ull));
692   EXPECT_EQ("-  42", format("{0:=5}", -42.0));
693   EXPECT_EQ("-  42", format("{0:=5}", -42.0l));
694   EXPECT_THROW_MSG(format("{0:=5", 'c'),
695       FormatError, "missing '}' in format string");
696   EXPECT_THROW_MSG(format("{0:=5}", 'c'),
697       FormatError, "invalid format specifier for char");
698   EXPECT_THROW_MSG(format("{0:=5}", "abc"),
699       FormatError, "format specifier '=' requires numeric argument");
700   EXPECT_THROW_MSG(format("{0:=8}", reinterpret_cast<void*>(0xface)),
701       FormatError, "format specifier '=' requires numeric argument");
702 }
703 
TEST(FormatterTest,CenterAlign)704 TEST(FormatterTest, CenterAlign) {
705   EXPECT_EQ(" 42  ", format("{0:^5}", 42));
706   EXPECT_EQ(" 42  ", format("{0:^5o}", 042));
707   EXPECT_EQ(" 42  ", format("{0:^5x}", 0x42));
708   EXPECT_EQ(" -42 ", format("{0:^5}", -42));
709   EXPECT_EQ(" 42  ", format("{0:^5}", 42u));
710   EXPECT_EQ(" -42 ", format("{0:^5}", -42l));
711   EXPECT_EQ(" 42  ", format("{0:^5}", 42ul));
712   EXPECT_EQ(" -42 ", format("{0:^5}", -42ll));
713   EXPECT_EQ(" 42  ", format("{0:^5}", 42ull));
714   EXPECT_EQ(" -42  ", format("{0:^6}", -42.0));
715   EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l));
716   EXPECT_EQ("  c  ", format("{0:^5}", 'c'));
717   EXPECT_EQ(" abc  ", format("{0:^6}", "abc"));
718   EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface)));
719 }
720 
TEST(FormatterTest,Fill)721 TEST(FormatterTest, Fill) {
722   EXPECT_THROW_MSG(format("{0:{<5}", 'c'),
723       FormatError, "invalid fill character '{'");
724   EXPECT_THROW_MSG(format("{0:{<5}}", 'c'),
725       FormatError, "invalid fill character '{'");
726   EXPECT_EQ("**42", format("{0:*>4}", 42));
727   EXPECT_EQ("**-42", format("{0:*>5}", -42));
728   EXPECT_EQ("***42", format("{0:*>5}", 42u));
729   EXPECT_EQ("**-42", format("{0:*>5}", -42l));
730   EXPECT_EQ("***42", format("{0:*>5}", 42ul));
731   EXPECT_EQ("**-42", format("{0:*>5}", -42ll));
732   EXPECT_EQ("***42", format("{0:*>5}", 42ull));
733   EXPECT_EQ("**-42", format("{0:*>5}", -42.0));
734   EXPECT_EQ("**-42", format("{0:*>5}", -42.0l));
735   EXPECT_EQ("c****", format("{0:*<5}", 'c'));
736   EXPECT_EQ("abc**", format("{0:*<5}", "abc"));
737   EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface)));
738 }
739 
TEST(FormatterTest,PlusSign)740 TEST(FormatterTest, PlusSign) {
741   EXPECT_EQ("+42", format("{0:+}", 42));
742   EXPECT_EQ("-42", format("{0:+}", -42));
743   EXPECT_EQ("+42", format("{0:+}", 42));
744   EXPECT_THROW_MSG(format("{0:+}", 42u),
745       FormatError, "format specifier '+' requires signed argument");
746   EXPECT_EQ("+42", format("{0:+}", 42l));
747   EXPECT_THROW_MSG(format("{0:+}", 42ul),
748       FormatError, "format specifier '+' requires signed argument");
749   EXPECT_EQ("+42", format("{0:+}", 42ll));
750   EXPECT_THROW_MSG(format("{0:+}", 42ull),
751       FormatError, "format specifier '+' requires signed argument");
752   EXPECT_EQ("+42", format("{0:+}", 42.0));
753   EXPECT_EQ("+42", format("{0:+}", 42.0l));
754   EXPECT_THROW_MSG(format("{0:+", 'c'),
755       FormatError, "missing '}' in format string");
756   EXPECT_THROW_MSG(format("{0:+}", 'c'),
757       FormatError, "invalid format specifier for char");
758   EXPECT_THROW_MSG(format("{0:+}", "abc"),
759       FormatError, "format specifier '+' requires numeric argument");
760   EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)),
761       FormatError, "format specifier '+' requires numeric argument");
762 }
763 
TEST(FormatterTest,MinusSign)764 TEST(FormatterTest, MinusSign) {
765   EXPECT_EQ("42", format("{0:-}", 42));
766   EXPECT_EQ("-42", format("{0:-}", -42));
767   EXPECT_EQ("42", format("{0:-}", 42));
768   EXPECT_THROW_MSG(format("{0:-}", 42u),
769       FormatError, "format specifier '-' requires signed argument");
770   EXPECT_EQ("42", format("{0:-}", 42l));
771   EXPECT_THROW_MSG(format("{0:-}", 42ul),
772       FormatError, "format specifier '-' requires signed argument");
773   EXPECT_EQ("42", format("{0:-}", 42ll));
774   EXPECT_THROW_MSG(format("{0:-}", 42ull),
775       FormatError, "format specifier '-' requires signed argument");
776   EXPECT_EQ("42", format("{0:-}", 42.0));
777   EXPECT_EQ("42", format("{0:-}", 42.0l));
778   EXPECT_THROW_MSG(format("{0:-", 'c'),
779       FormatError, "missing '}' in format string");
780   EXPECT_THROW_MSG(format("{0:-}", 'c'),
781       FormatError, "invalid format specifier for char");
782   EXPECT_THROW_MSG(format("{0:-}", "abc"),
783       FormatError, "format specifier '-' requires numeric argument");
784   EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)),
785       FormatError, "format specifier '-' requires numeric argument");
786 }
787 
TEST(FormatterTest,SpaceSign)788 TEST(FormatterTest, SpaceSign) {
789   EXPECT_EQ(" 42", format("{0: }", 42));
790   EXPECT_EQ("-42", format("{0: }", -42));
791   EXPECT_EQ(" 42", format("{0: }", 42));
792   EXPECT_THROW_MSG(format("{0: }", 42u),
793       FormatError, "format specifier ' ' requires signed argument");
794   EXPECT_EQ(" 42", format("{0: }", 42l));
795   EXPECT_THROW_MSG(format("{0: }", 42ul),
796       FormatError, "format specifier ' ' requires signed argument");
797   EXPECT_EQ(" 42", format("{0: }", 42ll));
798   EXPECT_THROW_MSG(format("{0: }", 42ull),
799       FormatError, "format specifier ' ' requires signed argument");
800   EXPECT_EQ(" 42", format("{0: }", 42.0));
801   EXPECT_EQ(" 42", format("{0: }", 42.0l));
802   EXPECT_THROW_MSG(format("{0: ", 'c'),
803       FormatError, "missing '}' in format string");
804   EXPECT_THROW_MSG(format("{0: }", 'c'),
805       FormatError, "invalid format specifier for char");
806   EXPECT_THROW_MSG(format("{0: }", "abc"),
807       FormatError, "format specifier ' ' requires numeric argument");
808   EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)),
809       FormatError, "format specifier ' ' requires numeric argument");
810 }
811 
TEST(FormatterTest,HashFlag)812 TEST(FormatterTest, HashFlag) {
813   EXPECT_EQ("42", format("{0:#}", 42));
814   EXPECT_EQ("-42", format("{0:#}", -42));
815   EXPECT_EQ("0b101010", format("{0:#b}", 42));
816   EXPECT_EQ("0B101010", format("{0:#B}", 42));
817   EXPECT_EQ("-0b101010", format("{0:#b}", -42));
818   EXPECT_EQ("0x42", format("{0:#x}", 0x42));
819   EXPECT_EQ("0X42", format("{0:#X}", 0x42));
820   EXPECT_EQ("-0x42", format("{0:#x}", -0x42));
821   EXPECT_EQ("042", format("{0:#o}", 042));
822   EXPECT_EQ("-042", format("{0:#o}", -042));
823   EXPECT_EQ("42", format("{0:#}", 42u));
824   EXPECT_EQ("0x42", format("{0:#x}", 0x42u));
825   EXPECT_EQ("042", format("{0:#o}", 042u));
826 
827   EXPECT_EQ("-42", format("{0:#}", -42l));
828   EXPECT_EQ("0x42", format("{0:#x}", 0x42l));
829   EXPECT_EQ("-0x42", format("{0:#x}", -0x42l));
830   EXPECT_EQ("042", format("{0:#o}", 042l));
831   EXPECT_EQ("-042", format("{0:#o}", -042l));
832   EXPECT_EQ("42", format("{0:#}", 42ul));
833   EXPECT_EQ("0x42", format("{0:#x}", 0x42ul));
834   EXPECT_EQ("042", format("{0:#o}", 042ul));
835 
836   EXPECT_EQ("-42", format("{0:#}", -42ll));
837   EXPECT_EQ("0x42", format("{0:#x}", 0x42ll));
838   EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll));
839   EXPECT_EQ("042", format("{0:#o}", 042ll));
840   EXPECT_EQ("-042", format("{0:#o}", -042ll));
841   EXPECT_EQ("42", format("{0:#}", 42ull));
842   EXPECT_EQ("0x42", format("{0:#x}", 0x42ull));
843   EXPECT_EQ("042", format("{0:#o}", 042ull));
844 
845   EXPECT_EQ("-42.0000", format("{0:#}", -42.0));
846   EXPECT_EQ("-42.0000", format("{0:#}", -42.0l));
847   EXPECT_THROW_MSG(format("{0:#", 'c'),
848       FormatError, "missing '}' in format string");
849   EXPECT_THROW_MSG(format("{0:#}", 'c'),
850       FormatError, "invalid format specifier for char");
851   EXPECT_THROW_MSG(format("{0:#}", "abc"),
852       FormatError, "format specifier '#' requires numeric argument");
853   EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)),
854       FormatError, "format specifier '#' requires numeric argument");
855 }
856 
TEST(FormatterTest,ZeroFlag)857 TEST(FormatterTest, ZeroFlag) {
858   EXPECT_EQ("42", format("{0:0}", 42));
859   EXPECT_EQ("-0042", format("{0:05}", -42));
860   EXPECT_EQ("00042", format("{0:05}", 42u));
861   EXPECT_EQ("-0042", format("{0:05}", -42l));
862   EXPECT_EQ("00042", format("{0:05}", 42ul));
863   EXPECT_EQ("-0042", format("{0:05}", -42ll));
864   EXPECT_EQ("00042", format("{0:05}", 42ull));
865   EXPECT_EQ("-0042", format("{0:05}", -42.0));
866   EXPECT_EQ("-0042", format("{0:05}", -42.0l));
867   EXPECT_THROW_MSG(format("{0:0", 'c'),
868       FormatError, "missing '}' in format string");
869   EXPECT_THROW_MSG(format("{0:05}", 'c'),
870       FormatError, "invalid format specifier for char");
871   EXPECT_THROW_MSG(format("{0:05}", "abc"),
872       FormatError, "format specifier '0' requires numeric argument");
873   EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)),
874       FormatError, "format specifier '0' requires numeric argument");
875 }
876 
TEST(FormatterTest,Width)877 TEST(FormatterTest, Width) {
878   char format_str[BUFFER_SIZE];
879   safe_sprintf(format_str, "{0:%u", UINT_MAX);
880   increment(format_str + 3);
881   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
882   std::size_t size = std::strlen(format_str);
883   format_str[size] = '}';
884   format_str[size + 1] = 0;
885   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
886 
887   safe_sprintf(format_str, "{0:%u", INT_MAX + 1u);
888   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
889   safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u);
890   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
891   EXPECT_EQ(" -42", format("{0:4}", -42));
892   EXPECT_EQ("   42", format("{0:5}", 42u));
893   EXPECT_EQ("   -42", format("{0:6}", -42l));
894   EXPECT_EQ("     42", format("{0:7}", 42ul));
895   EXPECT_EQ("   -42", format("{0:6}", -42ll));
896   EXPECT_EQ("     42", format("{0:7}", 42ull));
897   EXPECT_EQ("   -1.23", format("{0:8}", -1.23));
898   EXPECT_EQ("    -1.23", format("{0:9}", -1.23l));
899   EXPECT_EQ("    0xcafe", format("{0:10}", reinterpret_cast<void*>(0xcafe)));
900   EXPECT_EQ("x          ", format("{0:11}", 'x'));
901   EXPECT_EQ("str         ", format("{0:12}", "str"));
902 }
903 
TEST(FormatterTest,RuntimeWidth)904 TEST(FormatterTest, RuntimeWidth) {
905   char format_str[BUFFER_SIZE];
906   safe_sprintf(format_str, "{0:{%u", UINT_MAX);
907   increment(format_str + 4);
908   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
909   std::size_t size = std::strlen(format_str);
910   format_str[size] = '}';
911   format_str[size + 1] = 0;
912   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
913   format_str[size + 1] = '}';
914   format_str[size + 2] = 0;
915   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
916 
917   EXPECT_THROW_MSG(format("{0:{", 0),
918       FormatError, "invalid format string");
919   EXPECT_THROW_MSG(format("{0:{}", 0),
920       FormatError, "cannot switch from manual to automatic argument indexing");
921   EXPECT_THROW_MSG(format("{0:{?}}", 0),
922       FormatError, "invalid format string");
923   EXPECT_THROW_MSG(format("{0:{1}}", 0),
924       FormatError, "argument index out of range");
925 
926   EXPECT_THROW_MSG(format("{0:{0:}}", 0),
927       FormatError, "invalid format string");
928 
929   EXPECT_THROW_MSG(format("{0:{1}}", 0, -1),
930       FormatError, "negative width");
931   EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)),
932       FormatError, "number is too big");
933   EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l),
934       FormatError, "negative width");
935   if (fmt::internal::const_check(sizeof(long) > sizeof(int))) {
936     long value = INT_MAX;
937     EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)),
938         FormatError, "number is too big");
939   }
940   EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)),
941       FormatError, "number is too big");
942 
943   EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'),
944       FormatError, "width is not integer");
945   EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0),
946       FormatError, "width is not integer");
947 
948   EXPECT_EQ(" -42", format("{0:{1}}", -42, 4));
949   EXPECT_EQ("   42", format("{0:{1}}", 42u, 5));
950   EXPECT_EQ("   -42", format("{0:{1}}", -42l, 6));
951   EXPECT_EQ("     42", format("{0:{1}}", 42ul, 7));
952   EXPECT_EQ("   -42", format("{0:{1}}", -42ll, 6));
953   EXPECT_EQ("     42", format("{0:{1}}", 42ull, 7));
954   EXPECT_EQ("   -1.23", format("{0:{1}}", -1.23, 8));
955   EXPECT_EQ("    -1.23", format("{0:{1}}", -1.23l, 9));
956   EXPECT_EQ("    0xcafe",
957             format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10));
958   EXPECT_EQ("x          ", format("{0:{1}}", 'x', 11));
959   EXPECT_EQ("str         ", format("{0:{1}}", "str", 12));
960 }
961 
TEST(FormatterTest,Precision)962 TEST(FormatterTest, Precision) {
963   char format_str[BUFFER_SIZE];
964   safe_sprintf(format_str, "{0:.%u", UINT_MAX);
965   increment(format_str + 4);
966   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
967   std::size_t size = std::strlen(format_str);
968   format_str[size] = '}';
969   format_str[size + 1] = 0;
970   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
971 
972   safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u);
973   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
974   safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
975   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
976 
977   EXPECT_THROW_MSG(format("{0:.", 0),
978       FormatError, "missing precision specifier");
979   EXPECT_THROW_MSG(format("{0:.}", 0),
980       FormatError, "missing precision specifier");
981 
982   EXPECT_THROW_MSG(format("{0:.2", 0),
983       FormatError, "precision not allowed in integer format specifier");
984   EXPECT_THROW_MSG(format("{0:.2}", 42),
985       FormatError, "precision not allowed in integer format specifier");
986   EXPECT_THROW_MSG(format("{0:.2f}", 42),
987       FormatError, "precision not allowed in integer format specifier");
988   EXPECT_THROW_MSG(format("{0:.2}", 42u),
989       FormatError, "precision not allowed in integer format specifier");
990   EXPECT_THROW_MSG(format("{0:.2f}", 42u),
991       FormatError, "precision not allowed in integer format specifier");
992   EXPECT_THROW_MSG(format("{0:.2}", 42l),
993       FormatError, "precision not allowed in integer format specifier");
994   EXPECT_THROW_MSG(format("{0:.2f}", 42l),
995       FormatError, "precision not allowed in integer format specifier");
996   EXPECT_THROW_MSG(format("{0:.2}", 42ul),
997       FormatError, "precision not allowed in integer format specifier");
998   EXPECT_THROW_MSG(format("{0:.2f}", 42ul),
999       FormatError, "precision not allowed in integer format specifier");
1000   EXPECT_THROW_MSG(format("{0:.2}", 42ll),
1001       FormatError, "precision not allowed in integer format specifier");
1002   EXPECT_THROW_MSG(format("{0:.2f}", 42ll),
1003       FormatError, "precision not allowed in integer format specifier");
1004   EXPECT_THROW_MSG(format("{0:.2}", 42ull),
1005       FormatError, "precision not allowed in integer format specifier");
1006   EXPECT_THROW_MSG(format("{0:.2f}", 42ull),
1007       FormatError, "precision not allowed in integer format specifier");
1008   EXPECT_THROW_MSG(format("{0:3.0}", 'x'),
1009       FormatError, "precision not allowed in integer format specifier");
1010   EXPECT_EQ("1.2", format("{0:.2}", 1.2345));
1011   EXPECT_EQ("1.2", format("{0:.2}", 1.2345l));
1012 
1013   EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)),
1014       FormatError, "precision not allowed in pointer format specifier");
1015   EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)),
1016       FormatError, "precision not allowed in pointer format specifier");
1017 
1018   EXPECT_EQ("st", format("{0:.2}", "str"));
1019 }
1020 
TEST(FormatterTest,RuntimePrecision)1021 TEST(FormatterTest, RuntimePrecision) {
1022   char format_str[BUFFER_SIZE];
1023   safe_sprintf(format_str, "{0:.{%u", UINT_MAX);
1024   increment(format_str + 5);
1025   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
1026   std::size_t size = std::strlen(format_str);
1027   format_str[size] = '}';
1028   format_str[size + 1] = 0;
1029   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
1030   format_str[size + 1] = '}';
1031   format_str[size + 2] = 0;
1032   EXPECT_THROW_MSG(format(format_str, 0), FormatError, "number is too big");
1033 
1034   EXPECT_THROW_MSG(format("{0:.{", 0),
1035       FormatError, "invalid format string");
1036   EXPECT_THROW_MSG(format("{0:.{}", 0),
1037       FormatError, "cannot switch from manual to automatic argument indexing");
1038   EXPECT_THROW_MSG(format("{0:.{?}}", 0),
1039       FormatError, "invalid format string");
1040   EXPECT_THROW_MSG(format("{0:.{1}", 0, 0),
1041       FormatError, "precision not allowed in integer format specifier");
1042   EXPECT_THROW_MSG(format("{0:.{1}}", 0),
1043       FormatError, "argument index out of range");
1044 
1045   EXPECT_THROW_MSG(format("{0:.{0:}}", 0),
1046       FormatError, "invalid format string");
1047 
1048   EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1),
1049       FormatError, "negative precision");
1050   EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)),
1051       FormatError, "number is too big");
1052   EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l),
1053       FormatError, "negative precision");
1054   if (fmt::internal::const_check(sizeof(long) > sizeof(int))) {
1055     long value = INT_MAX;
1056     EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)),
1057         FormatError, "number is too big");
1058   }
1059   EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)),
1060       FormatError, "number is too big");
1061 
1062   EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'),
1063       FormatError, "precision is not integer");
1064   EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0),
1065       FormatError, "precision is not integer");
1066 
1067   EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2),
1068       FormatError, "precision not allowed in integer format specifier");
1069   EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2),
1070       FormatError, "precision not allowed in integer format specifier");
1071   EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2),
1072       FormatError, "precision not allowed in integer format specifier");
1073   EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2),
1074       FormatError, "precision not allowed in integer format specifier");
1075   EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2),
1076       FormatError, "precision not allowed in integer format specifier");
1077   EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2),
1078       FormatError, "precision not allowed in integer format specifier");
1079   EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2),
1080       FormatError, "precision not allowed in integer format specifier");
1081   EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2),
1082       FormatError, "precision not allowed in integer format specifier");
1083   EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2),
1084       FormatError, "precision not allowed in integer format specifier");
1085   EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2),
1086       FormatError, "precision not allowed in integer format specifier");
1087   EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2),
1088       FormatError, "precision not allowed in integer format specifier");
1089   EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2),
1090       FormatError, "precision not allowed in integer format specifier");
1091   EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0),
1092       FormatError, "precision not allowed in integer format specifier");
1093   EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2));
1094   EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l));
1095 
1096   EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2),
1097       FormatError, "precision not allowed in pointer format specifier");
1098   EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2),
1099       FormatError, "precision not allowed in pointer format specifier");
1100 
1101   EXPECT_EQ("st", format("{0:.{1}}", "str", 2));
1102 }
1103 
1104 template <typename T>
check_unknown_types(const T & value,const char * types,const char * type_name)1105 void check_unknown_types(
1106     const T &value, const char *types, const char *type_name) {
1107   char format_str[BUFFER_SIZE], message[BUFFER_SIZE];
1108   const char *special = ".0123456789}";
1109   for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
1110     char c = static_cast<char>(i);
1111     if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
1112     safe_sprintf(format_str, "{0:10%c}", c);
1113     if (std::isprint(static_cast<unsigned char>(c))) {
1114       safe_sprintf(message, "unknown format code '%c' for %s", c, type_name);
1115     } else {
1116       safe_sprintf(message, "unknown format code '\\x%02x' for %s", c,
1117                    type_name);
1118     }
1119     EXPECT_THROW_MSG(format(format_str, value), FormatError, message)
1120       << format_str << " " << message;
1121   }
1122 }
1123 
TEST(BoolTest,FormatBool)1124 TEST(BoolTest, FormatBool) {
1125   EXPECT_EQ("true", format("{}", true));
1126   EXPECT_EQ("false", format("{}", false));
1127   EXPECT_EQ("1", format("{:d}", true));
1128   EXPECT_EQ("true ", format("{:5}", true));
1129   EXPECT_EQ(L"true", format(L"{}", true));
1130 }
1131 
TEST(FormatterTest,FormatShort)1132 TEST(FormatterTest, FormatShort) {
1133   short s = 42;
1134   EXPECT_EQ("42", format("{0:d}", s));
1135   unsigned short us = 42;
1136   EXPECT_EQ("42", format("{0:d}", us));
1137 }
1138 
TEST(FormatterTest,FormatInt)1139 TEST(FormatterTest, FormatInt) {
1140   EXPECT_THROW_MSG(format("{0:v", 42),
1141       FormatError, "missing '}' in format string");
1142   check_unknown_types(42, "bBdoxXn", "integer");
1143 }
1144 
TEST(FormatterTest,FormatBin)1145 TEST(FormatterTest, FormatBin) {
1146   EXPECT_EQ("0", format("{0:b}", 0));
1147   EXPECT_EQ("101010", format("{0:b}", 42));
1148   EXPECT_EQ("101010", format("{0:b}", 42u));
1149   EXPECT_EQ("-101010", format("{0:b}", -42));
1150   EXPECT_EQ("11000000111001", format("{0:b}", 12345));
1151   EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678));
1152   EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF));
1153   EXPECT_EQ("11111111111111111111111111111111",
1154             format("{0:b}", std::numeric_limits<uint32_t>::max()));
1155 }
1156 
TEST(FormatterTest,FormatDec)1157 TEST(FormatterTest, FormatDec) {
1158   EXPECT_EQ("0", format("{0}", 0));
1159   EXPECT_EQ("42", format("{0}", 42));
1160   EXPECT_EQ("42", format("{0:d}", 42));
1161   EXPECT_EQ("42", format("{0}", 42u));
1162   EXPECT_EQ("-42", format("{0}", -42));
1163   EXPECT_EQ("12345", format("{0}", 12345));
1164   EXPECT_EQ("67890", format("{0}", 67890));
1165   char buffer[BUFFER_SIZE];
1166   safe_sprintf(buffer, "%d", INT_MIN);
1167   EXPECT_EQ(buffer, format("{0}", INT_MIN));
1168   safe_sprintf(buffer, "%d", INT_MAX);
1169   EXPECT_EQ(buffer, format("{0}", INT_MAX));
1170   safe_sprintf(buffer, "%u", UINT_MAX);
1171   EXPECT_EQ(buffer, format("{0}", UINT_MAX));
1172   safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN));
1173   EXPECT_EQ(buffer, format("{0}", LONG_MIN));
1174   safe_sprintf(buffer, "%ld", LONG_MAX);
1175   EXPECT_EQ(buffer, format("{0}", LONG_MAX));
1176   safe_sprintf(buffer, "%lu", ULONG_MAX);
1177   EXPECT_EQ(buffer, format("{0}", ULONG_MAX));
1178 }
1179 
TEST(FormatterTest,FormatHex)1180 TEST(FormatterTest, FormatHex) {
1181   EXPECT_EQ("0", format("{0:x}", 0));
1182   EXPECT_EQ("42", format("{0:x}", 0x42));
1183   EXPECT_EQ("42", format("{0:x}", 0x42u));
1184   EXPECT_EQ("-42", format("{0:x}", -0x42));
1185   EXPECT_EQ("12345678", format("{0:x}", 0x12345678));
1186   EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef));
1187   EXPECT_EQ("12345678", format("{0:X}", 0x12345678));
1188   EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF));
1189 
1190   char buffer[BUFFER_SIZE];
1191   safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN));
1192   EXPECT_EQ(buffer, format("{0:x}", INT_MIN));
1193   safe_sprintf(buffer, "%x", INT_MAX);
1194   EXPECT_EQ(buffer, format("{0:x}", INT_MAX));
1195   safe_sprintf(buffer, "%x", UINT_MAX);
1196   EXPECT_EQ(buffer, format("{0:x}", UINT_MAX));
1197   safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN));
1198   EXPECT_EQ(buffer, format("{0:x}", LONG_MIN));
1199   safe_sprintf(buffer, "%lx", LONG_MAX);
1200   EXPECT_EQ(buffer, format("{0:x}", LONG_MAX));
1201   safe_sprintf(buffer, "%lx", ULONG_MAX);
1202   EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX));
1203 }
1204 
TEST(FormatterTest,FormatOct)1205 TEST(FormatterTest, FormatOct) {
1206   EXPECT_EQ("0", format("{0:o}", 0));
1207   EXPECT_EQ("42", format("{0:o}", 042));
1208   EXPECT_EQ("42", format("{0:o}", 042u));
1209   EXPECT_EQ("-42", format("{0:o}", -042));
1210   EXPECT_EQ("12345670", format("{0:o}", 012345670));
1211   char buffer[BUFFER_SIZE];
1212   safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN));
1213   EXPECT_EQ(buffer, format("{0:o}", INT_MIN));
1214   safe_sprintf(buffer, "%o", INT_MAX);
1215   EXPECT_EQ(buffer, format("{0:o}", INT_MAX));
1216   safe_sprintf(buffer, "%o", UINT_MAX);
1217   EXPECT_EQ(buffer, format("{0:o}", UINT_MAX));
1218   safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN));
1219   EXPECT_EQ(buffer, format("{0:o}", LONG_MIN));
1220   safe_sprintf(buffer, "%lo", LONG_MAX);
1221   EXPECT_EQ(buffer, format("{0:o}", LONG_MAX));
1222   safe_sprintf(buffer, "%lo", ULONG_MAX);
1223   EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX));
1224 }
1225 
TEST(FormatterTest,FormatIntLocale)1226 TEST(FormatterTest, FormatIntLocale) {
1227   ScopedMock<LocaleMock> mock;
1228   lconv lc = lconv();
1229   char sep[] = "--";
1230   lc.thousands_sep = sep;
1231   EXPECT_CALL(mock, localeconv()).Times(3).WillRepeatedly(testing::Return(&lc));
1232   EXPECT_EQ("123", format("{:n}", 123));
1233   EXPECT_EQ("1--234", format("{:n}", 1234));
1234   EXPECT_EQ("1--234--567", format("{:n}", 1234567));
1235 }
1236 
TEST(FormatterTest,FormatFloat)1237 TEST(FormatterTest, FormatFloat) {
1238   EXPECT_EQ("392.500000", format("{0:f}", 392.5f));
1239 }
1240 
TEST(FormatterTest,FormatDouble)1241 TEST(FormatterTest, FormatDouble) {
1242   check_unknown_types(1.2, "eEfFgGaA", "double");
1243   EXPECT_EQ("0", format("{0:}", 0.0));
1244   EXPECT_EQ("0.000000", format("{0:f}", 0.0));
1245   EXPECT_EQ("392.65", format("{0:}", 392.65));
1246   EXPECT_EQ("392.65", format("{0:g}", 392.65));
1247   EXPECT_EQ("392.65", format("{0:G}", 392.65));
1248   EXPECT_EQ("392.650000", format("{0:f}", 392.65));
1249   EXPECT_EQ("392.650000", format("{0:F}", 392.65));
1250   char buffer[BUFFER_SIZE];
1251   safe_sprintf(buffer, "%e", 392.65);
1252   EXPECT_EQ(buffer, format("{0:e}", 392.65));
1253   safe_sprintf(buffer, "%E", 392.65);
1254   EXPECT_EQ(buffer, format("{0:E}", 392.65));
1255   EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65));
1256   safe_sprintf(buffer, "%a", -42.0);
1257   EXPECT_EQ(buffer, format("{:a}", -42.0));
1258   safe_sprintf(buffer, "%A", -42.0);
1259   EXPECT_EQ(buffer, format("{:A}", -42.0));
1260 }
1261 
TEST(FormatterTest,FormatNaN)1262 TEST(FormatterTest, FormatNaN) {
1263   double nan = std::numeric_limits<double>::quiet_NaN();
1264   EXPECT_EQ("nan", format("{}", nan));
1265   EXPECT_EQ("+nan", format("{:+}", nan));
1266   EXPECT_EQ(" nan", format("{: }", nan));
1267   EXPECT_EQ("NAN", format("{:F}", nan));
1268   EXPECT_EQ("nan    ", format("{:<7}", nan));
1269   EXPECT_EQ("  nan  ", format("{:^7}", nan));
1270   EXPECT_EQ("    nan", format("{:>7}", nan));
1271 }
1272 
TEST(FormatterTest,FormatInfinity)1273 TEST(FormatterTest, FormatInfinity) {
1274   double inf = std::numeric_limits<double>::infinity();
1275   EXPECT_EQ("inf", format("{}", inf));
1276   EXPECT_EQ("+inf", format("{:+}", inf));
1277   EXPECT_EQ("-inf", format("{}", -inf));
1278   EXPECT_EQ(" inf", format("{: }", inf));
1279   EXPECT_EQ("INF", format("{:F}", inf));
1280   EXPECT_EQ("inf    ", format("{:<7}", inf));
1281   EXPECT_EQ("  inf  ", format("{:^7}", inf));
1282   EXPECT_EQ("    inf", format("{:>7}", inf));
1283 }
1284 
TEST(FormatterTest,FormatLongDouble)1285 TEST(FormatterTest, FormatLongDouble) {
1286   EXPECT_EQ("0", format("{0:}", 0.0l));
1287   EXPECT_EQ("0.000000", format("{0:f}", 0.0l));
1288   EXPECT_EQ("392.65", format("{0:}", 392.65l));
1289   EXPECT_EQ("392.65", format("{0:g}", 392.65l));
1290   EXPECT_EQ("392.65", format("{0:G}", 392.65l));
1291   EXPECT_EQ("392.650000", format("{0:f}", 392.65l));
1292   EXPECT_EQ("392.650000", format("{0:F}", 392.65l));
1293   char buffer[BUFFER_SIZE];
1294   safe_sprintf(buffer, "%Le", 392.65l);
1295   EXPECT_EQ(buffer, format("{0:e}", 392.65l));
1296   EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l));
1297 }
1298 
TEST(FormatterTest,FormatChar)1299 TEST(FormatterTest, FormatChar) {
1300   const char types[] = "cbBdoxXn";
1301   check_unknown_types('a', types, "char");
1302   EXPECT_EQ("a", format("{0}", 'a'));
1303   EXPECT_EQ("z", format("{0:c}", 'z'));
1304   EXPECT_EQ(L"a", format(L"{0}", 'a'));
1305   int n = 'x';
1306   for (const char *type = types + 1; *type; ++type) {
1307     std::string format_str = fmt::format("{{:{}}}", *type);
1308     EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x'));
1309   }
1310   EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
1311 }
1312 
TEST(FormatterTest,FormatUnsignedChar)1313 TEST(FormatterTest, FormatUnsignedChar) {
1314   EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42)));
1315   EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42)));
1316 }
1317 
TEST(FormatterTest,FormatWChar)1318 TEST(FormatterTest, FormatWChar) {
1319   EXPECT_EQ(L"a", format(L"{0}", L'a'));
1320   // This shouldn't compile:
1321   //format("{}", L'a');
1322 }
1323 
TEST(FormatterTest,FormatCString)1324 TEST(FormatterTest, FormatCString) {
1325   check_unknown_types("test", "sp", "string");
1326   EXPECT_EQ("test", format("{0}", "test"));
1327   EXPECT_EQ("test", format("{0:s}", "test"));
1328   char nonconst[] = "nonconst";
1329   EXPECT_EQ("nonconst", format("{0}", nonconst));
1330   EXPECT_THROW_MSG(format("{0}", reinterpret_cast<const char*>(0)),
1331       FormatError, "string pointer is null");
1332 }
1333 
TEST(FormatterTest,FormatSCharString)1334 TEST(FormatterTest, FormatSCharString) {
1335   signed char str[] = "test";
1336   EXPECT_EQ("test", format("{0:s}", str));
1337   const signed char *const_str = str;
1338   EXPECT_EQ("test", format("{0:s}", const_str));
1339 }
1340 
TEST(FormatterTest,FormatUCharString)1341 TEST(FormatterTest, FormatUCharString) {
1342   unsigned char str[] = "test";
1343   EXPECT_EQ("test", format("{0:s}", str));
1344   const unsigned char *const_str = str;
1345   EXPECT_EQ("test", format("{0:s}", const_str));
1346   unsigned char *ptr = str;
1347   EXPECT_EQ("test", format("{0:s}", ptr));
1348 }
1349 
TEST(FormatterTest,FormatPointer)1350 TEST(FormatterTest, FormatPointer) {
1351   check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
1352   EXPECT_EQ("0x0", format("{0}", reinterpret_cast<void*>(0)));
1353   EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234)));
1354   EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234)));
1355   EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'),
1356       format("{0}", reinterpret_cast<void*>(~uintptr_t())));
1357 }
1358 
TEST(FormatterTest,FormatString)1359 TEST(FormatterTest, FormatString) {
1360   EXPECT_EQ("test", format("{0}", std::string("test")));
1361 }
1362 
TEST(FormatterTest,FormatStringRef)1363 TEST(FormatterTest, FormatStringRef) {
1364   EXPECT_EQ("test", format("{0}", StringRef("test")));
1365 }
1366 
TEST(FormatterTest,FormatCStringRef)1367 TEST(FormatterTest, FormatCStringRef) {
1368   EXPECT_EQ("test", format("{0}", CStringRef("test")));
1369 }
1370 
format_arg(fmt::BasicFormatter<char> & f,const char *,const Date & d)1371 void format_arg(fmt::BasicFormatter<char> &f, const char *, const Date &d) {
1372   f.writer() << d.year() << '-' << d.month() << '-' << d.day();
1373 }
1374 
TEST(FormatterTest,FormatCustom)1375 TEST(FormatterTest, FormatCustom) {
1376   Date date(2012, 12, 9);
1377   EXPECT_THROW_MSG(fmt::format("{:s}", date), FormatError,
1378                    "unmatched '}' in format string");
1379 }
1380 
1381 class Answer {};
1382 
1383 template <typename Char>
format_arg(fmt::BasicFormatter<Char> & f,const Char *,Answer)1384 void format_arg(fmt::BasicFormatter<Char> &f, const Char *, Answer) {
1385   f.writer() << "42";
1386 }
1387 
TEST(FormatterTest,CustomFormat)1388 TEST(FormatterTest, CustomFormat) {
1389   EXPECT_EQ("42", format("{0}", Answer()));
1390 }
1391 
TEST(FormatterTest,WideFormatString)1392 TEST(FormatterTest, WideFormatString) {
1393   EXPECT_EQ(L"42", format(L"{}", 42));
1394   EXPECT_EQ(L"4.2", format(L"{}", 4.2));
1395   EXPECT_EQ(L"abc", format(L"{}", L"abc"));
1396   EXPECT_EQ(L"z", format(L"{}", L'z'));
1397 }
1398 
TEST(FormatterTest,FormatStringFromSpeedTest)1399 TEST(FormatterTest, FormatStringFromSpeedTest) {
1400   EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
1401       format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%",
1402           1.234, 42, 3.13, "str", reinterpret_cast<void*>(1000), 'X'));
1403 }
1404 
TEST(FormatterTest,FormatExamples)1405 TEST(FormatterTest, FormatExamples) {
1406   using fmt::hex;
1407   EXPECT_EQ("0000cafe", (MemoryWriter() << pad(hex(0xcafe), 8, '0')).str());
1408 
1409   std::string message = format("The answer is {}", 42);
1410   EXPECT_EQ("The answer is 42", message);
1411 
1412   EXPECT_EQ("42", format("{}", 42));
1413   EXPECT_EQ("42", format(std::string("{}"), 42));
1414 
1415   MemoryWriter out;
1416   out << "The answer is " << 42 << "\n";
1417   out.write("({:+f}, {:+f})", -3.14, 3.14);
1418   EXPECT_EQ("The answer is 42\n(-3.140000, +3.140000)", out.str());
1419 
1420   {
1421     MemoryWriter writer;
1422     for (int i = 0; i < 10; i++)
1423       writer.write("{}", i);
1424     std::string s = writer.str(); // s == 0123456789
1425     EXPECT_EQ("0123456789", s);
1426   }
1427 
1428   const char *filename = "nonexistent";
1429   FILE *ftest = safe_fopen(filename, "r");
1430   if (ftest) fclose(ftest);
1431   int error_code = errno;
1432   EXPECT_TRUE(ftest == 0);
1433   EXPECT_SYSTEM_ERROR({
1434     FILE *f = safe_fopen(filename, "r");
1435     if (!f)
1436       throw fmt::SystemError(errno, "Cannot open file '{}'", filename);
1437     fclose(f);
1438   }, error_code, "Cannot open file 'nonexistent'");
1439 }
1440 
TEST(FormatterTest,Examples)1441 TEST(FormatterTest, Examples) {
1442   EXPECT_EQ("First, thou shalt count to three",
1443       format("First, thou shalt count to {0}", "three"));
1444   EXPECT_EQ("Bring me a shrubbery",
1445       format("Bring me a {}", "shrubbery"));
1446   EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3));
1447 
1448   char buffer[BUFFER_SIZE];
1449   safe_sprintf(buffer, "%03.2f", -1.2);
1450   EXPECT_EQ(buffer, format("{:03.2f}", -1.2));
1451 
1452   EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c'));
1453   EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c'));
1454   EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c'));
1455   EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
1456 
1457   EXPECT_EQ("left aligned                  ",
1458       format("{:<30}", "left aligned"));
1459   EXPECT_EQ("                 right aligned",
1460       format("{:>30}", "right aligned"));
1461   EXPECT_EQ("           centered           ",
1462       format("{:^30}", "centered"));
1463   EXPECT_EQ("***********centered***********",
1464       format("{:*^30}", "centered"));
1465 
1466   EXPECT_EQ("+3.140000; -3.140000",
1467       format("{:+f}; {:+f}", 3.14, -3.14));
1468   EXPECT_EQ(" 3.140000; -3.140000",
1469       format("{: f}; {: f}", 3.14, -3.14));
1470   EXPECT_EQ("3.140000; -3.140000",
1471       format("{:-f}; {:-f}", 3.14, -3.14));
1472 
1473   EXPECT_EQ("int: 42;  hex: 2a;  oct: 52",
1474       format("int: {0:d};  hex: {0:x};  oct: {0:o}", 42));
1475   EXPECT_EQ("int: 42;  hex: 0x2a;  oct: 052",
1476       format("int: {0:d};  hex: {0:#x};  oct: {0:#o}", 42));
1477 
1478   EXPECT_EQ("The answer is 42", format("The answer is {}", 42));
1479   EXPECT_THROW_MSG(
1480     format("The answer is {:d}", "forty-two"), FormatError,
1481     "unknown format code 'd' for string");
1482 
1483   EXPECT_EQ(L"Cyrillic letter \x42e",
1484     format(L"Cyrillic letter {}", L'\x42e'));
1485 
1486   EXPECT_WRITE(stdout,
1487       fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
1488 }
1489 
TEST(FormatIntTest,Data)1490 TEST(FormatIntTest, Data) {
1491   fmt::FormatInt format_int(42);
1492   EXPECT_EQ("42", std::string(format_int.data(), format_int.size()));
1493 }
1494 
TEST(FormatIntTest,FormatInt)1495 TEST(FormatIntTest, FormatInt) {
1496   EXPECT_EQ("42", fmt::FormatInt(42).str());
1497   EXPECT_EQ(2u, fmt::FormatInt(42).size());
1498   EXPECT_EQ("-42", fmt::FormatInt(-42).str());
1499   EXPECT_EQ(3u, fmt::FormatInt(-42).size());
1500   EXPECT_EQ("42", fmt::FormatInt(42ul).str());
1501   EXPECT_EQ("-42", fmt::FormatInt(-42l).str());
1502   EXPECT_EQ("42", fmt::FormatInt(42ull).str());
1503   EXPECT_EQ("-42", fmt::FormatInt(-42ll).str());
1504   std::ostringstream os;
1505   os << std::numeric_limits<int64_t>::max();
1506   EXPECT_EQ(os.str(),
1507             fmt::FormatInt(std::numeric_limits<int64_t>::max()).str());
1508 }
1509 
1510 template <typename T>
format_decimal(T value)1511 std::string format_decimal(T value) {
1512   char buffer[10];
1513   char *ptr = buffer;
1514   fmt::format_decimal(ptr, value);
1515   return std::string(buffer, ptr);
1516 }
1517 
TEST(FormatIntTest,FormatDec)1518 TEST(FormatIntTest, FormatDec) {
1519   EXPECT_EQ("-42", format_decimal(static_cast<signed char>(-42)));
1520   EXPECT_EQ("-42", format_decimal(static_cast<short>(-42)));
1521   std::ostringstream os;
1522   os << std::numeric_limits<unsigned short>::max();
1523   EXPECT_EQ(os.str(),
1524             format_decimal(std::numeric_limits<unsigned short>::max()));
1525   EXPECT_EQ("1", format_decimal(1));
1526   EXPECT_EQ("-1", format_decimal(-1));
1527   EXPECT_EQ("42", format_decimal(42));
1528   EXPECT_EQ("-42", format_decimal(-42));
1529   EXPECT_EQ("42", format_decimal(42l));
1530   EXPECT_EQ("42", format_decimal(42ul));
1531   EXPECT_EQ("42", format_decimal(42ll));
1532   EXPECT_EQ("42", format_decimal(42ull));
1533 }
1534 
TEST(FormatTest,Print)1535 TEST(FormatTest, Print) {
1536 #if FMT_USE_FILE_DESCRIPTORS
1537   EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
1538   EXPECT_WRITE(stderr,
1539       fmt::print(stderr, "Don't {}!", "panic"), "Don't panic!");
1540 #endif
1541 }
1542 
1543 #if FMT_USE_FILE_DESCRIPTORS
TEST(FormatTest,PrintColored)1544 TEST(FormatTest, PrintColored) {
1545   EXPECT_WRITE(stdout, fmt::print_colored(fmt::RED, "Hello, {}!\n", "world"),
1546     "\x1b[31mHello, world!\n\x1b[0m");
1547 }
1548 #endif
1549 
TEST(FormatTest,Variadic)1550 TEST(FormatTest, Variadic) {
1551   EXPECT_EQ("abc1", format("{}c{}", "ab", 1));
1552   EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1));
1553 }
1554 
1555 template <typename T>
str(const T & value)1556 std::string str(const T &value) {
1557   return fmt::format("{}", value);
1558 }
1559 
TEST(StrTest,Convert)1560 TEST(StrTest, Convert) {
1561   EXPECT_EQ("42", str(42));
1562   std::string s = str(Date(2012, 12, 9));
1563   EXPECT_EQ("2012-12-9", s);
1564 }
1565 
format_message(int id,const char * format,const fmt::ArgList & args)1566 std::string format_message(int id, const char *format,
1567     const fmt::ArgList &args) {
1568   MemoryWriter w;
1569   w.write("[{}] ", id);
1570   w.write(format, args);
1571   return w.str();
1572 }
1573 
FMT_VARIADIC(std::string,format_message,int,const char *)1574 FMT_VARIADIC(std::string, format_message, int, const char *)
1575 
1576 TEST(FormatTest, FormatMessageExample) {
1577   EXPECT_EQ("[42] something happened",
1578       format_message(42, "{} happened", "something"));
1579 }
1580 
1581 #if FMT_USE_VARIADIC_TEMPLATES
1582 template<typename... Args>
print_error(const char * file,int line,const char * format,const Args &...args)1583 void print_error(const char *file, int line, const char *format,
1584                  const Args & ... args) {
1585   fmt::print("{}: {}: ", file, line);
1586   fmt::print(format, args...);
1587 }
1588 #endif
1589 
TEST(FormatTest,MaxArgs)1590 TEST(FormatTest, MaxArgs) {
1591   EXPECT_EQ("0123456789abcde",
1592             fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}",
1593                         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e'));
1594 }
1595 
1596 #if FMT_USE_USER_DEFINED_LITERALS
1597 // Passing user-defined literals directly to EXPECT_EQ causes problems
1598 // with macro argument stringification (#) on some versions of GCC.
1599 // Workaround: Assing the UDL result to a variable before the macro.
1600 
1601 using namespace fmt::literals;
1602 
TEST(LiteralsTest,Format)1603 TEST(LiteralsTest, Format) {
1604   auto udl_format = "{}c{}"_format("ab", 1);
1605   EXPECT_EQ(format("{}c{}", "ab", 1), udl_format);
1606   auto udl_format_w = L"{}c{}"_format(L"ab", 1);
1607   EXPECT_EQ(format(L"{}c{}", L"ab", 1), udl_format_w);
1608 }
1609 
TEST(LiteralsTest,NamedArg)1610 TEST(LiteralsTest, NamedArg) {
1611   auto udl_a = format("{first}{second}{first}{third}",
1612                       "first"_a="abra", "second"_a="cad", "third"_a=99);
1613   EXPECT_EQ(format("{first}{second}{first}{third}",
1614                    fmt::arg("first", "abra"), fmt::arg("second", "cad"),
1615                    fmt::arg("third", 99)),
1616             udl_a);
1617   auto udl_a_w = format(L"{first}{second}{first}{third}",
1618                         L"first"_a=L"abra", L"second"_a=L"cad", L"third"_a=99);
1619   EXPECT_EQ(format(L"{first}{second}{first}{third}",
1620                    fmt::arg(L"first", L"abra"), fmt::arg(L"second", L"cad"),
1621                    fmt::arg(L"third", 99)),
1622             udl_a_w);
1623 }
1624 #endif // FMT_USE_USER_DEFINED_LITERALS
1625 
1626 enum TestEnum { A };
1627 
TEST(FormatTest,Enum)1628 TEST(FormatTest, Enum) {
1629   EXPECT_EQ("0", fmt::format("{}", A));
1630 }
1631 
1632 class MockArgFormatter :
1633     public fmt::internal::ArgFormatterBase<MockArgFormatter, char> {
1634  public:
1635   typedef fmt::internal::ArgFormatterBase<MockArgFormatter, char> Base;
1636 
MockArgFormatter(fmt::BasicFormatter<char,MockArgFormatter> & f,fmt::FormatSpec & s,const char *)1637   MockArgFormatter(fmt::BasicFormatter<char, MockArgFormatter> &f,
1638                    fmt::FormatSpec &s, const char *)
1639     : fmt::internal::ArgFormatterBase<MockArgFormatter, char>(f.writer(), s) {
1640     EXPECT_CALL(*this, visit_int(42));
1641   }
1642 
1643   MOCK_METHOD1(visit_int, void (int value));
1644 };
1645 
custom_format(const char * format_str,fmt::ArgList args)1646 void custom_format(const char *format_str, fmt::ArgList args) {
1647   fmt::MemoryWriter writer;
1648   fmt::BasicFormatter<char, MockArgFormatter> formatter(args, writer);
1649   formatter.format(format_str);
1650 }
FMT_VARIADIC(void,custom_format,const char *)1651 FMT_VARIADIC(void, custom_format, const char *)
1652 
1653 TEST(FormatTest, CustomArgFormatter) {
1654   custom_format("{}", 42);
1655 }
1656 
1657 void convert(int);
1658 
1659 // Check if there is no collision with convert function in the global namespace.
TEST(FormatTest,ConvertCollision)1660 TEST(FormatTest, ConvertCollision) {
1661   fmt::format("{}", 42);
1662 }
1663 
1664