xref: /aosp_15_r20/external/fmtlib/test/format-test.cc (revision 5c90c05cd622c0a81b57953a4d343e0e489f2e08)
1 // Formatting library for C++ - formatting library 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 // Check if fmt/format.h compiles with windows.h included before it.
9 #ifdef _WIN32
10 #  include <windows.h>
11 #endif
12 // clang-format off
13 #include "fmt/format.h"
14 // clang-format on
15 
16 #include <stdint.h>  // uint32_t
17 
18 #include <cfenv>               // fegetexceptflag and FE_ALL_EXCEPT
19 #include <climits>             // INT_MAX
20 #include <cmath>               // std::signbit
21 #include <condition_variable>  // std::condition_variable
22 #include <cstring>             // std::strlen
23 #include <iterator>            // std::back_inserter
24 #include <list>                // std::list
25 #include <mutex>               // std::mutex
26 #include <string>              // std::string
27 #include <thread>              // std::thread
28 #include <type_traits>         // std::is_default_constructible
29 #if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<version>)
30 #  include <version>
31 #endif
32 
33 #include <limits.h>
34 
35 #include <limits>
36 
37 #include "gtest-extra.h"
38 #include "mock-allocator.h"
39 #include "util.h"
40 using fmt::basic_memory_buffer;
41 using fmt::format_error;
42 using fmt::memory_buffer;
43 using fmt::runtime;
44 using fmt::string_view;
45 using fmt::detail::max_value;
46 using fmt::detail::uint128_fallback;
47 
48 using testing::Return;
49 using testing::StrictMock;
50 
51 #ifdef __cpp_lib_concepts
52 static_assert(std::output_iterator<fmt::appender, char>);
53 #endif
54 
55 enum { buffer_size = 256 };
56 
TEST(uint128_test,ctor)57 TEST(uint128_test, ctor) {
58   auto n = uint128_fallback();
59   EXPECT_EQ(n, 0);
60   n = uint128_fallback(42);
61   EXPECT_EQ(n, 42);
62   EXPECT_EQ(static_cast<uint64_t>(n), 42);
63 }
64 
TEST(uint128_test,shift)65 TEST(uint128_test, shift) {
66   auto n = uint128_fallback(42);
67   n = n << 64;
68   EXPECT_EQ(static_cast<uint64_t>(n), 0);
69   n = n >> 64;
70   EXPECT_EQ(static_cast<uint64_t>(n), 42);
71   n = n << 62;
72   EXPECT_EQ(static_cast<uint64_t>(n >> 64), 0xa);
73   EXPECT_EQ(static_cast<uint64_t>(n), 0x8000000000000000);
74   n = n >> 62;
75   EXPECT_EQ(static_cast<uint64_t>(n), 42);
76   EXPECT_EQ(uint128_fallback(1) << 112, uint128_fallback(0x1000000000000, 0));
77   EXPECT_EQ(uint128_fallback(0x1000000000000, 0) >> 112, uint128_fallback(1));
78 }
79 
TEST(uint128_test,minus)80 TEST(uint128_test, minus) {
81   auto n = uint128_fallback(42);
82   EXPECT_EQ(n - 2, 40);
83 }
84 
TEST(uint128_test,plus_assign)85 TEST(uint128_test, plus_assign) {
86   auto n = uint128_fallback(32);
87   n += uint128_fallback(10);
88   EXPECT_EQ(n, 42);
89   n = uint128_fallback(max_value<uint64_t>());
90   n += uint128_fallback(1);
91   EXPECT_EQ(n, uint128_fallback(1) << 64);
92 }
93 
TEST(uint128_test,multiply)94 TEST(uint128_test, multiply) {
95   auto n = uint128_fallback(2251799813685247);
96   n = n * 3611864890;
97   EXPECT_EQ(static_cast<uint64_t>(n >> 64), 440901);
98 }
99 
check_isfinite()100 template <typename Float> void check_isfinite() {
101   using fmt::detail::isfinite;
102   EXPECT_TRUE(isfinite(Float(0.0)));
103   EXPECT_TRUE(isfinite(Float(42.0)));
104   EXPECT_TRUE(isfinite(Float(-42.0)));
105   EXPECT_TRUE(isfinite(Float(fmt::detail::max_value<double>())));
106   // Use double because std::numeric_limits is broken for __float128.
107   using limits = std::numeric_limits<double>;
108   FMT_CONSTEXPR20 auto result = isfinite(Float(limits::infinity()));
109   EXPECT_FALSE(result);
110   EXPECT_FALSE(isfinite(Float(limits::infinity())));
111   EXPECT_FALSE(isfinite(Float(-limits::infinity())));
112   EXPECT_FALSE(isfinite(Float(limits::quiet_NaN())));
113   EXPECT_FALSE(isfinite(Float(-limits::quiet_NaN())));
114 }
115 
TEST(float_test,isfinite)116 TEST(float_test, isfinite) {
117   check_isfinite<double>();
118 #if FMT_USE_FLOAT128
119   check_isfinite<fmt::detail::float128>();
120 #endif
121 }
122 
check_no_fp_exception()123 void check_no_fp_exception() {
124   fexcept_t fe;
125   fegetexceptflag(&fe, FE_ALL_EXCEPT);
126 
127   // No exception flags should have been set
128   EXPECT_TRUE(fe == 0);
129 }
130 
check_isnan()131 template <typename Float> void check_isnan() {
132   using fmt::detail::isnan;
133   EXPECT_FALSE(isnan(Float(0.0)));
134   EXPECT_FALSE(isnan(Float(42.0)));
135   EXPECT_FALSE(isnan(Float(-42.0)));
136   EXPECT_FALSE(isnan(Float(fmt::detail::max_value<double>())));
137   // Use double because std::numeric_limits is broken for __float128.
138   using limits = std::numeric_limits<double>;
139   EXPECT_FALSE(isnan(Float(limits::infinity())));
140   EXPECT_FALSE(isnan(Float(-limits::infinity())));
141   EXPECT_TRUE(isnan(Float(limits::quiet_NaN())));
142   EXPECT_TRUE(isnan(Float(-limits::quiet_NaN())));
143 
144   // Sanity check: make sure no error has occurred before we start
145   check_no_fp_exception();
146 
147   // Check that no exception is raised for the non-NaN case
148   isnan(Float(42.0));
149   check_no_fp_exception();
150 
151   // Check that no exception is raised for the NaN case
152   isnan(Float(limits::quiet_NaN()));
153   check_no_fp_exception();
154 }
155 
TEST(float_test,isnan)156 TEST(float_test, isnan) {
157   check_isnan<double>();
158 #if FMT_USE_FLOAT128
159   check_isnan<fmt::detail::float128>();
160 #endif
161 }
162 
163 struct uint32_pair {
164   uint32_t u[2];
165 };
166 
TEST(util_test,bit_cast)167 TEST(util_test, bit_cast) {
168   auto s = fmt::detail::bit_cast<uint32_pair>(uint64_t{42});
169   EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), 42ull);
170   s = fmt::detail::bit_cast<uint32_pair>(~uint64_t{0});
171   EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), ~0ull);
172 }
173 
174 // Increment a number in a string.
increment(char * s)175 void increment(char* s) {
176   for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) {
177     if (s[i] != '9') {
178       ++s[i];
179       break;
180     }
181     s[i] = '0';
182   }
183 }
184 
TEST(util_test,increment)185 TEST(util_test, increment) {
186   char s[10] = "123";
187   increment(s);
188   EXPECT_STREQ("124", s);
189   s[2] = '8';
190   increment(s);
191   EXPECT_STREQ("129", s);
192   increment(s);
193   EXPECT_STREQ("130", s);
194   s[1] = s[2] = '9';
195   increment(s);
196   EXPECT_STREQ("200", s);
197 }
198 
TEST(util_test,parse_nonnegative_int)199 TEST(util_test, parse_nonnegative_int) {
200   auto s = fmt::string_view("10000000000");
201   auto begin = s.begin(), end = s.end();
202   EXPECT_EQ(fmt::detail::parse_nonnegative_int(begin, end, -1), -1);
203   s = "2147483649";
204   begin = s.begin();
205   end = s.end();
206   EXPECT_EQ(fmt::detail::parse_nonnegative_int(begin, end, -1), -1);
207 }
208 
TEST(format_impl_test,compute_width)209 TEST(format_impl_test, compute_width) {
210   EXPECT_EQ(fmt::detail::compute_width("вожык"), 5);
211 }
212 
TEST(util_test,utf8_to_utf16)213 TEST(util_test, utf8_to_utf16) {
214   auto u = fmt::detail::utf8_to_utf16("лошадка");
215   EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str());
216   EXPECT_EQ(7, u.size());
217   // U+10437 { DESERET SMALL LETTER YEE }
218   EXPECT_EQ(L"\xD801\xDC37", fmt::detail::utf8_to_utf16("��").str());
219   EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16("\xc3\x28"), std::runtime_error,
220                    "invalid utf8");
221   EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16(fmt::string_view("л", 1)),
222                    std::runtime_error, "invalid utf8");
223   EXPECT_EQ(L"123456", fmt::detail::utf8_to_utf16("123456").str());
224 }
225 
TEST(util_test,utf8_to_utf16_empty_string)226 TEST(util_test, utf8_to_utf16_empty_string) {
227   auto s = std::string();
228   auto u = fmt::detail::utf8_to_utf16(s.c_str());
229   EXPECT_EQ(L"", u.str());
230   EXPECT_EQ(s.size(), u.size());
231 }
232 
TEST(util_test,allocator_ref)233 TEST(util_test, allocator_ref) {
234   using test_allocator_ref = allocator_ref<mock_allocator<int>>;
235   auto check_forwarding = [](mock_allocator<int>& alloc,
236                              test_allocator_ref& ref) {
237     int mem;
238     // Check if value_type is properly defined.
239     allocator_ref<mock_allocator<int>>::value_type* ptr = &mem;
240     // Check forwarding.
241     EXPECT_CALL(alloc, allocate(42)).WillOnce(Return(ptr));
242     ref.allocate(42);
243     EXPECT_CALL(alloc, deallocate(ptr, 42));
244     ref.deallocate(ptr, 42);
245   };
246 
247   StrictMock<mock_allocator<int>> alloc;
248   auto ref = test_allocator_ref(&alloc);
249   // Check if allocator_ref forwards to the underlying allocator.
250   check_forwarding(alloc, ref);
251   test_allocator_ref ref2(ref);
252   check_forwarding(alloc, ref2);
253   test_allocator_ref ref3;
254   EXPECT_EQ(nullptr, ref3.get());
255   ref3 = ref;
256   check_forwarding(alloc, ref3);
257 }
258 
TEST(util_test,format_system_error)259 TEST(util_test, format_system_error) {
260   fmt::memory_buffer message;
261   fmt::format_system_error(message, EDOM, "test");
262   auto ec = std::error_code(EDOM, std::generic_category());
263   EXPECT_EQ(to_string(message), std::system_error(ec, "test").what());
264   message = fmt::memory_buffer();
265 
266   // Check if std::allocator throws on allocating max size_t / 2 chars.
267   size_t max_size = max_value<size_t>() / 2;
268   bool throws_on_alloc = false;
269   try {
270     auto alloc = std::allocator<char>();
271     alloc.deallocate(alloc.allocate(max_size), max_size);
272   } catch (const std::bad_alloc&) {
273     throws_on_alloc = true;
274   }
275   if (!throws_on_alloc) {
276     fmt::print(stderr, "warning: std::allocator allocates {} chars\n",
277                max_size);
278     return;
279   }
280 }
281 
TEST(util_test,system_error)282 TEST(util_test, system_error) {
283   auto test_error = fmt::system_error(EDOM, "test");
284   auto ec = std::error_code(EDOM, std::generic_category());
285   EXPECT_STREQ(test_error.what(), std::system_error(ec, "test").what());
286   EXPECT_EQ(test_error.code(), ec);
287 
288   auto error = std::system_error(std::error_code());
289   try {
290     throw fmt::system_error(EDOM, "test {}", "error");
291   } catch (const std::system_error& e) {
292     error = e;
293   }
294   fmt::memory_buffer message;
295   fmt::format_system_error(message, EDOM, "test error");
296   EXPECT_EQ(error.what(), to_string(message));
297   EXPECT_EQ(error.code(), std::error_code(EDOM, std::generic_category()));
298 }
299 
TEST(util_test,report_system_error)300 TEST(util_test, report_system_error) {
301   fmt::memory_buffer out;
302   fmt::format_system_error(out, EDOM, "test error");
303   out.push_back('\n');
304   EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"),
305                to_string(out));
306 }
307 
TEST(memory_buffer_test,ctor)308 TEST(memory_buffer_test, ctor) {
309   basic_memory_buffer<char, 123> buffer;
310   EXPECT_EQ(static_cast<size_t>(0), buffer.size());
311   EXPECT_EQ(123u, buffer.capacity());
312 }
313 
314 using std_allocator = allocator_ref<std::allocator<char>>;
315 
TEST(memory_buffer_test,move_ctor_inline_buffer)316 TEST(memory_buffer_test, move_ctor_inline_buffer) {
317   auto check_move_buffer =
318       [](const char* str, basic_memory_buffer<char, 5, std_allocator>& buffer) {
319         std::allocator<char>* alloc = buffer.get_allocator().get();
320         basic_memory_buffer<char, 5, std_allocator> buffer2(std::move(buffer));
321         // Move shouldn't destroy the inline content of the first buffer.
322         EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
323         EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
324         EXPECT_EQ(5u, buffer2.capacity());
325         // Move should transfer allocator.
326         EXPECT_EQ(nullptr, buffer.get_allocator().get());
327         EXPECT_EQ(alloc, buffer2.get_allocator().get());
328       };
329 
330   auto alloc = std::allocator<char>();
331   basic_memory_buffer<char, 5, std_allocator> buffer((std_allocator(&alloc)));
332   const char test[] = "test";
333   buffer.append(string_view(test, 4));
334   check_move_buffer("test", buffer);
335   // Adding one more character fills the inline buffer, but doesn't cause
336   // dynamic allocation.
337   buffer.push_back('a');
338   check_move_buffer("testa", buffer);
339 }
340 
TEST(memory_buffer_test,move_ctor_dynamic_buffer)341 TEST(memory_buffer_test, move_ctor_dynamic_buffer) {
342   auto alloc = std::allocator<char>();
343   basic_memory_buffer<char, 4, std_allocator> buffer((std_allocator(&alloc)));
344   const char test[] = "test";
345   buffer.append(test, test + 4);
346   const char* inline_buffer_ptr = &buffer[0];
347   // Adding one more character causes the content to move from the inline to
348   // a dynamically allocated buffer.
349   buffer.push_back('a');
350   basic_memory_buffer<char, 4, std_allocator> buffer2(std::move(buffer));
351   // Move should rip the guts of the first buffer.
352   EXPECT_EQ(&buffer[0], inline_buffer_ptr);
353   EXPECT_EQ(buffer.size(), 0);
354   EXPECT_EQ(std::string(&buffer2[0], buffer2.size()), "testa");
355   EXPECT_GT(buffer2.capacity(), 4u);
356 }
357 
check_move_assign_buffer(const char * str,basic_memory_buffer<char,5> & buffer)358 void check_move_assign_buffer(const char* str,
359                               basic_memory_buffer<char, 5>& buffer) {
360   basic_memory_buffer<char, 5> buffer2;
361   buffer2 = std::move(buffer);
362   // Move shouldn't destroy the inline content of the first buffer.
363   EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
364   EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
365   EXPECT_EQ(5u, buffer2.capacity());
366 }
367 
TEST(memory_buffer_test,move_assignment)368 TEST(memory_buffer_test, move_assignment) {
369   basic_memory_buffer<char, 5> buffer;
370   const char test[] = "test";
371   buffer.append(test, test + 4);
372   check_move_assign_buffer("test", buffer);
373   // Adding one more character fills the inline buffer, but doesn't cause
374   // dynamic allocation.
375   buffer.push_back('a');
376   check_move_assign_buffer("testa", buffer);
377   const char* inline_buffer_ptr = &buffer[0];
378   // Adding one more character causes the content to move from the inline to
379   // a dynamically allocated buffer.
380   buffer.push_back('b');
381   basic_memory_buffer<char, 5> buffer2;
382   buffer2 = std::move(buffer);
383   // Move should rip the guts of the first buffer.
384   EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
385   EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
386   EXPECT_GT(buffer2.capacity(), 5u);
387 }
388 
TEST(memory_buffer_test,grow)389 TEST(memory_buffer_test, grow) {
390   using allocator = allocator_ref<mock_allocator<int>>;
391   mock_allocator<int> alloc;
392   basic_memory_buffer<int, 10, allocator> buffer((allocator(&alloc)));
393   buffer.resize(7);
394   using fmt::detail::to_unsigned;
395   for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i;
396   EXPECT_EQ(10u, buffer.capacity());
397   int mem[20];
398   mem[7] = 0xdead;
399   EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem));
400   buffer.try_reserve(20);
401   EXPECT_EQ(20u, buffer.capacity());
402   // Check if size elements have been copied
403   for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
404   // and no more than that.
405   EXPECT_EQ(0xdead, buffer[7]);
406   EXPECT_CALL(alloc, deallocate(mem, 20));
407 }
408 
TEST(memory_buffer_test,allocator)409 TEST(memory_buffer_test, allocator) {
410   using test_allocator = allocator_ref<mock_allocator<char>>;
411   basic_memory_buffer<char, 10, test_allocator> buffer;
412   EXPECT_EQ(nullptr, buffer.get_allocator().get());
413   StrictMock<mock_allocator<char>> alloc;
414   char mem;
415   {
416     basic_memory_buffer<char, 10, test_allocator> buffer2(
417         (test_allocator(&alloc)));
418     EXPECT_EQ(&alloc, buffer2.get_allocator().get());
419     size_t size = 2 * fmt::inline_buffer_size;
420     EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
421     buffer2.reserve(size);
422     EXPECT_CALL(alloc, deallocate(&mem, size));
423   }
424 }
425 
TEST(memory_buffer_test,exception_in_deallocate)426 TEST(memory_buffer_test, exception_in_deallocate) {
427   using test_allocator = allocator_ref<mock_allocator<char>>;
428   StrictMock<mock_allocator<char>> alloc;
429   basic_memory_buffer<char, 10, test_allocator> buffer(
430       (test_allocator(&alloc)));
431   size_t size = 2 * fmt::inline_buffer_size;
432   auto mem = std::vector<char>(size);
433   {
434     EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0]));
435     buffer.resize(size);
436     std::fill(&buffer[0], &buffer[0] + size, 'x');
437   }
438   auto mem2 = std::vector<char>(2 * size);
439   {
440     EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0]));
441     auto e = std::exception();
442     EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e));
443     EXPECT_THROW(buffer.reserve(2 * size), std::exception);
444     EXPECT_EQ(&mem2[0], &buffer[0]);
445     // Check that the data has been copied.
446     for (size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]);
447   }
448   EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
449 }
450 
451 template <typename Allocator, size_t MaxSize>
452 class max_size_allocator : public Allocator {
453  public:
454   using typename Allocator::value_type;
max_size() const455   size_t max_size() const noexcept { return MaxSize; }
allocate(size_t n)456   value_type* allocate(size_t n) {
457     if (n > max_size()) {
458       throw std::length_error("size > max_size");
459     }
460     return std::allocator_traits<Allocator>::allocate(
461         *static_cast<Allocator*>(this), n);
462   }
deallocate(value_type * p,size_t n)463   void deallocate(value_type* p, size_t n) {
464     std::allocator_traits<Allocator>::deallocate(*static_cast<Allocator*>(this),
465                                                  p, n);
466   }
467 };
468 
TEST(memory_buffer_test,max_size_allocator)469 TEST(memory_buffer_test, max_size_allocator) {
470   // 160 = 128 + 32
471   using test_allocator = max_size_allocator<std::allocator<char>, 160>;
472   basic_memory_buffer<char, 10, test_allocator> buffer;
473   buffer.resize(128);
474   // new_capacity = 128 + 128/2 = 192 > 160
475   buffer.resize(160);  // Shouldn't throw.
476 }
477 
TEST(memory_buffer_test,max_size_allocator_overflow)478 TEST(memory_buffer_test, max_size_allocator_overflow) {
479   using test_allocator = max_size_allocator<std::allocator<char>, 160>;
480   basic_memory_buffer<char, 10, test_allocator> buffer;
481   EXPECT_THROW(buffer.resize(161), std::exception);
482 }
483 
TEST(format_test,digits2_alignment)484 TEST(format_test, digits2_alignment) {
485   auto p =
486       fmt::detail::bit_cast<fmt::detail::uintptr_t>(fmt::detail::digits2(0));
487   EXPECT_EQ(p % 2, 0);
488 }
489 
TEST(format_test,exception_from_lib)490 TEST(format_test, exception_from_lib) {
491   EXPECT_THROW_MSG(fmt::report_error("test"), format_error, "test");
492 }
493 
TEST(format_test,escape)494 TEST(format_test, escape) {
495   EXPECT_EQ(fmt::format("{{"), "{");
496   EXPECT_EQ(fmt::format("before {{"), "before {");
497   EXPECT_EQ(fmt::format("{{ after"), "{ after");
498   EXPECT_EQ(fmt::format("before {{ after"), "before { after");
499 
500   EXPECT_EQ(fmt::format("}}"), "}");
501   EXPECT_EQ(fmt::format("before }}"), "before }");
502   EXPECT_EQ(fmt::format("}} after"), "} after");
503   EXPECT_EQ(fmt::format("before }} after"), "before } after");
504 
505   EXPECT_EQ(fmt::format("{{}}"), "{}");
506   EXPECT_EQ(fmt::format("{{{0}}}", 42), "{42}");
507 }
508 
TEST(format_test,unmatched_braces)509 TEST(format_test, unmatched_braces) {
510   EXPECT_THROW_MSG((void)fmt::format(runtime("{")), format_error,
511                    "invalid format string");
512   EXPECT_THROW_MSG((void)fmt::format(runtime("}")), format_error,
513                    "unmatched '}' in format string");
514   EXPECT_THROW_MSG((void)fmt::format(runtime("{0{}")), format_error,
515                    "invalid format string");
516 }
517 
TEST(format_test,no_args)518 TEST(format_test, no_args) { EXPECT_EQ(fmt::format("test"), "test"); }
519 
TEST(format_test,args_in_different_positions)520 TEST(format_test, args_in_different_positions) {
521   EXPECT_EQ(fmt::format("{0}", 42), "42");
522   EXPECT_EQ(fmt::format("before {0}", 42), "before 42");
523   EXPECT_EQ(fmt::format("{0} after", 42), "42 after");
524   EXPECT_EQ(fmt::format("before {0} after", 42), "before 42 after");
525   EXPECT_EQ(fmt::format("{0} = {1}", "answer", 42), "answer = 42");
526   EXPECT_EQ(fmt::format("{1} is the {0}", "answer", 42), "42 is the answer");
527   EXPECT_EQ(fmt::format("{0}{1}{0}", "abra", "cad"), "abracadabra");
528 }
529 
TEST(format_test,arg_errors)530 TEST(format_test, arg_errors) {
531   EXPECT_THROW_MSG((void)fmt::format(runtime("{")), format_error,
532                    "invalid format string");
533   EXPECT_THROW_MSG((void)fmt::format(runtime("{?}")), format_error,
534                    "invalid format string");
535   EXPECT_THROW_MSG((void)fmt::format(runtime("{0")), format_error,
536                    "invalid format string");
537   EXPECT_THROW_MSG((void)fmt::format(runtime("{0}")), format_error,
538                    "argument not found");
539   EXPECT_THROW_MSG((void)fmt::format(runtime("{00}"), 42), format_error,
540                    "invalid format string");
541 
542   auto int_max = std::to_string(INT_MAX);
543   EXPECT_THROW_MSG((void)fmt::format(runtime("{" + int_max)), format_error,
544                    "invalid format string");
545   EXPECT_THROW_MSG((void)fmt::format(runtime("{" + int_max + "}")),
546                    format_error, "argument not found");
547 
548   auto int_maxer = std::to_string(INT_MAX + 1u);
549   EXPECT_THROW_MSG((void)fmt::format(runtime("{" + int_maxer)), format_error,
550                    "invalid format string");
551   EXPECT_THROW_MSG((void)fmt::format(runtime("{" + int_maxer + "}")),
552                    format_error, "argument not found");
553 }
554 
555 template <int N> struct test_format {
556   template <typename... T>
formattest_format557   static auto format(fmt::string_view fmt, const T&... args) -> std::string {
558     return test_format<N - 1>::format(fmt, N - 1, args...);
559   }
560 };
561 
562 template <> struct test_format<0> {
563   template <typename... T>
formattest_format564   static auto format(fmt::string_view fmt, const T&... args) -> std::string {
565     return fmt::format(runtime(fmt), args...);
566   }
567 };
568 
TEST(format_test,many_args)569 TEST(format_test, many_args) {
570   EXPECT_EQ("19", test_format<20>::format("{19}"));
571   EXPECT_THROW_MSG(test_format<20>::format("{20}"), format_error,
572                    "argument not found");
573   EXPECT_THROW_MSG(test_format<21>::format("{21}"), format_error,
574                    "argument not found");
575   using fmt::detail::max_packed_args;
576   std::string format_str = fmt::format("{{{}}}", max_packed_args + 1);
577   EXPECT_THROW_MSG(test_format<max_packed_args>::format(format_str),
578                    format_error, "argument not found");
579 }
580 
TEST(format_test,named_arg)581 TEST(format_test, named_arg) {
582   EXPECT_EQ("1/a/A", fmt::format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
583                                  fmt::arg("A_", "A"), fmt::arg("_1", 1)));
584   EXPECT_EQ(fmt::format("{0:{width}}", -42, fmt::arg("width", 4)), " -42");
585   EXPECT_EQ("st",
586             fmt::format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
587   EXPECT_EQ(fmt::format("{} {two}", 1, fmt::arg("two", 2)), "1 2");
588   EXPECT_EQ("42",
589             fmt::format("{c}", fmt::arg("a", 0), fmt::arg("b", 0),
590                         fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0),
591                         fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
592                         fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0),
593                         fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0),
594                         fmt::arg("o", 0), fmt::arg("p", 0)));
595   EXPECT_THROW_MSG((void)fmt::format(runtime("{a}")), format_error,
596                    "argument not found");
597   EXPECT_THROW_MSG((void)fmt::format(runtime("{a}"), 42), format_error,
598                    "argument not found");
599   EXPECT_THROW_MSG((void)fmt::format(runtime("{a} {}"), fmt::arg("a", 2), 42),
600                    format_error,
601                    "cannot switch from manual to automatic argument indexing");
602 }
603 
TEST(format_test,auto_arg_index)604 TEST(format_test, auto_arg_index) {
605   EXPECT_EQ(fmt::format("{}{}{}", 'a', 'b', 'c'), "abc");
606   EXPECT_THROW_MSG((void)fmt::format(runtime("{0}{}"), 'a', 'b'), format_error,
607                    "cannot switch from manual to automatic argument indexing");
608   EXPECT_THROW_MSG((void)fmt::format(runtime("{}{0}"), 'a', 'b'), format_error,
609                    "cannot switch from automatic to manual argument indexing");
610   EXPECT_EQ(fmt::format("{:.{}}", 1.2345, 2), "1.2");
611   EXPECT_THROW_MSG((void)fmt::format(runtime("{0}:.{}"), 1.2345, 2),
612                    format_error,
613                    "cannot switch from manual to automatic argument indexing");
614   EXPECT_THROW_MSG((void)fmt::format(runtime("{:.{0}}"), 1.2345, 2),
615                    format_error,
616                    "cannot switch from automatic to manual argument indexing");
617   EXPECT_THROW_MSG((void)fmt::format(runtime("{}")), format_error,
618                    "argument not found");
619 }
620 
TEST(format_test,empty_specs)621 TEST(format_test, empty_specs) { EXPECT_EQ(fmt::format("{0:}", 42), "42"); }
622 
TEST(format_test,left_align)623 TEST(format_test, left_align) {
624   EXPECT_EQ(fmt::format("{0:<4}", 42), "42  ");
625   EXPECT_EQ(fmt::format("{0:<4o}", 042), "42  ");
626   EXPECT_EQ(fmt::format("{0:<4x}", 0x42), "42  ");
627   EXPECT_EQ(fmt::format("{0:<5}", -42), "-42  ");
628   EXPECT_EQ(fmt::format("{0:<5}", 42u), "42   ");
629   EXPECT_EQ(fmt::format("{0:<5}", -42l), "-42  ");
630   EXPECT_EQ(fmt::format("{0:<5}", 42ul), "42   ");
631   EXPECT_EQ(fmt::format("{0:<5}", -42ll), "-42  ");
632   EXPECT_EQ(fmt::format("{0:<5}", 42ull), "42   ");
633   EXPECT_EQ(fmt::format("{0:<5}", -42.0), "-42  ");
634   EXPECT_EQ(fmt::format("{0:<5}", -42.0l), "-42  ");
635   EXPECT_EQ(fmt::format("{0:<5}", 'c'), "c    ");
636   EXPECT_EQ(fmt::format("{0:<5}", "abc"), "abc  ");
637   EXPECT_EQ(fmt::format("{0:<8}", reinterpret_cast<void*>(0xface)), "0xface  ");
638 }
639 
TEST(format_test,right_align)640 TEST(format_test, right_align) {
641   EXPECT_EQ(fmt::format("{0:>4}", 42), "  42");
642   EXPECT_EQ(fmt::format("{0:>4o}", 042), "  42");
643   EXPECT_EQ(fmt::format("{0:>4x}", 0x42), "  42");
644   EXPECT_EQ(fmt::format("{0:>5}", -42), "  -42");
645   EXPECT_EQ(fmt::format("{0:>5}", 42u), "   42");
646   EXPECT_EQ(fmt::format("{0:>5}", -42l), "  -42");
647   EXPECT_EQ(fmt::format("{0:>5}", 42ul), "   42");
648   EXPECT_EQ(fmt::format("{0:>5}", -42ll), "  -42");
649   EXPECT_EQ(fmt::format("{0:>5}", 42ull), "   42");
650   EXPECT_EQ(fmt::format("{0:>5}", -42.0), "  -42");
651   EXPECT_EQ(fmt::format("{0:>5}", -42.0l), "  -42");
652   EXPECT_EQ(fmt::format("{0:>5}", 'c'), "    c");
653   EXPECT_EQ(fmt::format("{0:>5}", "abc"), "  abc");
654   EXPECT_EQ(fmt::format("{0:>8}", reinterpret_cast<void*>(0xface)), "  0xface");
655 }
656 
TEST(format_test,center_align)657 TEST(format_test, center_align) {
658   EXPECT_EQ(fmt::format("{0:^5}", 42), " 42  ");
659   EXPECT_EQ(fmt::format("{0:^5o}", 042), " 42  ");
660   EXPECT_EQ(fmt::format("{0:^5x}", 0x42), " 42  ");
661   EXPECT_EQ(fmt::format("{0:^5}", -42), " -42 ");
662   EXPECT_EQ(fmt::format("{0:^5}", 42u), " 42  ");
663   EXPECT_EQ(fmt::format("{0:^5}", -42l), " -42 ");
664   EXPECT_EQ(fmt::format("{0:^5}", 42ul), " 42  ");
665   EXPECT_EQ(fmt::format("{0:^5}", -42ll), " -42 ");
666   EXPECT_EQ(fmt::format("{0:^5}", 42ull), " 42  ");
667   EXPECT_EQ(fmt::format("{0:^5}", -42.0), " -42 ");
668   EXPECT_EQ(fmt::format("{0:^5}", -42.0l), " -42 ");
669   EXPECT_EQ(fmt::format("{0:^5}", 'c'), "  c  ");
670   EXPECT_EQ(fmt::format("{0:^6}", "abc"), " abc  ");
671   EXPECT_EQ(fmt::format("{0:^8}", reinterpret_cast<void*>(0xface)), " 0xface ");
672 }
673 
TEST(format_test,fill)674 TEST(format_test, fill) {
675   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{<5}"), 'c'), format_error,
676                    "invalid fill character '{'");
677   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{<5}}"), 'c'), format_error,
678                    "invalid fill character '{'");
679   EXPECT_EQ(fmt::format("{0:*>4}", 42), "**42");
680   EXPECT_EQ(fmt::format("{0:*>5}", -42), "**-42");
681   EXPECT_EQ(fmt::format("{0:*>5}", 42u), "***42");
682   EXPECT_EQ(fmt::format("{0:*>5}", -42l), "**-42");
683   EXPECT_EQ(fmt::format("{0:*>5}", 42ul), "***42");
684   EXPECT_EQ(fmt::format("{0:*>5}", -42ll), "**-42");
685   EXPECT_EQ(fmt::format("{0:*>5}", 42ull), "***42");
686   EXPECT_EQ(fmt::format("{0:*>5}", -42.0), "**-42");
687   EXPECT_EQ(fmt::format("{0:*>5}", -42.0l), "**-42");
688   EXPECT_EQ(fmt::format("{0:*<5}", 'c'), "c****");
689   EXPECT_EQ(fmt::format("{0:*<5}", "abc"), "abc**");
690   EXPECT_EQ("**0xface",
691             fmt::format("{0:*>8}", reinterpret_cast<void*>(0xface)));
692   EXPECT_EQ(fmt::format("{:}=", "foo"), "foo=");
693   EXPECT_EQ(std::string("\0\0\0*", 4),
694             fmt::format(string_view("{:\0>4}", 6), '*'));
695   EXPECT_EQ(fmt::format("{0:ж>4}", 42), "жж42");
696   EXPECT_THROW_MSG((void)fmt::format(runtime("{:\x80\x80\x80\x80\x80>}"), 0),
697                    format_error, "invalid format specifier");
698 }
699 
TEST(format_test,plus_sign)700 TEST(format_test, plus_sign) {
701   EXPECT_EQ(fmt::format("{0:+}", 42), "+42");
702   EXPECT_EQ(fmt::format("{0:+}", -42), "-42");
703   EXPECT_EQ(fmt::format("{0:+}", 42), "+42");
704   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42u), format_error,
705                    "invalid format specifier");
706   EXPECT_EQ(fmt::format("{0:+}", 42l), "+42");
707   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42ul), format_error,
708                    "invalid format specifier");
709   EXPECT_EQ(fmt::format("{0:+}", 42ll), "+42");
710 #if FMT_USE_INT128
711   EXPECT_EQ(fmt::format("{0:+}", __int128_t(42)), "+42");
712 #endif
713   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 42ull), format_error,
714                    "invalid format specifier");
715   EXPECT_EQ(fmt::format("{0:+}", 42.0), "+42");
716   EXPECT_EQ(fmt::format("{0:+}", 42.0l), "+42");
717   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), 'c'), format_error,
718                    "invalid format specifier");
719   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:+}"), "abc"), format_error,
720                    "invalid format specifier");
721   EXPECT_THROW_MSG(
722       (void)fmt::format(runtime("{0:+}"), reinterpret_cast<void*>(0x42)),
723       format_error, "invalid format specifier");
724 }
725 
TEST(format_test,minus_sign)726 TEST(format_test, minus_sign) {
727   EXPECT_EQ(fmt::format("{0:-}", 42), "42");
728   EXPECT_EQ(fmt::format("{0:-}", -42), "-42");
729   EXPECT_EQ(fmt::format("{0:-}", 42), "42");
730   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42u), format_error,
731                    "invalid format specifier");
732   EXPECT_EQ(fmt::format("{0:-}", 42l), "42");
733   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42ul), format_error,
734                    "invalid format specifier");
735   EXPECT_EQ(fmt::format("{0:-}", 42ll), "42");
736   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 42ull), format_error,
737                    "invalid format specifier");
738   EXPECT_EQ(fmt::format("{0:-}", 42.0), "42");
739   EXPECT_EQ(fmt::format("{0:-}", 42.0l), "42");
740   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), 'c'), format_error,
741                    "invalid format specifier");
742   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:-}"), "abc"), format_error,
743                    "invalid format specifier");
744   EXPECT_THROW_MSG(
745       (void)fmt::format(runtime("{0:-}"), reinterpret_cast<void*>(0x42)),
746       format_error, "invalid format specifier");
747 }
748 
TEST(format_test,space_sign)749 TEST(format_test, space_sign) {
750   EXPECT_EQ(fmt::format("{0: }", 42), " 42");
751   EXPECT_EQ(fmt::format("{0: }", -42), "-42");
752   EXPECT_EQ(fmt::format("{0: }", 42), " 42");
753   EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42u), format_error,
754                    "invalid format specifier");
755   EXPECT_EQ(fmt::format("{0: }", 42l), " 42");
756   EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42ul), format_error,
757                    "invalid format specifier");
758   EXPECT_EQ(fmt::format("{0: }", 42ll), " 42");
759   EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 42ull), format_error,
760                    "invalid format specifier");
761   EXPECT_EQ(fmt::format("{0: }", 42.0), " 42");
762   EXPECT_EQ(fmt::format("{0: }", 42.0l), " 42");
763   EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), 'c'), format_error,
764                    "invalid format specifier");
765   EXPECT_THROW_MSG((void)fmt::format(runtime("{0: }"), "abc"), format_error,
766                    "invalid format specifier");
767   EXPECT_THROW_MSG(
768       (void)fmt::format(runtime("{0: }"), reinterpret_cast<void*>(0x42)),
769       format_error, "invalid format specifier");
770 }
771 
TEST(format_test,hash_flag)772 TEST(format_test, hash_flag) {
773   EXPECT_EQ(fmt::format("{0:#}", 42), "42");
774   EXPECT_EQ(fmt::format("{0:#}", -42), "-42");
775   EXPECT_EQ(fmt::format("{0:#b}", 42), "0b101010");
776   EXPECT_EQ(fmt::format("{0:#B}", 42), "0B101010");
777   EXPECT_EQ(fmt::format("{0:#b}", -42), "-0b101010");
778   EXPECT_EQ(fmt::format("{0:#x}", 0x42), "0x42");
779   EXPECT_EQ(fmt::format("{0:#X}", 0x42), "0X42");
780   EXPECT_EQ(fmt::format("{0:#x}", -0x42), "-0x42");
781   EXPECT_EQ(fmt::format("{0:#o}", 0), "0");
782   EXPECT_EQ(fmt::format("{0:#o}", 042), "042");
783   EXPECT_EQ(fmt::format("{0:#o}", -042), "-042");
784   EXPECT_EQ(fmt::format("{0:#}", 42u), "42");
785   EXPECT_EQ(fmt::format("{0:#x}", 0x42u), "0x42");
786   EXPECT_EQ(fmt::format("{0:#o}", 042u), "042");
787 
788   EXPECT_EQ(fmt::format("{0:#}", -42l), "-42");
789   EXPECT_EQ(fmt::format("{0:#x}", 0x42l), "0x42");
790   EXPECT_EQ(fmt::format("{0:#x}", -0x42l), "-0x42");
791   EXPECT_EQ(fmt::format("{0:#o}", 042l), "042");
792   EXPECT_EQ(fmt::format("{0:#o}", -042l), "-042");
793   EXPECT_EQ(fmt::format("{0:#}", 42ul), "42");
794   EXPECT_EQ(fmt::format("{0:#x}", 0x42ul), "0x42");
795   EXPECT_EQ(fmt::format("{0:#o}", 042ul), "042");
796 
797   EXPECT_EQ(fmt::format("{0:#}", -42ll), "-42");
798   EXPECT_EQ(fmt::format("{0:#x}", 0x42ll), "0x42");
799   EXPECT_EQ(fmt::format("{0:#x}", -0x42ll), "-0x42");
800   EXPECT_EQ(fmt::format("{0:#o}", 042ll), "042");
801   EXPECT_EQ(fmt::format("{0:#o}", -042ll), "-042");
802   EXPECT_EQ(fmt::format("{0:#}", 42ull), "42");
803   EXPECT_EQ(fmt::format("{0:#x}", 0x42ull), "0x42");
804   EXPECT_EQ(fmt::format("{0:#o}", 042ull), "042");
805 
806   EXPECT_EQ(fmt::format("{0:#}", -42.0), "-42.");
807   EXPECT_EQ(fmt::format("{0:#}", -42.0l), "-42.");
808   EXPECT_EQ(fmt::format("{:#.0e}", 42.0), "4.e+01");
809   EXPECT_EQ(fmt::format("{:#.0f}", 0.01), "0.");
810   EXPECT_EQ(fmt::format("{:#.2g}", 0.5), "0.50");
811   EXPECT_EQ(fmt::format("{:#.0f}", 0.5), "0.");
812   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#"), 'c'), format_error,
813                    "invalid format specifier for char");
814   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), 'c'), format_error,
815                    "invalid format specifier for char");
816   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:#}"), "abc"), format_error,
817                    "invalid format specifier");
818   EXPECT_THROW_MSG(
819       (void)fmt::format(runtime("{0:#}"), reinterpret_cast<void*>(0x42)),
820       format_error, "invalid format specifier");
821 }
822 
TEST(format_test,zero_flag)823 TEST(format_test, zero_flag) {
824   EXPECT_EQ(fmt::format("{0:0}", 42), "42");
825   EXPECT_EQ(fmt::format("{0:05}", -42), "-0042");
826   EXPECT_EQ(fmt::format("{0:05}", 42u), "00042");
827   EXPECT_EQ(fmt::format("{0:05}", -42l), "-0042");
828   EXPECT_EQ(fmt::format("{0:05}", 42ul), "00042");
829   EXPECT_EQ(fmt::format("{0:05}", -42ll), "-0042");
830   EXPECT_EQ(fmt::format("{0:05}", 42ull), "00042");
831   EXPECT_EQ(fmt::format("{0:07}", -42.0), "-000042");
832   EXPECT_EQ(fmt::format("{0:07}", -42.0l), "-000042");
833   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:0"), 'c'), format_error,
834                    "invalid format specifier for char");
835   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), 'c'), format_error,
836                    "invalid format specifier for char");
837   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:05}"), "abc"), format_error,
838                    "format specifier requires numeric argument");
839   EXPECT_THROW_MSG(
840       (void)fmt::format(runtime("{0:05}"), reinterpret_cast<void*>(0x42)),
841       format_error, "format specifier requires numeric argument");
842 }
843 
TEST(format_test,zero_flag_and_align)844 TEST(format_test, zero_flag_and_align) {
845   // If the 0 character and an align option both appear, the 0 character is
846   // ignored.
847   EXPECT_EQ(fmt::format("{:<05}", 42), "42   ");
848   EXPECT_EQ(fmt::format("{:<05}", -42), "-42  ");
849   EXPECT_EQ(fmt::format("{:^05}", 42), " 42  ");
850   EXPECT_EQ(fmt::format("{:^05}", -42), " -42 ");
851   EXPECT_EQ(fmt::format("{:>05}", 42), "   42");
852   EXPECT_EQ(fmt::format("{:>05}", -42), "  -42");
853 }
854 
TEST(format_test,width)855 TEST(format_test, width) {
856   auto int_maxer = std::to_string(INT_MAX + 1u);
857   EXPECT_THROW_MSG((void)fmt::format(runtime("{:" + int_maxer), 0),
858                    format_error, "number is too big");
859   EXPECT_THROW_MSG((void)fmt::format(runtime("{:" + int_maxer + "}"), 0),
860                    format_error, "number is too big");
861 
862   EXPECT_EQ(fmt::format("{:4}", -42), " -42");
863   EXPECT_EQ(fmt::format("{:5}", 42u), "   42");
864   EXPECT_EQ(fmt::format("{:6}", -42l), "   -42");
865   EXPECT_EQ(fmt::format("{:7}", 42ul), "     42");
866   EXPECT_EQ(fmt::format("{:6}", -42ll), "   -42");
867   EXPECT_EQ(fmt::format("{:7}", 42ull), "     42");
868   EXPECT_EQ(fmt::format("{:8}", -1.23), "   -1.23");
869   EXPECT_EQ(fmt::format("{:9}", -1.23l), "    -1.23");
870   EXPECT_EQ(fmt::format("{:10}", reinterpret_cast<void*>(0xcafe)),
871             "    0xcafe");
872   EXPECT_EQ(fmt::format("{:11}", 'x'), "x          ");
873   EXPECT_EQ(fmt::format("{:12}", "str"), "str         ");
874   EXPECT_EQ(fmt::format("{:*^6}", "��"), "**��**");
875   EXPECT_EQ(fmt::format("{:*^8}", "你好"), "**你好**");
876   EXPECT_EQ(fmt::format("{:#6}", 42.0), "   42.");
877   EXPECT_EQ(fmt::format("{:6c}", static_cast<int>('x')), "x     ");
878   EXPECT_EQ(fmt::format("{:>06.0f}", 0.00884311), "     0");
879 }
880 
881 auto bad_dynamic_spec_msg = FMT_BUILTIN_TYPES
882                                 ? "width/precision is out of range"
883                                 : "width/precision is not integer";
884 
TEST(format_test,runtime_width)885 TEST(format_test, runtime_width) {
886   auto int_maxer = std::to_string(INT_MAX + 1u);
887   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{" + int_maxer), 0),
888                    format_error, "invalid format string");
889   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{" + int_maxer + "}"), 0),
890                    format_error, "argument not found");
891   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{" + int_maxer + "}}"), 0),
892                    format_error, "argument not found");
893 
894   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{"), 0), format_error,
895                    "invalid format string");
896   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{}"), 0), format_error,
897                    "cannot switch from manual to automatic argument indexing");
898   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{?}}"), 0), format_error,
899                    "invalid format string");
900   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0), format_error,
901                    "argument not found");
902 
903   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{0:}}"), 0), format_error,
904                    "invalid format string");
905 
906   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1), format_error,
907                    "width/precision is out of range");
908   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1u)),
909                    format_error, bad_dynamic_spec_msg);
910   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, -1l), format_error,
911                    bad_dynamic_spec_msg);
912   if (fmt::detail::const_check(sizeof(long) > sizeof(int))) {
913     long value = INT_MAX;
914     EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (value + 1)),
915                      format_error, bad_dynamic_spec_msg);
916   }
917   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, (INT_MAX + 1ul)),
918                    format_error, bad_dynamic_spec_msg);
919 
920   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, '0'), format_error,
921                    "width/precision is not integer");
922   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:{1}}"), 0, 0.0), format_error,
923                    "width/precision is not integer");
924 
925   EXPECT_EQ(fmt::format("{0:{1}}", -42, 4), " -42");
926   EXPECT_EQ(fmt::format("{0:{1}}", 42u, 5), "   42");
927   EXPECT_EQ(fmt::format("{0:{1}}", -42l, 6), "   -42");
928   EXPECT_EQ(fmt::format("{0:{1}}", 42ul, 7), "     42");
929   EXPECT_EQ(fmt::format("{0:{1}}", -42ll, 6), "   -42");
930   EXPECT_EQ(fmt::format("{0:{1}}", 42ull, 7), "     42");
931   EXPECT_EQ(fmt::format("{0:{1}}", -1.23, 8), "   -1.23");
932   EXPECT_EQ(fmt::format("{0:{1}}", -1.23l, 9), "    -1.23");
933   EXPECT_EQ("    0xcafe",
934             fmt::format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10));
935   EXPECT_EQ(fmt::format("{0:{1}}", 'x', 11), "x          ");
936   EXPECT_EQ(fmt::format("{0:{1}}", "str", 12), "str         ");
937   EXPECT_EQ(fmt::format("{:{}}", 42, short(4)), "  42");
938 }
939 
TEST(format_test,exponent_range)940 TEST(format_test, exponent_range) {
941   for (int e = -1074; e <= 1023; ++e) (void)fmt::format("{}", std::ldexp(1, e));
942 }
943 
TEST(format_test,precision)944 TEST(format_test, precision) {
945   char format_str[buffer_size];
946   safe_sprintf(format_str, "{0:.%u", UINT_MAX);
947   increment(format_str + 4);
948   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
949                    "number is too big");
950   size_t size = std::strlen(format_str);
951   format_str[size] = '}';
952   format_str[size + 1] = 0;
953   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
954                    "number is too big");
955 
956   safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u);
957   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
958                    "number is too big");
959   safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
960   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
961                    "number is too big");
962 
963   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:."), 0.0), format_error,
964                    "invalid precision");
965   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.}"), 0.0), format_error,
966                    "invalid format string");
967 
968   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2"), 0), format_error,
969                    "invalid format specifier");
970   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42), format_error,
971                    "invalid format specifier");
972   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42), format_error,
973                    "invalid format specifier");
974   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42u), format_error,
975                    "invalid format specifier");
976   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42u), format_error,
977                    "invalid format specifier");
978   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42l), format_error,
979                    "invalid format specifier");
980   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42l), format_error,
981                    "invalid format specifier");
982   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ul), format_error,
983                    "invalid format specifier");
984   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ul), format_error,
985                    "invalid format specifier");
986   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ll), format_error,
987                    "invalid format specifier");
988   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ll), format_error,
989                    "invalid format specifier");
990   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2}"), 42ull), format_error,
991                    "invalid format specifier");
992   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.2f}"), 42ull), format_error,
993                    "invalid format specifier");
994   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:3.0}"), 'x'), format_error,
995                    "invalid format specifier");
996   EXPECT_EQ(fmt::format("{0:.2}", 1.2345), "1.2");
997   EXPECT_EQ(fmt::format("{0:.2}", 1.2345l), "1.2");
998   EXPECT_EQ(fmt::format("{:.2}", 1.234e56), "1.2e+56");
999   EXPECT_EQ(fmt::format("{0:.3}", 1.1), "1.1");
1000   EXPECT_EQ(fmt::format("{:.0e}", 1.0L), "1e+00");
1001   EXPECT_EQ(fmt::format("{:9.1e}", 0.0), "  0.0e+00");
1002   EXPECT_EQ(fmt::format("{:.7f}", 0.0000000000000071054273576010018587L),
1003             "0.0000000");
1004 
1005   EXPECT_EQ(
1006       fmt::format("{:.494}", 4.9406564584124654E-324),
1007       "4.9406564584124654417656879286822137236505980261432476442558568250067550"
1008       "727020875186529983636163599237979656469544571773092665671035593979639877"
1009       "479601078187812630071319031140452784581716784898210368871863605699873072"
1010       "305000638740915356498438731247339727316961514003171538539807412623856559"
1011       "117102665855668676818703956031062493194527159149245532930545654440112748"
1012       "012970999954193198940908041656332452475714786901472678015935523861155013"
1013       "480352649347201937902681071074917033322268447533357208324319361e-324");
1014   EXPECT_EQ(
1015       fmt::format("{:.1074f}", 1.1125369292536e-308),
1016       "0.0000000000000000000000000000000000000000000000000000000000000000000000"
1017       "000000000000000000000000000000000000000000000000000000000000000000000000"
1018       "000000000000000000000000000000000000000000000000000000000000000000000000"
1019       "000000000000000000000000000000000000000000000000000000000000000000000000"
1020       "000000000000000000000111253692925360019747947051741965785554081512200979"
1021       "355021686109411883779182127659725163430929750364498219730822952552570601"
1022       "152163505899912777129583674906301179059298598412303893909188340988729019"
1023       "014361467448914817838555156840459458527907308695109202499990850735085304"
1024       "478476991912072201449236975063640913461919914396877093174125167509869762"
1025       "482369631100360266123742648159508919592746619553246586039571522788247697"
1026       "156360766271842991667238355464496455107749716934387136380536472531224398"
1027       "559833794807213172371254492216255558078524900147957309382830827524104234"
1028       "530961756787819847850302379672357738807808384667004752163416921762619527"
1029       "462847642037420991432005657440259928195996762610375541867198059294212446"
1030       "81962777939941034720757232455434770912461317493580281734466552734375");
1031 
1032   std::string outputs[] = {
1033       "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000"
1034       "000000000000000000000000000000000000000000000000000000000000000000000000"
1035       "000000000000000000000000000000000000000000000000000000000000000000000000"
1036       "000000000000000000000000000000000000000000000000000000000000000000000000"
1037       "000000000000000000000000000000000000000000000000000000000000000000000000"
1038       "000000000000000000000000000000000000000000000000000000000000000000000000"
1039       "000000000000000000000000000000000000000000000000000000000000000000000000"
1040       "000000000000000000000000000000000000000000000000000000000000000000000000"
1041       "000000000000000000000000000000000000000000000000000000000000000000000000"
1042       "000000000000000000000000000000000000000000000000000000000000000000000000"
1043       "000000000000000000000000000000000000000000000000000000000000000000000000"
1044       "000000000000000000000000000000000000000000000000000P+127",
1045       "-0XA.0FF1FFF38E4F0000000000000000000000000000000000000000000000000000000"
1046       "000000000000000000000000000000000000000000000000000000000000000000000000"
1047       "000000000000000000000000000000000000000000000000000000000000000000000000"
1048       "000000000000000000000000000000000000000000000000000000000000000000000000"
1049       "000000000000000000000000000000000000000000000000000000000000000000000000"
1050       "000000000000000000000000000000000000000000000000000000000000000000000000"
1051       "000000000000000000000000000000000000000000000000000000000000000000000000"
1052       "000000000000000000000000000000000000000000000000000000000000000000000000"
1053       "000000000000000000000000000000000000000000000000000000000000000000000000"
1054       "000000000000000000000000000000000000000000000000000000000000000000000000"
1055       "000000000000000000000000000000000000000000000000000000000000000000000000"
1056       "000000000000000000000000000000000000000000000000000P+124"};
1057   EXPECT_THAT(outputs,
1058               testing::Contains(fmt::format("{:.838A}", -2.14001164E+38)));
1059 
1060   if (std::numeric_limits<long double>::digits == 64) {
1061     auto ld = (std::numeric_limits<long double>::min)();
1062     EXPECT_EQ(fmt::format("{:.0}", ld), "3e-4932");
1063     EXPECT_EQ(
1064         fmt::format("{:0g}", std::numeric_limits<long double>::denorm_min()),
1065         "3.6452e-4951");
1066   }
1067 
1068   EXPECT_EQ(fmt::format("{:#.0f}", 123.0), "123.");
1069   EXPECT_EQ(fmt::format("{:.02f}", 1.234), "1.23");
1070   EXPECT_EQ(fmt::format("{:.1g}", 0.001), "0.001");
1071   EXPECT_EQ(fmt::format("{}", 1019666432.0f), "1019666400");
1072   EXPECT_EQ(fmt::format("{:.0e}", 9.5), "1e+01");
1073   EXPECT_EQ(fmt::format("{:.1e}", 1e-34), "1.0e-34");
1074 
1075   EXPECT_THROW_MSG(
1076       (void)fmt::format(runtime("{0:.2}"), reinterpret_cast<void*>(0xcafe)),
1077       format_error, "invalid format specifier");
1078   EXPECT_THROW_MSG(
1079       (void)fmt::format(runtime("{0:.2f}"), reinterpret_cast<void*>(0xcafe)),
1080       format_error, "invalid format specifier");
1081   EXPECT_THROW_MSG((void)fmt::format(runtime("{:.{}e}"), 42.0,
1082                                      fmt::detail::max_value<int>()),
1083                    format_error, "number is too big");
1084   EXPECT_THROW_MSG(
1085       (void)fmt::format("{:.2147483646f}", -2.2121295195081227E+304),
1086       format_error, "number is too big");
1087   EXPECT_THROW_MSG((void)fmt::format(runtime("{:.f}"), 42.0), format_error,
1088                    "invalid format string");
1089 
1090   EXPECT_EQ(fmt::format("{0:.2}", "str"), "st");
1091   EXPECT_EQ(fmt::format("{0:.5}", "вожыкі"), "вожык");
1092   EXPECT_EQ(fmt::format("{0:.6}", "123456\xad"), "123456");
1093 }
1094 
TEST(format_test,utf8_precision)1095 TEST(format_test, utf8_precision) {
1096   auto result = fmt::format("{:.4}", "caf\u00e9s");  // cafés
1097   EXPECT_EQ(fmt::detail::compute_width(result), 4);
1098   EXPECT_EQ(result, "caf\u00e9");
1099 }
1100 
TEST(format_test,runtime_precision)1101 TEST(format_test, runtime_precision) {
1102   char format_str[buffer_size];
1103   safe_sprintf(format_str, "{0:.{%u", UINT_MAX);
1104   increment(format_str + 5);
1105   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
1106                    "invalid format string");
1107   size_t size = std::strlen(format_str);
1108   format_str[size] = '}';
1109   format_str[size + 1] = 0;
1110   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
1111                    "argument not found");
1112   format_str[size + 1] = '}';
1113   format_str[size + 2] = 0;
1114   EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), 0.0), format_error,
1115                    "argument not found");
1116 
1117   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{"), 0.0), format_error,
1118                    "invalid format string");
1119   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{}"), 0.0), format_error,
1120                    "cannot switch from manual to automatic argument indexing");
1121   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{?}}"), 0.0), format_error,
1122                    "invalid format string");
1123   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}"), 0, 0), format_error,
1124                    "invalid format specifier");
1125   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0), format_error,
1126                    "argument not found");
1127 
1128   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{0:}}"), 0.0), format_error,
1129                    "invalid format string");
1130 
1131   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, -1),
1132                    format_error, "width/precision is out of range");
1133   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (INT_MAX + 1u)),
1134                    format_error, bad_dynamic_spec_msg);
1135   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, -1l),
1136                    format_error, bad_dynamic_spec_msg);
1137   if (fmt::detail::const_check(sizeof(long) > sizeof(int))) {
1138     long value = INT_MAX;
1139     EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (value + 1)),
1140                      format_error, bad_dynamic_spec_msg);
1141   }
1142   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, (INT_MAX + 1ul)),
1143                    format_error, bad_dynamic_spec_msg);
1144 
1145   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, '0'),
1146                    format_error, "width/precision is not integer");
1147   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 0.0, 0.0),
1148                    format_error, "width/precision is not integer");
1149 
1150   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42, 2), format_error,
1151                    "invalid format specifier");
1152   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42, 2), format_error,
1153                    "invalid format specifier");
1154   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42u, 2), format_error,
1155                    "invalid format specifier");
1156   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42u, 2),
1157                    format_error, "invalid format specifier");
1158   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42l, 2), format_error,
1159                    "invalid format specifier");
1160   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42l, 2),
1161                    format_error, "invalid format specifier");
1162   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ul, 2),
1163                    format_error, "invalid format specifier");
1164   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ul, 2),
1165                    format_error, "invalid format specifier");
1166   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ll, 2),
1167                    format_error, "invalid format specifier");
1168   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ll, 2),
1169                    format_error, "invalid format specifier");
1170   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"), 42ull, 2),
1171                    format_error, "invalid format specifier");
1172   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"), 42ull, 2),
1173                    format_error, "invalid format specifier");
1174   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:3.{1}}"), 'x', 0),
1175                    format_error, "invalid format specifier");
1176   EXPECT_EQ(fmt::format("{0:.{1}}", 1.2345, 2), "1.2");
1177   EXPECT_EQ(fmt::format("{1:.{0}}", 2, 1.2345l), "1.2");
1178 
1179   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}}"),
1180                                      reinterpret_cast<void*>(0xcafe), 2),
1181                    format_error, "invalid format specifier");
1182   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:.{1}f}"),
1183                                      reinterpret_cast<void*>(0xcafe), 2),
1184                    format_error, "invalid format specifier");
1185 
1186   EXPECT_EQ(fmt::format("{0:.{1}}", "str", 2), "st");
1187 }
1188 
TEST(format_test,format_bool)1189 TEST(format_test, format_bool) {
1190   EXPECT_EQ(fmt::format("{}", true), "true");
1191   EXPECT_EQ(fmt::format("{}", false), "false");
1192   EXPECT_EQ(fmt::format("{:d}", true), "1");
1193   EXPECT_EQ(fmt::format("{:5}", true), "true ");
1194   EXPECT_EQ(fmt::format("{:s}", true), "true");
1195   EXPECT_EQ(fmt::format("{:s}", false), "false");
1196   EXPECT_EQ(fmt::format("{:6s}", false), "false ");
1197   EXPECT_THROW_MSG((void)fmt::format(runtime("{:c}"), false), format_error,
1198                    "invalid format specifier");
1199 }
1200 
TEST(format_test,format_short)1201 TEST(format_test, format_short) {
1202   short s = 42;
1203   EXPECT_EQ(fmt::format("{0:d}", s), "42");
1204   unsigned short us = 42;
1205   EXPECT_EQ(fmt::format("{0:d}", us), "42");
1206 }
1207 
1208 template <typename T>
check_unknown_types(const T & value,const char * types,const char *)1209 void check_unknown_types(const T& value, const char* types, const char*) {
1210   char format_str[buffer_size];
1211   const char* special = ".0123456789L?}";
1212   for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
1213     char c = static_cast<char>(i);
1214     if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
1215     safe_sprintf(format_str, "{0:10%c}", c);
1216     const char* message = "invalid format specifier";
1217     EXPECT_THROW_MSG((void)fmt::format(runtime(format_str), value),
1218                      format_error, message)
1219         << format_str << " " << message;
1220   }
1221 }
1222 
TEST(format_test,format_int)1223 TEST(format_test, format_int) {
1224   EXPECT_THROW_MSG((void)fmt::format(runtime("{0:v"), 42), format_error,
1225                    "invalid format specifier");
1226   check_unknown_types(42, "bBdoxXnLc", "integer");
1227   EXPECT_EQ(fmt::format("{:c}", static_cast<int>('x')), "x");
1228 }
1229 
TEST(format_test,format_bin)1230 TEST(format_test, format_bin) {
1231   EXPECT_EQ(fmt::format("{0:b}", 0), "0");
1232   EXPECT_EQ(fmt::format("{0:b}", 42), "101010");
1233   EXPECT_EQ(fmt::format("{0:b}", 42u), "101010");
1234   EXPECT_EQ(fmt::format("{0:b}", -42), "-101010");
1235   EXPECT_EQ(fmt::format("{0:b}", 12345), "11000000111001");
1236   EXPECT_EQ(fmt::format("{0:b}", 0x12345678), "10010001101000101011001111000");
1237   EXPECT_EQ("10010000101010111100110111101111",
1238             fmt::format("{0:b}", 0x90ABCDEF));
1239   EXPECT_EQ("11111111111111111111111111111111",
1240             fmt::format("{0:b}", max_value<uint32_t>()));
1241 }
1242 
1243 #if FMT_USE_INT128
1244 constexpr auto int128_max = static_cast<__int128_t>(
1245     (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1);
1246 constexpr auto int128_min = -int128_max - 1;
1247 
1248 constexpr auto uint128_max = ~static_cast<__uint128_t>(0);
1249 #endif
1250 
TEST(format_test,format_dec)1251 TEST(format_test, format_dec) {
1252   EXPECT_EQ(fmt::format("{0}", 0), "0");
1253   EXPECT_EQ(fmt::format("{0}", 42), "42");
1254   EXPECT_EQ(fmt::format("{:}>", 42), "42>");
1255   EXPECT_EQ(fmt::format("{0:d}", 42), "42");
1256   EXPECT_EQ(fmt::format("{0}", 42u), "42");
1257   EXPECT_EQ(fmt::format("{0}", -42), "-42");
1258   EXPECT_EQ(fmt::format("{0}", 12345), "12345");
1259   EXPECT_EQ(fmt::format("{0}", 67890), "67890");
1260 #if FMT_USE_INT128
1261   EXPECT_EQ(fmt::format("{0}", static_cast<__int128_t>(0)), "0");
1262   EXPECT_EQ(fmt::format("{0}", static_cast<__uint128_t>(0)), "0");
1263   EXPECT_EQ("9223372036854775808",
1264             fmt::format("{0}", static_cast<__int128_t>(INT64_MAX) + 1));
1265   EXPECT_EQ("-9223372036854775809",
1266             fmt::format("{0}", static_cast<__int128_t>(INT64_MIN) - 1));
1267   EXPECT_EQ("18446744073709551616",
1268             fmt::format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1));
1269   EXPECT_EQ("170141183460469231731687303715884105727",
1270             fmt::format("{0}", int128_max));
1271   EXPECT_EQ("-170141183460469231731687303715884105728",
1272             fmt::format("{0}", int128_min));
1273   EXPECT_EQ("340282366920938463463374607431768211455",
1274             fmt::format("{0}", uint128_max));
1275 #endif
1276 
1277   char buffer[buffer_size];
1278   safe_sprintf(buffer, "%d", INT_MIN);
1279   EXPECT_EQ(buffer, fmt::format("{0}", INT_MIN));
1280   safe_sprintf(buffer, "%d", INT_MAX);
1281   EXPECT_EQ(buffer, fmt::format("{0}", INT_MAX));
1282   safe_sprintf(buffer, "%u", UINT_MAX);
1283   EXPECT_EQ(buffer, fmt::format("{0}", UINT_MAX));
1284   safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN));
1285   EXPECT_EQ(buffer, fmt::format("{0}", LONG_MIN));
1286   safe_sprintf(buffer, "%ld", LONG_MAX);
1287   EXPECT_EQ(buffer, fmt::format("{0}", LONG_MAX));
1288   safe_sprintf(buffer, "%lu", ULONG_MAX);
1289   EXPECT_EQ(buffer, fmt::format("{0}", ULONG_MAX));
1290 }
1291 
TEST(format_test,format_hex)1292 TEST(format_test, format_hex) {
1293   EXPECT_EQ(fmt::format("{0:x}", 0), "0");
1294   EXPECT_EQ(fmt::format("{0:x}", 0x42), "42");
1295   EXPECT_EQ(fmt::format("{0:x}", 0x42u), "42");
1296   EXPECT_EQ(fmt::format("{0:x}", -0x42), "-42");
1297   EXPECT_EQ(fmt::format("{0:x}", 0x12345678), "12345678");
1298   EXPECT_EQ(fmt::format("{0:x}", 0x90abcdef), "90abcdef");
1299   EXPECT_EQ(fmt::format("{0:X}", 0x12345678), "12345678");
1300   EXPECT_EQ(fmt::format("{0:X}", 0x90ABCDEF), "90ABCDEF");
1301 #if FMT_USE_INT128
1302   EXPECT_EQ(fmt::format("{0:x}", static_cast<__int128_t>(0)), "0");
1303   EXPECT_EQ(fmt::format("{0:x}", static_cast<__uint128_t>(0)), "0");
1304   EXPECT_EQ("8000000000000000",
1305             fmt::format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1));
1306   EXPECT_EQ("-8000000000000001",
1307             fmt::format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1));
1308   EXPECT_EQ("10000000000000000",
1309             fmt::format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1));
1310   EXPECT_EQ("7fffffffffffffffffffffffffffffff",
1311             fmt::format("{0:x}", int128_max));
1312   EXPECT_EQ("-80000000000000000000000000000000",
1313             fmt::format("{0:x}", int128_min));
1314   EXPECT_EQ("ffffffffffffffffffffffffffffffff",
1315             fmt::format("{0:x}", uint128_max));
1316 #endif
1317 
1318   char buffer[buffer_size];
1319   safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN));
1320   EXPECT_EQ(buffer, fmt::format("{0:x}", INT_MIN));
1321   safe_sprintf(buffer, "%x", INT_MAX);
1322   EXPECT_EQ(buffer, fmt::format("{0:x}", INT_MAX));
1323   safe_sprintf(buffer, "%x", UINT_MAX);
1324   EXPECT_EQ(buffer, fmt::format("{0:x}", UINT_MAX));
1325   safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN));
1326   EXPECT_EQ(buffer, fmt::format("{0:x}", LONG_MIN));
1327   safe_sprintf(buffer, "%lx", LONG_MAX);
1328   EXPECT_EQ(buffer, fmt::format("{0:x}", LONG_MAX));
1329   safe_sprintf(buffer, "%lx", ULONG_MAX);
1330   EXPECT_EQ(buffer, fmt::format("{0:x}", ULONG_MAX));
1331 }
1332 
TEST(format_test,format_oct)1333 TEST(format_test, format_oct) {
1334   EXPECT_EQ(fmt::format("{0:o}", 0), "0");
1335   EXPECT_EQ(fmt::format("{0:o}", 042), "42");
1336   EXPECT_EQ(fmt::format("{0:o}", 042u), "42");
1337   EXPECT_EQ(fmt::format("{0:o}", -042), "-42");
1338   EXPECT_EQ(fmt::format("{0:o}", 012345670), "12345670");
1339 #if FMT_USE_INT128
1340   EXPECT_EQ(fmt::format("{0:o}", static_cast<__int128_t>(0)), "0");
1341   EXPECT_EQ(fmt::format("{0:o}", static_cast<__uint128_t>(0)), "0");
1342   EXPECT_EQ("1000000000000000000000",
1343             fmt::format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1));
1344   EXPECT_EQ("-1000000000000000000001",
1345             fmt::format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1));
1346   EXPECT_EQ("2000000000000000000000",
1347             fmt::format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1));
1348   EXPECT_EQ("1777777777777777777777777777777777777777777",
1349             fmt::format("{0:o}", int128_max));
1350   EXPECT_EQ("-2000000000000000000000000000000000000000000",
1351             fmt::format("{0:o}", int128_min));
1352   EXPECT_EQ("3777777777777777777777777777777777777777777",
1353             fmt::format("{0:o}", uint128_max));
1354 #endif
1355 
1356   char buffer[buffer_size];
1357   safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN));
1358   EXPECT_EQ(buffer, fmt::format("{0:o}", INT_MIN));
1359   safe_sprintf(buffer, "%o", INT_MAX);
1360   EXPECT_EQ(buffer, fmt::format("{0:o}", INT_MAX));
1361   safe_sprintf(buffer, "%o", UINT_MAX);
1362   EXPECT_EQ(buffer, fmt::format("{0:o}", UINT_MAX));
1363   safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN));
1364   EXPECT_EQ(buffer, fmt::format("{0:o}", LONG_MIN));
1365   safe_sprintf(buffer, "%lo", LONG_MAX);
1366   EXPECT_EQ(buffer, fmt::format("{0:o}", LONG_MAX));
1367   safe_sprintf(buffer, "%lo", ULONG_MAX);
1368   EXPECT_EQ(buffer, fmt::format("{0:o}", ULONG_MAX));
1369 }
1370 
TEST(format_test,format_int_locale)1371 TEST(format_test, format_int_locale) {
1372   EXPECT_EQ(fmt::format("{:L}", 1234), "1234");
1373 }
1374 
TEST(format_test,format_float)1375 TEST(format_test, format_float) {
1376   EXPECT_EQ(fmt::format("{}", 0.0f), "0");
1377   EXPECT_EQ(fmt::format("{0:f}", 392.5f), "392.500000");
1378 }
1379 
TEST(format_test,format_double)1380 TEST(format_test, format_double) {
1381   EXPECT_EQ(fmt::format("{}", 0.0), "0");
1382   check_unknown_types(1.2, "eEfFgGaAnL%", "double");
1383   EXPECT_EQ(fmt::format("{:}", 0.0), "0");
1384   EXPECT_EQ(fmt::format("{:f}", 0.0), "0.000000");
1385   EXPECT_EQ(fmt::format("{:g}", 0.0), "0");
1386   EXPECT_EQ(fmt::format("{:}", 392.65), "392.65");
1387   EXPECT_EQ(fmt::format("{:g}", 392.65), "392.65");
1388   EXPECT_EQ(fmt::format("{:G}", 392.65), "392.65");
1389   EXPECT_EQ(fmt::format("{:g}", 4.9014e6), "4.9014e+06");
1390   EXPECT_EQ(fmt::format("{:f}", 392.65), "392.650000");
1391   EXPECT_EQ(fmt::format("{:F}", 392.65), "392.650000");
1392   EXPECT_EQ(fmt::format("{:L}", 42.0), "42");
1393   EXPECT_EQ(fmt::format("{:24a}", 4.2f), "           0x1.0cccccp+2");
1394   EXPECT_EQ(fmt::format("{:24a}", 4.2), "    0x1.0cccccccccccdp+2");
1395   EXPECT_EQ(fmt::format("{:<24a}", 4.2), "0x1.0cccccccccccdp+2    ");
1396   EXPECT_EQ(fmt::format("{0:e}", 392.65), "3.926500e+02");
1397   EXPECT_EQ(fmt::format("{0:E}", 392.65), "3.926500E+02");
1398   EXPECT_EQ(fmt::format("{0:+010.4g}", 392.65), "+0000392.6");
1399 
1400 #if FMT_CPLUSPLUS >= 201703L
1401   double xd = 0x1.ffffffffffp+2;
1402   EXPECT_EQ(fmt::format("{:.10a}", xd), "0x1.ffffffffffp+2");
1403   EXPECT_EQ(fmt::format("{:.9a}", xd), "0x2.000000000p+2");
1404 
1405   if (std::numeric_limits<long double>::digits == 64) {
1406     auto ld = 0xf.ffffffffffp-3l;
1407     EXPECT_EQ(fmt::format("{:a}", ld), "0xf.ffffffffffp-3");
1408     EXPECT_EQ(fmt::format("{:.10a}", ld), "0xf.ffffffffffp-3");
1409     EXPECT_EQ(fmt::format("{:.9a}", ld), "0x1.000000000p+1");
1410   }
1411 #endif
1412 
1413   if (fmt::detail::const_check(std::numeric_limits<double>::is_iec559)) {
1414     double d = (std::numeric_limits<double>::min)();
1415     EXPECT_EQ(fmt::format("{:a}", d), "0x1p-1022");
1416     EXPECT_EQ(fmt::format("{:#a}", d), "0x1.p-1022");
1417 
1418     d = (std::numeric_limits<double>::max)();
1419     EXPECT_EQ(fmt::format("{:a}", d), "0x1.fffffffffffffp+1023");
1420 
1421     d = std::numeric_limits<double>::denorm_min();
1422     EXPECT_EQ(fmt::format("{:a}", d), "0x0.0000000000001p-1022");
1423   }
1424 
1425   if (std::numeric_limits<long double>::digits == 64) {
1426     auto ld = (std::numeric_limits<long double>::min)();
1427     EXPECT_EQ(fmt::format("{:a}", ld), "0x8p-16385");
1428 
1429     ld = (std::numeric_limits<long double>::max)();
1430     EXPECT_EQ(fmt::format("{:a}", ld), "0xf.fffffffffffffffp+16380");
1431 
1432     ld = std::numeric_limits<long double>::denorm_min();
1433     EXPECT_EQ(fmt::format("{:a}", ld), "0x0.000000000000001p-16382");
1434   }
1435 
1436   EXPECT_EQ(fmt::format("{:.10a}", 4.2), "0x1.0ccccccccdp+2");
1437 
1438   EXPECT_EQ(fmt::format("{:a}", -42.0), "-0x1.5p+5");
1439   EXPECT_EQ(fmt::format("{:A}", -42.0), "-0X1.5P+5");
1440 
1441   EXPECT_EQ(fmt::format("{:f}", 9223372036854775807.0),
1442             "9223372036854775808.000000");
1443 }
1444 
TEST(format_test,precision_rounding)1445 TEST(format_test, precision_rounding) {
1446   EXPECT_EQ(fmt::format("{:.0f}", 0.0), "0");
1447   EXPECT_EQ(fmt::format("{:.0f}", 0.01), "0");
1448   EXPECT_EQ(fmt::format("{:.0f}", 0.1), "0");
1449   EXPECT_EQ(fmt::format("{:.3f}", 0.00049), "0.000");
1450   EXPECT_EQ(fmt::format("{:.3f}", 0.0005), "0.001");
1451   EXPECT_EQ(fmt::format("{:.3f}", 0.00149), "0.001");
1452   EXPECT_EQ(fmt::format("{:.3f}", 0.0015), "0.002");
1453   EXPECT_EQ(fmt::format("{:.3f}", 0.9999), "1.000");
1454   EXPECT_EQ(fmt::format("{:.3}", 0.00123), "0.00123");
1455   EXPECT_EQ(fmt::format("{:.16g}", 0.1), "0.1");
1456   EXPECT_EQ(fmt::format("{:.0}", 1.0), "1");
1457   EXPECT_EQ("225.51575035152063720",
1458             fmt::format("{:.17f}", 225.51575035152064));
1459   EXPECT_EQ(fmt::format("{:.1f}", -761519619559038.2), "-761519619559038.2");
1460   EXPECT_EQ("1.9156918820264798e-56",
1461             fmt::format("{}", 1.9156918820264798e-56));
1462   EXPECT_EQ(fmt::format("{:.4f}", 7.2809479766055470e-15), "0.0000");
1463 }
1464 
TEST(format_test,prettify_float)1465 TEST(format_test, prettify_float) {
1466   EXPECT_EQ(fmt::format("{}", 1e-4), "0.0001");
1467   EXPECT_EQ(fmt::format("{}", 1e-5), "1e-05");
1468   EXPECT_EQ(fmt::format("{}", 1e15), "1000000000000000");
1469   EXPECT_EQ(fmt::format("{}", 1e16), "1e+16");
1470   EXPECT_EQ(fmt::format("{}", 9.999e-5), "9.999e-05");
1471   EXPECT_EQ(fmt::format("{}", 1e10), "10000000000");
1472   EXPECT_EQ(fmt::format("{}", 1e11), "100000000000");
1473   EXPECT_EQ(fmt::format("{}", 1234e7), "12340000000");
1474   EXPECT_EQ(fmt::format("{}", 1234e-2), "12.34");
1475   EXPECT_EQ(fmt::format("{}", 1234e-6), "0.001234");
1476   EXPECT_EQ(fmt::format("{}", 0.1f), "0.1");
1477   EXPECT_EQ(fmt::format("{}", 1.35631564e-19f), "1.3563156e-19");
1478 }
1479 
TEST(format_test,format_nan)1480 TEST(format_test, format_nan) {
1481   double nan = std::numeric_limits<double>::quiet_NaN();
1482   EXPECT_EQ(fmt::format("{}", nan), "nan");
1483   EXPECT_EQ(fmt::format("{:+}", nan), "+nan");
1484   EXPECT_EQ(fmt::format("{:+06}", nan), "  +nan");
1485   EXPECT_EQ(fmt::format("{:<+06}", nan), "+nan  ");
1486   EXPECT_EQ(fmt::format("{:^+06}", nan), " +nan ");
1487   EXPECT_EQ(fmt::format("{:>+06}", nan), "  +nan");
1488   if (std::signbit(-nan)) {
1489     EXPECT_EQ(fmt::format("{}", -nan), "-nan");
1490     EXPECT_EQ(fmt::format("{:+06}", -nan), "  -nan");
1491   } else {
1492     fmt::print("Warning: compiler doesn't handle negative NaN correctly");
1493   }
1494   EXPECT_EQ(fmt::format("{: }", nan), " nan");
1495   EXPECT_EQ(fmt::format("{:F}", nan), "NAN");
1496   EXPECT_EQ(fmt::format("{:<7}", nan), "nan    ");
1497   EXPECT_EQ(fmt::format("{:^7}", nan), "  nan  ");
1498   EXPECT_EQ(fmt::format("{:>7}", nan), "    nan");
1499 }
1500 
TEST(format_test,format_infinity)1501 TEST(format_test, format_infinity) {
1502   double inf = std::numeric_limits<double>::infinity();
1503   EXPECT_EQ(fmt::format("{}", inf), "inf");
1504   EXPECT_EQ(fmt::format("{:+}", inf), "+inf");
1505   EXPECT_EQ(fmt::format("{}", -inf), "-inf");
1506   EXPECT_EQ(fmt::format("{:+06}", inf), "  +inf");
1507   EXPECT_EQ(fmt::format("{:+06}", -inf), "  -inf");
1508   EXPECT_EQ(fmt::format("{:<+06}", inf), "+inf  ");
1509   EXPECT_EQ(fmt::format("{:^+06}", inf), " +inf ");
1510   EXPECT_EQ(fmt::format("{:>+06}", inf), "  +inf");
1511   EXPECT_EQ(fmt::format("{: }", inf), " inf");
1512   EXPECT_EQ(fmt::format("{:F}", inf), "INF");
1513   EXPECT_EQ(fmt::format("{:<7}", inf), "inf    ");
1514   EXPECT_EQ(fmt::format("{:^7}", inf), "  inf  ");
1515   EXPECT_EQ(fmt::format("{:>7}", inf), "    inf");
1516 }
1517 
TEST(format_test,format_long_double)1518 TEST(format_test, format_long_double) {
1519   EXPECT_EQ(fmt::format("{0:}", 0.0l), "0");
1520   EXPECT_EQ(fmt::format("{0:f}", 0.0l), "0.000000");
1521   EXPECT_EQ(fmt::format("{:.1f}", 0.000000001l), "0.0");
1522   EXPECT_EQ(fmt::format("{:.2f}", 0.099l), "0.10");
1523   EXPECT_EQ(fmt::format("{0:}", 392.65l), "392.65");
1524   EXPECT_EQ(fmt::format("{0:g}", 392.65l), "392.65");
1525   EXPECT_EQ(fmt::format("{0:G}", 392.65l), "392.65");
1526   EXPECT_EQ(fmt::format("{0:f}", 392.65l), "392.650000");
1527   EXPECT_EQ(fmt::format("{0:F}", 392.65l), "392.650000");
1528   char buffer[buffer_size];
1529   safe_sprintf(buffer, "%Le", 392.65l);
1530   EXPECT_EQ(buffer, fmt::format("{0:e}", 392.65l));
1531   EXPECT_EQ(fmt::format("{0:+010.4g}", 392.64l), "+0000392.6");
1532 
1533   auto ld = 3.31l;
1534   if (fmt::detail::is_double_double<decltype(ld)>::value) {
1535     safe_sprintf(buffer, "%a", static_cast<double>(ld));
1536     EXPECT_EQ(buffer, fmt::format("{:a}", ld));
1537   } else if (std::numeric_limits<long double>::digits == 64) {
1538     EXPECT_EQ(fmt::format("{:a}", ld), "0xd.3d70a3d70a3d70ap-2");
1539   }
1540 }
1541 
TEST(format_test,format_char)1542 TEST(format_test, format_char) {
1543   const char types[] = "cbBdoxX";
1544   check_unknown_types('a', types, "char");
1545   EXPECT_EQ(fmt::format("{0}", 'a'), "a");
1546   EXPECT_EQ(fmt::format("{0:c}", 'z'), "z");
1547   int n = 'x';
1548   for (const char* type = types + 1; *type; ++type) {
1549     std::string format_str = fmt::format("{{:{}}}", *type);
1550     EXPECT_EQ(fmt::format(runtime(format_str), n),
1551               fmt::format(runtime(format_str), 'x'))
1552         << format_str;
1553   }
1554   EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
1555 
1556   EXPECT_EQ(fmt::format("{}", '\n'), "\n");
1557   EXPECT_EQ(fmt::format("{:?}", '\n'), "'\\n'");
1558   EXPECT_EQ(fmt::format("{:x}", '\xff'), "ff");
1559 }
1560 
TEST(format_test,format_volatile_char)1561 TEST(format_test, format_volatile_char) {
1562   volatile char c = 'x';
1563   EXPECT_EQ(fmt::format("{}", c), "x");
1564 }
1565 
TEST(format_test,format_unsigned_char)1566 TEST(format_test, format_unsigned_char) {
1567   EXPECT_EQ(fmt::format("{}", static_cast<unsigned char>(42)), "42");
1568   EXPECT_EQ(fmt::format("{}", static_cast<uint8_t>(42)), "42");
1569 }
1570 
TEST(format_test,format_cstring)1571 TEST(format_test, format_cstring) {
1572   check_unknown_types("test", "sp", "string");
1573   EXPECT_EQ(fmt::format("{0}", "test"), "test");
1574   EXPECT_EQ(fmt::format("{0:s}", "test"), "test");
1575   char nonconst[] = "nonconst";
1576   EXPECT_EQ(fmt::format("{0}", nonconst), "nonconst");
1577   auto nullstr = static_cast<const char*>(nullptr);
1578   EXPECT_THROW_MSG((void)fmt::format("{}", nullstr), format_error,
1579                    "string pointer is null");
1580   EXPECT_THROW_MSG((void)fmt::format("{:s}", nullstr), format_error,
1581                    "string pointer is null");
1582 }
1583 
function_pointer_test(int,double,std::string)1584 void function_pointer_test(int, double, std::string) {}
1585 
TEST(format_test,format_pointer)1586 TEST(format_test, format_pointer) {
1587   check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
1588   EXPECT_EQ(fmt::format("{0}", static_cast<void*>(nullptr)), "0x0");
1589   EXPECT_EQ(fmt::format("{0}", reinterpret_cast<void*>(0x1234)), "0x1234");
1590   EXPECT_EQ(fmt::format("{0:p}", reinterpret_cast<void*>(0x1234)), "0x1234");
1591   // On CHERI (or other fat-pointer) systems, the size of a pointer is greater
1592   // than the size an integer that can hold a virtual address.  There is no
1593   // portable address-as-an-integer type (yet) in C++, so we use `size_t` as
1594   // the closest equivalent for now.
1595   EXPECT_EQ("0x" + std::string(sizeof(size_t) * CHAR_BIT / 4, 'f'),
1596             fmt::format("{0}", reinterpret_cast<void*>(~uintptr_t())));
1597   EXPECT_EQ("0x1234",
1598             fmt::format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234))));
1599   EXPECT_EQ(fmt::format("{}", fmt::detail::bit_cast<const void*>(
1600                                   &function_pointer_test)),
1601             fmt::format("{}", fmt::ptr(function_pointer_test)));
1602   EXPECT_EQ(fmt::format("{}", nullptr), "0x0");
1603 }
1604 
TEST(format_test,write_uintptr_fallback)1605 TEST(format_test, write_uintptr_fallback) {
1606   // Test that formatting a pointer by converting it to uint128_fallback works.
1607   // This is needed to support systems without uintptr_t.
1608   auto s = std::string();
1609   fmt::detail::write_ptr<char>(
1610       std::back_inserter(s),
1611       fmt::detail::bit_cast<fmt::detail::uint128_fallback>(
1612           reinterpret_cast<void*>(0xface)),
1613       nullptr);
1614   EXPECT_EQ(s, "0xface");
1615 }
1616 
1617 enum class color { red, green, blue };
1618 
1619 namespace test_ns {
1620 enum class color { red, green, blue };
1621 using fmt::enums::format_as;
1622 }  // namespace test_ns
1623 
TEST(format_test,format_enum_class)1624 TEST(format_test, format_enum_class) {
1625   EXPECT_EQ(fmt::format("{}", fmt::underlying(color::red)), "0");
1626   EXPECT_EQ(fmt::format("{}", test_ns::color::red), "0");
1627 }
1628 
TEST(format_test,format_string)1629 TEST(format_test, format_string) {
1630   EXPECT_EQ(fmt::format("{0}", std::string("test")), "test");
1631   EXPECT_EQ(fmt::format("{0}", std::string("test")), "test");
1632   EXPECT_EQ(fmt::format("{:?}", std::string("test")), "\"test\"");
1633   EXPECT_EQ(fmt::format("{:*^10?}", std::string("test")), "**\"test\"**");
1634   EXPECT_EQ(fmt::format("{:?}", std::string("\test")), "\"\\test\"");
1635   EXPECT_THROW((void)fmt::format(fmt::runtime("{:x}"), std::string("test")),
1636                fmt::format_error);
1637 }
1638 
TEST(format_test,format_string_view)1639 TEST(format_test, format_string_view) {
1640   EXPECT_EQ(fmt::format("{}", string_view("test")), "test");
1641   EXPECT_EQ(fmt::format("{:?}", string_view("t\nst")), "\"t\\nst\"");
1642   EXPECT_EQ(fmt::format("{}", string_view()), "");
1643 }
1644 
1645 #ifdef FMT_USE_STRING_VIEW
1646 struct string_viewable {};
1647 
1648 FMT_BEGIN_NAMESPACE
1649 template <> struct formatter<string_viewable> : formatter<std::string_view> {
formatformatter1650   auto format(string_viewable, format_context& ctx) const
1651       -> decltype(ctx.out()) {
1652     return formatter<std::string_view>::format("foo", ctx);
1653   }
1654 };
1655 FMT_END_NAMESPACE
1656 
TEST(format_test,format_std_string_view)1657 TEST(format_test, format_std_string_view) {
1658   EXPECT_EQ(fmt::format("{}", std::string_view("test")), "test");
1659   EXPECT_EQ(fmt::format("{}", string_viewable()), "foo");
1660 }
1661 
1662 struct explicitly_convertible_to_std_string_view {
operator std::string_viewexplicitly_convertible_to_std_string_view1663   explicit operator std::string_view() const { return "foo"; }
1664 };
1665 
1666 template <>
1667 struct fmt::formatter<explicitly_convertible_to_std_string_view>
1668     : formatter<std::string_view> {
formatfmt::formatter1669   auto format(explicitly_convertible_to_std_string_view v,
1670               format_context& ctx) const -> decltype(ctx.out()) {
1671     return fmt::format_to(ctx.out(), "'{}'", std::string_view(v));
1672   }
1673 };
1674 
TEST(format_test,format_explicitly_convertible_to_std_string_view)1675 TEST(format_test, format_explicitly_convertible_to_std_string_view) {
1676   EXPECT_EQ("'foo'",
1677             fmt::format("{}", explicitly_convertible_to_std_string_view()));
1678 }
1679 
1680 struct convertible_to_std_string_view {
operator std::string_viewconvertible_to_std_string_view1681   operator std::string_view() const noexcept { return "Hi there"; }
1682 };
1683 FMT_BEGIN_NAMESPACE
1684 template <>
1685 class formatter<convertible_to_std_string_view>
1686     : public formatter<std::string_view> {};
1687 FMT_END_NAMESPACE
1688 
TEST(format_test,format_implicitly_convertible_and_inherits_string_view)1689 TEST(format_test, format_implicitly_convertible_and_inherits_string_view) {
1690   static_assert(fmt::is_formattable<convertible_to_std_string_view>{}, "");
1691   EXPECT_EQ("Hi there", fmt::format("{}", convertible_to_std_string_view{}));
1692 }
1693 #endif
1694 
1695 class Answer {};
1696 
1697 FMT_BEGIN_NAMESPACE
1698 template <> struct formatter<date> {
1699   template <typename ParseContext>
parseformatter1700   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
1701     auto it = ctx.begin();
1702     if (it != ctx.end() && *it == 'd') ++it;
1703     return it;
1704   }
1705 
formatformatter1706   auto format(const date& d, format_context& ctx) const -> decltype(ctx.out()) {
1707     // Namespace-qualify to avoid ambiguity with std::format_to.
1708     fmt::format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day());
1709     return ctx.out();
1710   }
1711 };
1712 
1713 template <> struct formatter<Answer> : formatter<int> {
1714   template <typename FormatContext>
formatformatter1715   auto format(Answer, FormatContext& ctx) const -> decltype(ctx.out()) {
1716     return formatter<int>::format(42, ctx);
1717   }
1718 };
1719 FMT_END_NAMESPACE
1720 
TEST(format_test,format_custom)1721 TEST(format_test, format_custom) {
1722   EXPECT_THROW_MSG((void)fmt::format(runtime("{:s}"), date(2012, 12, 9)),
1723                    format_error, "unknown format specifier");
1724   EXPECT_EQ(fmt::format("{0}", Answer()), "42");
1725   EXPECT_EQ(fmt::format("{:04}", Answer()), "0042");
1726 }
1727 
TEST(format_test,format_to_custom)1728 TEST(format_test, format_to_custom) {
1729   char buf[10] = {};
1730   auto end = fmt::format_to(buf, "{}", Answer());
1731   EXPECT_EQ(end, buf + 2);
1732   EXPECT_STREQ(buf, "42");
1733 }
1734 
TEST(format_test,format_string_from_speed_test)1735 TEST(format_test, format_string_from_speed_test) {
1736   EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
1737             fmt::format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42,
1738                         3.13, "str", reinterpret_cast<void*>(1000), 'X'));
1739 }
1740 
TEST(format_test,format_examples)1741 TEST(format_test, format_examples) {
1742   std::string message = fmt::format("The answer is {}", 42);
1743   EXPECT_EQ("The answer is 42", message);
1744 
1745   EXPECT_EQ(fmt::format("{}", 42), "42");
1746 
1747   memory_buffer out;
1748   fmt::format_to(std::back_inserter(out), "The answer is {}.", 42);
1749   EXPECT_EQ("The answer is 42.", to_string(out));
1750 
1751   const char* filename = "nonexistent";
1752   FILE* ftest = safe_fopen(filename, "r");
1753   if (ftest) fclose(ftest);
1754   int error_code = errno;
1755   EXPECT_TRUE(ftest == nullptr);
1756   EXPECT_SYSTEM_ERROR(
1757       {
1758         FILE* f = safe_fopen(filename, "r");
1759         if (!f)
1760           throw fmt::system_error(errno, "Cannot open file '{}'", filename);
1761         fclose(f);
1762       },
1763       error_code, "Cannot open file 'nonexistent'");
1764 
1765   EXPECT_EQ("First, thou shalt count to three",
1766             fmt::format("First, thou shalt count to {0}", "three"));
1767   EXPECT_EQ(fmt::format("Bring me a {}", "shrubbery"), "Bring me a shrubbery");
1768   EXPECT_EQ(fmt::format("From {} to {}", 1, 3), "From 1 to 3");
1769 
1770   char buffer[buffer_size];
1771   safe_sprintf(buffer, "%03.2f", -1.2);
1772   EXPECT_EQ(buffer, fmt::format("{:03.2f}", -1.2));
1773 
1774   EXPECT_EQ(fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'), "a, b, c");
1775   EXPECT_EQ(fmt::format("{}, {}, {}", 'a', 'b', 'c'), "a, b, c");
1776   EXPECT_EQ(fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'), "c, b, a");
1777   EXPECT_EQ(fmt::format("{0}{1}{0}", "abra", "cad"), "abracadabra");
1778 
1779   EXPECT_EQ("left aligned                  ",
1780             fmt::format("{:<30}", "left aligned"));
1781   EXPECT_EQ("                 right aligned",
1782             fmt::format("{:>30}", "right aligned"));
1783   EXPECT_EQ("           centered           ",
1784             fmt::format("{:^30}", "centered"));
1785   EXPECT_EQ("***********centered***********",
1786             fmt::format("{:*^30}", "centered"));
1787 
1788   EXPECT_EQ(fmt::format("{:+f}; {:+f}", 3.14, -3.14), "+3.140000; -3.140000");
1789   EXPECT_EQ(fmt::format("{: f}; {: f}", 3.14, -3.14), " 3.140000; -3.140000");
1790   EXPECT_EQ(fmt::format("{:-f}; {:-f}", 3.14, -3.14), "3.140000; -3.140000");
1791 
1792   EXPECT_EQ("int: 42;  hex: 2a;  oct: 52",
1793             fmt::format("int: {0:d};  hex: {0:x};  oct: {0:o}", 42));
1794   EXPECT_EQ("int: 42;  hex: 0x2a;  oct: 052",
1795             fmt::format("int: {0:d};  hex: {0:#x};  oct: {0:#o}", 42));
1796 
1797   EXPECT_EQ(fmt::format("The answer is {}", 42), "The answer is 42");
1798   EXPECT_THROW_MSG(
1799       (void)fmt::format(runtime("The answer is {:d}"), "forty-two"),
1800       format_error, "invalid format specifier");
1801 
1802   EXPECT_WRITE(
1803       stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
1804 }
1805 
TEST(format_test,print)1806 TEST(format_test, print) {
1807   EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
1808   EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"),
1809                "Don't panic!");
1810   EXPECT_WRITE(stdout, fmt::println("Don't {}!", "panic"), "Don't panic!\n");
1811   EXPECT_WRITE(stderr, fmt::println(stderr, "Don't {}!", "panic"),
1812                "Don't panic!\n");
1813 }
1814 
TEST(format_test,big_print)1815 TEST(format_test, big_print) {
1816   enum { count = 5000 };
1817   auto big_print = []() {
1818     for (int i = 0; i < count / 5; ++i) fmt::print("xxxxx");
1819   };
1820   EXPECT_WRITE(stdout, big_print(), std::string(count, 'x'));
1821 }
1822 
1823 // Windows CRT implements _IOLBF incorrectly (full buffering).
1824 #if FMT_USE_FCNTL && !defined(_WIN32)
TEST(format_test,line_buffering)1825 TEST(format_test, line_buffering) {
1826   auto pipe = fmt::pipe();
1827 
1828   int write_fd = pipe.write_end.descriptor();
1829   auto write_end = pipe.write_end.fdopen("w");
1830   setvbuf(write_end.get(), nullptr, _IOLBF, 4096);
1831   write_end.print("42\n");
1832   close(write_fd);
1833   try {
1834     write_end.close();
1835   } catch (const std::system_error&) {
1836   }
1837 
1838   auto read_end = pipe.read_end.fdopen("r");
1839   std::thread reader([&]() {
1840     int n = 0;
1841     int result = fscanf(read_end.get(), "%d", &n);
1842     (void)result;
1843     EXPECT_EQ(n, 42);
1844   });
1845 
1846   reader.join();
1847 }
1848 #endif
1849 
1850 struct deadlockable {
1851   int value = 0;
1852   mutable std::mutex mutex;
1853 };
1854 
1855 FMT_BEGIN_NAMESPACE
1856 template <> struct formatter<deadlockable> {
parseformatter1857   FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
1858     return ctx.begin();
1859   }
1860 
formatformatter1861   auto format(const deadlockable& d, format_context& ctx) const
1862       -> decltype(ctx.out()) {
1863     std::lock_guard<std::mutex> lock(d.mutex);
1864     return format_to(ctx.out(), "{}", d.value);
1865   }
1866 };
1867 FMT_END_NAMESPACE
1868 
TEST(format_test,locking_formatter)1869 TEST(format_test, locking_formatter) {
1870   auto f = fmt::buffered_file();
1871   try {
1872     f = fmt::buffered_file("/dev/null", "w");
1873   } catch (const std::system_error&) {
1874     fmt::print(stderr, "warning: /dev/null is not supported\n");
1875     return;
1876   }
1877   deadlockable d;
1878   auto t = std::thread([&]() {
1879     fmt::print(f.get(), "start t\n");
1880     std::lock_guard<std::mutex> lock(d.mutex);
1881     for (int i = 0; i < 1000000; ++i) d.value += 10;
1882     fmt::print(f.get(), "done\n");
1883   });
1884   for (int i = 0; i < 100; ++i) fmt::print(f.get(), "{}", d);
1885   t.join();
1886 }
1887 
TEST(format_test,variadic)1888 TEST(format_test, variadic) {
1889   EXPECT_EQ(fmt::format("{}c{}", "ab", 1), "abc1");
1890 }
1891 
TEST(format_test,bytes)1892 TEST(format_test, bytes) {
1893   auto s = fmt::format("{:10}", fmt::bytes("ёжик"));
1894   EXPECT_EQ("ёжик  ", s);
1895   EXPECT_EQ(10, s.size());
1896 }
1897 
TEST(format_test,group_digits_view)1898 TEST(format_test, group_digits_view) {
1899   EXPECT_EQ(fmt::format("{}", fmt::group_digits(10000000)), "10,000,000");
1900   EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(1000)), "   1,000");
1901   EXPECT_EQ(fmt::format("{}", fmt::group_digits(-10000000)), "-10,000,000");
1902   EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(-1000)), "  -1,000");
1903   EXPECT_EQ(fmt::format("{:8}", fmt::group_digits(-100)), "    -100");
1904 }
1905 
1906 #ifdef __cpp_generic_lambdas
1907 struct point {
1908   double x, y;
1909 };
1910 
1911 FMT_BEGIN_NAMESPACE
1912 template <> struct formatter<point> : nested_formatter<double> {
formatformatter1913   auto format(point p, format_context& ctx) const -> decltype(ctx.out()) {
1914     return write_padded(ctx, [this, p](auto out) -> decltype(out) {
1915       return fmt::format_to(out, "({}, {})", this->nested(p.x),
1916                             this->nested(p.y));
1917     });
1918   }
1919 };
1920 FMT_END_NAMESPACE
1921 
TEST(format_test,nested_formatter)1922 TEST(format_test, nested_formatter) {
1923   EXPECT_EQ(fmt::format("{:>16.2f}", point{1, 2}), "    (1.00, 2.00)");
1924 }
1925 #endif  // __cpp_generic_lambdas
1926 
1927 enum test_enum { foo, bar };
format_as(test_enum e)1928 auto format_as(test_enum e) -> int { return e; }
1929 
vformat_message(int id,const char * format,fmt::format_args args)1930 std::string vformat_message(int id, const char* format, fmt::format_args args) {
1931   auto buffer = fmt::memory_buffer();
1932   fmt::format_to(fmt::appender(buffer), "[{}] ", id);
1933   vformat_to(fmt::appender(buffer), format, args);
1934   return to_string(buffer);
1935 }
1936 
1937 template <typename... Args>
format_message(int id,const char * format,const Args &...args)1938 std::string format_message(int id, const char* format, const Args&... args) {
1939   auto va = fmt::make_format_args(args...);
1940   return vformat_message(id, format, va);
1941 }
1942 
TEST(format_test,format_message_example)1943 TEST(format_test, format_message_example) {
1944   EXPECT_EQ("[42] something happened",
1945             format_message(42, "{} happened", "something"));
1946 }
1947 
1948 template <typename... Args>
print_error(const char * file,int line,const char * format,const Args &...args)1949 void print_error(const char* file, int line, const char* format,
1950                  const Args&... args) {
1951   fmt::print("{}: {}: ", file, line);
1952   fmt::print(format, args...);
1953 }
1954 
TEST(format_test,unpacked_args)1955 TEST(format_test, unpacked_args) {
1956   EXPECT_EQ("0123456789abcdefg",
1957             fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5,
1958                         6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g'));
1959 }
1960 
1961 constexpr char with_null[3] = {'{', '}', '\0'};
1962 constexpr char no_null[2] = {'{', '}'};
1963 static constexpr const char static_with_null[3] = {'{', '}', '\0'};
1964 static constexpr const char static_no_null[2] = {'{', '}'};
1965 
TEST(format_test,compile_time_string)1966 TEST(format_test, compile_time_string) {
1967   EXPECT_EQ(fmt::format(FMT_STRING("foo")), "foo");
1968   EXPECT_EQ(fmt::format(FMT_STRING("{}"), 42), "42");
1969 
1970 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
1971   using namespace fmt::literals;
1972   EXPECT_EQ("foobar", fmt::format(FMT_STRING("{foo}{bar}"), "bar"_a = "bar",
1973                                   "foo"_a = "foo"));
1974   EXPECT_EQ(fmt::format(FMT_STRING("")), "");
1975   EXPECT_EQ(fmt::format(FMT_STRING(""), "arg"_a = 42), "");
1976   EXPECT_EQ(fmt::format(FMT_STRING("{answer}"), "answer"_a = Answer()), "42");
1977   EXPECT_EQ(fmt::format(FMT_STRING("{} {two}"), 1, "two"_a = 2), "1 2");
1978 #endif
1979 
1980   (void)static_with_null;
1981   (void)static_no_null;
1982 #ifndef _MSC_VER
1983   EXPECT_EQ(fmt::format(FMT_STRING(static_with_null), 42), "42");
1984   EXPECT_EQ(fmt::format(FMT_STRING(static_no_null), 42), "42");
1985 #endif
1986 
1987   (void)with_null;
1988   (void)no_null;
1989 #if FMT_CPLUSPLUS >= 201703L
1990   EXPECT_EQ(fmt::format(FMT_STRING(with_null), 42), "42");
1991   EXPECT_EQ(fmt::format(FMT_STRING(no_null), 42), "42");
1992 #endif
1993 #if defined(FMT_USE_STRING_VIEW) && FMT_CPLUSPLUS >= 201703L
1994   EXPECT_EQ(fmt::format(FMT_STRING(std::string_view("{}")), 42), "42");
1995 #endif
1996 }
1997 
TEST(format_test,custom_format_compile_time_string)1998 TEST(format_test, custom_format_compile_time_string) {
1999   EXPECT_EQ(fmt::format(FMT_STRING("{}"), Answer()), "42");
2000   auto answer = Answer();
2001   EXPECT_EQ(fmt::format(FMT_STRING("{}"), answer), "42");
2002   char buf[10] = {};
2003   fmt::format_to(buf, FMT_STRING("{}"), answer);
2004   const Answer const_answer = Answer();
2005   EXPECT_EQ(fmt::format(FMT_STRING("{}"), const_answer), "42");
2006 }
2007 
TEST(format_test,named_arg_udl)2008 TEST(format_test, named_arg_udl) {
2009   using namespace fmt::literals;
2010   auto udl_a = fmt::format("{first}{second}{first}{third}", "first"_a = "abra",
2011                            "second"_a = "cad", "third"_a = 99);
2012   EXPECT_EQ(
2013       fmt::format("{first}{second}{first}{third}", fmt::arg("first", "abra"),
2014                   fmt::arg("second", "cad"), fmt::arg("third", 99)),
2015       udl_a);
2016 
2017   EXPECT_EQ(fmt::format("{answer}", "answer"_a = Answer()), "42");
2018 }
2019 
TEST(format_test,enum)2020 TEST(format_test, enum) { EXPECT_EQ(fmt::format("{}", foo), "0"); }
2021 
TEST(format_test,formatter_not_specialized)2022 TEST(format_test, formatter_not_specialized) {
2023   static_assert(!fmt::is_formattable<fmt::formatter<test_enum>,
2024                                      fmt::format_context>::value,
2025                 "");
2026 }
2027 
2028 #if FMT_HAS_FEATURE(cxx_strong_enums)
2029 enum big_enum : unsigned long long { big_enum_value = 5000000000ULL };
format_as(big_enum e)2030 auto format_as(big_enum e) -> unsigned long long { return e; }
2031 
TEST(format_test,strong_enum)2032 TEST(format_test, strong_enum) {
2033   auto arg = fmt::basic_format_arg<fmt::context>(big_enum_value);
2034   EXPECT_EQ(arg.type(), fmt::detail::type::ulong_long_type);
2035   EXPECT_EQ(fmt::format("{}", big_enum_value), "5000000000");
2036 }
2037 #endif
2038 
TEST(format_test,non_null_terminated_format_string)2039 TEST(format_test, non_null_terminated_format_string) {
2040   EXPECT_EQ(fmt::format(string_view("{}foo", 2), 42), "42");
2041 }
2042 
2043 namespace adl_test {
2044 namespace fmt {
2045 namespace detail {
2046 struct foo {};
2047 template <typename, typename OutputIt> void write(OutputIt, foo) = delete;
2048 }  // namespace detail
2049 }  // namespace fmt
2050 }  // namespace adl_test
2051 
2052 FMT_BEGIN_NAMESPACE
2053 template <>
2054 struct formatter<adl_test::fmt::detail::foo> : formatter<std::string> {
formatformatter2055   auto format(adl_test::fmt::detail::foo, format_context& ctx) const
2056       -> decltype(ctx.out()) {
2057     return formatter<std::string>::format("foo", ctx);
2058   }
2059 };
2060 FMT_END_NAMESPACE
2061 
TEST(format_test,to_string)2062 TEST(format_test, to_string) {
2063   EXPECT_EQ(fmt::to_string(42), "42");
2064   EXPECT_EQ(fmt::to_string(reinterpret_cast<void*>(0x1234)), "0x1234");
2065   EXPECT_EQ(fmt::to_string(adl_test::fmt::detail::foo()), "foo");
2066   EXPECT_EQ(fmt::to_string(foo), "0");
2067 
2068 #if FMT_USE_FLOAT128
2069   EXPECT_EQ(fmt::to_string(__float128(0.5)), "0.5");
2070 #endif
2071 
2072 #if defined(FMT_USE_STRING_VIEW) && FMT_CPLUSPLUS >= 201703L
2073   EXPECT_EQ(fmt::to_string(std::string_view()), "");
2074 #endif
2075 }
2076 
TEST(format_test,output_iterators)2077 TEST(format_test, output_iterators) {
2078   std::list<char> out;
2079   fmt::format_to(std::back_inserter(out), "{}", 42);
2080   EXPECT_EQ("42", std::string(out.begin(), out.end()));
2081   std::stringstream s;
2082   fmt::format_to(std::ostream_iterator<char>(s), "{}", 42);
2083   EXPECT_EQ("42", s.str());
2084 }
2085 
TEST(format_test,fill_via_appender)2086 TEST(format_test, fill_via_appender) {
2087   fmt::memory_buffer buf;
2088   auto it = fmt::appender(buf);
2089   std::fill_n(it, 3, '~');
2090   EXPECT_EQ(fmt::to_string(buf), "~~~");
2091 }
2092 
TEST(format_test,formatted_size)2093 TEST(format_test, formatted_size) {
2094   EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
2095   EXPECT_EQ(2u, fmt::formatted_size(std::locale(), "{}", 42));
2096 }
2097 
TEST(format_test,format_to_no_args)2098 TEST(format_test, format_to_no_args) {
2099   std::string s;
2100   fmt::format_to(std::back_inserter(s), "test");
2101   EXPECT_EQ("test", s);
2102 }
2103 
TEST(format_test,format_to)2104 TEST(format_test, format_to) {
2105   std::string s;
2106   fmt::format_to(std::back_inserter(s), "part{0}", 1);
2107   EXPECT_EQ("part1", s);
2108   fmt::format_to(std::back_inserter(s), "part{0}", 2);
2109   EXPECT_EQ("part1part2", s);
2110 }
2111 
TEST(format_test,format_to_memory_buffer)2112 TEST(format_test, format_to_memory_buffer) {
2113   auto buf = fmt::basic_memory_buffer<char, 100>();
2114   fmt::format_to(fmt::appender(buf), "{}", "foo");
2115   EXPECT_EQ("foo", to_string(buf));
2116 }
2117 
TEST(format_test,format_to_vector)2118 TEST(format_test, format_to_vector) {
2119   std::vector<char> v;
2120   fmt::format_to(std::back_inserter(v), "{}", "foo");
2121   EXPECT_EQ(string_view(v.data(), v.size()), "foo");
2122 }
2123 
2124 struct nongrowing_container {
2125   using value_type = char;
push_backnongrowing_container2126   void push_back(char) { throw std::runtime_error("can't take it any more"); }
2127 };
2128 
TEST(format_test,format_to_propagates_exceptions)2129 TEST(format_test, format_to_propagates_exceptions) {
2130   auto c = nongrowing_container();
2131   EXPECT_THROW(fmt::format_to(std::back_inserter(c), "{}", 42),
2132                std::runtime_error);
2133 }
2134 
TEST(format_test,format_to_n)2135 TEST(format_test, format_to_n) {
2136   char buffer[4];
2137   buffer[3] = 'x';
2138   auto result = fmt::format_to_n(buffer, 3, "{}", 12345);
2139   EXPECT_EQ(5u, result.size);
2140   EXPECT_EQ(buffer + 3, result.out);
2141   EXPECT_EQ("123x", fmt::string_view(buffer, 4));
2142 
2143   result = fmt::format_to_n(buffer, 3, "{:s}", "foobar");
2144   EXPECT_EQ(6u, result.size);
2145   EXPECT_EQ(buffer + 3, result.out);
2146   EXPECT_EQ("foox", fmt::string_view(buffer, 4));
2147 
2148   buffer[0] = 'x';
2149   buffer[1] = 'x';
2150   buffer[2] = 'x';
2151   result = fmt::format_to_n(buffer, 3, "{}", 'A');
2152   EXPECT_EQ(1u, result.size);
2153   EXPECT_EQ(buffer + 1, result.out);
2154   EXPECT_EQ("Axxx", fmt::string_view(buffer, 4));
2155 
2156   result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C');
2157   EXPECT_EQ(3u, result.size);
2158   EXPECT_EQ(buffer + 3, result.out);
2159   EXPECT_EQ("BC x", fmt::string_view(buffer, 4));
2160 
2161   result = fmt::format_to_n(buffer, 4, "{}", "ABCDE");
2162   EXPECT_EQ(5u, result.size);
2163   EXPECT_EQ("ABCD", fmt::string_view(buffer, 4));
2164 
2165   buffer[3] = 'x';
2166   result = fmt::format_to_n(buffer, 3, "{}", std::string(1000, '*'));
2167   EXPECT_EQ(1000u, result.size);
2168   EXPECT_EQ("***x", fmt::string_view(buffer, 4));
2169 }
2170 
2171 struct test_output_iterator {
2172   char* data;
2173 
2174   using iterator_category = std::output_iterator_tag;
2175   using value_type = void;
2176   using difference_type = void;
2177   using pointer = void;
2178   using reference = void;
2179 
operator ++test_output_iterator2180   auto operator++() -> test_output_iterator& {
2181     ++data;
2182     return *this;
2183   }
operator ++test_output_iterator2184   auto operator++(int) -> test_output_iterator {
2185     auto tmp = *this;
2186     ++data;
2187     return tmp;
2188   }
operator *test_output_iterator2189   auto operator*() -> char& { return *data; }
2190 };
2191 
TEST(format_test,format_to_n_output_iterator)2192 TEST(format_test, format_to_n_output_iterator) {
2193   char buf[10] = {};
2194   fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42);
2195   EXPECT_STREQ(buf, "42");
2196 }
2197 
TEST(format_test,vformat_to)2198 TEST(format_test, vformat_to) {
2199   using context = fmt::format_context;
2200   int n = 42;
2201   auto args = fmt::make_format_args<context>(n);
2202   auto s = std::string();
2203   fmt::vformat_to(std::back_inserter(s), "{}", args);
2204   EXPECT_EQ(s, "42");
2205   s.clear();
2206   fmt::vformat_to(std::back_inserter(s), "{}", args);
2207   EXPECT_EQ(s, "42");
2208 }
2209 
TEST(format_test,char_traits_not_ambiguous)2210 TEST(format_test, char_traits_not_ambiguous) {
2211   // Test that we don't inject detail names into the std namespace.
2212   using namespace std;
2213   auto c = char_traits<char>::char_type();
2214   (void)c;
2215 #if FMT_CPLUSPLUS >= 201103L
2216   auto s = std::string();
2217   auto lval = begin(s);
2218   (void)lval;
2219 #endif
2220 }
2221 
2222 struct check_back_appender {};
2223 
2224 FMT_BEGIN_NAMESPACE
2225 template <> struct formatter<check_back_appender> {
parseformatter2226   FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
2227     return ctx.begin();
2228   }
2229 
2230   template <typename Context>
formatformatter2231   auto format(check_back_appender, Context& ctx) const -> decltype(ctx.out()) {
2232     auto out = ctx.out();
2233     static_assert(std::is_same<decltype(++out), decltype(out)&>::value,
2234                   "needs to satisfy weakly_incrementable");
2235     *out = 'y';
2236     return ++out;
2237   }
2238 };
2239 FMT_END_NAMESPACE
2240 
TEST(format_test,back_insert_slicing)2241 TEST(format_test, back_insert_slicing) {
2242   EXPECT_EQ(fmt::format("{}", check_back_appender{}), "y");
2243 }
2244 
2245 namespace test {
2246 enum class scoped_enum_as_int {};
format_as(scoped_enum_as_int)2247 auto format_as(scoped_enum_as_int) -> int { return 42; }
2248 
2249 enum class scoped_enum_as_string_view {};
format_as(scoped_enum_as_string_view)2250 auto format_as(scoped_enum_as_string_view) -> fmt::string_view { return "foo"; }
2251 
2252 enum class scoped_enum_as_string {};
format_as(scoped_enum_as_string)2253 auto format_as(scoped_enum_as_string) -> std::string { return "foo"; }
2254 
2255 struct struct_as_int {};
format_as(struct_as_int)2256 auto format_as(struct_as_int) -> int { return 42; }
2257 
2258 struct struct_as_const_reference {
2259   const std::string name = "foo";
2260 };
format_as(const struct_as_const_reference & s)2261 auto format_as(const struct_as_const_reference& s) -> const std::string& {
2262   return s.name;
2263 }
2264 }  // namespace test
2265 
TEST(format_test,format_as)2266 TEST(format_test, format_as) {
2267   EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_int()), "42");
2268   EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string_view()), "foo");
2269   EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string()), "foo");
2270   EXPECT_EQ(fmt::format("{}", test::struct_as_int()), "42");
2271   EXPECT_EQ(fmt::format("{}", test::struct_as_const_reference()), "foo");
2272 }
2273 
TEST(format_test,format_as_to_string)2274 TEST(format_test, format_as_to_string) {
2275   EXPECT_EQ(fmt::to_string(test::scoped_enum_as_int()), "42");
2276   EXPECT_EQ(fmt::to_string(test::scoped_enum_as_string_view()), "foo");
2277   EXPECT_EQ(fmt::to_string(test::scoped_enum_as_string()), "foo");
2278   EXPECT_EQ(fmt::to_string(test::struct_as_int()), "42");
2279 }
2280 
check_enabled_formatter()2281 template <typename Char, typename T> auto check_enabled_formatter() -> bool {
2282   static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
2283                 "");
2284   return true;
2285 }
2286 
check_enabled_formatters()2287 template <typename Char, typename... T> void check_enabled_formatters() {
2288   auto dummy = {check_enabled_formatter<Char, T>()...};
2289   (void)dummy;
2290 }
2291 
TEST(format_test,test_formatters_enabled)2292 TEST(format_test, test_formatters_enabled) {
2293   using custom_string =
2294       std::basic_string<char, std::char_traits<char>, mock_allocator<char>>;
2295   using custom_wstring = std::basic_string<wchar_t, std::char_traits<wchar_t>,
2296                                            mock_allocator<wchar_t>>;
2297 
2298   check_enabled_formatters<char, bool, char, signed char, unsigned char, short,
2299                            unsigned short, int, unsigned, long, unsigned long,
2300                            long long, unsigned long long, float, double,
2301                            long double, void*, const void*, char*, const char*,
2302                            std::string, custom_string, std::nullptr_t>();
2303   check_enabled_formatters<
2304       wchar_t, bool, wchar_t, signed char, unsigned char, short, unsigned short,
2305       int, unsigned, long, unsigned long, long long, unsigned long long, float,
2306       double, long double, void*, const void*, wchar_t*, const wchar_t*,
2307       std::wstring, custom_wstring, std::nullptr_t>();
2308 }
2309 
TEST(format_int_test,data)2310 TEST(format_int_test, data) {
2311   fmt::format_int format_int(42);
2312   EXPECT_EQ(std::string(format_int.data(), format_int.size()), "42");
2313 }
2314 
TEST(format_int_test,format_int)2315 TEST(format_int_test, format_int) {
2316   EXPECT_EQ(fmt::format_int(42).str(), "42");
2317   EXPECT_EQ(fmt::format_int(42).size(), 2u);
2318   EXPECT_EQ(fmt::format_int(-42).str(), "-42");
2319   EXPECT_EQ(fmt::format_int(-42).size(), 3u);
2320   EXPECT_EQ(fmt::format_int(42ul).str(), "42");
2321   EXPECT_EQ(fmt::format_int(-42l).str(), "-42");
2322   EXPECT_EQ(fmt::format_int(42ull).str(), "42");
2323   EXPECT_EQ(fmt::format_int(-42ll).str(), "-42");
2324   EXPECT_EQ(fmt::format_int(max_value<int64_t>()).str(),
2325             std::to_string(max_value<int64_t>()));
2326 }
2327 
2328 #ifndef FMT_STATIC_THOUSANDS_SEPARATOR
2329 
2330 #  include <locale>
2331 
2332 class format_facet : public fmt::format_facet<std::locale> {
2333  protected:
2334   struct int_formatter {
2335     fmt::appender out;
2336 
2337     template <typename T, FMT_ENABLE_IF(fmt::detail::is_integer<T>::value)>
operator ()format_facet::int_formatter2338     auto operator()(T value) -> bool {
2339       fmt::format_to(out, "[{}]", value);
2340       return true;
2341     }
2342 
2343     template <typename T, FMT_ENABLE_IF(!fmt::detail::is_integer<T>::value)>
operator ()format_facet::int_formatter2344     auto operator()(T) -> bool {
2345       return false;
2346     }
2347   };
2348 
2349   auto do_put(fmt::appender out, fmt::loc_value val,
2350               const fmt::format_specs&) const -> bool override;
2351 };
2352 
do_put(fmt::appender out,fmt::loc_value val,const fmt::format_specs &) const2353 auto format_facet::do_put(fmt::appender out, fmt::loc_value val,
2354                           const fmt::format_specs&) const -> bool {
2355   return val.visit(int_formatter{out});
2356 }
2357 
TEST(format_test,format_facet)2358 TEST(format_test, format_facet) {
2359   auto loc = std::locale(std::locale(), new format_facet());
2360   EXPECT_EQ(fmt::format(loc, "{:L}", 42), "[42]");
2361   EXPECT_EQ(fmt::format(loc, "{:L}", -42), "[-42]");
2362 }
2363 
TEST(format_test,format_facet_separator)2364 TEST(format_test, format_facet_separator) {
2365   // U+2019 RIGHT SINGLE QUOTATION MARK is a digit separator in the de_CH
2366   // locale.
2367   auto loc =
2368       std::locale({}, new fmt::format_facet<std::locale>("\xe2\x80\x99"));
2369   EXPECT_EQ(fmt::format(loc, "{:L}", 1000),
2370             "1\xe2\x80\x99"
2371             "000");
2372 }
2373 
TEST(format_test,format_facet_grouping)2374 TEST(format_test, format_facet_grouping) {
2375   auto loc =
2376       std::locale({}, new fmt::format_facet<std::locale>(",", {1, 2, 3}));
2377   EXPECT_EQ(fmt::format(loc, "{:L}", 1234567890), "1,234,567,89,0");
2378 }
2379 
TEST(format_test,format_named_arg_with_locale)2380 TEST(format_test, format_named_arg_with_locale) {
2381   EXPECT_EQ(fmt::format(std::locale(), "{answer}", fmt::arg("answer", 42)),
2382             "42");
2383 }
2384 
TEST(format_test,format_locale)2385 TEST(format_test, format_locale) {
2386   auto loc = std::locale({}, new fmt::format_facet<std::locale>(","));
2387   EXPECT_EQ(fmt::format(loc, "{:Lx}", 123456789), "7,5bc,d15");
2388   EXPECT_EQ(fmt::format(loc, "{:#Lb}", -123456789),
2389             "-0b111,010,110,111,100,110,100,010,101");
2390   EXPECT_EQ(fmt::format(loc, "{:10Lo}", 12345), "    30,071");
2391 }
2392 
2393 #endif  // FMT_STATIC_THOUSANDS_SEPARATOR
2394 
2395 struct convertible_to_nonconst_cstring {
operator char*convertible_to_nonconst_cstring2396   operator char*() const {
2397     static char c[] = "bar";
2398     return c;
2399   }
2400 };
2401 
2402 FMT_BEGIN_NAMESPACE
2403 template <>
2404 struct formatter<convertible_to_nonconst_cstring> : formatter<char*> {};
2405 FMT_END_NAMESPACE
2406 
TEST(format_test,formatter_nonconst_char)2407 TEST(format_test, formatter_nonconst_char) {
2408   EXPECT_EQ(fmt::format("{}", convertible_to_nonconst_cstring()), "bar");
2409 }
2410 
2411 namespace adl_test {
2412 template <typename... T> void make_format_args(const T&...) = delete;
2413 
2414 struct string : std::string {};
format_as(const string & s)2415 auto format_as(const string& s) -> std::string { return s; }
2416 }  // namespace adl_test
2417 
2418 // Test that formatting functions compile when make_format_args is found by ADL.
TEST(format_test,adl)2419 TEST(format_test, adl) {
2420   // Only check compilation and don't run the code to avoid polluting the output
2421   // and since the output is tested elsewhere.
2422   if (fmt::detail::const_check(true)) return;
2423   auto s = adl_test::string();
2424   char buf[10];
2425   (void)fmt::format("{}", s);
2426   fmt::format_to(buf, "{}", s);
2427   fmt::format_to_n(buf, 10, "{}", s);
2428   (void)fmt::formatted_size("{}", s);
2429   fmt::print("{}", s);
2430   fmt::print(stdout, "{}", s);
2431 }
2432 
2433 struct convertible_to_int {
operator intconvertible_to_int2434   operator int() const { return 42; }
2435 };
2436 
2437 struct convertible_to_cstring {
operator const char*convertible_to_cstring2438   operator const char*() const { return "foo"; }
2439 };
2440 
2441 FMT_BEGIN_NAMESPACE
2442 template <> struct formatter<convertible_to_int> {
parseformatter2443   FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
2444     return ctx.begin();
2445   }
formatformatter2446   auto format(convertible_to_int, format_context& ctx) const
2447       -> decltype(ctx.out()) {
2448     auto out = ctx.out();
2449     *out++ = 'x';
2450     return out;
2451   }
2452 };
2453 
2454 template <> struct formatter<convertible_to_cstring> {
parseformatter2455   FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
2456     return ctx.begin();
2457   }
formatformatter2458   auto format(convertible_to_cstring, format_context& ctx) const
2459       -> decltype(ctx.out()) {
2460     auto out = ctx.out();
2461     *out++ = 'y';
2462     return out;
2463   }
2464 };
2465 FMT_END_NAMESPACE
2466 
TEST(format_test,formatter_overrides_implicit_conversion)2467 TEST(format_test, formatter_overrides_implicit_conversion) {
2468   EXPECT_EQ(fmt::format("{}", convertible_to_int()), "x");
2469   EXPECT_EQ(fmt::format("{}", convertible_to_cstring()), "y");
2470 }
2471 
2472 struct ustring {
2473   using value_type = unsigned;
2474 
2475   auto find_first_of(value_type, size_t) const -> size_t;
2476 
2477   auto data() const -> const char*;
2478   auto size() const -> size_t;
2479 };
2480 
2481 FMT_BEGIN_NAMESPACE
2482 template <> struct formatter<ustring> : formatter<std::string> {
formatformatter2483   auto format(const ustring&, format_context& ctx) const
2484       -> decltype(ctx.out()) {
2485     return formatter<std::string>::format("ustring", ctx);
2486   }
2487 };
2488 FMT_END_NAMESPACE
2489 
TEST(format_test,ustring)2490 TEST(format_test, ustring) {
2491   EXPECT_EQ(fmt::format("{}", ustring()), "ustring");
2492 }
2493 
TEST(format_test,writer)2494 TEST(format_test, writer) {
2495   auto write_to_stdout = []() {
2496     auto w = fmt::writer(stdout);
2497     w.print("{}", 42);
2498   };
2499   EXPECT_WRITE(stdout, write_to_stdout(), "42");
2500 
2501 #if FMT_USE_FCNTL
2502   auto pipe = fmt::pipe();
2503   auto write_end = pipe.write_end.fdopen("w");
2504   fmt::writer(write_end.get()).print("42");
2505   write_end.close();
2506   auto read_end = pipe.read_end.fdopen("r");
2507   int n = 0;
2508   int result = fscanf(read_end.get(), "%d", &n);
2509   (void)result;
2510   EXPECT_EQ(n, 42);
2511 #endif
2512 
2513   auto s = fmt::string_buffer();
2514   fmt::writer(s).print("foo");
2515   EXPECT_EQ(s.str(), "foo");
2516 }
2517 
2518 #if FMT_USE_BITINT
2519 FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension")
2520 
TEST(format_test,bitint)2521 TEST(format_test, bitint) {
2522   using fmt::detail::bitint;
2523   using fmt::detail::ubitint;
2524 
2525   EXPECT_EQ(fmt::format("{}", ubitint<3>(7)), "7");
2526   EXPECT_EQ(fmt::format("{}", bitint<7>()), "0");
2527 
2528   EXPECT_EQ(fmt::format("{}", ubitint<15>(31000)), "31000");
2529   EXPECT_EQ(fmt::format("{}", bitint<16>(INT16_MIN)), "-32768");
2530   EXPECT_EQ(fmt::format("{}", bitint<16>(INT16_MAX)), "32767");
2531 
2532   EXPECT_EQ(fmt::format("{}", ubitint<32>(4294967295)), "4294967295");
2533 
2534   EXPECT_EQ(fmt::format("{}", ubitint<47>(140737488355327ULL)),
2535             "140737488355327");
2536   EXPECT_EQ(fmt::format("{}", bitint<47>(-40737488355327LL)),
2537             "-40737488355327");
2538 
2539   // Check lvalues and const
2540   auto a = bitint<8>(0);
2541   auto b = ubitint<32>(4294967295);
2542   const auto c = bitint<7>(0);
2543   const auto d = ubitint<32>(4294967295);
2544   EXPECT_EQ(fmt::format("{}", a), "0");
2545   EXPECT_EQ(fmt::format("{}", b), "4294967295");
2546   EXPECT_EQ(fmt::format("{}", c), "0");
2547   EXPECT_EQ(fmt::format("{}", d), "4294967295");
2548 
2549   static_assert(fmt::is_formattable<bitint<64>, char>{}, "");
2550   static_assert(fmt::is_formattable<ubitint<64>, char>{}, "");
2551 }
2552 #endif
2553 
2554 #ifdef __cpp_lib_byte
TEST(base_test,format_byte)2555 TEST(base_test, format_byte) {
2556   auto s = std::string();
2557   fmt::format_to(std::back_inserter(s), "{}", std::byte(42));
2558   EXPECT_EQ(s, "42");
2559 }
2560 #endif
2561