1 // Formatting library for C++ - formatting library tests
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
6 // For the license information refer to format.h.
18 // Check if fmt/format.h compiles with windows.h included before it.
23 #include "fmt/format.h"
25 #include "gtest-extra.h"
26 #include "mock-allocator.h"
35 using fmt::basic_memory_buffer
;
36 using fmt::basic_writer
;
38 using fmt::format_error
;
39 using fmt::string_view
;
40 using fmt::memory_buffer
;
41 using fmt::wmemory_buffer
;
43 using testing::Return
;
44 using testing::StrictMock
;
48 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 408
49 template <typename Char
, typename T
>
50 bool check_enabled_formatter() {
52 std::is_default_constructible
<fmt::formatter
<T
, Char
>>::value
, "");
56 template <typename Char
, typename
... T
>
57 void check_enabled_formatters() {
58 auto dummy
= {check_enabled_formatter
<Char
, T
>()...};
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
>();
74 check_enabled_formatters
<char, std::nullptr_t
>();
75 check_enabled_formatters
<wchar_t, std::nullptr_t
>();
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
;
89 // Workaround a bug in formatting long double in MinGW.
90 void std_format(long double value
, std::string
&result
) {
92 safe_sprintf(buffer
, "%Lg", value
);
95 void std_format(long double value
, std::wstring
&result
) {
97 swprintf(buffer
, L
"%Lg", value
);
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
);
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";
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
;
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");
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)
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)
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
) {
155 EXPECT_EQ(i
, fmt::internal::count_digits(n
- 1));
156 EXPECT_EQ(i
+ 1, fmt::internal::count_digits(n
));
160 TEST(UtilTest
, CountDigits
) {
161 test_count_digits
<uint32_t>();
162 test_count_digits
<uint64_t>();
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);
176 TEST(UtilTest
, Increment
) {
179 EXPECT_STREQ("124", s
);
182 EXPECT_STREQ("129", s
);
184 EXPECT_STREQ("130", s
);
187 EXPECT_STREQ("200", s
);
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");
196 const char *s
= "10000000000";
198 parse_nonnegative_int(s
, fmt::internal::error_handler()),
199 fmt::format_error
, "number is too big");
202 parse_nonnegative_int(s
, fmt::internal::error_handler()),
203 fmt::format_error
, "number is too big");
206 TEST(IteratorTest
, CountingIterator
) {
207 fmt::internal::counting_iterator
<char> it
;
209 EXPECT_EQ(prev
.count(), 0);
210 EXPECT_EQ(it
.count(), 1);
213 TEST(IteratorTest
, TruncatingIterator
) {
215 fmt::internal::truncating_iterator
<char*> it(p
, 3);
217 EXPECT_EQ(prev
.base(), p
);
218 EXPECT_EQ(it
.base(), p
+ 1);
221 TEST(IteratorTest
, TruncatingBackInserter
) {
223 auto bi
= std::back_inserter(buffer
);
224 fmt::internal::truncating_iterator
<decltype(bi
)> it(bi
, 2);
228 EXPECT_EQ(buffer
.size(), 2);
229 EXPECT_EQ(buffer
, "42");
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
);
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());
256 static void check_forwarding(
257 mock_allocator
<int> &alloc
, allocator_ref
<mock_allocator
<int>> &ref
) {
259 // Check if value_type is properly defined.
260 allocator_ref
< mock_allocator
<int> >::value_type
*ptr
= &mem
;
262 EXPECT_CALL(alloc
, allocate(42)).WillOnce(testing::Return(ptr
));
264 EXPECT_CALL(alloc
, deallocate(ptr
, 42));
265 ref
.deallocate(ptr
, 42);
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());
279 check_forwarding(alloc
, ref3
);
282 typedef allocator_ref
< std::allocator
<char> > TestAllocator
;
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());
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);
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());
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);
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
)));
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());
364 EXPECT_CALL(alloc
, allocate(20)).WillOnce(Return(mem
));
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));
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
;
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
));
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
);
398 EXPECT_CALL(alloc
, allocate(size
)).WillOnce(Return(&mem
[0]));
400 std::fill(&buffer
[0], &buffer
[0] + size
, 'x');
402 std::vector
<char> mem2(2 * size
);
404 EXPECT_CALL(alloc
, allocate(2 * size
)).WillOnce(Return(&mem2
[0]));
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
]);
413 EXPECT_CALL(alloc
, deallocate(&mem2
[0], 2 * size
));
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());
424 TEST(UtilTest
, UTF16ToUTF8EmptyString
) {
426 fmt::internal::utf16_to_utf8
u(L
"");
427 EXPECT_EQ(s
, u
.str());
428 EXPECT_EQ(s
.size(), u
.size());
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());
438 TEST(UtilTest
, UTF8ToUTF16EmptyString
) {
440 fmt::internal::utf8_to_utf16
u(s
.c_str());
441 EXPECT_EQ(L
"", u
.str());
442 EXPECT_EQ(s
.size(), u
.size());
445 template <typename Converter
, typename Char
>
446 void check_utf_conversion_error(
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, "");
454 } catch (const fmt::system_error
&e
) {
457 EXPECT_EQ(ERROR_INVALID_PARAMETER
, error
.error_code());
458 EXPECT_EQ(fmt::to_string(out
), error
.what());
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");
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));
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)));
481 typedef void (*FormatErrorMessage
)(
482 fmt::internal::buffer
&out
, int error_code
, string_view message
);
484 template <typename Error
>
485 void check_throw_error(int error_code
, FormatErrorMessage format
) {
486 fmt::system_error
error(0, "");
488 throw Error(error_code
, "test {}", "error");
489 } catch (const fmt::system_error
&e
) {
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());
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
)),
503 message
= fmt::memory_buffer();
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;
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;
514 if (!throws_on_alloc
) {
515 fmt::print("warning: std::allocator allocates {} chars", max_size
);
518 fmt::format_system_error(message
, EDOM
, fmt::string_view(FMT_NULL
, max_size
));
519 EXPECT_EQ(fmt::format("error {}", EDOM
), to_string(message
));
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
);
529 TEST(UtilTest
, ReportSystemError
) {
530 fmt::memory_buffer out
;
531 fmt::format_system_error(out
, EDOM
, "test error");
533 EXPECT_WRITE(stderr
, fmt::report_system_error(EDOM
, "test error"),
539 TEST(UtilTest
, FormatWindowsError
) {
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
);
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
));
560 TEST(UtilTest
, FormatLongWindowsError
) {
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
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) {
573 fmt::internal::utf16_to_utf8
utf8_message(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
));
582 TEST(UtilTest
, WindowsError
) {
583 check_throw_error
<fmt::windows_error
>(
584 ERROR_FILE_EXISTS
, fmt::internal::format_windows_error
);
587 TEST(UtilTest
, ReportWindowsError
) {
588 fmt::memory_buffer out
;
589 fmt::internal::format_windows_error(out
, ERROR_FILE_EXISTS
, "test error");
592 fmt::report_windows_error(ERROR_FILE_EXISTS
, "test error"),
593 fmt::to_string(out
));
598 TEST(StringViewTest
, Ctor
) {
599 EXPECT_STREQ("abc", string_view("abc").data());
600 EXPECT_EQ(3u, string_view("abc").size());
602 EXPECT_STREQ("defg", string_view(std::string("defg")).data());
603 EXPECT_EQ(4u, string_view(std::string("defg")).size());
606 TEST(WriterTest
, Data
) {
610 EXPECT_EQ("42", to_string(buf
));
613 TEST(WriterTest
, WriteInt
) {
616 CHECK_WRITE(static_cast<short>(12));
618 CHECK_WRITE(std::numeric_limits
<int>::min());
619 CHECK_WRITE(std::numeric_limits
<int>::max());
620 CHECK_WRITE(std::numeric_limits
<unsigned>::max());
623 TEST(WriterTest
, WriteLong
) {
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());
631 TEST(WriterTest
, WriteLongLong
) {
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());
639 TEST(WriterTest
, WriteDouble
) {
642 CHECK_WRITE(std::numeric_limits
<double>::min());
643 CHECK_WRITE(std::numeric_limits
<double>::max());
646 TEST(WriterTest
, WriteLongDouble
) {
648 CHECK_WRITE_CHAR(-4.2l);
650 std_format(4.2l, str
);
652 CHECK_WRITE_WCHAR(-4.2l);
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());
659 TEST(WriterTest
, WriteDoubleAtBufferBoundary
) {
661 fmt::writer
writer(buf
);
662 for (int i
= 0; i
< 100; ++i
)
663 writer
.write(1.23456789);
666 TEST(WriterTest
, WriteDoubleWithFilledBuffer
) {
668 fmt::writer
writer(buf
);
670 for (int i
= 0; i
< fmt::inline_buffer_size
; ++i
)
673 fmt::string_view
sv(buf
.data(), buf
.size());
674 sv
.remove_prefix(fmt::inline_buffer_size
);
675 EXPECT_EQ("1.2", sv
);
678 TEST(WriterTest
, WriteChar
) {
682 TEST(WriterTest
, WriteWideChar
) {
683 CHECK_WRITE_WCHAR(L
'a');
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");
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");
699 TEST(FormatToTest
, FormatWithoutArgs
) {
701 fmt::format_to(std::back_inserter(s
), "test");
702 EXPECT_EQ("test", s
);
705 TEST(FormatToTest
, Format
) {
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
);
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");
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
);
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
));
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"));
740 EXPECT_EQ("}", format("}}"));
741 EXPECT_EQ("before }", format("before }}"));
742 EXPECT_EQ("} after", format("}} after"));
743 EXPECT_EQ("before } after", format("before }} after"));
745 EXPECT_EQ("{}", format("{{}}"));
746 EXPECT_EQ("{42}", format("{{{0}}}", 42));
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");
755 TEST(FormatterTest
, NoArgs
) {
756 EXPECT_EQ("test", format("test"));
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"));
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");
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");
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");
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
...);
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
...);
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");
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)));
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");
845 TEST(FormatterTest
, EmptySpecs
) {
846 EXPECT_EQ("42", format("{0:}", 42));
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)));
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)));
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));
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)));
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"));
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");
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");
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");
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));
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));
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));
1052 EXPECT_EQ("-42.0", format("{0:#}", -42.0));
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");
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");
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");
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"));
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");
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");
1135 EXPECT_THROW_MSG(format("{0:{0:}}", 0),
1136 format_error
, "invalid format string");
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");
1149 EXPECT_THROW_MSG(format("{0:{1}}", 0, (INT_MAX
+ 1ul)),
1150 format_error
, "number is too big");
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");
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));
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");
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");
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");
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));
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");
1227 EXPECT_EQ("st", format("{0:.2}", "str"));
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");
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");
1254 EXPECT_THROW_MSG(format("{0:.{0:}}", 0),
1255 format_error
, "invalid format string");
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");
1268 EXPECT_THROW_MSG(format("{0:.{1}}", 0, (INT_MAX
+ 1ul)),
1269 format_error
, "number is too big");
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");
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));
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");
1310 EXPECT_EQ("st", format("{0:.{1}}", "str", 2));
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
;
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));
1335 TEST(FormatterTest
, FormatShort
) {
1337 EXPECT_EQ("42", format("{0:d}", s
));
1338 unsigned short us
= 42;
1339 EXPECT_EQ("42", format("{0:d}", us
));
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");
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()));
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
));
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));
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
));
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
));
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()));
1437 struct ConvertibleToLongLong
{
1438 operator long long() const { return 1LL << 32; }
1441 TEST(FormatterTest
, FormatConvertibleToLongLong
) {
1442 EXPECT_EQ("100000000", format("{:x}", ConvertibleToLongLong()));
1445 TEST(FormatterTest
, FormatFloat
) {
1446 EXPECT_EQ("392.500000", format("{0:f}", 392.5f
));
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));
1471 TEST(FormatterTest
, FormatDoubleBigPrecision
) {
1472 // sprintf with big precision is broken in MSVC2013, so only test on Grisu.
1474 EXPECT_EQ(format("0.{:0<1000}", ""), format("{:.1000f}", 0.0));
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
));
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
));
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));
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'));
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'));
1525 EXPECT_EQ(fmt::format("{:02X}", n
), fmt::format("{:02X}", 'x'));
1528 TEST(FormatterTest
, FormatUnsignedChar
) {
1529 EXPECT_EQ("42", format("{}", static_cast<unsigned char>(42)));
1530 EXPECT_EQ("42", format("{}", static_cast<uint8_t>(42)));
1533 TEST(FormatterTest
, FormatWChar
) {
1534 EXPECT_EQ(L
"a", format(L
"{0}", L
'a'));
1535 // This shouldn't compile:
1536 //format("{}", L'a');
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");
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
));
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
));
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))));
1574 EXPECT_EQ("0x0", format("{}", FMT_NULL
));
1578 TEST(FormatterTest
, FormatString
) {
1579 EXPECT_EQ("test", format("{0}", std::string("test")));
1582 TEST(FormatterTest
, FormatStringView
) {
1583 EXPECT_EQ("test", format("{}", string_view("test")));
1584 EXPECT_EQ("", format("{}", string_view()));
1587 #ifdef FMT_USE_STD_STRING_VIEW
1588 TEST(FormatterTest
, FormatStdStringView
) {
1589 EXPECT_EQ("test", format("{0}", std::string_view("test")));
1595 struct formatter
<Date
> {
1596 template <typename ParseContext
>
1597 FMT_CONSTEXPR
auto parse(ParseContext
&ctx
) -> decltype(ctx
.begin()) {
1598 auto it
= ctx
.begin();
1604 auto format(const Date
&d
, format_context
&ctx
) -> decltype(ctx
.out()) {
1605 format_to(ctx
.out(), "{}-{}-{}", d
.year(), d
.month(), d
.day());
1611 TEST(FormatterTest
, FormatCustom
) {
1612 Date
date(2012, 12, 9);
1613 EXPECT_THROW_MSG(fmt::format("{:s}", date
), format_error
,
1614 "unknown format specifier");
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
);
1629 TEST(FormatterTest
, CustomFormat
) {
1630 EXPECT_EQ("42", format("{0}", Answer()));
1631 EXPECT_EQ("0042", format("{:04}", Answer()));
1634 TEST(FormatterTest
, CustomFormatTo
) {
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");
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'));
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'));
1655 TEST(FormatterTest
, FormatExamples
) {
1656 std::string message
= format("The answer is {}", 42);
1657 EXPECT_EQ("The answer is 42", message
);
1659 EXPECT_EQ("42", format("{}", 42));
1660 EXPECT_EQ("42", format(std::string("{}"), 42));
1663 format_to(out
, "The answer is {}.", 42);
1664 EXPECT_EQ("The answer is 42.", to_string(out
));
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");
1674 throw fmt::system_error(errno
, "Cannot open file '{}'", filename
);
1676 }, error_code
, "Cannot open file 'nonexistent'");
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));
1686 char buffer
[BUFFER_SIZE
];
1687 safe_sprintf(buffer
, "%03.2f", -1.2);
1688 EXPECT_EQ(buffer
, format("{:03.2f}", -1.2));
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"));
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"));
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));
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));
1716 EXPECT_EQ("The answer is 42", format("The answer is {}", 42));
1718 format("The answer is {:d}", "forty-two"), format_error
,
1719 "invalid type specifier");
1721 EXPECT_EQ(L
"Cyrillic letter \x42e",
1722 format(L
"Cyrillic letter {}", L
'\x42e'));
1724 EXPECT_WRITE(stdout
,
1725 fmt::print("{}", std::numeric_limits
<double>::infinity()), "inf");
1728 TEST(FormatIntTest
, Data
) {
1729 fmt::format_int
format_int(42);
1730 EXPECT_EQ("42", std::string(format_int
.data(), format_int
.size()));
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();
1745 fmt::format_int(std::numeric_limits
<int64_t>::max()).str());
1748 template <typename T
>
1749 std::string
format_decimal(T value
) {
1752 fmt::format_decimal(ptr
, value
);
1753 return std::string(buffer
, ptr
);
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();
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));
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!");
1781 TEST(FormatTest
, Variadic
) {
1782 EXPECT_EQ("abc1", format("{}c{}", "ab", 1));
1783 EXPECT_EQ(L
"abc1", format(L
"{}c{}", L
"ab", 1));
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
));
1793 std::string result
= fmt::vformat("{} and {} and {}",
1794 fmt::basic_format_args
<ctx
>(
1796 static_cast<unsigned>(args
.size())));
1798 EXPECT_EQ("42 and abc1 and 1.2", result
);
1801 TEST(FormatTest
, JoinArg
) {
1803 int v1
[3] = { 1, 2, 3 };
1804 std::vector
<float> v2
;
1807 void *v3
[2] = { &v1
[0], &v1
[1] };
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(), ", ")));
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));
1819 EXPECT_EQ(format("{}, {}", v3
[0], v3
[1]),
1820 format("{}", join(v3
, v3
+ 2, ", ")));
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
, ", ")));
1828 template <typename T
>
1829 std::string
str(const T
&value
) {
1830 return fmt::format("{}", value
);
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
);
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
);
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
);
1852 TEST(FormatTest
, FormatMessageExample
) {
1853 EXPECT_EQ("[42] something happened",
1854 format_message(42, "{} happened", "something"));
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
...);
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',
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.
1876 using namespace fmt::literals
;
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
);
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)),
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)),
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));
1906 #endif // FMT_USE_USER_DEFINED_LITERALS
1908 enum TestEnum
{ A
};
1910 TEST(FormatTest
, Enum
) {
1911 EXPECT_EQ("0", fmt::format("{}", A
));
1914 TEST(FormatTest
, EnumFormatterUnambiguous
) {
1915 fmt::formatter
<TestEnum
> f
;
1918 #if FMT_HAS_FEATURE(cxx_strong_enums)
1919 enum TestFixedEnum
: short { B
};
1921 TEST(FormatTest
, FixedEnum
) {
1922 EXPECT_EQ("0", fmt::format("{}", B
));
1926 typedef fmt::back_insert_range
<fmt::internal::buffer
> buffer_range
;
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
> {
1933 MOCK_METHOD1(call
, void (long long value
));
1936 typedef fmt::internal::arg_formatter_base
<buffer_range
> base
;
1937 typedef buffer_range range
;
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));
1944 template <typename T
>
1945 typename
std::enable_if
<std::is_integral
<T
>::value
, iterator
>::type
1946 operator()(T value
) {
1948 return base::operator()(value
);
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
);
1957 iterator
operator()(fmt::basic_format_arg
<fmt::format_context
>::handle
) {
1958 return base::operator()(fmt::monostate());
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
);
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
);
1973 TEST(FormatTest
, CustomArgFormatter
) {
1974 custom_format("{}", 42);
1977 TEST(FormatTest
, NonNullTerminatedFormatString
) {
1978 EXPECT_EQ("42", format(string_view("{}foo", 2), 42));
1982 enum {INT
, STRING
} type
;
1983 explicit variant(int) : type(INT
) {}
1984 explicit variant(const char *) : type(STRING
) {}
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
);
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");
2024 TEST(FormatTest
, ToString
) {
2025 EXPECT_EQ("42", fmt::to_string(42));
2026 EXPECT_EQ("0x1234", fmt::to_string(reinterpret_cast<void*>(0x1234)));
2029 TEST(FormatTest
, ToWString
) {
2030 EXPECT_EQ(L
"42", fmt::to_wstring(42));
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());
2042 TEST(FormatTest
, FormattedSize
) {
2043 EXPECT_EQ(2u, fmt::formatted_size("{}", 42));
2046 TEST(FormatTest
, FormatToN
) {
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));
2059 TEST(FormatTest
, WideFormatToN
) {
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));
2068 #if FMT_USE_CONSTEXPR
2069 struct test_arg_id_handler
{
2070 enum result
{ NONE
, EMPTY
, INDEX
, NAME
, ERROR
};
2075 FMT_CONSTEXPR
void operator()() { res
= EMPTY
; }
2077 FMT_CONSTEXPR
void operator()(unsigned i
) {
2082 FMT_CONSTEXPR
void operator()(string_view n
) {
2087 FMT_CONSTEXPR
void on_error(const char *) { res
= ERROR
; }
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
);
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
, "");
2106 struct test_format_specs_handler
{
2107 enum Result
{ NONE
, PLUS
, MINUS
, SPACE
, HASH
, ZERO
, ERROR
};
2110 fmt::alignment align_
= fmt::ALIGN_DEFAULT
;
2113 fmt::internal::arg_ref
<char> width_ref
;
2114 unsigned precision
= 0;
2115 fmt::internal::arg_ref
<char> precision_ref
;
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
),
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
; }
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
) {}
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
;
2145 FMT_CONSTEXPR
void on_dynamic_precision(string_view
) {}
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
; }
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
);
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
, "");
2175 struct test_context
{
2176 typedef char char_type
;
2178 FMT_CONSTEXPR
fmt::basic_format_arg
<test_context
> next_arg() {
2179 return fmt::internal::make_arg
<test_context
>(11);
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);
2187 template <typename Id
>
2188 FMT_CONSTEXPR
void check_arg_id(Id
) {}
2190 FMT_CONSTEXPR
unsigned next_arg_id() { return 33; }
2192 void on_error(const char *) {}
2194 FMT_CONSTEXPR test_context
&parse_context() { return *this; }
2195 FMT_CONSTEXPR test_context
error_handler() { return *this; }
2198 FMT_CONSTEXPR
fmt::format_specs
parse_specs(const char *s
) {
2199 fmt::format_specs specs
;
2201 fmt::internal::specs_handler
<test_context
> h(specs
, ctx
);
2202 parse_format_specs(s
, h
);
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', "");
2223 FMT_CONSTEXPR
fmt::internal::dynamic_format_specs
<char>
2224 parse_dynamic_specs(const char *s
) {
2225 fmt::internal::dynamic_format_specs
<char> specs
;
2227 fmt::internal::dynamic_specs_handler
<test_context
> h(specs
, ctx
);
2228 parse_format_specs(s
, h
);
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', "");
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
);
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
, "");
2273 struct test_format_string_handler
{
2274 FMT_CONSTEXPR
void on_text(const char *, const char *) {}
2276 FMT_CONSTEXPR
void on_arg_id() {}
2278 template <typename T
>
2279 FMT_CONSTEXPR
void on_arg_id(T
) {}
2281 template <typename Iterator
>
2282 FMT_CONSTEXPR
void on_replacement_field(Iterator
) {}
2284 template <typename Iterator
>
2285 FMT_CONSTEXPR Iterator
on_format_specs(Iterator it
) { return it
; }
2287 FMT_CONSTEXPR
void on_error(const char *) { error
= true; }
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
);
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("{:}"), "");
2308 struct test_error_handler
{
2311 FMT_CONSTEXPR
test_error_handler(const char *&err
): error(err
) {}
2313 FMT_CONSTEXPR
test_error_handler(const test_error_handler
&other
)
2314 : error(other
.error
) {}
2316 FMT_CONSTEXPR
void on_error(const char *message
) {
2322 FMT_CONSTEXPR
size_t len(const char *s
) {
2329 FMT_CONSTEXPR
bool equal(const char *s1
, const char *s2
) {
2332 while (*s1
&& *s1
== *s2
) {
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
);
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), "")
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
);
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",
2365 EXPECT_ERROR("{:+}", "format specifier requires numeric argument",
2367 EXPECT_ERROR("{:-}", "format specifier requires numeric argument",
2369 EXPECT_ERROR("{:#}", "format specifier requires numeric argument",
2371 EXPECT_ERROR("{: }", "format specifier requires numeric argument",
2373 EXPECT_ERROR("{:0}", "format specifier requires numeric argument",
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 *);
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",
2402 EXPECT_ERROR("{}{1}",
2403 "cannot switch from automatic to manual argument indexing",
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);
2412 fmt::vformat_to(std::back_inserter(s
), "{}", args
);
2415 fmt::vformat_to(std::back_inserter(s
), FMT_STRING("{}"), args
);
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);
2422 fmt::vformat_to(std::back_inserter(w
), L
"{}", wargs
);
2423 EXPECT_EQ(L
"42", w
);
2425 fmt::vformat_to(std::back_inserter(w
), FMT_STRING(L
"{}"), wargs
);
2426 EXPECT_EQ(L
"42", w
);
2429 #endif // FMT_USE_CONSTEXPR
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');
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');
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
);
2460 TEST(FormatTest
, FormatU8String
) {
2461 EXPECT_EQ(format(fmt::u8string_view("{}"), 42), fmt::u8string_view("42"));