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