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 #include <stdint.h>
9
10 #include <cctype>
11 #include <cfloat>
12 #include <climits>
13 #include <cmath>
14 #include <cstring>
15 #include <list>
16 #include <memory>
17 #include <string>
18
19 // Check if fmt/format.h compiles with windows.h included before it.
20 #ifdef _WIN32
21 # include <windows.h>
22 #endif
23
24 // Check if fmt/format.h compiles with the X11 index macro defined.
25 #define index(x, y) no nice things
26
27 #include "fmt/format.h"
28
29 #undef index
30
31 #include "gmock.h"
32 #include "gtest-extra.h"
33 #include "mock-allocator.h"
34 #include "util.h"
35
36 #undef ERROR
37
38 using fmt::basic_memory_buffer;
39 using fmt::format;
40 using fmt::format_error;
41 using fmt::memory_buffer;
42 using fmt::string_view;
43 using fmt::wmemory_buffer;
44 using fmt::wstring_view;
45 using fmt::detail::max_value;
46
47 using testing::Return;
48 using testing::StrictMock;
49
50 namespace {
51
52 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408
check_enabled_formatter()53 template <typename Char, typename T> bool check_enabled_formatter() {
54 static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
55 "");
56 return true;
57 }
58
check_enabled_formatters()59 template <typename Char, typename... T> void check_enabled_formatters() {
60 auto dummy = {check_enabled_formatter<Char, T>()...};
61 (void)dummy;
62 }
63
TEST(FormatterTest,TestFormattersEnabled)64 TEST(FormatterTest, TestFormattersEnabled) {
65 check_enabled_formatters<char, bool, char, signed char, unsigned char, short,
66 unsigned short, int, unsigned, long, unsigned long,
67 long long, unsigned long long, float, double,
68 long double, void*, const void*, char*, const char*,
69 std::string, std::nullptr_t>();
70 check_enabled_formatters<wchar_t, bool, wchar_t, signed char, unsigned char,
71 short, unsigned short, int, unsigned, long,
72 unsigned long, long long, unsigned long long, float,
73 double, long double, void*, const void*, wchar_t*,
74 const wchar_t*, std::wstring, std::nullptr_t>();
75 }
76 #endif
77
78 // Format value using the standard library.
79 template <typename Char, typename T>
std_format(const T & value,std::basic_string<Char> & result)80 void std_format(const T& value, std::basic_string<Char>& result) {
81 std::basic_ostringstream<Char> os;
82 os << value;
83 result = os.str();
84 }
85
86 #ifdef __MINGW32__
87 // Workaround a bug in formatting long double in MinGW.
std_format(long double value,std::string & result)88 void std_format(long double value, std::string& result) {
89 char buffer[100];
90 safe_sprintf(buffer, "%Lg", value);
91 result = buffer;
92 }
std_format(long double value,std::wstring & result)93 void std_format(long double value, std::wstring& result) {
94 wchar_t buffer[100];
95 swprintf(buffer, L"%Lg", value);
96 result = buffer;
97 }
98 #endif
99 } // namespace
100
101 struct uint32_pair {
102 uint32_t u[2];
103 };
104
TEST(UtilTest,BitCast)105 TEST(UtilTest, BitCast) {
106 auto s = fmt::detail::bit_cast<uint32_pair>(uint64_t{42});
107 EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), 42ull);
108 s = fmt::detail::bit_cast<uint32_pair>(uint64_t(~0ull));
109 EXPECT_EQ(fmt::detail::bit_cast<uint64_t>(s), ~0ull);
110 }
111
TEST(UtilTest,Increment)112 TEST(UtilTest, Increment) {
113 char s[10] = "123";
114 increment(s);
115 EXPECT_STREQ("124", s);
116 s[2] = '8';
117 increment(s);
118 EXPECT_STREQ("129", s);
119 increment(s);
120 EXPECT_STREQ("130", s);
121 s[1] = s[2] = '9';
122 increment(s);
123 EXPECT_STREQ("200", s);
124 }
125
TEST(UtilTest,ParseNonnegativeInt)126 TEST(UtilTest, ParseNonnegativeInt) {
127 if (max_value<int>() != static_cast<int>(static_cast<unsigned>(1) << 31)) {
128 fmt::print("Skipping parse_nonnegative_int test\n");
129 return;
130 }
131 fmt::string_view s = "10000000000";
132 auto begin = s.begin(), end = s.end();
133 EXPECT_THROW_MSG(
134 parse_nonnegative_int(begin, end, fmt::detail::error_handler()),
135 fmt::format_error, "number is too big");
136 s = "2147483649";
137 begin = s.begin();
138 end = s.end();
139 EXPECT_THROW_MSG(
140 parse_nonnegative_int(begin, end, fmt::detail::error_handler()),
141 fmt::format_error, "number is too big");
142 }
143
TEST(IteratorTest,CountingIterator)144 TEST(IteratorTest, CountingIterator) {
145 fmt::detail::counting_iterator it;
146 auto prev = it++;
147 EXPECT_EQ(prev.count(), 0);
148 EXPECT_EQ(it.count(), 1);
149 EXPECT_EQ((it + 41).count(), 42);
150 }
151
TEST(IteratorTest,TruncatingIterator)152 TEST(IteratorTest, TruncatingIterator) {
153 char* p = nullptr;
154 fmt::detail::truncating_iterator<char*> it(p, 3);
155 auto prev = it++;
156 EXPECT_EQ(prev.base(), p);
157 EXPECT_EQ(it.base(), p + 1);
158 }
159
TEST(IteratorTest,TruncatingBackInserter)160 TEST(IteratorTest, TruncatingBackInserter) {
161 std::string buffer;
162 auto bi = std::back_inserter(buffer);
163 fmt::detail::truncating_iterator<decltype(bi)> it(bi, 2);
164 *it++ = '4';
165 *it++ = '2';
166 *it++ = '1';
167 EXPECT_EQ(buffer.size(), 2);
168 EXPECT_EQ(buffer, "42");
169 }
170
TEST(IteratorTest,IsOutputIterator)171 TEST(IteratorTest, IsOutputIterator) {
172 EXPECT_TRUE((fmt::detail::is_output_iterator<char*, char>::value));
173 EXPECT_FALSE((fmt::detail::is_output_iterator<const char*, char>::value));
174 EXPECT_FALSE((fmt::detail::is_output_iterator<std::string, char>::value));
175 EXPECT_TRUE(
176 (fmt::detail::is_output_iterator<std::back_insert_iterator<std::string>,
177 char>::value));
178 EXPECT_TRUE(
179 (fmt::detail::is_output_iterator<std::string::iterator, char>::value));
180 EXPECT_FALSE((fmt::detail::is_output_iterator<std::string::const_iterator,
181 char>::value));
182 EXPECT_FALSE((fmt::detail::is_output_iterator<std::list<char>, char>::value));
183 EXPECT_TRUE((
184 fmt::detail::is_output_iterator<std::list<char>::iterator, char>::value));
185 EXPECT_FALSE((fmt::detail::is_output_iterator<std::list<char>::const_iterator,
186 char>::value));
187 EXPECT_FALSE((fmt::detail::is_output_iterator<uint32_pair, char>::value));
188 }
189
TEST(MemoryBufferTest,Ctor)190 TEST(MemoryBufferTest, Ctor) {
191 basic_memory_buffer<char, 123> buffer;
192 EXPECT_EQ(static_cast<size_t>(0), buffer.size());
193 EXPECT_EQ(123u, buffer.capacity());
194 }
195
check_forwarding(mock_allocator<int> & alloc,allocator_ref<mock_allocator<int>> & ref)196 static void check_forwarding(mock_allocator<int>& alloc,
197 allocator_ref<mock_allocator<int>>& ref) {
198 int mem;
199 // Check if value_type is properly defined.
200 allocator_ref<mock_allocator<int>>::value_type* ptr = &mem;
201 // Check forwarding.
202 EXPECT_CALL(alloc, allocate(42)).WillOnce(testing::Return(ptr));
203 ref.allocate(42);
204 EXPECT_CALL(alloc, deallocate(ptr, 42));
205 ref.deallocate(ptr, 42);
206 }
207
TEST(AllocatorTest,allocator_ref)208 TEST(AllocatorTest, allocator_ref) {
209 StrictMock<mock_allocator<int>> alloc;
210 typedef allocator_ref<mock_allocator<int>> test_allocator_ref;
211 test_allocator_ref ref(&alloc);
212 // Check if allocator_ref forwards to the underlying allocator.
213 check_forwarding(alloc, ref);
214 test_allocator_ref ref2(ref);
215 check_forwarding(alloc, ref2);
216 test_allocator_ref ref3;
217 EXPECT_EQ(nullptr, ref3.get());
218 ref3 = ref;
219 check_forwarding(alloc, ref3);
220 }
221
222 typedef allocator_ref<std::allocator<char>> TestAllocator;
223
check_move_buffer(const char * str,basic_memory_buffer<char,5,TestAllocator> & buffer)224 static void check_move_buffer(
225 const char* str, basic_memory_buffer<char, 5, TestAllocator>& buffer) {
226 std::allocator<char>* alloc = buffer.get_allocator().get();
227 basic_memory_buffer<char, 5, TestAllocator> buffer2(std::move(buffer));
228 // Move shouldn't destroy the inline content of the first buffer.
229 EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
230 EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
231 EXPECT_EQ(5u, buffer2.capacity());
232 // Move should transfer allocator.
233 EXPECT_EQ(nullptr, buffer.get_allocator().get());
234 EXPECT_EQ(alloc, buffer2.get_allocator().get());
235 }
236
TEST(MemoryBufferTest,MoveCtorInlineBuffer)237 TEST(MemoryBufferTest, MoveCtorInlineBuffer) {
238 std::allocator<char> alloc;
239 basic_memory_buffer<char, 5, TestAllocator> buffer((TestAllocator(&alloc)));
240 const char test[] = "test";
241 buffer.append(string_view(test, 4));
242 check_move_buffer("test", buffer);
243 // Adding one more character fills the inline buffer, but doesn't cause
244 // dynamic allocation.
245 buffer.push_back('a');
246 check_move_buffer("testa", buffer);
247 }
248
TEST(MemoryBufferTest,MoveCtorDynamicBuffer)249 TEST(MemoryBufferTest, MoveCtorDynamicBuffer) {
250 std::allocator<char> alloc;
251 basic_memory_buffer<char, 4, TestAllocator> buffer((TestAllocator(&alloc)));
252 const char test[] = "test";
253 buffer.append(test, test + 4);
254 const char* inline_buffer_ptr = &buffer[0];
255 // Adding one more character causes the content to move from the inline to
256 // a dynamically allocated buffer.
257 buffer.push_back('a');
258 basic_memory_buffer<char, 4, TestAllocator> buffer2(std::move(buffer));
259 // Move should rip the guts of the first buffer.
260 EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
261 EXPECT_EQ("testa", std::string(&buffer2[0], buffer2.size()));
262 EXPECT_GT(buffer2.capacity(), 4u);
263 }
264
check_move_assign_buffer(const char * str,basic_memory_buffer<char,5> & buffer)265 static void check_move_assign_buffer(const char* str,
266 basic_memory_buffer<char, 5>& buffer) {
267 basic_memory_buffer<char, 5> buffer2;
268 buffer2 = std::move(buffer);
269 // Move shouldn't destroy the inline content of the first buffer.
270 EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
271 EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
272 EXPECT_EQ(5u, buffer2.capacity());
273 }
274
TEST(MemoryBufferTest,MoveAssignment)275 TEST(MemoryBufferTest, MoveAssignment) {
276 basic_memory_buffer<char, 5> buffer;
277 const char test[] = "test";
278 buffer.append(test, test + 4);
279 check_move_assign_buffer("test", buffer);
280 // Adding one more character fills the inline buffer, but doesn't cause
281 // dynamic allocation.
282 buffer.push_back('a');
283 check_move_assign_buffer("testa", buffer);
284 const char* inline_buffer_ptr = &buffer[0];
285 // Adding one more character causes the content to move from the inline to
286 // a dynamically allocated buffer.
287 buffer.push_back('b');
288 basic_memory_buffer<char, 5> buffer2;
289 buffer2 = std::move(buffer);
290 // Move should rip the guts of the first buffer.
291 EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
292 EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
293 EXPECT_GT(buffer2.capacity(), 5u);
294 }
295
TEST(MemoryBufferTest,Grow)296 TEST(MemoryBufferTest, Grow) {
297 typedef allocator_ref<mock_allocator<int>> Allocator;
298 mock_allocator<int> alloc;
299 basic_memory_buffer<int, 10, Allocator> buffer((Allocator(&alloc)));
300 buffer.resize(7);
301 using fmt::detail::to_unsigned;
302 for (int i = 0; i < 7; ++i) buffer[to_unsigned(i)] = i * i;
303 EXPECT_EQ(10u, buffer.capacity());
304 int mem[20];
305 mem[7] = 0xdead;
306 EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem));
307 buffer.try_reserve(20);
308 EXPECT_EQ(20u, buffer.capacity());
309 // Check if size elements have been copied
310 for (int i = 0; i < 7; ++i) EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
311 // and no more than that.
312 EXPECT_EQ(0xdead, buffer[7]);
313 EXPECT_CALL(alloc, deallocate(mem, 20));
314 }
315
TEST(MemoryBufferTest,Allocator)316 TEST(MemoryBufferTest, Allocator) {
317 typedef allocator_ref<mock_allocator<char>> TestAllocator;
318 basic_memory_buffer<char, 10, TestAllocator> buffer;
319 EXPECT_EQ(nullptr, buffer.get_allocator().get());
320 StrictMock<mock_allocator<char>> alloc;
321 char mem;
322 {
323 basic_memory_buffer<char, 10, TestAllocator> buffer2(
324 (TestAllocator(&alloc)));
325 EXPECT_EQ(&alloc, buffer2.get_allocator().get());
326 size_t size = 2 * fmt::inline_buffer_size;
327 EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
328 buffer2.reserve(size);
329 EXPECT_CALL(alloc, deallocate(&mem, size));
330 }
331 }
332
TEST(MemoryBufferTest,ExceptionInDeallocate)333 TEST(MemoryBufferTest, ExceptionInDeallocate) {
334 typedef allocator_ref<mock_allocator<char>> TestAllocator;
335 StrictMock<mock_allocator<char>> alloc;
336 basic_memory_buffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc)));
337 size_t size = 2 * fmt::inline_buffer_size;
338 std::vector<char> mem(size);
339 {
340 EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0]));
341 buffer.resize(size);
342 std::fill(&buffer[0], &buffer[0] + size, 'x');
343 }
344 std::vector<char> mem2(2 * size);
345 {
346 EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0]));
347 std::exception e;
348 EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e));
349 EXPECT_THROW(buffer.reserve(2 * size), std::exception);
350 EXPECT_EQ(&mem2[0], &buffer[0]);
351 // Check that the data has been copied.
352 for (size_t i = 0; i < size; ++i) EXPECT_EQ('x', buffer[i]);
353 }
354 EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
355 }
356
TEST(UtilTest,UTF8ToUTF16)357 TEST(UtilTest, UTF8ToUTF16) {
358 fmt::detail::utf8_to_utf16 u("лошадка");
359 EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str());
360 EXPECT_EQ(7, u.size());
361 // U+10437 { DESERET SMALL LETTER YEE }
362 EXPECT_EQ(L"\xD801\xDC37", fmt::detail::utf8_to_utf16("").str());
363 EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16("\xc3\x28"), std::runtime_error,
364 "invalid utf8");
365 EXPECT_THROW_MSG(fmt::detail::utf8_to_utf16(fmt::string_view("л", 1)),
366 std::runtime_error, "invalid utf8");
367 EXPECT_EQ(L"123456", fmt::detail::utf8_to_utf16("123456").str());
368 }
369
TEST(UtilTest,UTF8ToUTF16EmptyString)370 TEST(UtilTest, UTF8ToUTF16EmptyString) {
371 std::string s = "";
372 fmt::detail::utf8_to_utf16 u(s.c_str());
373 EXPECT_EQ(L"", u.str());
374 EXPECT_EQ(s.size(), u.size());
375 }
376
TEST(UtilTest,FormatSystemError)377 TEST(UtilTest, FormatSystemError) {
378 fmt::memory_buffer message;
379 fmt::format_system_error(message, EDOM, "test");
380 EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)),
381 to_string(message));
382 message = fmt::memory_buffer();
383
384 // Check if std::allocator throws on allocating max size_t / 2 chars.
385 size_t max_size = max_value<size_t>() / 2;
386 bool throws_on_alloc = false;
387 try {
388 std::allocator<char> alloc;
389 alloc.deallocate(alloc.allocate(max_size), max_size);
390 } catch (const std::bad_alloc&) {
391 throws_on_alloc = true;
392 }
393 if (!throws_on_alloc) {
394 fmt::print("warning: std::allocator allocates {} chars", max_size);
395 return;
396 }
397 fmt::format_system_error(message, EDOM, fmt::string_view(nullptr, max_size));
398 EXPECT_EQ(fmt::format("error {}", EDOM), to_string(message));
399 }
400
TEST(UtilTest,SystemError)401 TEST(UtilTest, SystemError) {
402 fmt::system_error e(EDOM, "test");
403 EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what());
404 EXPECT_EQ(EDOM, e.error_code());
405
406 fmt::system_error error(0, "");
407 try {
408 throw fmt::system_error(EDOM, "test {}", "error");
409 } catch (const fmt::system_error& e) {
410 error = e;
411 }
412 fmt::memory_buffer message;
413 fmt::format_system_error(message, EDOM, "test error");
414 EXPECT_EQ(to_string(message), error.what());
415 EXPECT_EQ(EDOM, error.error_code());
416 }
417
TEST(UtilTest,ReportSystemError)418 TEST(UtilTest, ReportSystemError) {
419 fmt::memory_buffer out;
420 fmt::format_system_error(out, EDOM, "test error");
421 out.push_back('\n');
422 EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"),
423 to_string(out));
424 }
425
TEST(StringViewTest,Ctor)426 TEST(StringViewTest, Ctor) {
427 EXPECT_STREQ("abc", string_view("abc").data());
428 EXPECT_EQ(3u, string_view("abc").size());
429
430 EXPECT_STREQ("defg", string_view(std::string("defg")).data());
431 EXPECT_EQ(4u, string_view(std::string("defg")).size());
432 }
433
TEST(FormatToTest,FormatWithoutArgs)434 TEST(FormatToTest, FormatWithoutArgs) {
435 std::string s;
436 fmt::format_to(std::back_inserter(s), "test");
437 EXPECT_EQ("test", s);
438 }
439
TEST(FormatToTest,Format)440 TEST(FormatToTest, Format) {
441 std::string s;
442 fmt::format_to(std::back_inserter(s), "part{0}", 1);
443 EXPECT_EQ("part1", s);
444 fmt::format_to(std::back_inserter(s), "part{0}", 2);
445 EXPECT_EQ("part1part2", s);
446 }
447
TEST(FormatToTest,WideString)448 TEST(FormatToTest, WideString) {
449 std::vector<wchar_t> buf;
450 fmt::format_to(std::back_inserter(buf), L"{}{}", 42, L'\0');
451 EXPECT_STREQ(buf.data(), L"42");
452 }
453
TEST(FormatToTest,FormatToMemoryBuffer)454 TEST(FormatToTest, FormatToMemoryBuffer) {
455 fmt::basic_memory_buffer<char, 100> buffer;
456 fmt::format_to(buffer, "{}", "foo");
457 EXPECT_EQ("foo", to_string(buffer));
458 fmt::wmemory_buffer wbuffer;
459 fmt::format_to(wbuffer, L"{}", L"foo");
460 EXPECT_EQ(L"foo", to_string(wbuffer));
461 }
462
TEST(FormatterTest,Escape)463 TEST(FormatterTest, Escape) {
464 EXPECT_EQ("{", format("{{"));
465 EXPECT_EQ("before {", format("before {{"));
466 EXPECT_EQ("{ after", format("{{ after"));
467 EXPECT_EQ("before { after", format("before {{ after"));
468
469 EXPECT_EQ("}", format("}}"));
470 EXPECT_EQ("before }", format("before }}"));
471 EXPECT_EQ("} after", format("}} after"));
472 EXPECT_EQ("before } after", format("before }} after"));
473
474 EXPECT_EQ("{}", format("{{}}"));
475 EXPECT_EQ("{42}", format("{{{0}}}", 42));
476 }
477
TEST(FormatterTest,UnmatchedBraces)478 TEST(FormatterTest, UnmatchedBraces) {
479 EXPECT_THROW_MSG(format("{"), format_error, "invalid format string");
480 EXPECT_THROW_MSG(format("}"), format_error, "unmatched '}' in format string");
481 EXPECT_THROW_MSG(format("{0{}"), format_error, "invalid format string");
482 }
483
TEST(FormatterTest,NoArgs)484 TEST(FormatterTest, NoArgs) { EXPECT_EQ("test", format("test")); }
485
TEST(FormatterTest,ArgsInDifferentPositions)486 TEST(FormatterTest, ArgsInDifferentPositions) {
487 EXPECT_EQ("42", format("{0}", 42));
488 EXPECT_EQ("before 42", format("before {0}", 42));
489 EXPECT_EQ("42 after", format("{0} after", 42));
490 EXPECT_EQ("before 42 after", format("before {0} after", 42));
491 EXPECT_EQ("answer = 42", format("{0} = {1}", "answer", 42));
492 EXPECT_EQ("42 is the answer", format("{1} is the {0}", "answer", 42));
493 EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
494 }
495
TEST(FormatterTest,ArgErrors)496 TEST(FormatterTest, ArgErrors) {
497 EXPECT_THROW_MSG(format("{"), format_error, "invalid format string");
498 EXPECT_THROW_MSG(format("{?}"), format_error, "invalid format string");
499 EXPECT_THROW_MSG(format("{0"), format_error, "invalid format string");
500 EXPECT_THROW_MSG(format("{0}"), format_error, "argument not found");
501 EXPECT_THROW_MSG(format("{00}", 42), format_error, "invalid format string");
502
503 char format_str[BUFFER_SIZE];
504 safe_sprintf(format_str, "{%u", INT_MAX);
505 EXPECT_THROW_MSG(format(format_str), format_error, "invalid format string");
506 safe_sprintf(format_str, "{%u}", INT_MAX);
507 EXPECT_THROW_MSG(format(format_str), format_error, "argument not found");
508
509 safe_sprintf(format_str, "{%u", INT_MAX + 1u);
510 EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
511 safe_sprintf(format_str, "{%u}", INT_MAX + 1u);
512 EXPECT_THROW_MSG(format(format_str), format_error, "number is too big");
513 }
514
515 template <int N> struct TestFormat {
516 template <typename... Args>
formatTestFormat517 static std::string format(fmt::string_view format_str, const Args&... args) {
518 return TestFormat<N - 1>::format(format_str, N - 1, args...);
519 }
520 };
521
522 template <> struct TestFormat<0> {
523 template <typename... Args>
formatTestFormat524 static std::string format(fmt::string_view format_str, const Args&... args) {
525 return fmt::format(format_str, args...);
526 }
527 };
528
TEST(FormatterTest,ManyArgs)529 TEST(FormatterTest, ManyArgs) {
530 EXPECT_EQ("19", TestFormat<20>::format("{19}"));
531 EXPECT_THROW_MSG(TestFormat<20>::format("{20}"), format_error,
532 "argument not found");
533 EXPECT_THROW_MSG(TestFormat<21>::format("{21}"), format_error,
534 "argument not found");
535 enum { max_packed_args = fmt::detail::max_packed_args };
536 std::string format_str = fmt::format("{{{}}}", max_packed_args + 1);
537 EXPECT_THROW_MSG(TestFormat<max_packed_args>::format(format_str),
538 format_error, "argument not found");
539 }
540
TEST(FormatterTest,NamedArg)541 TEST(FormatterTest, NamedArg) {
542 EXPECT_EQ("1/a/A", format("{_1}/{a_}/{A_}", fmt::arg("a_", 'a'),
543 fmt::arg("A_", "A"), fmt::arg("_1", 1)));
544 EXPECT_EQ(" -42", format("{0:{width}}", -42, fmt::arg("width", 4)));
545 EXPECT_EQ("st", format("{0:.{precision}}", "str", fmt::arg("precision", 2)));
546 EXPECT_EQ("1 2", format("{} {two}", 1, fmt::arg("two", 2)));
547 EXPECT_EQ("42", format("{c}", fmt::arg("a", 0), fmt::arg("b", 0),
548 fmt::arg("c", 42), fmt::arg("d", 0), fmt::arg("e", 0),
549 fmt::arg("f", 0), fmt::arg("g", 0), fmt::arg("h", 0),
550 fmt::arg("i", 0), fmt::arg("j", 0), fmt::arg("k", 0),
551 fmt::arg("l", 0), fmt::arg("m", 0), fmt::arg("n", 0),
552 fmt::arg("o", 0), fmt::arg("p", 0)));
553 EXPECT_THROW_MSG(format("{a}"), format_error, "argument not found");
554 EXPECT_THROW_MSG(format("{a}", 42), format_error, "argument not found");
555 }
556
TEST(FormatterTest,AutoArgIndex)557 TEST(FormatterTest, AutoArgIndex) {
558 EXPECT_EQ("abc", format("{}{}{}", 'a', 'b', 'c'));
559 EXPECT_THROW_MSG(format("{0}{}", 'a', 'b'), format_error,
560 "cannot switch from manual to automatic argument indexing");
561 EXPECT_THROW_MSG(format("{}{0}", 'a', 'b'), format_error,
562 "cannot switch from automatic to manual argument indexing");
563 EXPECT_EQ("1.2", format("{:.{}}", 1.2345, 2));
564 EXPECT_THROW_MSG(format("{0}:.{}", 1.2345, 2), format_error,
565 "cannot switch from manual to automatic argument indexing");
566 EXPECT_THROW_MSG(format("{:.{0}}", 1.2345, 2), format_error,
567 "cannot switch from automatic to manual argument indexing");
568 EXPECT_THROW_MSG(format("{}"), format_error, "argument not found");
569 }
570
TEST(FormatterTest,EmptySpecs)571 TEST(FormatterTest, EmptySpecs) { EXPECT_EQ("42", format("{0:}", 42)); }
572
TEST(FormatterTest,LeftAlign)573 TEST(FormatterTest, LeftAlign) {
574 EXPECT_EQ("42 ", format("{0:<4}", 42));
575 EXPECT_EQ("42 ", format("{0:<4o}", 042));
576 EXPECT_EQ("42 ", format("{0:<4x}", 0x42));
577 EXPECT_EQ("-42 ", format("{0:<5}", -42));
578 EXPECT_EQ("42 ", format("{0:<5}", 42u));
579 EXPECT_EQ("-42 ", format("{0:<5}", -42l));
580 EXPECT_EQ("42 ", format("{0:<5}", 42ul));
581 EXPECT_EQ("-42 ", format("{0:<5}", -42ll));
582 EXPECT_EQ("42 ", format("{0:<5}", 42ull));
583 EXPECT_EQ("-42 ", format("{0:<5}", -42.0));
584 EXPECT_EQ("-42 ", format("{0:<5}", -42.0l));
585 EXPECT_EQ("c ", format("{0:<5}", 'c'));
586 EXPECT_EQ("abc ", format("{0:<5}", "abc"));
587 EXPECT_EQ("0xface ", format("{0:<8}", reinterpret_cast<void*>(0xface)));
588 }
589
TEST(FormatterTest,RightAlign)590 TEST(FormatterTest, RightAlign) {
591 EXPECT_EQ(" 42", format("{0:>4}", 42));
592 EXPECT_EQ(" 42", format("{0:>4o}", 042));
593 EXPECT_EQ(" 42", format("{0:>4x}", 0x42));
594 EXPECT_EQ(" -42", format("{0:>5}", -42));
595 EXPECT_EQ(" 42", format("{0:>5}", 42u));
596 EXPECT_EQ(" -42", format("{0:>5}", -42l));
597 EXPECT_EQ(" 42", format("{0:>5}", 42ul));
598 EXPECT_EQ(" -42", format("{0:>5}", -42ll));
599 EXPECT_EQ(" 42", format("{0:>5}", 42ull));
600 EXPECT_EQ(" -42", format("{0:>5}", -42.0));
601 EXPECT_EQ(" -42", format("{0:>5}", -42.0l));
602 EXPECT_EQ(" c", format("{0:>5}", 'c'));
603 EXPECT_EQ(" abc", format("{0:>5}", "abc"));
604 EXPECT_EQ(" 0xface", format("{0:>8}", reinterpret_cast<void*>(0xface)));
605 }
606
607 #if FMT_DEPRECATED_NUMERIC_ALIGN
TEST(FormatterTest,NumericAlign)608 TEST(FormatterTest, NumericAlign) { EXPECT_EQ("0042", format("{0:=4}", 42)); }
609 #endif
610
TEST(FormatterTest,CenterAlign)611 TEST(FormatterTest, CenterAlign) {
612 EXPECT_EQ(" 42 ", format("{0:^5}", 42));
613 EXPECT_EQ(" 42 ", format("{0:^5o}", 042));
614 EXPECT_EQ(" 42 ", format("{0:^5x}", 0x42));
615 EXPECT_EQ(" -42 ", format("{0:^5}", -42));
616 EXPECT_EQ(" 42 ", format("{0:^5}", 42u));
617 EXPECT_EQ(" -42 ", format("{0:^5}", -42l));
618 EXPECT_EQ(" 42 ", format("{0:^5}", 42ul));
619 EXPECT_EQ(" -42 ", format("{0:^5}", -42ll));
620 EXPECT_EQ(" 42 ", format("{0:^5}", 42ull));
621 EXPECT_EQ(" -42 ", format("{0:^5}", -42.0));
622 EXPECT_EQ(" -42 ", format("{0:^5}", -42.0l));
623 EXPECT_EQ(" c ", format("{0:^5}", 'c'));
624 EXPECT_EQ(" abc ", format("{0:^6}", "abc"));
625 EXPECT_EQ(" 0xface ", format("{0:^8}", reinterpret_cast<void*>(0xface)));
626 }
627
TEST(FormatterTest,Fill)628 TEST(FormatterTest, Fill) {
629 EXPECT_THROW_MSG(format("{0:{<5}", 'c'), format_error,
630 "invalid fill character '{'");
631 EXPECT_THROW_MSG(format("{0:{<5}}", 'c'), format_error,
632 "invalid fill character '{'");
633 EXPECT_EQ("**42", format("{0:*>4}", 42));
634 EXPECT_EQ("**-42", format("{0:*>5}", -42));
635 EXPECT_EQ("***42", format("{0:*>5}", 42u));
636 EXPECT_EQ("**-42", format("{0:*>5}", -42l));
637 EXPECT_EQ("***42", format("{0:*>5}", 42ul));
638 EXPECT_EQ("**-42", format("{0:*>5}", -42ll));
639 EXPECT_EQ("***42", format("{0:*>5}", 42ull));
640 EXPECT_EQ("**-42", format("{0:*>5}", -42.0));
641 EXPECT_EQ("**-42", format("{0:*>5}", -42.0l));
642 EXPECT_EQ("c****", format("{0:*<5}", 'c'));
643 EXPECT_EQ("abc**", format("{0:*<5}", "abc"));
644 EXPECT_EQ("**0xface", format("{0:*>8}", reinterpret_cast<void*>(0xface)));
645 EXPECT_EQ("foo=", format("{:}=", "foo"));
646 EXPECT_EQ(std::string("\0\0\0*", 4), format(string_view("{:\0>4}", 6), '*'));
647 EXPECT_EQ("жж42", format("{0:ж>4}", 42));
648 EXPECT_THROW_MSG(format("{:\x80\x80\x80\x80\x80>}", 0), format_error,
649 "missing '}' in format string");
650 }
651
TEST(FormatterTest,PlusSign)652 TEST(FormatterTest, PlusSign) {
653 EXPECT_EQ("+42", format("{0:+}", 42));
654 EXPECT_EQ("-42", format("{0:+}", -42));
655 EXPECT_EQ("+42", format("{0:+}", 42));
656 EXPECT_THROW_MSG(format("{0:+}", 42u), format_error,
657 "format specifier requires signed argument");
658 EXPECT_EQ("+42", format("{0:+}", 42l));
659 EXPECT_THROW_MSG(format("{0:+}", 42ul), format_error,
660 "format specifier requires signed argument");
661 EXPECT_EQ("+42", format("{0:+}", 42ll));
662 EXPECT_THROW_MSG(format("{0:+}", 42ull), format_error,
663 "format specifier requires signed argument");
664 EXPECT_EQ("+42", format("{0:+}", 42.0));
665 EXPECT_EQ("+42", format("{0:+}", 42.0l));
666 EXPECT_THROW_MSG(format("{0:+", 'c'), format_error,
667 "missing '}' in format string");
668 EXPECT_THROW_MSG(format("{0:+}", 'c'), format_error,
669 "invalid format specifier for char");
670 EXPECT_THROW_MSG(format("{0:+}", "abc"), format_error,
671 "format specifier requires numeric argument");
672 EXPECT_THROW_MSG(format("{0:+}", reinterpret_cast<void*>(0x42)), format_error,
673 "format specifier requires numeric argument");
674 }
675
TEST(FormatterTest,MinusSign)676 TEST(FormatterTest, MinusSign) {
677 EXPECT_EQ("42", format("{0:-}", 42));
678 EXPECT_EQ("-42", format("{0:-}", -42));
679 EXPECT_EQ("42", format("{0:-}", 42));
680 EXPECT_THROW_MSG(format("{0:-}", 42u), format_error,
681 "format specifier requires signed argument");
682 EXPECT_EQ("42", format("{0:-}", 42l));
683 EXPECT_THROW_MSG(format("{0:-}", 42ul), format_error,
684 "format specifier requires signed argument");
685 EXPECT_EQ("42", format("{0:-}", 42ll));
686 EXPECT_THROW_MSG(format("{0:-}", 42ull), format_error,
687 "format specifier requires signed argument");
688 EXPECT_EQ("42", format("{0:-}", 42.0));
689 EXPECT_EQ("42", format("{0:-}", 42.0l));
690 EXPECT_THROW_MSG(format("{0:-", 'c'), format_error,
691 "missing '}' in format string");
692 EXPECT_THROW_MSG(format("{0:-}", 'c'), format_error,
693 "invalid format specifier for char");
694 EXPECT_THROW_MSG(format("{0:-}", "abc"), format_error,
695 "format specifier requires numeric argument");
696 EXPECT_THROW_MSG(format("{0:-}", reinterpret_cast<void*>(0x42)), format_error,
697 "format specifier requires numeric argument");
698 }
699
TEST(FormatterTest,SpaceSign)700 TEST(FormatterTest, SpaceSign) {
701 EXPECT_EQ(" 42", format("{0: }", 42));
702 EXPECT_EQ("-42", format("{0: }", -42));
703 EXPECT_EQ(" 42", format("{0: }", 42));
704 EXPECT_THROW_MSG(format("{0: }", 42u), format_error,
705 "format specifier requires signed argument");
706 EXPECT_EQ(" 42", format("{0: }", 42l));
707 EXPECT_THROW_MSG(format("{0: }", 42ul), format_error,
708 "format specifier requires signed argument");
709 EXPECT_EQ(" 42", format("{0: }", 42ll));
710 EXPECT_THROW_MSG(format("{0: }", 42ull), format_error,
711 "format specifier requires signed argument");
712 EXPECT_EQ(" 42", format("{0: }", 42.0));
713 EXPECT_EQ(" 42", format("{0: }", 42.0l));
714 EXPECT_THROW_MSG(format("{0: ", 'c'), format_error,
715 "missing '}' in format string");
716 EXPECT_THROW_MSG(format("{0: }", 'c'), format_error,
717 "invalid format specifier for char");
718 EXPECT_THROW_MSG(format("{0: }", "abc"), format_error,
719 "format specifier requires numeric argument");
720 EXPECT_THROW_MSG(format("{0: }", reinterpret_cast<void*>(0x42)), format_error,
721 "format specifier requires numeric argument");
722 }
723
TEST(FormatterTest,SignNotTruncated)724 TEST(FormatterTest, SignNotTruncated) {
725 wchar_t format_str[] = {L'{', L':',
726 '+' | (1 << fmt::detail::num_bits<char>()), L'}', 0};
727 EXPECT_THROW(format(format_str, 42), format_error);
728 }
729
TEST(FormatterTest,HashFlag)730 TEST(FormatterTest, HashFlag) {
731 EXPECT_EQ("42", format("{0:#}", 42));
732 EXPECT_EQ("-42", format("{0:#}", -42));
733 EXPECT_EQ("0b101010", format("{0:#b}", 42));
734 EXPECT_EQ("0B101010", format("{0:#B}", 42));
735 EXPECT_EQ("-0b101010", format("{0:#b}", -42));
736 EXPECT_EQ("0x42", format("{0:#x}", 0x42));
737 EXPECT_EQ("0X42", format("{0:#X}", 0x42));
738 EXPECT_EQ("-0x42", format("{0:#x}", -0x42));
739 EXPECT_EQ("0", format("{0:#o}", 0));
740 EXPECT_EQ("042", format("{0:#o}", 042));
741 EXPECT_EQ("-042", format("{0:#o}", -042));
742 EXPECT_EQ("42", format("{0:#}", 42u));
743 EXPECT_EQ("0x42", format("{0:#x}", 0x42u));
744 EXPECT_EQ("042", format("{0:#o}", 042u));
745
746 EXPECT_EQ("-42", format("{0:#}", -42l));
747 EXPECT_EQ("0x42", format("{0:#x}", 0x42l));
748 EXPECT_EQ("-0x42", format("{0:#x}", -0x42l));
749 EXPECT_EQ("042", format("{0:#o}", 042l));
750 EXPECT_EQ("-042", format("{0:#o}", -042l));
751 EXPECT_EQ("42", format("{0:#}", 42ul));
752 EXPECT_EQ("0x42", format("{0:#x}", 0x42ul));
753 EXPECT_EQ("042", format("{0:#o}", 042ul));
754
755 EXPECT_EQ("-42", format("{0:#}", -42ll));
756 EXPECT_EQ("0x42", format("{0:#x}", 0x42ll));
757 EXPECT_EQ("-0x42", format("{0:#x}", -0x42ll));
758 EXPECT_EQ("042", format("{0:#o}", 042ll));
759 EXPECT_EQ("-042", format("{0:#o}", -042ll));
760 EXPECT_EQ("42", format("{0:#}", 42ull));
761 EXPECT_EQ("0x42", format("{0:#x}", 0x42ull));
762 EXPECT_EQ("042", format("{0:#o}", 042ull));
763
764 EXPECT_EQ("-42.0", format("{0:#}", -42.0));
765 EXPECT_EQ("-42.0", format("{0:#}", -42.0l));
766 EXPECT_EQ("4.e+01", format("{:#.0e}", 42.0));
767 EXPECT_EQ("0.", format("{:#.0f}", 0.01));
768 EXPECT_EQ("0.50", format("{:#.2g}", 0.5));
769 EXPECT_EQ("0.", format("{:#.0f}", 0.5));
770 EXPECT_THROW_MSG(format("{0:#", 'c'), format_error,
771 "missing '}' in format string");
772 EXPECT_THROW_MSG(format("{0:#}", 'c'), format_error,
773 "invalid format specifier for char");
774 EXPECT_THROW_MSG(format("{0:#}", "abc"), format_error,
775 "format specifier requires numeric argument");
776 EXPECT_THROW_MSG(format("{0:#}", reinterpret_cast<void*>(0x42)), format_error,
777 "format specifier requires numeric argument");
778 }
779
TEST(FormatterTest,ZeroFlag)780 TEST(FormatterTest, ZeroFlag) {
781 EXPECT_EQ("42", format("{0:0}", 42));
782 EXPECT_EQ("-0042", format("{0:05}", -42));
783 EXPECT_EQ("00042", format("{0:05}", 42u));
784 EXPECT_EQ("-0042", format("{0:05}", -42l));
785 EXPECT_EQ("00042", format("{0:05}", 42ul));
786 EXPECT_EQ("-0042", format("{0:05}", -42ll));
787 EXPECT_EQ("00042", format("{0:05}", 42ull));
788 EXPECT_EQ("-000042", format("{0:07}", -42.0));
789 EXPECT_EQ("-000042", format("{0:07}", -42.0l));
790 EXPECT_THROW_MSG(format("{0:0", 'c'), format_error,
791 "missing '}' in format string");
792 EXPECT_THROW_MSG(format("{0:05}", 'c'), format_error,
793 "invalid format specifier for char");
794 EXPECT_THROW_MSG(format("{0:05}", "abc"), format_error,
795 "format specifier requires numeric argument");
796 EXPECT_THROW_MSG(format("{0:05}", reinterpret_cast<void*>(0x42)),
797 format_error, "format specifier requires numeric argument");
798 }
799
TEST(FormatterTest,Width)800 TEST(FormatterTest, Width) {
801 char format_str[BUFFER_SIZE];
802 safe_sprintf(format_str, "{0:%u", UINT_MAX);
803 increment(format_str + 3);
804 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
805 size_t size = std::strlen(format_str);
806 format_str[size] = '}';
807 format_str[size + 1] = 0;
808 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
809
810 safe_sprintf(format_str, "{0:%u", INT_MAX + 1u);
811 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
812 safe_sprintf(format_str, "{0:%u}", INT_MAX + 1u);
813 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
814 EXPECT_EQ(" -42", format("{0:4}", -42));
815 EXPECT_EQ(" 42", format("{0:5}", 42u));
816 EXPECT_EQ(" -42", format("{0:6}", -42l));
817 EXPECT_EQ(" 42", format("{0:7}", 42ul));
818 EXPECT_EQ(" -42", format("{0:6}", -42ll));
819 EXPECT_EQ(" 42", format("{0:7}", 42ull));
820 EXPECT_EQ(" -1.23", format("{0:8}", -1.23));
821 EXPECT_EQ(" -1.23", format("{0:9}", -1.23l));
822 EXPECT_EQ(" 0xcafe", format("{0:10}", reinterpret_cast<void*>(0xcafe)));
823 EXPECT_EQ("x ", format("{0:11}", 'x'));
824 EXPECT_EQ("str ", format("{0:12}", "str"));
825 EXPECT_EQ(fmt::format("{:*^5}", ""), "****");
826 }
827
const_check(T value)828 template <typename T> inline T const_check(T value) { return value; }
829
TEST(FormatterTest,RuntimeWidth)830 TEST(FormatterTest, RuntimeWidth) {
831 char format_str[BUFFER_SIZE];
832 safe_sprintf(format_str, "{0:{%u", UINT_MAX);
833 increment(format_str + 4);
834 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
835 size_t size = std::strlen(format_str);
836 format_str[size] = '}';
837 format_str[size + 1] = 0;
838 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
839 format_str[size + 1] = '}';
840 format_str[size + 2] = 0;
841 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
842
843 EXPECT_THROW_MSG(format("{0:{", 0), format_error, "invalid format string");
844 EXPECT_THROW_MSG(format("{0:{}", 0), format_error,
845 "cannot switch from manual to automatic argument indexing");
846 EXPECT_THROW_MSG(format("{0:{?}}", 0), format_error, "invalid format string");
847 EXPECT_THROW_MSG(format("{0:{1}}", 0), format_error, "argument not found");
848
849 EXPECT_THROW_MSG(format("{0:{0:}}", 0), format_error,
850 "invalid format string");
851
852 EXPECT_THROW_MSG(format("{0:{1}}", 0, -1), format_error, "negative width");
853 EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1u)), format_error,
854 "number is too big");
855 EXPECT_THROW_MSG(format("{0:{1}}", 0, -1l), format_error, "negative width");
856 if (const_check(sizeof(long) > sizeof(int))) {
857 long value = INT_MAX;
858 EXPECT_THROW_MSG(format("{0:{1}}", 0, (value + 1)), format_error,
859 "number is too big");
860 }
861 EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX + 1ul)), format_error,
862 "number is too big");
863
864 EXPECT_THROW_MSG(format("{0:{1}}", 0, '0'), format_error,
865 "width is not integer");
866 EXPECT_THROW_MSG(format("{0:{1}}", 0, 0.0), format_error,
867 "width is not integer");
868
869 EXPECT_EQ(" -42", format("{0:{1}}", -42, 4));
870 EXPECT_EQ(" 42", format("{0:{1}}", 42u, 5));
871 EXPECT_EQ(" -42", format("{0:{1}}", -42l, 6));
872 EXPECT_EQ(" 42", format("{0:{1}}", 42ul, 7));
873 EXPECT_EQ(" -42", format("{0:{1}}", -42ll, 6));
874 EXPECT_EQ(" 42", format("{0:{1}}", 42ull, 7));
875 EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23, 8));
876 EXPECT_EQ(" -1.23", format("{0:{1}}", -1.23l, 9));
877 EXPECT_EQ(" 0xcafe",
878 format("{0:{1}}", reinterpret_cast<void*>(0xcafe), 10));
879 EXPECT_EQ("x ", format("{0:{1}}", 'x', 11));
880 EXPECT_EQ("str ", format("{0:{1}}", "str", 12));
881 }
882
TEST(FormatterTest,Precision)883 TEST(FormatterTest, Precision) {
884 char format_str[BUFFER_SIZE];
885 safe_sprintf(format_str, "{0:.%u", UINT_MAX);
886 increment(format_str + 4);
887 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
888 size_t size = std::strlen(format_str);
889 format_str[size] = '}';
890 format_str[size + 1] = 0;
891 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
892
893 safe_sprintf(format_str, "{0:.%u", INT_MAX + 1u);
894 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
895 safe_sprintf(format_str, "{0:.%u}", INT_MAX + 1u);
896 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
897
898 EXPECT_THROW_MSG(format("{0:.", 0), format_error,
899 "missing precision specifier");
900 EXPECT_THROW_MSG(format("{0:.}", 0), format_error,
901 "missing precision specifier");
902
903 EXPECT_THROW_MSG(format("{0:.2", 0), format_error,
904 "precision not allowed for this argument type");
905 EXPECT_THROW_MSG(format("{0:.2}", 42), format_error,
906 "precision not allowed for this argument type");
907 EXPECT_THROW_MSG(format("{0:.2f}", 42), format_error,
908 "precision not allowed for this argument type");
909 EXPECT_THROW_MSG(format("{0:.2}", 42u), format_error,
910 "precision not allowed for this argument type");
911 EXPECT_THROW_MSG(format("{0:.2f}", 42u), format_error,
912 "precision not allowed for this argument type");
913 EXPECT_THROW_MSG(format("{0:.2}", 42l), format_error,
914 "precision not allowed for this argument type");
915 EXPECT_THROW_MSG(format("{0:.2f}", 42l), format_error,
916 "precision not allowed for this argument type");
917 EXPECT_THROW_MSG(format("{0:.2}", 42ul), format_error,
918 "precision not allowed for this argument type");
919 EXPECT_THROW_MSG(format("{0:.2f}", 42ul), format_error,
920 "precision not allowed for this argument type");
921 EXPECT_THROW_MSG(format("{0:.2}", 42ll), format_error,
922 "precision not allowed for this argument type");
923 EXPECT_THROW_MSG(format("{0:.2f}", 42ll), format_error,
924 "precision not allowed for this argument type");
925 EXPECT_THROW_MSG(format("{0:.2}", 42ull), format_error,
926 "precision not allowed for this argument type");
927 EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error,
928 "precision not allowed for this argument type");
929 EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error,
930 "precision not allowed for this argument type");
931 EXPECT_EQ("1.2", format("{0:.2}", 1.2345));
932 EXPECT_EQ("1.2", format("{0:.2}", 1.2345l));
933 EXPECT_EQ("1.2e+56", format("{:.2}", 1.234e56));
934 EXPECT_EQ("1e+00", format("{:.0e}", 1.0L));
935 EXPECT_EQ(" 0.0e+00", format("{:9.1e}", 0.0));
936 EXPECT_EQ(
937 "4.9406564584124654417656879286822137236505980261432476442558568250067550"
938 "727020875186529983636163599237979656469544571773092665671035593979639877"
939 "479601078187812630071319031140452784581716784898210368871863605699873072"
940 "305000638740915356498438731247339727316961514003171538539807412623856559"
941 "117102665855668676818703956031062493194527159149245532930545654440112748"
942 "012970999954193198940908041656332452475714786901472678015935523861155013"
943 "480352649347201937902681071074917033322268447533357208324319361e-324",
944 format("{:.494}", 4.9406564584124654E-324));
945 EXPECT_EQ(
946 "-0X1.41FE3FFE71C9E000000000000000000000000000000000000000000000000000000"
947 "000000000000000000000000000000000000000000000000000000000000000000000000"
948 "000000000000000000000000000000000000000000000000000000000000000000000000"
949 "000000000000000000000000000000000000000000000000000000000000000000000000"
950 "000000000000000000000000000000000000000000000000000000000000000000000000"
951 "000000000000000000000000000000000000000000000000000000000000000000000000"
952 "000000000000000000000000000000000000000000000000000000000000000000000000"
953 "000000000000000000000000000000000000000000000000000000000000000000000000"
954 "000000000000000000000000000000000000000000000000000000000000000000000000"
955 "000000000000000000000000000000000000000000000000000000000000000000000000"
956 "000000000000000000000000000000000000000000000000000000000000000000000000"
957 "000000000000000000000000000000000000000000000000000P+127",
958 format("{:.838A}", -2.14001164E+38));
959 EXPECT_EQ("123.", format("{:#.0f}", 123.0));
960 EXPECT_EQ("1.23", format("{:.02f}", 1.234));
961 EXPECT_EQ("0.001", format("{:.1g}", 0.001));
962 EXPECT_EQ("1019666400", format("{}", 1019666432.0f));
963 EXPECT_EQ("1e+01", format("{:.0e}", 9.5));
964 EXPECT_EQ("1.0e-34", fmt::format("{:.1e}", 1e-34));
965
966 EXPECT_THROW_MSG(format("{0:.2}", reinterpret_cast<void*>(0xcafe)),
967 format_error,
968 "precision not allowed for this argument type");
969 EXPECT_THROW_MSG(format("{0:.2f}", reinterpret_cast<void*>(0xcafe)),
970 format_error,
971 "precision not allowed for this argument type");
972 EXPECT_THROW_MSG(format("{:.{}e}", 42.0, fmt::detail::max_value<int>()),
973 format_error, "number is too big");
974
975 EXPECT_EQ("st", format("{0:.2}", "str"));
976 }
977
TEST(FormatterTest,RuntimePrecision)978 TEST(FormatterTest, RuntimePrecision) {
979 char format_str[BUFFER_SIZE];
980 safe_sprintf(format_str, "{0:.{%u", UINT_MAX);
981 increment(format_str + 5);
982 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
983 size_t size = std::strlen(format_str);
984 format_str[size] = '}';
985 format_str[size + 1] = 0;
986 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
987 format_str[size + 1] = '}';
988 format_str[size + 2] = 0;
989 EXPECT_THROW_MSG(format(format_str, 0), format_error, "number is too big");
990
991 EXPECT_THROW_MSG(format("{0:.{", 0), format_error, "invalid format string");
992 EXPECT_THROW_MSG(format("{0:.{}", 0), format_error,
993 "cannot switch from manual to automatic argument indexing");
994 EXPECT_THROW_MSG(format("{0:.{?}}", 0), format_error,
995 "invalid format string");
996 EXPECT_THROW_MSG(format("{0:.{1}", 0, 0), format_error,
997 "precision not allowed for this argument type");
998 EXPECT_THROW_MSG(format("{0:.{1}}", 0), format_error, "argument not found");
999
1000 EXPECT_THROW_MSG(format("{0:.{0:}}", 0), format_error,
1001 "invalid format string");
1002
1003 EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1), format_error,
1004 "negative precision");
1005 EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1u)), format_error,
1006 "number is too big");
1007 EXPECT_THROW_MSG(format("{0:.{1}}", 0, -1l), format_error,
1008 "negative precision");
1009 if (const_check(sizeof(long) > sizeof(int))) {
1010 long value = INT_MAX;
1011 EXPECT_THROW_MSG(format("{0:.{1}}", 0, (value + 1)), format_error,
1012 "number is too big");
1013 }
1014 EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX + 1ul)), format_error,
1015 "number is too big");
1016
1017 EXPECT_THROW_MSG(format("{0:.{1}}", 0, '0'), format_error,
1018 "precision is not integer");
1019 EXPECT_THROW_MSG(format("{0:.{1}}", 0, 0.0), format_error,
1020 "precision is not integer");
1021
1022 EXPECT_THROW_MSG(format("{0:.{1}}", 42, 2), format_error,
1023 "precision not allowed for this argument type");
1024 EXPECT_THROW_MSG(format("{0:.{1}f}", 42, 2), format_error,
1025 "precision not allowed for this argument type");
1026 EXPECT_THROW_MSG(format("{0:.{1}}", 42u, 2), format_error,
1027 "precision not allowed for this argument type");
1028 EXPECT_THROW_MSG(format("{0:.{1}f}", 42u, 2), format_error,
1029 "precision not allowed for this argument type");
1030 EXPECT_THROW_MSG(format("{0:.{1}}", 42l, 2), format_error,
1031 "precision not allowed for this argument type");
1032 EXPECT_THROW_MSG(format("{0:.{1}f}", 42l, 2), format_error,
1033 "precision not allowed for this argument type");
1034 EXPECT_THROW_MSG(format("{0:.{1}}", 42ul, 2), format_error,
1035 "precision not allowed for this argument type");
1036 EXPECT_THROW_MSG(format("{0:.{1}f}", 42ul, 2), format_error,
1037 "precision not allowed for this argument type");
1038 EXPECT_THROW_MSG(format("{0:.{1}}", 42ll, 2), format_error,
1039 "precision not allowed for this argument type");
1040 EXPECT_THROW_MSG(format("{0:.{1}f}", 42ll, 2), format_error,
1041 "precision not allowed for this argument type");
1042 EXPECT_THROW_MSG(format("{0:.{1}}", 42ull, 2), format_error,
1043 "precision not allowed for this argument type");
1044 EXPECT_THROW_MSG(format("{0:.{1}f}", 42ull, 2), format_error,
1045 "precision not allowed for this argument type");
1046 EXPECT_THROW_MSG(format("{0:3.{1}}", 'x', 0), format_error,
1047 "precision not allowed for this argument type");
1048 EXPECT_EQ("1.2", format("{0:.{1}}", 1.2345, 2));
1049 EXPECT_EQ("1.2", format("{1:.{0}}", 2, 1.2345l));
1050
1051 EXPECT_THROW_MSG(format("{0:.{1}}", reinterpret_cast<void*>(0xcafe), 2),
1052 format_error,
1053 "precision not allowed for this argument type");
1054 EXPECT_THROW_MSG(format("{0:.{1}f}", reinterpret_cast<void*>(0xcafe), 2),
1055 format_error,
1056 "precision not allowed for this argument type");
1057
1058 EXPECT_EQ("st", format("{0:.{1}}", "str", 2));
1059 }
1060
1061 template <typename T>
check_unknown_types(const T & value,const char * types,const char *)1062 void check_unknown_types(const T& value, const char* types, const char*) {
1063 char format_str[BUFFER_SIZE];
1064 const char* special = ".0123456789}";
1065 for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) {
1066 char c = static_cast<char>(i);
1067 if (std::strchr(types, c) || std::strchr(special, c) || !c) continue;
1068 safe_sprintf(format_str, "{0:10%c}", c);
1069 const char* message = "invalid type specifier";
1070 EXPECT_THROW_MSG(format(format_str, value), format_error, message)
1071 << format_str << " " << message;
1072 }
1073 }
1074
TEST(BoolTest,FormatBool)1075 TEST(BoolTest, FormatBool) {
1076 EXPECT_EQ("true", format("{}", true));
1077 EXPECT_EQ("false", format("{}", false));
1078 EXPECT_EQ("1", format("{:d}", true));
1079 EXPECT_EQ("true ", format("{:5}", true));
1080 EXPECT_EQ(L"true", format(L"{}", true));
1081 }
1082
TEST(FormatterTest,FormatShort)1083 TEST(FormatterTest, FormatShort) {
1084 short s = 42;
1085 EXPECT_EQ("42", format("{0:d}", s));
1086 unsigned short us = 42;
1087 EXPECT_EQ("42", format("{0:d}", us));
1088 }
1089
TEST(FormatterTest,FormatInt)1090 TEST(FormatterTest, FormatInt) {
1091 EXPECT_THROW_MSG(format("{0:v", 42), format_error,
1092 "missing '}' in format string");
1093 check_unknown_types(42, "bBdoxXnLc", "integer");
1094 EXPECT_EQ("x", format("{:c}", static_cast<int>('x')));
1095 }
1096
TEST(FormatterTest,FormatBin)1097 TEST(FormatterTest, FormatBin) {
1098 EXPECT_EQ("0", format("{0:b}", 0));
1099 EXPECT_EQ("101010", format("{0:b}", 42));
1100 EXPECT_EQ("101010", format("{0:b}", 42u));
1101 EXPECT_EQ("-101010", format("{0:b}", -42));
1102 EXPECT_EQ("11000000111001", format("{0:b}", 12345));
1103 EXPECT_EQ("10010001101000101011001111000", format("{0:b}", 0x12345678));
1104 EXPECT_EQ("10010000101010111100110111101111", format("{0:b}", 0x90ABCDEF));
1105 EXPECT_EQ("11111111111111111111111111111111",
1106 format("{0:b}", max_value<uint32_t>()));
1107 }
1108
1109 #if FMT_USE_INT128
1110 constexpr auto int128_max = static_cast<__int128_t>(
1111 (static_cast<__uint128_t>(1) << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1);
1112 constexpr auto int128_min = -int128_max - 1;
1113
1114 constexpr auto uint128_max = ~static_cast<__uint128_t>(0);
1115 #endif
1116
TEST(FormatterTest,FormatDec)1117 TEST(FormatterTest, FormatDec) {
1118 EXPECT_EQ("0", format("{0}", 0));
1119 EXPECT_EQ("42", format("{0}", 42));
1120 EXPECT_EQ("42", format("{0:d}", 42));
1121 EXPECT_EQ("42", format("{0}", 42u));
1122 EXPECT_EQ("-42", format("{0}", -42));
1123 EXPECT_EQ("12345", format("{0}", 12345));
1124 EXPECT_EQ("67890", format("{0}", 67890));
1125 #if FMT_USE_INT128
1126 EXPECT_EQ("0", format("{0}", static_cast<__int128_t>(0)));
1127 EXPECT_EQ("0", format("{0}", static_cast<__uint128_t>(0)));
1128 EXPECT_EQ("9223372036854775808",
1129 format("{0}", static_cast<__int128_t>(INT64_MAX) + 1));
1130 EXPECT_EQ("-9223372036854775809",
1131 format("{0}", static_cast<__int128_t>(INT64_MIN) - 1));
1132 EXPECT_EQ("18446744073709551616",
1133 format("{0}", static_cast<__int128_t>(UINT64_MAX) + 1));
1134 EXPECT_EQ("170141183460469231731687303715884105727",
1135 format("{0}", int128_max));
1136 EXPECT_EQ("-170141183460469231731687303715884105728",
1137 format("{0}", int128_min));
1138 EXPECT_EQ("340282366920938463463374607431768211455",
1139 format("{0}", uint128_max));
1140 #endif
1141
1142 char buffer[BUFFER_SIZE];
1143 safe_sprintf(buffer, "%d", INT_MIN);
1144 EXPECT_EQ(buffer, format("{0}", INT_MIN));
1145 safe_sprintf(buffer, "%d", INT_MAX);
1146 EXPECT_EQ(buffer, format("{0}", INT_MAX));
1147 safe_sprintf(buffer, "%u", UINT_MAX);
1148 EXPECT_EQ(buffer, format("{0}", UINT_MAX));
1149 safe_sprintf(buffer, "%ld", 0 - static_cast<unsigned long>(LONG_MIN));
1150 EXPECT_EQ(buffer, format("{0}", LONG_MIN));
1151 safe_sprintf(buffer, "%ld", LONG_MAX);
1152 EXPECT_EQ(buffer, format("{0}", LONG_MAX));
1153 safe_sprintf(buffer, "%lu", ULONG_MAX);
1154 EXPECT_EQ(buffer, format("{0}", ULONG_MAX));
1155 }
1156
TEST(FormatterTest,FormatHex)1157 TEST(FormatterTest, FormatHex) {
1158 EXPECT_EQ("0", format("{0:x}", 0));
1159 EXPECT_EQ("42", format("{0:x}", 0x42));
1160 EXPECT_EQ("42", format("{0:x}", 0x42u));
1161 EXPECT_EQ("-42", format("{0:x}", -0x42));
1162 EXPECT_EQ("12345678", format("{0:x}", 0x12345678));
1163 EXPECT_EQ("90abcdef", format("{0:x}", 0x90abcdef));
1164 EXPECT_EQ("12345678", format("{0:X}", 0x12345678));
1165 EXPECT_EQ("90ABCDEF", format("{0:X}", 0x90ABCDEF));
1166 #if FMT_USE_INT128
1167 EXPECT_EQ("0", format("{0:x}", static_cast<__int128_t>(0)));
1168 EXPECT_EQ("0", format("{0:x}", static_cast<__uint128_t>(0)));
1169 EXPECT_EQ("8000000000000000",
1170 format("{0:x}", static_cast<__int128_t>(INT64_MAX) + 1));
1171 EXPECT_EQ("-8000000000000001",
1172 format("{0:x}", static_cast<__int128_t>(INT64_MIN) - 1));
1173 EXPECT_EQ("10000000000000000",
1174 format("{0:x}", static_cast<__int128_t>(UINT64_MAX) + 1));
1175 EXPECT_EQ("7fffffffffffffffffffffffffffffff", format("{0:x}", int128_max));
1176 EXPECT_EQ("-80000000000000000000000000000000", format("{0:x}", int128_min));
1177 EXPECT_EQ("ffffffffffffffffffffffffffffffff", format("{0:x}", uint128_max));
1178 #endif
1179
1180 char buffer[BUFFER_SIZE];
1181 safe_sprintf(buffer, "-%x", 0 - static_cast<unsigned>(INT_MIN));
1182 EXPECT_EQ(buffer, format("{0:x}", INT_MIN));
1183 safe_sprintf(buffer, "%x", INT_MAX);
1184 EXPECT_EQ(buffer, format("{0:x}", INT_MAX));
1185 safe_sprintf(buffer, "%x", UINT_MAX);
1186 EXPECT_EQ(buffer, format("{0:x}", UINT_MAX));
1187 safe_sprintf(buffer, "-%lx", 0 - static_cast<unsigned long>(LONG_MIN));
1188 EXPECT_EQ(buffer, format("{0:x}", LONG_MIN));
1189 safe_sprintf(buffer, "%lx", LONG_MAX);
1190 EXPECT_EQ(buffer, format("{0:x}", LONG_MAX));
1191 safe_sprintf(buffer, "%lx", ULONG_MAX);
1192 EXPECT_EQ(buffer, format("{0:x}", ULONG_MAX));
1193 }
1194
TEST(FormatterTest,FormatOct)1195 TEST(FormatterTest, FormatOct) {
1196 EXPECT_EQ("0", format("{0:o}", 0));
1197 EXPECT_EQ("42", format("{0:o}", 042));
1198 EXPECT_EQ("42", format("{0:o}", 042u));
1199 EXPECT_EQ("-42", format("{0:o}", -042));
1200 EXPECT_EQ("12345670", format("{0:o}", 012345670));
1201 #if FMT_USE_INT128
1202 EXPECT_EQ("0", format("{0:o}", static_cast<__int128_t>(0)));
1203 EXPECT_EQ("0", format("{0:o}", static_cast<__uint128_t>(0)));
1204 EXPECT_EQ("1000000000000000000000",
1205 format("{0:o}", static_cast<__int128_t>(INT64_MAX) + 1));
1206 EXPECT_EQ("-1000000000000000000001",
1207 format("{0:o}", static_cast<__int128_t>(INT64_MIN) - 1));
1208 EXPECT_EQ("2000000000000000000000",
1209 format("{0:o}", static_cast<__int128_t>(UINT64_MAX) + 1));
1210 EXPECT_EQ("1777777777777777777777777777777777777777777",
1211 format("{0:o}", int128_max));
1212 EXPECT_EQ("-2000000000000000000000000000000000000000000",
1213 format("{0:o}", int128_min));
1214 EXPECT_EQ("3777777777777777777777777777777777777777777",
1215 format("{0:o}", uint128_max));
1216 #endif
1217
1218 char buffer[BUFFER_SIZE];
1219 safe_sprintf(buffer, "-%o", 0 - static_cast<unsigned>(INT_MIN));
1220 EXPECT_EQ(buffer, format("{0:o}", INT_MIN));
1221 safe_sprintf(buffer, "%o", INT_MAX);
1222 EXPECT_EQ(buffer, format("{0:o}", INT_MAX));
1223 safe_sprintf(buffer, "%o", UINT_MAX);
1224 EXPECT_EQ(buffer, format("{0:o}", UINT_MAX));
1225 safe_sprintf(buffer, "-%lo", 0 - static_cast<unsigned long>(LONG_MIN));
1226 EXPECT_EQ(buffer, format("{0:o}", LONG_MIN));
1227 safe_sprintf(buffer, "%lo", LONG_MAX);
1228 EXPECT_EQ(buffer, format("{0:o}", LONG_MAX));
1229 safe_sprintf(buffer, "%lo", ULONG_MAX);
1230 EXPECT_EQ(buffer, format("{0:o}", ULONG_MAX));
1231 }
1232
TEST(FormatterTest,FormatIntLocale)1233 TEST(FormatterTest, FormatIntLocale) {
1234 EXPECT_EQ("1234", format("{:L}", 1234));
1235 }
1236
1237 struct ConvertibleToLongLong {
operator long longConvertibleToLongLong1238 operator long long() const { return 1LL << 32; }
1239 };
1240
TEST(FormatterTest,FormatConvertibleToLongLong)1241 TEST(FormatterTest, FormatConvertibleToLongLong) {
1242 EXPECT_EQ("100000000", format("{:x}", ConvertibleToLongLong()));
1243 }
1244
TEST(FormatterTest,FormatFloat)1245 TEST(FormatterTest, FormatFloat) {
1246 EXPECT_EQ("0", format("{}", 0.0f));
1247 EXPECT_EQ("392.500000", format("{0:f}", 392.5f));
1248 }
1249
TEST(FormatterTest,FormatDouble)1250 TEST(FormatterTest, FormatDouble) {
1251 EXPECT_EQ("0", format("{}", 0.0));
1252 check_unknown_types(1.2, "eEfFgGaAnL%", "double");
1253 EXPECT_EQ("0", format("{:}", 0.0));
1254 EXPECT_EQ("0.000000", format("{:f}", 0.0));
1255 EXPECT_EQ("0", format("{:g}", 0.0));
1256 EXPECT_EQ("392.65", format("{:}", 392.65));
1257 EXPECT_EQ("392.65", format("{:g}", 392.65));
1258 EXPECT_EQ("392.65", format("{:G}", 392.65));
1259 EXPECT_EQ("4.9014e+06", format("{:g}", 4.9014e6));
1260 EXPECT_EQ("392.650000", format("{:f}", 392.65));
1261 EXPECT_EQ("392.650000", format("{:F}", 392.65));
1262 EXPECT_EQ("42", format("{:L}", 42.0));
1263 char buffer[BUFFER_SIZE];
1264 safe_sprintf(buffer, "%e", 392.65);
1265 EXPECT_EQ(buffer, format("{0:e}", 392.65));
1266 safe_sprintf(buffer, "%E", 392.65);
1267 EXPECT_EQ(buffer, format("{0:E}", 392.65));
1268 EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.65));
1269 safe_sprintf(buffer, "%a", -42.0);
1270 EXPECT_EQ(buffer, format("{:a}", -42.0));
1271 safe_sprintf(buffer, "%A", -42.0);
1272 EXPECT_EQ(buffer, format("{:A}", -42.0));
1273 EXPECT_EQ("9223372036854775808.000000",
1274 format("{:f}", 9223372036854775807.0));
1275 }
1276
TEST(FormatterTest,PrecisionRounding)1277 TEST(FormatterTest, PrecisionRounding) {
1278 EXPECT_EQ("0", format("{:.0f}", 0.0));
1279 EXPECT_EQ("0", format("{:.0f}", 0.01));
1280 EXPECT_EQ("0", format("{:.0f}", 0.1));
1281 EXPECT_EQ("0.000", format("{:.3f}", 0.00049));
1282 EXPECT_EQ("0.001", format("{:.3f}", 0.0005));
1283 EXPECT_EQ("0.001", format("{:.3f}", 0.00149));
1284 EXPECT_EQ("0.002", format("{:.3f}", 0.0015));
1285 EXPECT_EQ("1.000", format("{:.3f}", 0.9999));
1286 EXPECT_EQ("0.00123", format("{:.3}", 0.00123));
1287 EXPECT_EQ("0.1", format("{:.16g}", 0.1));
1288 EXPECT_EQ("1", fmt::format("{:.0}", 1.0));
1289 EXPECT_EQ("225.51575035152063720",
1290 fmt::format("{:.17f}", 225.51575035152064));
1291 EXPECT_EQ("-761519619559038.2", fmt::format("{:.1f}", -761519619559038.2));
1292 EXPECT_EQ("1.9156918820264798e-56",
1293 fmt::format("{}", 1.9156918820264798e-56));
1294 EXPECT_EQ("0.0000", fmt::format("{:.4f}", 7.2809479766055470e-15));
1295
1296 // Trigger a rounding error in Grisu by a specially chosen number.
1297 EXPECT_EQ("3788512123356.985352", format("{:f}", 3788512123356.985352));
1298 }
1299
TEST(FormatterTest,PrettifyFloat)1300 TEST(FormatterTest, PrettifyFloat) {
1301 EXPECT_EQ("0.0001", fmt::format("{}", 1e-4));
1302 EXPECT_EQ("1e-05", fmt::format("{}", 1e-5));
1303 EXPECT_EQ("1000000000000000", fmt::format("{}", 1e15));
1304 EXPECT_EQ("1e+16", fmt::format("{}", 1e16));
1305 EXPECT_EQ("9.999e-05", fmt::format("{}", 9.999e-5));
1306 EXPECT_EQ("10000000000", fmt::format("{}", 1e10));
1307 EXPECT_EQ("100000000000", fmt::format("{}", 1e11));
1308 EXPECT_EQ("12340000000", fmt::format("{}", 1234e7));
1309 EXPECT_EQ("12.34", fmt::format("{}", 1234e-2));
1310 EXPECT_EQ("0.001234", fmt::format("{}", 1234e-6));
1311 EXPECT_EQ("0.1", fmt::format("{}", 0.1f));
1312 EXPECT_EQ("0.10000000149011612", fmt::format("{}", double(0.1f)));
1313 EXPECT_EQ("1.3563156e-19", fmt::format("{}", 1.35631564e-19f));
1314 }
1315
TEST(FormatterTest,FormatNaN)1316 TEST(FormatterTest, FormatNaN) {
1317 double nan = std::numeric_limits<double>::quiet_NaN();
1318 EXPECT_EQ("nan", format("{}", nan));
1319 EXPECT_EQ("+nan", format("{:+}", nan));
1320 if (std::signbit(-nan))
1321 EXPECT_EQ("-nan", format("{}", -nan));
1322 else
1323 fmt::print("Warning: compiler doesn't handle negative NaN correctly");
1324 EXPECT_EQ(" nan", format("{: }", nan));
1325 EXPECT_EQ("NAN", format("{:F}", nan));
1326 EXPECT_EQ("nan ", format("{:<7}", nan));
1327 EXPECT_EQ(" nan ", format("{:^7}", nan));
1328 EXPECT_EQ(" nan", format("{:>7}", nan));
1329 }
1330
TEST(FormatterTest,FormatInfinity)1331 TEST(FormatterTest, FormatInfinity) {
1332 double inf = std::numeric_limits<double>::infinity();
1333 EXPECT_EQ("inf", format("{}", inf));
1334 EXPECT_EQ("+inf", format("{:+}", inf));
1335 EXPECT_EQ("-inf", format("{}", -inf));
1336 EXPECT_EQ(" inf", format("{: }", inf));
1337 EXPECT_EQ("INF", format("{:F}", inf));
1338 EXPECT_EQ("inf ", format("{:<7}", inf));
1339 EXPECT_EQ(" inf ", format("{:^7}", inf));
1340 EXPECT_EQ(" inf", format("{:>7}", inf));
1341 }
1342
TEST(FormatterTest,FormatLongDouble)1343 TEST(FormatterTest, FormatLongDouble) {
1344 EXPECT_EQ("0", format("{0:}", 0.0l));
1345 EXPECT_EQ("0.000000", format("{0:f}", 0.0l));
1346 EXPECT_EQ("392.65", format("{0:}", 392.65l));
1347 EXPECT_EQ("392.65", format("{0:g}", 392.65l));
1348 EXPECT_EQ("392.65", format("{0:G}", 392.65l));
1349 EXPECT_EQ("392.650000", format("{0:f}", 392.65l));
1350 EXPECT_EQ("392.650000", format("{0:F}", 392.65l));
1351 char buffer[BUFFER_SIZE];
1352 safe_sprintf(buffer, "%Le", 392.65l);
1353 EXPECT_EQ(buffer, format("{0:e}", 392.65l));
1354 EXPECT_EQ("+0000392.6", format("{0:+010.4g}", 392.64l));
1355 safe_sprintf(buffer, "%La", 3.31l);
1356 EXPECT_EQ(buffer, format("{:a}", 3.31l));
1357 }
1358
TEST(FormatterTest,FormatChar)1359 TEST(FormatterTest, FormatChar) {
1360 const char types[] = "cbBdoxXL";
1361 check_unknown_types('a', types, "char");
1362 EXPECT_EQ("a", format("{0}", 'a'));
1363 EXPECT_EQ("z", format("{0:c}", 'z'));
1364 EXPECT_EQ(L"a", format(L"{0}", 'a'));
1365 int n = 'x';
1366 for (const char* type = types + 1; *type; ++type) {
1367 std::string format_str = fmt::format("{{:{}}}", *type);
1368 EXPECT_EQ(fmt::format(format_str, n), fmt::format(format_str, 'x'));
1369 }
1370 EXPECT_EQ(fmt::format("{:02X}", n), fmt::format("{:02X}", 'x'));
1371 }
1372
TEST(FormatterTest,FormatVolatileChar)1373 TEST(FormatterTest, FormatVolatileChar) {
1374 volatile char c = 'x';
1375 EXPECT_EQ("x", format("{}", c));
1376 }
1377
TEST(FormatterTest,FormatUnsignedChar)1378 TEST(FormatterTest, FormatUnsignedChar) {
1379 EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42)));
1380 EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42)));
1381 }
1382
TEST(FormatterTest,FormatWChar)1383 TEST(FormatterTest, FormatWChar) {
1384 EXPECT_EQ(L"a", format(L"{0}", L'a'));
1385 // This shouldn't compile:
1386 // format("{}", L'a');
1387 }
1388
TEST(FormatterTest,FormatCString)1389 TEST(FormatterTest, FormatCString) {
1390 check_unknown_types("test", "sp", "string");
1391 EXPECT_EQ("test", format("{0}", "test"));
1392 EXPECT_EQ("test", format("{0:s}", "test"));
1393 char nonconst[] = "nonconst";
1394 EXPECT_EQ("nonconst", format("{0}", nonconst));
1395 EXPECT_THROW_MSG(format("{0}", static_cast<const char*>(nullptr)),
1396 format_error, "string pointer is null");
1397 }
1398
TEST(FormatterTest,FormatSCharString)1399 TEST(FormatterTest, FormatSCharString) {
1400 signed char str[] = "test";
1401 EXPECT_EQ("test", format("{0:s}", str));
1402 const signed char* const_str = str;
1403 EXPECT_EQ("test", format("{0:s}", const_str));
1404 }
1405
TEST(FormatterTest,FormatUCharString)1406 TEST(FormatterTest, FormatUCharString) {
1407 unsigned char str[] = "test";
1408 EXPECT_EQ("test", format("{0:s}", str));
1409 const unsigned char* const_str = str;
1410 EXPECT_EQ("test", format("{0:s}", const_str));
1411 unsigned char* ptr = str;
1412 EXPECT_EQ("test", format("{0:s}", ptr));
1413 }
1414
TEST(FormatterTest,FormatPointer)1415 TEST(FormatterTest, FormatPointer) {
1416 check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
1417 EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr)));
1418 EXPECT_EQ("0x1234", format("{0}", reinterpret_cast<void*>(0x1234)));
1419 EXPECT_EQ("0x1234", format("{0:p}", reinterpret_cast<void*>(0x1234)));
1420 EXPECT_EQ("0x" + std::string(sizeof(void*) * CHAR_BIT / 4, 'f'),
1421 format("{0}", reinterpret_cast<void*>(~uintptr_t())));
1422 EXPECT_EQ("0x1234", format("{}", fmt::ptr(reinterpret_cast<int*>(0x1234))));
1423 std::unique_ptr<int> up(new int(1));
1424 EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up)));
1425 std::shared_ptr<int> sp(new int(1));
1426 EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp)));
1427 EXPECT_EQ("0x0", format("{}", nullptr));
1428 }
1429
TEST(FormatterTest,FormatString)1430 TEST(FormatterTest, FormatString) {
1431 EXPECT_EQ("test", format("{0}", std::string("test")));
1432 }
1433
TEST(FormatterTest,FormatStringView)1434 TEST(FormatterTest, FormatStringView) {
1435 EXPECT_EQ("test", format("{}", string_view("test")));
1436 EXPECT_EQ("", format("{}", string_view()));
1437 }
1438
1439 #ifdef FMT_USE_STRING_VIEW
1440 struct string_viewable {};
1441
1442 FMT_BEGIN_NAMESPACE
1443 template <> struct formatter<string_viewable> : formatter<std::string_view> {
formatformatter1444 auto format(string_viewable, format_context& ctx) -> decltype(ctx.out()) {
1445 return formatter<std::string_view>::format("foo", ctx);
1446 }
1447 };
1448 FMT_END_NAMESPACE
1449
TEST(FormatterTest,FormatStdStringView)1450 TEST(FormatterTest, FormatStdStringView) {
1451 EXPECT_EQ("test", format("{}", std::string_view("test")));
1452 EXPECT_EQ("foo", format("{}", string_viewable()));
1453 }
1454
1455 struct explicitly_convertible_to_std_string_view {
operator std::string_viewexplicitly_convertible_to_std_string_view1456 explicit operator std::string_view() const { return "foo"; }
1457 };
1458
1459 namespace fmt {
1460 template <>
1461 struct formatter<explicitly_convertible_to_std_string_view>
1462 : formatter<std::string_view> {
formatfmt::formatter1463 auto format(const explicitly_convertible_to_std_string_view& v,
1464 format_context& ctx) -> decltype(ctx.out()) {
1465 return format_to(ctx.out(), "'{}'", std::string_view(v));
1466 }
1467 };
1468 } // namespace fmt
1469
TEST(FormatterTest,FormatExplicitlyConvertibleToStdStringView)1470 TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) {
1471 EXPECT_EQ("'foo'",
1472 fmt::format("{}", explicitly_convertible_to_std_string_view()));
1473 }
1474 #endif
1475
1476 // std::is_constructible is broken in MSVC until version 2015.
1477 #if !FMT_MSC_VER || FMT_MSC_VER >= 1900
1478 struct explicitly_convertible_to_wstring_view {
operator fmt::wstring_viewexplicitly_convertible_to_wstring_view1479 explicit operator fmt::wstring_view() const { return L"foo"; }
1480 };
1481
TEST(FormatTest,FormatExplicitlyConvertibleToWStringView)1482 TEST(FormatTest, FormatExplicitlyConvertibleToWStringView) {
1483 EXPECT_EQ(L"foo",
1484 fmt::format(L"{}", explicitly_convertible_to_wstring_view()));
1485 }
1486 #endif
1487
1488 namespace fake_qt {
1489 class QString {
1490 public:
QString(const wchar_t * s)1491 QString(const wchar_t* s) : s_(std::make_shared<std::wstring>(s)) {}
utf16() const1492 const wchar_t* utf16() const FMT_NOEXCEPT { return s_->data(); }
size() const1493 int size() const FMT_NOEXCEPT { return static_cast<int>(s_->size()); }
1494
1495 private:
1496 std::shared_ptr<std::wstring> s_;
1497 };
1498
to_string_view(const QString & s)1499 fmt::basic_string_view<wchar_t> to_string_view(const QString& s) FMT_NOEXCEPT {
1500 return {s.utf16(), static_cast<size_t>(s.size())};
1501 }
1502 } // namespace fake_qt
1503
TEST(FormatTest,FormatForeignStrings)1504 TEST(FormatTest, FormatForeignStrings) {
1505 using fake_qt::QString;
1506 EXPECT_EQ(fmt::format(QString(L"{}"), 42), L"42");
1507 EXPECT_EQ(fmt::format(QString(L"{}"), QString(L"42")), L"42");
1508 }
1509
1510 FMT_BEGIN_NAMESPACE
1511 template <> struct formatter<Date> {
1512 template <typename ParseContext>
parseformatter1513 FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
1514 auto it = ctx.begin();
1515 if (it != ctx.end() && *it == 'd') ++it;
1516 return it;
1517 }
1518
formatformatter1519 auto format(const Date& d, format_context& ctx) -> decltype(ctx.out()) {
1520 format_to(ctx.out(), "{}-{}-{}", d.year(), d.month(), d.day());
1521 return ctx.out();
1522 }
1523 };
1524 FMT_END_NAMESPACE
1525
TEST(FormatterTest,FormatCustom)1526 TEST(FormatterTest, FormatCustom) {
1527 Date date(2012, 12, 9);
1528 EXPECT_THROW_MSG(fmt::format("{:s}", date), format_error,
1529 "unknown format specifier");
1530 }
1531
1532 class Answer {};
1533
1534 FMT_BEGIN_NAMESPACE
1535 template <> struct formatter<Answer> : formatter<int> {
1536 template <typename FormatContext>
formatformatter1537 auto format(Answer, FormatContext& ctx) -> decltype(ctx.out()) {
1538 return formatter<int>::format(42, ctx);
1539 }
1540 };
1541 FMT_END_NAMESPACE
1542
TEST(FormatterTest,CustomFormat)1543 TEST(FormatterTest, CustomFormat) {
1544 EXPECT_EQ("42", format("{0}", Answer()));
1545 EXPECT_EQ("0042", format("{:04}", Answer()));
1546 }
1547
TEST(FormatterTest,CustomFormatTo)1548 TEST(FormatterTest, CustomFormatTo) {
1549 char buf[10] = {};
1550 auto end =
1551 &*fmt::format_to(fmt::detail::make_checked(buf, 10), "{}", Answer());
1552 EXPECT_EQ(end, buf + 2);
1553 EXPECT_STREQ(buf, "42");
1554 }
1555
TEST(FormatterTest,WideFormatString)1556 TEST(FormatterTest, WideFormatString) {
1557 EXPECT_EQ(L"42", format(L"{}", 42));
1558 EXPECT_EQ(L"4.2", format(L"{}", 4.2));
1559 EXPECT_EQ(L"abc", format(L"{}", L"abc"));
1560 EXPECT_EQ(L"z", format(L"{}", L'z'));
1561 EXPECT_THROW(fmt::format(L"{:*\x343E}", 42), fmt::format_error);
1562 }
1563
TEST(FormatterTest,FormatStringFromSpeedTest)1564 TEST(FormatterTest, FormatStringFromSpeedTest) {
1565 EXPECT_EQ("1.2340000000:0042:+3.13:str:0x3e8:X:%",
1566 format("{0:0.10f}:{1:04}:{2:+g}:{3}:{4}:{5}:%", 1.234, 42, 3.13,
1567 "str", reinterpret_cast<void*>(1000), 'X'));
1568 }
1569
TEST(FormatterTest,FormatExamples)1570 TEST(FormatterTest, FormatExamples) {
1571 std::string message = format("The answer is {}", 42);
1572 EXPECT_EQ("The answer is 42", message);
1573
1574 EXPECT_EQ("42", format("{}", 42));
1575 EXPECT_EQ("42", format(std::string("{}"), 42));
1576
1577 memory_buffer out;
1578 format_to(out, "The answer is {}.", 42);
1579 EXPECT_EQ("The answer is 42.", to_string(out));
1580
1581 const char* filename = "nonexistent";
1582 FILE* ftest = safe_fopen(filename, "r");
1583 if (ftest) fclose(ftest);
1584 int error_code = errno;
1585 EXPECT_TRUE(ftest == nullptr);
1586 EXPECT_SYSTEM_ERROR(
1587 {
1588 FILE* f = safe_fopen(filename, "r");
1589 if (!f)
1590 throw fmt::system_error(errno, "Cannot open file '{}'", filename);
1591 fclose(f);
1592 },
1593 error_code, "Cannot open file 'nonexistent'");
1594 }
1595
TEST(FormatterTest,Examples)1596 TEST(FormatterTest, Examples) {
1597 EXPECT_EQ("First, thou shalt count to three",
1598 format("First, thou shalt count to {0}", "three"));
1599 EXPECT_EQ("Bring me a shrubbery", format("Bring me a {}", "shrubbery"));
1600 EXPECT_EQ("From 1 to 3", format("From {} to {}", 1, 3));
1601
1602 char buffer[BUFFER_SIZE];
1603 safe_sprintf(buffer, "%03.2f", -1.2);
1604 EXPECT_EQ(buffer, format("{:03.2f}", -1.2));
1605
1606 EXPECT_EQ("a, b, c", format("{0}, {1}, {2}", 'a', 'b', 'c'));
1607 EXPECT_EQ("a, b, c", format("{}, {}, {}", 'a', 'b', 'c'));
1608 EXPECT_EQ("c, b, a", format("{2}, {1}, {0}", 'a', 'b', 'c'));
1609 EXPECT_EQ("abracadabra", format("{0}{1}{0}", "abra", "cad"));
1610
1611 EXPECT_EQ("left aligned ", format("{:<30}", "left aligned"));
1612 EXPECT_EQ(" right aligned",
1613 format("{:>30}", "right aligned"));
1614 EXPECT_EQ(" centered ", format("{:^30}", "centered"));
1615 EXPECT_EQ("***********centered***********", format("{:*^30}", "centered"));
1616
1617 EXPECT_EQ("+3.140000; -3.140000", format("{:+f}; {:+f}", 3.14, -3.14));
1618 EXPECT_EQ(" 3.140000; -3.140000", format("{: f}; {: f}", 3.14, -3.14));
1619 EXPECT_EQ("3.140000; -3.140000", format("{:-f}; {:-f}", 3.14, -3.14));
1620
1621 EXPECT_EQ("int: 42; hex: 2a; oct: 52",
1622 format("int: {0:d}; hex: {0:x}; oct: {0:o}", 42));
1623 EXPECT_EQ("int: 42; hex: 0x2a; oct: 052",
1624 format("int: {0:d}; hex: {0:#x}; oct: {0:#o}", 42));
1625
1626 EXPECT_EQ("The answer is 42", format("The answer is {}", 42));
1627 EXPECT_THROW_MSG(format("The answer is {:d}", "forty-two"), format_error,
1628 "invalid type specifier");
1629
1630 EXPECT_EQ(L"Cyrillic letter \x42e", format(L"Cyrillic letter {}", L'\x42e'));
1631
1632 EXPECT_WRITE(
1633 stdout, fmt::print("{}", std::numeric_limits<double>::infinity()), "inf");
1634 }
1635
TEST(FormatIntTest,Data)1636 TEST(FormatIntTest, Data) {
1637 fmt::format_int format_int(42);
1638 EXPECT_EQ("42", std::string(format_int.data(), format_int.size()));
1639 }
1640
TEST(FormatIntTest,FormatInt)1641 TEST(FormatIntTest, FormatInt) {
1642 EXPECT_EQ("42", fmt::format_int(42).str());
1643 EXPECT_EQ(2u, fmt::format_int(42).size());
1644 EXPECT_EQ("-42", fmt::format_int(-42).str());
1645 EXPECT_EQ(3u, fmt::format_int(-42).size());
1646 EXPECT_EQ("42", fmt::format_int(42ul).str());
1647 EXPECT_EQ("-42", fmt::format_int(-42l).str());
1648 EXPECT_EQ("42", fmt::format_int(42ull).str());
1649 EXPECT_EQ("-42", fmt::format_int(-42ll).str());
1650 std::ostringstream os;
1651 os << max_value<int64_t>();
1652 EXPECT_EQ(os.str(), fmt::format_int(max_value<int64_t>()).str());
1653 }
1654
TEST(FormatTest,Print)1655 TEST(FormatTest, Print) {
1656 #if FMT_USE_FCNTL
1657 EXPECT_WRITE(stdout, fmt::print("Don't {}!", "panic"), "Don't panic!");
1658 EXPECT_WRITE(stderr, fmt::print(stderr, "Don't {}!", "panic"),
1659 "Don't panic!");
1660 #endif
1661 // Check that the wide print overload compiles.
1662 if (fmt::detail::const_check(false)) fmt::print(L"test");
1663 }
1664
TEST(FormatTest,Variadic)1665 TEST(FormatTest, Variadic) {
1666 EXPECT_EQ("abc1", format("{}c{}", "ab", 1));
1667 EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1));
1668 }
1669
TEST(FormatTest,Dynamic)1670 TEST(FormatTest, Dynamic) {
1671 typedef fmt::format_context ctx;
1672 std::vector<fmt::basic_format_arg<ctx>> args;
1673 args.emplace_back(fmt::detail::make_arg<ctx>(42));
1674 args.emplace_back(fmt::detail::make_arg<ctx>("abc1"));
1675 args.emplace_back(fmt::detail::make_arg<ctx>(1.5f));
1676
1677 std::string result = fmt::vformat(
1678 "{} and {} and {}",
1679 fmt::basic_format_args<ctx>(args.data(), static_cast<int>(args.size())));
1680
1681 EXPECT_EQ("42 and abc1 and 1.5", result);
1682 }
1683
TEST(FormatTest,Bytes)1684 TEST(FormatTest, Bytes) {
1685 auto s = fmt::format("{:10}", fmt::bytes("ёжик"));
1686 EXPECT_EQ("ёжик ", s);
1687 EXPECT_EQ(10, s.size());
1688 }
1689
TEST(FormatTest,JoinArg)1690 TEST(FormatTest, JoinArg) {
1691 using fmt::join;
1692 int v1[3] = {1, 2, 3};
1693 std::vector<float> v2;
1694 v2.push_back(1.2f);
1695 v2.push_back(3.4f);
1696 void* v3[2] = {&v1[0], &v1[1]};
1697
1698 EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, v1 + 3, ", ")));
1699 EXPECT_EQ("(1)", format("({})", join(v1, v1 + 1, ", ")));
1700 EXPECT_EQ("()", format("({})", join(v1, v1, ", ")));
1701 EXPECT_EQ("(001, 002, 003)", format("({:03})", join(v1, v1 + 3, ", ")));
1702 EXPECT_EQ("(+01.20, +03.40)",
1703 format("({:+06.2f})", join(v2.begin(), v2.end(), ", ")));
1704
1705 EXPECT_EQ(L"(1, 2, 3)", format(L"({})", join(v1, v1 + 3, L", ")));
1706 EXPECT_EQ("1, 2, 3", format("{0:{1}}", join(v1, v1 + 3, ", "), 1));
1707
1708 EXPECT_EQ(format("{}, {}", v3[0], v3[1]),
1709 format("{}", join(v3, v3 + 2, ", ")));
1710
1711 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 405
1712 EXPECT_EQ("(1, 2, 3)", format("({})", join(v1, ", ")));
1713 EXPECT_EQ("(+01.20, +03.40)", format("({:+06.2f})", join(v2, ", ")));
1714 #endif
1715 }
1716
str(const T & value)1717 template <typename T> std::string str(const T& value) {
1718 return fmt::format("{}", value);
1719 }
1720
TEST(StrTest,Convert)1721 TEST(StrTest, Convert) {
1722 EXPECT_EQ("42", str(42));
1723 std::string s = str(Date(2012, 12, 9));
1724 EXPECT_EQ("2012-12-9", s);
1725 }
1726
vformat_message(int id,const char * format,fmt::format_args args)1727 std::string vformat_message(int id, const char* format, fmt::format_args args) {
1728 fmt::memory_buffer buffer;
1729 format_to(buffer, "[{}] ", id);
1730 vformat_to(buffer, format, args);
1731 return to_string(buffer);
1732 }
1733
1734 template <typename... Args>
format_message(int id,const char * format,const Args &...args)1735 std::string format_message(int id, const char* format, const Args&... args) {
1736 auto va = fmt::make_format_args(args...);
1737 return vformat_message(id, format, va);
1738 }
1739
TEST(FormatTest,FormatMessageExample)1740 TEST(FormatTest, FormatMessageExample) {
1741 EXPECT_EQ("[42] something happened",
1742 format_message(42, "{} happened", "something"));
1743 }
1744
1745 template <typename... Args>
print_error(const char * file,int line,const char * format,const Args &...args)1746 void print_error(const char* file, int line, const char* format,
1747 const Args&... args) {
1748 fmt::print("{}: {}: ", file, line);
1749 fmt::print(format, args...);
1750 }
1751
TEST(FormatTest,UnpackedArgs)1752 TEST(FormatTest, UnpackedArgs) {
1753 EXPECT_EQ("0123456789abcdefg",
1754 fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}", 0, 1, 2, 3, 4, 5,
1755 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g'));
1756 }
1757
1758 struct string_like {};
to_string_view(string_like)1759 fmt::string_view to_string_view(string_like) { return "foo"; }
1760
1761 constexpr char with_null[3] = {'{', '}', '\0'};
1762 constexpr char no_null[2] = {'{', '}'};
1763
TEST(FormatTest,CompileTimeString)1764 TEST(FormatTest, CompileTimeString) {
1765 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), 42));
1766 EXPECT_EQ(L"42", fmt::format(FMT_STRING(L"{}"), 42));
1767 EXPECT_EQ("foo", fmt::format(FMT_STRING("{}"), string_like()));
1768 (void)with_null;
1769 (void)no_null;
1770 #if __cplusplus >= 201703L
1771 EXPECT_EQ("42", fmt::format(FMT_STRING(with_null), 42));
1772 EXPECT_EQ("42", fmt::format(FMT_STRING(no_null), 42));
1773 #endif
1774 #if defined(FMT_USE_STRING_VIEW) && __cplusplus >= 201703L
1775 EXPECT_EQ("42", fmt::format(FMT_STRING(std::string_view("{}")), 42));
1776 EXPECT_EQ(L"42", fmt::format(FMT_STRING(std::wstring_view(L"{}")), 42));
1777 #endif
1778 }
1779
TEST(FormatTest,CustomFormatCompileTimeString)1780 TEST(FormatTest, CustomFormatCompileTimeString) {
1781 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), Answer()));
1782 Answer answer;
1783 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), answer));
1784 char buf[10] = {};
1785 fmt::format_to(buf, FMT_STRING("{}"), answer);
1786 const Answer const_answer = Answer();
1787 EXPECT_EQ("42", fmt::format(FMT_STRING("{}"), const_answer));
1788 }
1789
1790 #if FMT_USE_USER_DEFINED_LITERALS
1791 // Passing user-defined literals directly to EXPECT_EQ causes problems
1792 // with macro argument stringification (#) on some versions of GCC.
1793 // Workaround: Assing the UDL result to a variable before the macro.
1794
1795 using namespace fmt::literals;
1796
TEST(LiteralsTest,Format)1797 TEST(LiteralsTest, Format) {
1798 auto udl_format = "{}c{}"_format("ab", 1);
1799 EXPECT_EQ(format("{}c{}", "ab", 1), udl_format);
1800 auto udl_format_w = L"{}c{}"_format(L"ab", 1);
1801 EXPECT_EQ(format(L"{}c{}", L"ab", 1), udl_format_w);
1802 }
1803
TEST(LiteralsTest,NamedArg)1804 TEST(LiteralsTest, NamedArg) {
1805 auto udl_a = format("{first}{second}{first}{third}", "first"_a = "abra",
1806 "second"_a = "cad", "third"_a = 99);
1807 EXPECT_EQ(format("{first}{second}{first}{third}", fmt::arg("first", "abra"),
1808 fmt::arg("second", "cad"), fmt::arg("third", 99)),
1809 udl_a);
1810 auto udl_a_w = format(L"{first}{second}{first}{third}", L"first"_a = L"abra",
1811 L"second"_a = L"cad", L"third"_a = 99);
1812 EXPECT_EQ(
1813 format(L"{first}{second}{first}{third}", fmt::arg(L"first", L"abra"),
1814 fmt::arg(L"second", L"cad"), fmt::arg(L"third", 99)),
1815 udl_a_w);
1816 }
1817
TEST(FormatTest,UdlTemplate)1818 TEST(FormatTest, UdlTemplate) {
1819 EXPECT_EQ("foo", "foo"_format());
1820 EXPECT_EQ(" 42", "{0:10}"_format(42));
1821 }
1822
TEST(FormatTest,UdlPassUserDefinedObjectAsLvalue)1823 TEST(FormatTest, UdlPassUserDefinedObjectAsLvalue) {
1824 Date date(2015, 10, 21);
1825 EXPECT_EQ("2015-10-21", "{}"_format(date));
1826 }
1827 #endif // FMT_USE_USER_DEFINED_LITERALS
1828
1829 enum TestEnum { A };
1830
TEST(FormatTest,Enum)1831 TEST(FormatTest, Enum) { EXPECT_EQ("0", fmt::format("{}", A)); }
1832
TEST(FormatTest,FormatterNotSpecialized)1833 TEST(FormatTest, FormatterNotSpecialized) {
1834 static_assert(
1835 !fmt::has_formatter<fmt::formatter<TestEnum>, fmt::format_context>::value,
1836 "");
1837 }
1838
1839 #if FMT_HAS_FEATURE(cxx_strong_enums)
1840 enum big_enum : unsigned long long { big_enum_value = 5000000000ULL };
1841
TEST(FormatTest,StrongEnum)1842 TEST(FormatTest, StrongEnum) {
1843 EXPECT_EQ("5000000000", fmt::format("{}", big_enum_value));
1844 }
1845 #endif
1846
TEST(FormatTest,NonNullTerminatedFormatString)1847 TEST(FormatTest, NonNullTerminatedFormatString) {
1848 EXPECT_EQ("42", format(string_view("{}foo", 2), 42));
1849 }
1850
1851 struct variant {
1852 enum { INT, STRING } type;
variantvariant1853 explicit variant(int) : type(INT) {}
variantvariant1854 explicit variant(const char*) : type(STRING) {}
1855 };
1856
1857 FMT_BEGIN_NAMESPACE
1858 template <> struct formatter<variant> : dynamic_formatter<> {
formatformatter1859 auto format(variant value, format_context& ctx) -> decltype(ctx.out()) {
1860 if (value.type == variant::INT) return dynamic_formatter<>::format(42, ctx);
1861 return dynamic_formatter<>::format("foo", ctx);
1862 }
1863 };
1864 FMT_END_NAMESPACE
1865
TEST(FormatTest,DynamicFormatter)1866 TEST(FormatTest, DynamicFormatter) {
1867 auto num = variant(42);
1868 auto str = variant("foo");
1869 EXPECT_EQ("42", format("{:d}", num));
1870 EXPECT_EQ("foo", format("{:s}", str));
1871 EXPECT_EQ(" 42 foo ", format("{:{}} {:{}}", num, 3, str, 4));
1872 EXPECT_THROW_MSG(format("{0:{}}", num), format_error,
1873 "cannot switch from manual to automatic argument indexing");
1874 EXPECT_THROW_MSG(format("{:{0}}", num), format_error,
1875 "cannot switch from automatic to manual argument indexing");
1876 #if FMT_DEPRECATED_NUMERIC_ALIGN
1877 EXPECT_THROW_MSG(format("{:=}", str), format_error,
1878 "format specifier requires numeric argument");
1879 #endif
1880 EXPECT_THROW_MSG(format("{:+}", str), format_error,
1881 "format specifier requires numeric argument");
1882 EXPECT_THROW_MSG(format("{:-}", str), format_error,
1883 "format specifier requires numeric argument");
1884 EXPECT_THROW_MSG(format("{: }", str), format_error,
1885 "format specifier requires numeric argument");
1886 EXPECT_THROW_MSG(format("{:#}", str), format_error,
1887 "format specifier requires numeric argument");
1888 EXPECT_THROW_MSG(format("{:0}", str), format_error,
1889 "format specifier requires numeric argument");
1890 EXPECT_THROW_MSG(format("{:.2}", num), format_error,
1891 "precision not allowed for this argument type");
1892 }
1893
1894 namespace adl_test {
1895 namespace fmt {
1896 namespace detail {
1897 struct foo {};
1898 template <typename, typename OutputIt> void write(OutputIt, foo) = delete;
1899 } // namespace detail
1900 } // namespace fmt
1901 } // namespace adl_test
1902
1903 FMT_BEGIN_NAMESPACE
1904 template <>
1905 struct formatter<adl_test::fmt::detail::foo> : formatter<std::string> {
1906 template <typename FormatContext>
formatformatter1907 auto format(adl_test::fmt::detail::foo, FormatContext& ctx)
1908 -> decltype(ctx.out()) {
1909 return formatter<std::string>::format("foo", ctx);
1910 }
1911 };
1912 FMT_END_NAMESPACE
1913
TEST(FormatTest,ToString)1914 TEST(FormatTest, ToString) {
1915 EXPECT_EQ("42", fmt::to_string(42));
1916 EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234)));
1917 EXPECT_EQ("foo", fmt::to_string(adl_test::fmt::detail::foo()));
1918 }
1919
TEST(FormatTest,ToWString)1920 TEST(FormatTest, ToWString) { EXPECT_EQ(L"42", fmt::to_wstring(42)); }
1921
TEST(FormatTest,OutputIterators)1922 TEST(FormatTest, OutputIterators) {
1923 std::list<char> out;
1924 fmt::format_to(std::back_inserter(out), "{}", 42);
1925 EXPECT_EQ("42", std::string(out.begin(), out.end()));
1926 std::stringstream s;
1927 fmt::format_to(std::ostream_iterator<char>(s), "{}", 42);
1928 EXPECT_EQ("42", s.str());
1929 }
1930
TEST(FormatTest,FormattedSize)1931 TEST(FormatTest, FormattedSize) {
1932 EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
1933 }
1934
TEST(FormatTest,FormatTo)1935 TEST(FormatTest, FormatTo) {
1936 std::vector<char> v;
1937 fmt::format_to(std::back_inserter(v), "{}", "foo");
1938 EXPECT_EQ(string_view(v.data(), v.size()), "foo");
1939 }
1940
TEST(FormatTest,FormatToN)1941 TEST(FormatTest, FormatToN) {
1942 char buffer[4];
1943 buffer[3] = 'x';
1944 auto result = fmt::format_to_n(buffer, 3, "{}", 12345);
1945 EXPECT_EQ(5u, result.size);
1946 EXPECT_EQ(buffer + 3, result.out);
1947 EXPECT_EQ("123x", fmt::string_view(buffer, 4));
1948
1949 result = fmt::format_to_n(buffer, 3, "{:s}", "foobar");
1950 EXPECT_EQ(6u, result.size);
1951 EXPECT_EQ(buffer + 3, result.out);
1952 EXPECT_EQ("foox", fmt::string_view(buffer, 4));
1953
1954 buffer[0] = 'x';
1955 buffer[1] = 'x';
1956 buffer[2] = 'x';
1957 result = fmt::format_to_n(buffer, 3, "{}", 'A');
1958 EXPECT_EQ(1u, result.size);
1959 EXPECT_EQ(buffer + 1, result.out);
1960 EXPECT_EQ("Axxx", fmt::string_view(buffer, 4));
1961
1962 result = fmt::format_to_n(buffer, 3, "{}{} ", 'B', 'C');
1963 EXPECT_EQ(3u, result.size);
1964 EXPECT_EQ(buffer + 3, result.out);
1965 EXPECT_EQ("BC x", fmt::string_view(buffer, 4));
1966
1967 result = fmt::format_to_n(buffer, 4, "{}", "ABCDE");
1968 EXPECT_EQ(5u, result.size);
1969 EXPECT_EQ("ABCD", fmt::string_view(buffer, 4));
1970
1971 buffer[3] = 'x';
1972 result = fmt::format_to_n(buffer, 3, "{}", std::string(1000, '*'));
1973 EXPECT_EQ(1000u, result.size);
1974 EXPECT_EQ("***x", fmt::string_view(buffer, 4));
1975 }
1976
TEST(FormatTest,WideFormatToN)1977 TEST(FormatTest, WideFormatToN) {
1978 wchar_t buffer[4];
1979 buffer[3] = L'x';
1980 auto result = fmt::format_to_n(buffer, 3, L"{}", 12345);
1981 EXPECT_EQ(5u, result.size);
1982 EXPECT_EQ(buffer + 3, result.out);
1983 EXPECT_EQ(L"123x", fmt::wstring_view(buffer, 4));
1984 buffer[0] = L'x';
1985 buffer[1] = L'x';
1986 buffer[2] = L'x';
1987 result = fmt::format_to_n(buffer, 3, L"{}", L'A');
1988 EXPECT_EQ(1u, result.size);
1989 EXPECT_EQ(buffer + 1, result.out);
1990 EXPECT_EQ(L"Axxx", fmt::wstring_view(buffer, 4));
1991 result = fmt::format_to_n(buffer, 3, L"{}{} ", L'B', L'C');
1992 EXPECT_EQ(3u, result.size);
1993 EXPECT_EQ(buffer + 3, result.out);
1994 EXPECT_EQ(L"BC x", fmt::wstring_view(buffer, 4));
1995 }
1996
1997 struct test_output_iterator {
1998 char* data;
1999
2000 using iterator_category = std::output_iterator_tag;
2001 using value_type = void;
2002 using difference_type = void;
2003 using pointer = void;
2004 using reference = void;
2005
operator ++test_output_iterator2006 test_output_iterator& operator++() {
2007 ++data;
2008 return *this;
2009 }
operator ++test_output_iterator2010 test_output_iterator operator++(int) {
2011 auto tmp = *this;
2012 ++data;
2013 return tmp;
2014 }
operator *test_output_iterator2015 char& operator*() { return *data; }
2016 };
2017
TEST(FormatTest,FormatToNOutputIterator)2018 TEST(FormatTest, FormatToNOutputIterator) {
2019 char buf[10] = {};
2020 fmt::format_to_n(test_output_iterator{buf}, 10, "{}", 42);
2021 EXPECT_STREQ(buf, "42");
2022 }
2023
2024 #if FMT_USE_CONSTEXPR
2025 struct test_arg_id_handler {
2026 enum result { NONE, EMPTY, INDEX, NAME, ERROR };
2027 result res = NONE;
2028 int index = 0;
2029 string_view name;
2030
operator ()test_arg_id_handler2031 FMT_CONSTEXPR void operator()() { res = EMPTY; }
2032
operator ()test_arg_id_handler2033 FMT_CONSTEXPR void operator()(int i) {
2034 res = INDEX;
2035 index = i;
2036 }
2037
operator ()test_arg_id_handler2038 FMT_CONSTEXPR void operator()(string_view n) {
2039 res = NAME;
2040 name = n;
2041 }
2042
on_errortest_arg_id_handler2043 FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
2044 };
2045
2046 template <size_t N>
parse_arg_id(const char (& s)[N])2047 FMT_CONSTEXPR test_arg_id_handler parse_arg_id(const char (&s)[N]) {
2048 test_arg_id_handler h;
2049 fmt::detail::parse_arg_id(s, s + N, h);
2050 return h;
2051 }
2052
TEST(FormatTest,ConstexprParseArgID)2053 TEST(FormatTest, ConstexprParseArgID) {
2054 static_assert(parse_arg_id(":").res == test_arg_id_handler::EMPTY, "");
2055 static_assert(parse_arg_id("}").res == test_arg_id_handler::EMPTY, "");
2056 static_assert(parse_arg_id("42:").res == test_arg_id_handler::INDEX, "");
2057 static_assert(parse_arg_id("42:").index == 42, "");
2058 static_assert(parse_arg_id("foo:").res == test_arg_id_handler::NAME, "");
2059 static_assert(parse_arg_id("foo:").name.size() == 3, "");
2060 static_assert(parse_arg_id("!").res == test_arg_id_handler::ERROR, "");
2061 }
2062
2063 struct test_format_specs_handler {
2064 enum Result { NONE, PLUS, MINUS, SPACE, HASH, ZERO, ERROR };
2065 Result res = NONE;
2066
2067 fmt::align_t align = fmt::align::none;
2068 char fill = 0;
2069 int width = 0;
2070 fmt::detail::arg_ref<char> width_ref;
2071 int precision = 0;
2072 fmt::detail::arg_ref<char> precision_ref;
2073 char type = 0;
2074
2075 // Workaround for MSVC2017 bug that results in "expression did not evaluate
2076 // to a constant" with compiler-generated copy ctor.
test_format_specs_handlertest_format_specs_handler2077 FMT_CONSTEXPR test_format_specs_handler() {}
test_format_specs_handlertest_format_specs_handler2078 FMT_CONSTEXPR test_format_specs_handler(
2079 const test_format_specs_handler& other)
2080 : res(other.res),
2081 align(other.align),
2082 fill(other.fill),
2083 width(other.width),
2084 width_ref(other.width_ref),
2085 precision(other.precision),
2086 precision_ref(other.precision_ref),
2087 type(other.type) {}
2088
on_aligntest_format_specs_handler2089 FMT_CONSTEXPR void on_align(fmt::align_t a) { align = a; }
on_filltest_format_specs_handler2090 FMT_CONSTEXPR void on_fill(fmt::string_view f) { fill = f[0]; }
on_plustest_format_specs_handler2091 FMT_CONSTEXPR void on_plus() { res = PLUS; }
on_minustest_format_specs_handler2092 FMT_CONSTEXPR void on_minus() { res = MINUS; }
on_spacetest_format_specs_handler2093 FMT_CONSTEXPR void on_space() { res = SPACE; }
on_hashtest_format_specs_handler2094 FMT_CONSTEXPR void on_hash() { res = HASH; }
on_zerotest_format_specs_handler2095 FMT_CONSTEXPR void on_zero() { res = ZERO; }
2096
on_widthtest_format_specs_handler2097 FMT_CONSTEXPR void on_width(int w) { width = w; }
on_dynamic_widthtest_format_specs_handler2098 FMT_CONSTEXPR void on_dynamic_width(fmt::detail::auto_id) {}
on_dynamic_widthtest_format_specs_handler2099 FMT_CONSTEXPR void on_dynamic_width(int index) { width_ref = index; }
on_dynamic_widthtest_format_specs_handler2100 FMT_CONSTEXPR void on_dynamic_width(string_view) {}
2101
on_precisiontest_format_specs_handler2102 FMT_CONSTEXPR void on_precision(int p) { precision = p; }
on_dynamic_precisiontest_format_specs_handler2103 FMT_CONSTEXPR void on_dynamic_precision(fmt::detail::auto_id) {}
on_dynamic_precisiontest_format_specs_handler2104 FMT_CONSTEXPR void on_dynamic_precision(int index) { precision_ref = index; }
on_dynamic_precisiontest_format_specs_handler2105 FMT_CONSTEXPR void on_dynamic_precision(string_view) {}
2106
end_precisiontest_format_specs_handler2107 FMT_CONSTEXPR void end_precision() {}
on_typetest_format_specs_handler2108 FMT_CONSTEXPR void on_type(char t) { type = t; }
on_errortest_format_specs_handler2109 FMT_CONSTEXPR void on_error(const char*) { res = ERROR; }
2110 };
2111
2112 template <size_t N>
parse_test_specs(const char (& s)[N])2113 FMT_CONSTEXPR test_format_specs_handler parse_test_specs(const char (&s)[N]) {
2114 test_format_specs_handler h;
2115 fmt::detail::parse_format_specs(s, s + N, h);
2116 return h;
2117 }
2118
TEST(FormatTest,ConstexprParseFormatSpecs)2119 TEST(FormatTest, ConstexprParseFormatSpecs) {
2120 typedef test_format_specs_handler handler;
2121 static_assert(parse_test_specs("<").align == fmt::align::left, "");
2122 static_assert(parse_test_specs("*^").fill == '*', "");
2123 static_assert(parse_test_specs("+").res == handler::PLUS, "");
2124 static_assert(parse_test_specs("-").res == handler::MINUS, "");
2125 static_assert(parse_test_specs(" ").res == handler::SPACE, "");
2126 static_assert(parse_test_specs("#").res == handler::HASH, "");
2127 static_assert(parse_test_specs("0").res == handler::ZERO, "");
2128 static_assert(parse_test_specs("42").width == 42, "");
2129 static_assert(parse_test_specs("{42}").width_ref.val.index == 42, "");
2130 static_assert(parse_test_specs(".42").precision == 42, "");
2131 static_assert(parse_test_specs(".{42}").precision_ref.val.index == 42, "");
2132 static_assert(parse_test_specs("d").type == 'd', "");
2133 static_assert(parse_test_specs("{<").res == handler::ERROR, "");
2134 }
2135
2136 struct test_parse_context {
2137 typedef char char_type;
2138
next_arg_idtest_parse_context2139 FMT_CONSTEXPR int next_arg_id() { return 11; }
check_arg_idtest_parse_context2140 template <typename Id> FMT_CONSTEXPR void check_arg_id(Id) {}
2141
begintest_parse_context2142 FMT_CONSTEXPR const char* begin() { return nullptr; }
endtest_parse_context2143 FMT_CONSTEXPR const char* end() { return nullptr; }
2144
on_errortest_parse_context2145 void on_error(const char*) {}
2146 };
2147
2148 struct test_context {
2149 using char_type = char;
2150 using format_arg = fmt::basic_format_arg<test_context>;
2151 using parse_context_type = fmt::format_parse_context;
2152
2153 template <typename T> struct formatter_type {
2154 typedef fmt::formatter<T, char_type> type;
2155 };
2156
2157 template <typename Id>
argtest_context2158 FMT_CONSTEXPR fmt::basic_format_arg<test_context> arg(Id id) {
2159 return fmt::detail::make_arg<test_context>(id);
2160 }
2161
on_errortest_context2162 void on_error(const char*) {}
2163
error_handlertest_context2164 FMT_CONSTEXPR test_context error_handler() { return *this; }
2165 };
2166
2167 template <size_t N>
parse_specs(const char (& s)[N])2168 FMT_CONSTEXPR fmt::format_specs parse_specs(const char (&s)[N]) {
2169 auto specs = fmt::format_specs();
2170 auto parse_ctx = test_parse_context();
2171 auto ctx = test_context();
2172 fmt::detail::specs_handler<test_parse_context, test_context> h(
2173 specs, parse_ctx, ctx);
2174 parse_format_specs(s, s + N, h);
2175 return specs;
2176 }
2177
TEST(FormatTest,ConstexprSpecsHandler)2178 TEST(FormatTest, ConstexprSpecsHandler) {
2179 static_assert(parse_specs("<").align == fmt::align::left, "");
2180 static_assert(parse_specs("*^").fill[0] == '*', "");
2181 static_assert(parse_specs("+").sign == fmt::sign::plus, "");
2182 static_assert(parse_specs("-").sign == fmt::sign::minus, "");
2183 static_assert(parse_specs(" ").sign == fmt::sign::space, "");
2184 static_assert(parse_specs("#").alt, "");
2185 static_assert(parse_specs("0").align == fmt::align::numeric, "");
2186 static_assert(parse_specs("42").width == 42, "");
2187 static_assert(parse_specs("{}").width == 11, "");
2188 static_assert(parse_specs("{22}").width == 22, "");
2189 static_assert(parse_specs(".42").precision == 42, "");
2190 static_assert(parse_specs(".{}").precision == 11, "");
2191 static_assert(parse_specs(".{22}").precision == 22, "");
2192 static_assert(parse_specs("d").type == 'd', "");
2193 }
2194
2195 template <size_t N>
parse_dynamic_specs(const char (& s)[N])2196 FMT_CONSTEXPR fmt::detail::dynamic_format_specs<char> parse_dynamic_specs(
2197 const char (&s)[N]) {
2198 fmt::detail::dynamic_format_specs<char> specs;
2199 test_parse_context ctx{};
2200 fmt::detail::dynamic_specs_handler<test_parse_context> h(specs, ctx);
2201 parse_format_specs(s, s + N, h);
2202 return specs;
2203 }
2204
TEST(FormatTest,ConstexprDynamicSpecsHandler)2205 TEST(FormatTest, ConstexprDynamicSpecsHandler) {
2206 static_assert(parse_dynamic_specs("<").align == fmt::align::left, "");
2207 static_assert(parse_dynamic_specs("*^").fill[0] == '*', "");
2208 static_assert(parse_dynamic_specs("+").sign == fmt::sign::plus, "");
2209 static_assert(parse_dynamic_specs("-").sign == fmt::sign::minus, "");
2210 static_assert(parse_dynamic_specs(" ").sign == fmt::sign::space, "");
2211 static_assert(parse_dynamic_specs("#").alt, "");
2212 static_assert(parse_dynamic_specs("0").align == fmt::align::numeric, "");
2213 static_assert(parse_dynamic_specs("42").width == 42, "");
2214 static_assert(parse_dynamic_specs("{}").width_ref.val.index == 11, "");
2215 static_assert(parse_dynamic_specs("{42}").width_ref.val.index == 42, "");
2216 static_assert(parse_dynamic_specs(".42").precision == 42, "");
2217 static_assert(parse_dynamic_specs(".{}").precision_ref.val.index == 11, "");
2218 static_assert(parse_dynamic_specs(".{42}").precision_ref.val.index == 42, "");
2219 static_assert(parse_dynamic_specs("d").type == 'd', "");
2220 }
2221
2222 template <size_t N>
check_specs(const char (& s)[N])2223 FMT_CONSTEXPR test_format_specs_handler check_specs(const char (&s)[N]) {
2224 fmt::detail::specs_checker<test_format_specs_handler> checker(
2225 test_format_specs_handler(), fmt::detail::type::double_type);
2226 parse_format_specs(s, s + N, checker);
2227 return checker;
2228 }
2229
TEST(FormatTest,ConstexprSpecsChecker)2230 TEST(FormatTest, ConstexprSpecsChecker) {
2231 typedef test_format_specs_handler handler;
2232 static_assert(check_specs("<").align == fmt::align::left, "");
2233 static_assert(check_specs("*^").fill == '*', "");
2234 static_assert(check_specs("+").res == handler::PLUS, "");
2235 static_assert(check_specs("-").res == handler::MINUS, "");
2236 static_assert(check_specs(" ").res == handler::SPACE, "");
2237 static_assert(check_specs("#").res == handler::HASH, "");
2238 static_assert(check_specs("0").res == handler::ZERO, "");
2239 static_assert(check_specs("42").width == 42, "");
2240 static_assert(check_specs("{42}").width_ref.val.index == 42, "");
2241 static_assert(check_specs(".42").precision == 42, "");
2242 static_assert(check_specs(".{42}").precision_ref.val.index == 42, "");
2243 static_assert(check_specs("d").type == 'd', "");
2244 static_assert(check_specs("{<").res == handler::ERROR, "");
2245 }
2246
2247 struct test_format_string_handler {
on_texttest_format_string_handler2248 FMT_CONSTEXPR void on_text(const char*, const char*) {}
2249
on_arg_idtest_format_string_handler2250 FMT_CONSTEXPR int on_arg_id() { return 0; }
2251
on_arg_idtest_format_string_handler2252 template <typename T> FMT_CONSTEXPR int on_arg_id(T) { return 0; }
2253
on_replacement_fieldtest_format_string_handler2254 FMT_CONSTEXPR void on_replacement_field(int, const char*) {}
2255
on_format_specstest_format_string_handler2256 FMT_CONSTEXPR const char* on_format_specs(int, const char* begin,
2257 const char*) {
2258 return begin;
2259 }
2260
on_errortest_format_string_handler2261 FMT_CONSTEXPR void on_error(const char*) { error = true; }
2262
2263 bool error = false;
2264 };
2265
parse_string(const char (& s)[N])2266 template <size_t N> FMT_CONSTEXPR bool parse_string(const char (&s)[N]) {
2267 test_format_string_handler h;
2268 fmt::detail::parse_format_string<true>(fmt::string_view(s, N - 1), h);
2269 return !h.error;
2270 }
2271
TEST(FormatTest,ConstexprParseFormatString)2272 TEST(FormatTest, ConstexprParseFormatString) {
2273 static_assert(parse_string("foo"), "");
2274 static_assert(!parse_string("}"), "");
2275 static_assert(parse_string("{}"), "");
2276 static_assert(parse_string("{42}"), "");
2277 static_assert(parse_string("{foo}"), "");
2278 static_assert(parse_string("{:}"), "");
2279 }
2280
2281 struct test_error_handler {
2282 const char*& error;
2283
test_error_handlertest_error_handler2284 FMT_CONSTEXPR test_error_handler(const char*& err) : error(err) {}
2285
test_error_handlertest_error_handler2286 FMT_CONSTEXPR test_error_handler(const test_error_handler& other)
2287 : error(other.error) {}
2288
on_errortest_error_handler2289 FMT_CONSTEXPR void on_error(const char* message) {
2290 if (!error) error = message;
2291 }
2292 };
2293
len(const char * s)2294 FMT_CONSTEXPR size_t len(const char* s) {
2295 size_t len = 0;
2296 while (*s++) ++len;
2297 return len;
2298 }
2299
equal(const char * s1,const char * s2)2300 FMT_CONSTEXPR bool equal(const char* s1, const char* s2) {
2301 if (!s1 || !s2) return s1 == s2;
2302 while (*s1 && *s1 == *s2) {
2303 ++s1;
2304 ++s2;
2305 }
2306 return *s1 == *s2;
2307 }
2308
2309 template <typename... Args>
test_error(const char * fmt,const char * expected_error)2310 FMT_CONSTEXPR bool test_error(const char* fmt, const char* expected_error) {
2311 const char* actual_error = nullptr;
2312 string_view s(fmt, len(fmt));
2313 fmt::detail::format_string_checker<char, test_error_handler, Args...> checker(
2314 s, test_error_handler(actual_error));
2315 fmt::detail::parse_format_string<true>(s, checker);
2316 return equal(actual_error, expected_error);
2317 }
2318
2319 # define EXPECT_ERROR_NOARGS(fmt, error) \
2320 static_assert(test_error(fmt, error), "")
2321 # define EXPECT_ERROR(fmt, error, ...) \
2322 static_assert(test_error<__VA_ARGS__>(fmt, error), "")
2323
TEST(FormatTest,FormatStringErrors)2324 TEST(FormatTest, FormatStringErrors) {
2325 EXPECT_ERROR_NOARGS("foo", nullptr);
2326 EXPECT_ERROR_NOARGS("}", "unmatched '}' in format string");
2327 EXPECT_ERROR("{0:s", "unknown format specifier", Date);
2328 # if !FMT_MSC_VER || FMT_MSC_VER >= 1916
2329 // This causes an detail compiler error in MSVC2017.
2330 EXPECT_ERROR("{:{<}", "invalid fill character '{'", int);
2331 EXPECT_ERROR("{:10000000000}", "number is too big", int);
2332 EXPECT_ERROR("{:.10000000000}", "number is too big", int);
2333 EXPECT_ERROR_NOARGS("{:x}", "argument not found");
2334 # if FMT_DEPRECATED_NUMERIC_ALIGN
2335 EXPECT_ERROR("{0:=5", "unknown format specifier", int);
2336 EXPECT_ERROR("{:=}", "format specifier requires numeric argument",
2337 const char*);
2338 # endif
2339 EXPECT_ERROR("{:+}", "format specifier requires numeric argument",
2340 const char*);
2341 EXPECT_ERROR("{:-}", "format specifier requires numeric argument",
2342 const char*);
2343 EXPECT_ERROR("{:#}", "format specifier requires numeric argument",
2344 const char*);
2345 EXPECT_ERROR("{: }", "format specifier requires numeric argument",
2346 const char*);
2347 EXPECT_ERROR("{:0}", "format specifier requires numeric argument",
2348 const char*);
2349 EXPECT_ERROR("{:+}", "format specifier requires signed argument", unsigned);
2350 EXPECT_ERROR("{:-}", "format specifier requires signed argument", unsigned);
2351 EXPECT_ERROR("{: }", "format specifier requires signed argument", unsigned);
2352 EXPECT_ERROR("{:{}}", "argument not found", int);
2353 EXPECT_ERROR("{:.{}}", "argument not found", double);
2354 EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int);
2355 EXPECT_ERROR("{:s}", "invalid type specifier", int);
2356 EXPECT_ERROR("{:s}", "invalid type specifier", bool);
2357 EXPECT_ERROR("{:s}", "invalid type specifier", char);
2358 EXPECT_ERROR("{:+}", "invalid format specifier for char", char);
2359 EXPECT_ERROR("{:s}", "invalid type specifier", double);
2360 EXPECT_ERROR("{:d}", "invalid type specifier", const char*);
2361 EXPECT_ERROR("{:d}", "invalid type specifier", std::string);
2362 EXPECT_ERROR("{:s}", "invalid type specifier", void*);
2363 # else
2364 fmt::print("warning: constexpr is broken in this version of MSVC\n");
2365 # endif
2366 EXPECT_ERROR("{foo", "compile-time checks don't support named arguments",
2367 int);
2368 EXPECT_ERROR_NOARGS("{10000000000}", "number is too big");
2369 EXPECT_ERROR_NOARGS("{0x}", "invalid format string");
2370 EXPECT_ERROR_NOARGS("{-}", "invalid format string");
2371 EXPECT_ERROR("{:{0x}}", "invalid format string", int);
2372 EXPECT_ERROR("{:{-}}", "invalid format string", int);
2373 EXPECT_ERROR("{:.{0x}}", "invalid format string", int);
2374 EXPECT_ERROR("{:.{-}}", "invalid format string", int);
2375 EXPECT_ERROR("{:.x}", "missing precision specifier", int);
2376 EXPECT_ERROR_NOARGS("{}", "argument not found");
2377 EXPECT_ERROR("{1}", "argument not found", int);
2378 EXPECT_ERROR("{1}{}",
2379 "cannot switch from manual to automatic argument indexing", int,
2380 int);
2381 EXPECT_ERROR("{}{1}",
2382 "cannot switch from automatic to manual argument indexing", int,
2383 int);
2384 }
2385
TEST(FormatTest,VFormatTo)2386 TEST(FormatTest, VFormatTo) {
2387 typedef fmt::format_context context;
2388 fmt::basic_format_arg<context> arg = fmt::detail::make_arg<context>(42);
2389 fmt::basic_format_args<context> args(&arg, 1);
2390 std::string s;
2391 fmt::vformat_to(std::back_inserter(s), "{}", args);
2392 EXPECT_EQ("42", s);
2393 s.clear();
2394 fmt::vformat_to(std::back_inserter(s), FMT_STRING("{}"), args);
2395 EXPECT_EQ("42", s);
2396
2397 typedef fmt::wformat_context wcontext;
2398 fmt::basic_format_arg<wcontext> warg = fmt::detail::make_arg<wcontext>(42);
2399 fmt::basic_format_args<wcontext> wargs(&warg, 1);
2400 std::wstring w;
2401 fmt::vformat_to(std::back_inserter(w), L"{}", wargs);
2402 EXPECT_EQ(L"42", w);
2403 w.clear();
2404 fmt::vformat_to(std::back_inserter(w), FMT_STRING(L"{}"), wargs);
2405 EXPECT_EQ(L"42", w);
2406 }
2407
FmtToString(const T & t)2408 template <typename T> static std::string FmtToString(const T& t) {
2409 return fmt::format(FMT_STRING("{}"), t);
2410 }
2411
TEST(FormatTest,FmtStringInTemplate)2412 TEST(FormatTest, FmtStringInTemplate) {
2413 EXPECT_EQ(FmtToString(1), "1");
2414 EXPECT_EQ(FmtToString(0), "0");
2415 }
2416
2417 #endif // FMT_USE_CONSTEXPR
2418
TEST(FormatTest,CharTraitsIsNotAmbiguous)2419 TEST(FormatTest, CharTraitsIsNotAmbiguous) {
2420 // Test that we don't inject detail names into the std namespace.
2421 using namespace std;
2422 char_traits<char>::char_type c;
2423 (void)c;
2424 #if __cplusplus >= 201103L
2425 std::string s;
2426 auto lval = begin(s);
2427 (void)lval;
2428 #endif
2429 }
2430
2431 #if __cplusplus > 201103L
2432 struct custom_char {
2433 int value;
2434 custom_char() = default;
2435
2436 template <typename T>
custom_charcustom_char2437 constexpr custom_char(T val) : value(static_cast<int>(val)) {}
2438
operator intcustom_char2439 operator int() const { return value; }
2440 };
2441
to_ascii(custom_char c)2442 int to_ascii(custom_char c) { return c; }
2443
2444 FMT_BEGIN_NAMESPACE
2445 template <> struct is_char<custom_char> : std::true_type {};
2446 FMT_END_NAMESPACE
2447
TEST(FormatTest,FormatCustomChar)2448 TEST(FormatTest, FormatCustomChar) {
2449 const custom_char format[] = {'{', '}', 0};
2450 auto result = fmt::format(format, custom_char('x'));
2451 EXPECT_EQ(result.size(), 1);
2452 EXPECT_EQ(result[0], custom_char('x'));
2453 }
2454 #endif
2455
2456 // Convert a char8_t string to std::string. Otherwise GTest will insist on
2457 // inserting `char8_t` NTBS into a `char` stream which is disabled by P1423.
from_u8str(const S & str)2458 template <typename S> std::string from_u8str(const S& str) {
2459 return std::string(str.begin(), str.end());
2460 }
2461
TEST(FormatTest,FormatUTF8Precision)2462 TEST(FormatTest, FormatUTF8Precision) {
2463 using str_type = std::basic_string<fmt::detail::char8_type>;
2464 str_type format(reinterpret_cast<const fmt::detail::char8_type*>(u8"{:.4}"));
2465 str_type str(reinterpret_cast<const fmt::detail::char8_type*>(
2466 u8"caf\u00e9s")); // cafés
2467 auto result = fmt::format(format, str);
2468 EXPECT_EQ(fmt::detail::count_code_points(result), 4);
2469 EXPECT_EQ(result.size(), 5);
2470 EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5)));
2471 }
2472
2473 struct check_back_appender {};
2474
2475 FMT_BEGIN_NAMESPACE
2476 template <> struct formatter<check_back_appender> {
2477 template <typename ParseContext>
parseformatter2478 auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
2479 return ctx.begin();
2480 }
2481
2482 template <typename Context>
formatformatter2483 auto format(check_back_appender, Context& ctx) -> decltype(ctx.out()) {
2484 auto out = ctx.out();
2485 static_assert(std::is_same<decltype(++out), decltype(out)&>::value,
2486 "needs to satisfy weakly_incrementable");
2487 *out = 'y';
2488 return ++out;
2489 }
2490 };
2491 FMT_END_NAMESPACE
2492
TEST(FormatTest,BackInsertSlicing)2493 TEST(FormatTest, BackInsertSlicing) {
2494 EXPECT_EQ(fmt::format("{}", check_back_appender{}), "y");
2495 }
2496