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