• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Formatting library for C++ - core 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 <algorithm>
9 #include <climits>
10 #include <cstring>
11 #include <functional>
12 #include <iterator>
13 #include <limits>
14 #include <memory>
15 #include <string>
16 #include <type_traits>
17 
18 #include "gmock.h"
19 #include "test-assert.h"
20 
21 // Check if fmt/core.h compiles with windows.h included before it.
22 #ifdef _WIN32
23 #  include <windows.h>
24 #endif
25 
26 #include "fmt/core.h"
27 
28 #undef min
29 #undef max
30 
31 using fmt::basic_format_arg;
32 using fmt::string_view;
33 using fmt::detail::buffer;
34 using fmt::detail::make_arg;
35 using fmt::detail::value;
36 
37 using testing::_;
38 using testing::Invoke;
39 using testing::Return;
40 using testing::StrictMock;
41 
42 struct test_struct {};
43 
44 FMT_BEGIN_NAMESPACE
45 template <typename Char> struct formatter<test_struct, Char> {
46   template <typename ParseContext>
parseformatter47   auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
48     return ctx.begin();
49   }
50 
formatformatter51   auto format(test_struct, format_context& ctx) -> decltype(ctx.out()) {
52     const Char* test = "test";
53     return std::copy_n(test, std::strlen(test), ctx.out());
54   }
55 };
56 FMT_END_NAMESPACE
57 
58 #if !FMT_GCC_VERSION || FMT_GCC_VERSION >= 470
TEST(BufferTest,Noncopyable)59 TEST(BufferTest, Noncopyable) {
60   EXPECT_FALSE(std::is_copy_constructible<buffer<char>>::value);
61 #  if !FMT_MSC_VER
62   // std::is_copy_assignable is broken in MSVC2013.
63   EXPECT_FALSE(std::is_copy_assignable<buffer<char>>::value);
64 #  endif
65 }
66 
TEST(BufferTest,Nonmoveable)67 TEST(BufferTest, Nonmoveable) {
68   EXPECT_FALSE(std::is_move_constructible<buffer<char>>::value);
69 #  if !FMT_MSC_VER
70   // std::is_move_assignable is broken in MSVC2013.
71   EXPECT_FALSE(std::is_move_assignable<buffer<char>>::value);
72 #  endif
73 }
74 #endif
75 
TEST(BufferTest,Indestructible)76 TEST(BufferTest, Indestructible) {
77   static_assert(!std::is_destructible<fmt::detail::buffer<int>>(),
78                 "buffer's destructor is protected");
79 }
80 
81 template <typename T> struct mock_buffer final : buffer<T> {
82   MOCK_METHOD1(do_grow, size_t(size_t capacity));
83 
growmock_buffer84   void grow(size_t capacity) { this->set(this->data(), do_grow(capacity)); }
85 
mock_buffermock_buffer86   mock_buffer(T* data = nullptr, size_t capacity = 0) {
87     this->set(data, capacity);
88     ON_CALL(*this, do_grow(_)).WillByDefault(Invoke([](size_t capacity) {
89       return capacity;
90     }));
91   }
92 };
93 
TEST(BufferTest,Ctor)94 TEST(BufferTest, Ctor) {
95   {
96     mock_buffer<int> buffer;
97     EXPECT_EQ(nullptr, buffer.data());
98     EXPECT_EQ(static_cast<size_t>(0), buffer.size());
99     EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
100   }
101   {
102     int dummy;
103     mock_buffer<int> buffer(&dummy);
104     EXPECT_EQ(&dummy, &buffer[0]);
105     EXPECT_EQ(static_cast<size_t>(0), buffer.size());
106     EXPECT_EQ(static_cast<size_t>(0), buffer.capacity());
107   }
108   {
109     int dummy;
110     size_t capacity = std::numeric_limits<size_t>::max();
111     mock_buffer<int> buffer(&dummy, capacity);
112     EXPECT_EQ(&dummy, &buffer[0]);
113     EXPECT_EQ(static_cast<size_t>(0), buffer.size());
114     EXPECT_EQ(capacity, buffer.capacity());
115   }
116 }
117 
TEST(BufferTest,Access)118 TEST(BufferTest, Access) {
119   char data[10];
120   mock_buffer<char> buffer(data, sizeof(data));
121   buffer[0] = 11;
122   EXPECT_EQ(11, buffer[0]);
123   buffer[3] = 42;
124   EXPECT_EQ(42, *(&buffer[0] + 3));
125   const fmt::detail::buffer<char>& const_buffer = buffer;
126   EXPECT_EQ(42, const_buffer[3]);
127 }
128 
TEST(BufferTest,TryResize)129 TEST(BufferTest, TryResize) {
130   char data[123];
131   mock_buffer<char> buffer(data, sizeof(data));
132   buffer[10] = 42;
133   EXPECT_EQ(42, buffer[10]);
134   buffer.try_resize(20);
135   EXPECT_EQ(20u, buffer.size());
136   EXPECT_EQ(123u, buffer.capacity());
137   EXPECT_EQ(42, buffer[10]);
138   buffer.try_resize(5);
139   EXPECT_EQ(5u, buffer.size());
140   EXPECT_EQ(123u, buffer.capacity());
141   EXPECT_EQ(42, buffer[10]);
142   // Check if try_resize calls grow.
143   EXPECT_CALL(buffer, do_grow(124));
144   buffer.try_resize(124);
145   EXPECT_CALL(buffer, do_grow(200));
146   buffer.try_resize(200);
147 }
148 
TEST(BufferTest,TryResizePartial)149 TEST(BufferTest, TryResizePartial) {
150   char data[10];
151   mock_buffer<char> buffer(data, sizeof(data));
152   EXPECT_CALL(buffer, do_grow(20)).WillOnce(Return(15));
153   buffer.try_resize(20);
154   EXPECT_EQ(buffer.capacity(), 15);
155   EXPECT_EQ(buffer.size(), 15);
156 }
157 
TEST(BufferTest,Clear)158 TEST(BufferTest, Clear) {
159   mock_buffer<char> buffer;
160   EXPECT_CALL(buffer, do_grow(20));
161   buffer.try_resize(20);
162   buffer.try_resize(0);
163   EXPECT_EQ(static_cast<size_t>(0), buffer.size());
164   EXPECT_EQ(20u, buffer.capacity());
165 }
166 
TEST(BufferTest,Append)167 TEST(BufferTest, Append) {
168   char data[15];
169   mock_buffer<char> buffer(data, 10);
170   auto test = "test";
171   buffer.append(test, test + 5);
172   EXPECT_STREQ(test, &buffer[0]);
173   EXPECT_EQ(5u, buffer.size());
174   buffer.try_resize(10);
175   EXPECT_CALL(buffer, do_grow(12));
176   buffer.append(test, test + 2);
177   EXPECT_EQ('t', buffer[10]);
178   EXPECT_EQ('e', buffer[11]);
179   EXPECT_EQ(12u, buffer.size());
180 }
181 
TEST(BufferTest,AppendPartial)182 TEST(BufferTest, AppendPartial) {
183   char data[10];
184   mock_buffer<char> buffer(data, sizeof(data));
185   testing::InSequence seq;
186   EXPECT_CALL(buffer, do_grow(15)).WillOnce(Return(10));
187   EXPECT_CALL(buffer, do_grow(15)).WillOnce(Invoke([&buffer](size_t) {
188     EXPECT_EQ(fmt::string_view(buffer.data(), buffer.size()), "0123456789");
189     buffer.clear();
190     return 10;
191   }));
192   auto test = "0123456789abcde";
193   buffer.append(test, test + 15);
194 }
195 
TEST(BufferTest,AppendAllocatesEnoughStorage)196 TEST(BufferTest, AppendAllocatesEnoughStorage) {
197   char data[19];
198   mock_buffer<char> buffer(data, 10);
199   auto test = "abcdefgh";
200   buffer.try_resize(10);
201   EXPECT_CALL(buffer, do_grow(19));
202   buffer.append(test, test + 9);
203 }
204 
TEST(ArgTest,FormatArgs)205 TEST(ArgTest, FormatArgs) {
206   auto args = fmt::format_args();
207   EXPECT_FALSE(args.get(1));
208 }
209 
210 struct custom_context {
211   using char_type = char;
212   using parse_context_type = fmt::format_parse_context;
213 
214   template <typename T> struct formatter_type {
215     template <typename ParseContext>
parsecustom_context::formatter_type216     auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
217       return ctx.begin();
218     }
219 
formatcustom_context::formatter_type220     const char* format(const T&, custom_context& ctx) {
221       ctx.called = true;
222       return nullptr;
223     }
224   };
225 
226   bool called;
227   fmt::format_parse_context ctx;
228 
parse_contextcustom_context229   fmt::format_parse_context& parse_context() { return ctx; }
advance_tocustom_context230   void advance_to(const char*) {}
231 };
232 
TEST(ArgTest,MakeValueWithCustomContext)233 TEST(ArgTest, MakeValueWithCustomContext) {
234   auto t = test_struct();
235   fmt::detail::value<custom_context> arg(
236       fmt::detail::arg_mapper<custom_context>().map(t));
237   custom_context ctx = {false, fmt::format_parse_context("")};
238   arg.custom.format(&t, ctx.parse_context(), ctx);
239   EXPECT_TRUE(ctx.called);
240 }
241 
242 FMT_BEGIN_NAMESPACE
243 namespace detail {
244 template <typename Char>
operator ==(custom_value<Char> lhs,custom_value<Char> rhs)245 bool operator==(custom_value<Char> lhs, custom_value<Char> rhs) {
246   return lhs.value == rhs.value;
247 }
248 }  // namespace detail
249 FMT_END_NAMESPACE
250 
251 // Use a unique result type to make sure that there are no undesirable
252 // conversions.
253 struct test_result {};
254 
255 template <typename T> struct mock_visitor {
256   template <typename U> struct result { using type = test_result; };
257 
mock_visitormock_visitor258   mock_visitor() {
259     ON_CALL(*this, visit(_)).WillByDefault(Return(test_result()));
260   }
261 
262   MOCK_METHOD1_T(visit, test_result(T value));
263   MOCK_METHOD0_T(unexpected, void());
264 
operator ()mock_visitor265   test_result operator()(T value) { return visit(value); }
266 
operator ()mock_visitor267   template <typename U> test_result operator()(U) {
268     unexpected();
269     return test_result();
270   }
271 };
272 
273 template <typename T> struct visit_type { using type = T; };
274 
275 #define VISIT_TYPE(type_, visit_type_) \
276   template <> struct visit_type<type_> { using type = visit_type_; }
277 
278 VISIT_TYPE(signed char, int);
279 VISIT_TYPE(unsigned char, unsigned);
280 VISIT_TYPE(short, int);
281 VISIT_TYPE(unsigned short, unsigned);
282 
283 #if LONG_MAX == INT_MAX
284 VISIT_TYPE(long, int);
285 VISIT_TYPE(unsigned long, unsigned);
286 #else
287 VISIT_TYPE(long, long long);
288 VISIT_TYPE(unsigned long, unsigned long long);
289 #endif
290 
291 #define CHECK_ARG_(Char, expected, value)                                     \
292   {                                                                           \
293     testing::StrictMock<mock_visitor<decltype(expected)>> visitor;            \
294     EXPECT_CALL(visitor, visit(expected));                                    \
295     using iterator = std::back_insert_iterator<buffer<Char>>;                 \
296     fmt::visit_format_arg(                                                    \
297         visitor, make_arg<fmt::basic_format_context<iterator, Char>>(value)); \
298   }
299 
300 #define CHECK_ARG(value, typename_)                          \
301   {                                                          \
302     using value_type = decltype(value);                      \
303     typename_ visit_type<value_type>::type expected = value; \
304     CHECK_ARG_(char, expected, value)                        \
305     CHECK_ARG_(wchar_t, expected, value)                     \
306   }
307 
308 template <typename T> class NumericArgTest : public testing::Test {};
309 
310 using types =
311     ::testing::Types<bool, signed char, unsigned char, signed, unsigned short,
312                      int, unsigned, long, unsigned long, long long,
313                      unsigned long long, float, double, long double>;
314 TYPED_TEST_CASE(NumericArgTest, types);
315 
316 template <typename T>
test_value()317 fmt::enable_if_t<std::is_integral<T>::value, T> test_value() {
318   return static_cast<T>(42);
319 }
320 
321 template <typename T>
test_value()322 fmt::enable_if_t<std::is_floating_point<T>::value, T> test_value() {
323   return static_cast<T>(4.2);
324 }
325 
TYPED_TEST(NumericArgTest,MakeAndVisit)326 TYPED_TEST(NumericArgTest, MakeAndVisit) {
327   CHECK_ARG(test_value<TypeParam>(), typename);
328   CHECK_ARG(std::numeric_limits<TypeParam>::min(), typename);
329   CHECK_ARG(std::numeric_limits<TypeParam>::max(), typename);
330 }
331 
TEST(ArgTest,CharArg)332 TEST(ArgTest, CharArg) {
333   CHECK_ARG_(char, 'a', 'a');
334   CHECK_ARG_(wchar_t, L'a', 'a');
335   CHECK_ARG_(wchar_t, L'a', L'a');
336 }
337 
TEST(ArgTest,StringArg)338 TEST(ArgTest, StringArg) {
339   char str_data[] = "test";
340   char* str = str_data;
341   const char* cstr = str;
342   CHECK_ARG_(char, cstr, str);
343 
344   auto sref = string_view(str);
345   CHECK_ARG_(char, sref, std::string(str));
346 }
347 
TEST(ArgTest,WStringArg)348 TEST(ArgTest, WStringArg) {
349   wchar_t str_data[] = L"test";
350   wchar_t* str = str_data;
351   const wchar_t* cstr = str;
352 
353   fmt::wstring_view sref(str);
354   CHECK_ARG_(wchar_t, cstr, str);
355   CHECK_ARG_(wchar_t, cstr, cstr);
356   CHECK_ARG_(wchar_t, sref, std::wstring(str));
357   CHECK_ARG_(wchar_t, sref, fmt::wstring_view(str));
358 }
359 
TEST(ArgTest,PointerArg)360 TEST(ArgTest, PointerArg) {
361   void* p = nullptr;
362   const void* cp = nullptr;
363   CHECK_ARG_(char, cp, p);
364   CHECK_ARG_(wchar_t, cp, p);
365   CHECK_ARG(cp, );
366 }
367 
368 struct check_custom {
operator ()check_custom369   test_result operator()(
370       fmt::basic_format_arg<fmt::format_context>::handle h) const {
371     struct test_buffer final : fmt::detail::buffer<char> {
372       char data[10];
373       test_buffer() : fmt::detail::buffer<char>(data, 0, 10) {}
374       void grow(size_t) {}
375     } buffer;
376     fmt::format_parse_context parse_ctx("");
377     fmt::format_context ctx{fmt::detail::buffer_appender<char>(buffer),
378                             fmt::format_args()};
379     h.format(parse_ctx, ctx);
380     EXPECT_EQ("test", std::string(buffer.data, buffer.size()));
381     return test_result();
382   }
383 };
384 
TEST(ArgTest,CustomArg)385 TEST(ArgTest, CustomArg) {
386   test_struct test;
387   using visitor =
388       mock_visitor<fmt::basic_format_arg<fmt::format_context>::handle>;
389   testing::StrictMock<visitor> v;
390   EXPECT_CALL(v, visit(_)).WillOnce(Invoke(check_custom()));
391   fmt::visit_format_arg(v, make_arg<fmt::format_context>(test));
392 }
393 
TEST(ArgTest,VisitInvalidArg)394 TEST(ArgTest, VisitInvalidArg) {
395   testing::StrictMock<mock_visitor<fmt::monostate>> visitor;
396   EXPECT_CALL(visitor, visit(_));
397   fmt::basic_format_arg<fmt::format_context> arg;
398   fmt::visit_format_arg(visitor, arg);
399 }
400 
TEST(FormatDynArgsTest,Basic)401 TEST(FormatDynArgsTest, Basic) {
402   fmt::dynamic_format_arg_store<fmt::format_context> store;
403   store.push_back(42);
404   store.push_back("abc1");
405   store.push_back(1.5f);
406   EXPECT_EQ("42 and abc1 and 1.5", fmt::vformat("{} and {} and {}", store));
407 }
408 
TEST(FormatDynArgsTest,StringsAndRefs)409 TEST(FormatDynArgsTest, StringsAndRefs) {
410   // Unfortunately the tests are compiled with old ABI so strings use COW.
411   fmt::dynamic_format_arg_store<fmt::format_context> store;
412   char str[] = "1234567890";
413   store.push_back(str);
414   store.push_back(std::cref(str));
415   store.push_back(fmt::string_view{str});
416   str[0] = 'X';
417 
418   std::string result = fmt::vformat("{} and {} and {}", store);
419   EXPECT_EQ("1234567890 and X234567890 and X234567890", result);
420 }
421 
422 struct custom_type {
423   int i = 0;
424 };
425 
426 FMT_BEGIN_NAMESPACE
427 template <> struct formatter<custom_type> {
parseformatter428   auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
429     return ctx.begin();
430   }
431 
432   template <typename FormatContext>
formatformatter433   auto format(const custom_type& p, FormatContext& ctx) -> decltype(ctx.out()) {
434     return format_to(ctx.out(), "cust={}", p.i);
435   }
436 };
437 FMT_END_NAMESPACE
438 
TEST(FormatDynArgsTest,CustomFormat)439 TEST(FormatDynArgsTest, CustomFormat) {
440   fmt::dynamic_format_arg_store<fmt::format_context> store;
441   custom_type c{};
442   store.push_back(c);
443   ++c.i;
444   store.push_back(c);
445   ++c.i;
446   store.push_back(std::cref(c));
447   ++c.i;
448   std::string result = fmt::vformat("{} and {} and {}", store);
449   EXPECT_EQ("cust=0 and cust=1 and cust=3", result);
450 }
451 
TEST(FormatDynArgsTest,NamedInt)452 TEST(FormatDynArgsTest, NamedInt) {
453   fmt::dynamic_format_arg_store<fmt::format_context> store;
454   store.push_back(fmt::arg("a1", 42));
455   EXPECT_EQ("42", fmt::vformat("{a1}", store));
456 }
457 
TEST(FormatDynArgsTest,NamedStrings)458 TEST(FormatDynArgsTest, NamedStrings) {
459   fmt::dynamic_format_arg_store<fmt::format_context> store;
460   char str[]{"1234567890"};
461   store.push_back(fmt::arg("a1", str));
462   store.push_back(fmt::arg("a2", std::cref(str)));
463   str[0] = 'X';
464   EXPECT_EQ("1234567890 and X234567890", fmt::vformat("{a1} and {a2}", store));
465 }
466 
TEST(FormatDynArgsTest,NamedArgByRef)467 TEST(FormatDynArgsTest, NamedArgByRef) {
468   fmt::dynamic_format_arg_store<fmt::format_context> store;
469 
470   // Note: fmt::arg() constructs an object which holds a reference
471   // to its value. It's not an aggregate, so it doesn't extend the
472   // reference lifetime. As a result, it's a very bad idea passing temporary
473   // as a named argument value. Only GCC with optimization level >0
474   // complains about this.
475   //
476   // A real life usecase is when you have both name and value alive
477   // guarantee their lifetime and thus don't want them to be copied into
478   // storages.
479   int a1_val{42};
480   auto a1 = fmt::arg("a1_", a1_val);
481   store.push_back("abc");
482   store.push_back(1.5f);
483   store.push_back(std::cref(a1));
484 
485   std::string result = fmt::vformat("{a1_} and {} and {} and {}", store);
486   EXPECT_EQ("42 and abc and 1.5 and 42", result);
487 }
488 
TEST(FormatDynArgsTest,NamedCustomFormat)489 TEST(FormatDynArgsTest, NamedCustomFormat) {
490   fmt::dynamic_format_arg_store<fmt::format_context> store;
491   custom_type c{};
492   store.push_back(fmt::arg("c1", c));
493   ++c.i;
494   store.push_back(fmt::arg("c2", c));
495   ++c.i;
496   store.push_back(fmt::arg("c_ref", std::cref(c)));
497   ++c.i;
498   std::string result = fmt::vformat("{c1} and {c2} and {c_ref}", store);
499   EXPECT_EQ("cust=0 and cust=1 and cust=3", result);
500 }
501 
TEST(FormatDynArgsTest,Clear)502 TEST(FormatDynArgsTest, Clear) {
503   fmt::dynamic_format_arg_store<fmt::format_context> store;
504   store.push_back(42);
505 
506   std::string result = fmt::vformat("{}", store);
507   EXPECT_EQ("42", result);
508 
509   store.push_back(43);
510   result = fmt::vformat("{} and {}", store);
511   EXPECT_EQ("42 and 43", result);
512 
513   store.clear();
514   store.push_back(44);
515   result = fmt::vformat("{}", store);
516   EXPECT_EQ("44", result);
517 }
518 
TEST(FormatDynArgsTest,Reserve)519 TEST(FormatDynArgsTest, Reserve) {
520   fmt::dynamic_format_arg_store<fmt::format_context> store;
521   store.reserve(2, 1);
522   store.push_back(1.5f);
523   store.push_back(fmt::arg("a1", 42));
524   std::string result = fmt::vformat("{a1} and {}", store);
525   EXPECT_EQ("42 and 1.5", result);
526 }
527 
528 struct copy_throwable {
copy_throwablecopy_throwable529   copy_throwable() {}
copy_throwablecopy_throwable530   copy_throwable(const copy_throwable&) { throw "deal with it"; }
531 };
532 
533 FMT_BEGIN_NAMESPACE
534 template <> struct formatter<copy_throwable> {
parseformatter535   auto parse(format_parse_context& ctx) const -> decltype(ctx.begin()) {
536     return ctx.begin();
537   }
formatformatter538   auto format(copy_throwable, format_context& ctx) -> decltype(ctx.out()) {
539     return ctx.out();
540   }
541 };
542 FMT_END_NAMESPACE
543 
TEST(FormatDynArgsTest,ThrowOnCopy)544 TEST(FormatDynArgsTest, ThrowOnCopy) {
545   fmt::dynamic_format_arg_store<fmt::format_context> store;
546   store.push_back(std::string("foo"));
547   try {
548     store.push_back(copy_throwable());
549   } catch (...) {
550   }
551   EXPECT_EQ(fmt::vformat("{}", store), "foo");
552 }
553 
TEST(StringViewTest,ValueType)554 TEST(StringViewTest, ValueType) {
555   static_assert(std::is_same<string_view::value_type, char>::value, "");
556 }
557 
TEST(StringViewTest,Length)558 TEST(StringViewTest, Length) {
559   // Test that string_view::size() returns string length, not buffer size.
560   char str[100] = "some string";
561   EXPECT_EQ(std::strlen(str), string_view(str).size());
562   EXPECT_LT(std::strlen(str), sizeof(str));
563 }
564 
565 // Check string_view's comparison operator.
check_op()566 template <template <typename> class Op> void check_op() {
567   const char* inputs[] = {"foo", "fop", "fo"};
568   size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
569   for (size_t i = 0; i < num_inputs; ++i) {
570     for (size_t j = 0; j < num_inputs; ++j) {
571       string_view lhs(inputs[i]), rhs(inputs[j]);
572       EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<string_view>()(lhs, rhs));
573     }
574   }
575 }
576 
TEST(StringViewTest,Compare)577 TEST(StringViewTest, Compare) {
578   EXPECT_EQ(string_view("foo").compare(string_view("foo")), 0);
579   EXPECT_GT(string_view("fop").compare(string_view("foo")), 0);
580   EXPECT_LT(string_view("foo").compare(string_view("fop")), 0);
581   EXPECT_GT(string_view("foo").compare(string_view("fo")), 0);
582   EXPECT_LT(string_view("fo").compare(string_view("foo")), 0);
583   check_op<std::equal_to>();
584   check_op<std::not_equal_to>();
585   check_op<std::less>();
586   check_op<std::less_equal>();
587   check_op<std::greater>();
588   check_op<std::greater_equal>();
589 }
590 
591 struct enabled_formatter {};
592 struct disabled_formatter {};
593 struct disabled_formatter_convertible {
operator intdisabled_formatter_convertible594   operator int() const { return 42; }
595 };
596 
597 FMT_BEGIN_NAMESPACE
598 template <> struct formatter<enabled_formatter> {
parseformatter599   auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
600     return ctx.begin();
601   }
formatformatter602   auto format(enabled_formatter, format_context& ctx) -> decltype(ctx.out()) {
603     return ctx.out();
604   }
605 };
606 FMT_END_NAMESPACE
607 
TEST(CoreTest,HasFormatter)608 TEST(CoreTest, HasFormatter) {
609   using fmt::has_formatter;
610   using context = fmt::format_context;
611   static_assert(has_formatter<enabled_formatter, context>::value, "");
612   static_assert(!has_formatter<disabled_formatter, context>::value, "");
613   static_assert(!has_formatter<disabled_formatter_convertible, context>::value,
614                 "");
615 }
616 
617 struct convertible_to_int {
operator intconvertible_to_int618   operator int() const { return 42; }
619 };
620 
621 struct convertible_to_c_string {
operator const char*convertible_to_c_string622   operator const char*() const { return "foo"; }
623 };
624 
625 FMT_BEGIN_NAMESPACE
626 template <> struct formatter<convertible_to_int> {
parseformatter627   auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
628     return ctx.begin();
629   }
formatformatter630   auto format(convertible_to_int, format_context& ctx) -> decltype(ctx.out()) {
631     return std::copy_n("foo", 3, ctx.out());
632   }
633 };
634 
635 template <> struct formatter<convertible_to_c_string> {
parseformatter636   auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
637     return ctx.begin();
638   }
formatformatter639   auto format(convertible_to_c_string, format_context& ctx)
640       -> decltype(ctx.out()) {
641     return std::copy_n("bar", 3, ctx.out());
642   }
643 };
644 FMT_END_NAMESPACE
645 
TEST(CoreTest,FormatterOverridesImplicitConversion)646 TEST(CoreTest, FormatterOverridesImplicitConversion) {
647   EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo");
648   EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar");
649 }
650 
651 namespace my_ns {
652 template <typename Char> class my_string {
653  private:
654   std::basic_string<Char> s_;
655 
656  public:
my_string(const Char * s)657   my_string(const Char* s) : s_(s) {}
data() const658   const Char* data() const FMT_NOEXCEPT { return s_.data(); }
length() const659   size_t length() const FMT_NOEXCEPT { return s_.size(); }
operator const Char*() const660   operator const Char*() const { return s_.c_str(); }
661 };
662 
663 template <typename Char>
to_string_view(const my_string<Char> & s)664 inline fmt::basic_string_view<Char> to_string_view(const my_string<Char>& s)
665     FMT_NOEXCEPT {
666   return {s.data(), s.length()};
667 }
668 
669 struct non_string {};
670 }  // namespace my_ns
671 
672 template <typename T> class IsStringTest : public testing::Test {};
673 
674 typedef ::testing::Types<char, wchar_t, char16_t, char32_t> StringCharTypes;
675 TYPED_TEST_CASE(IsStringTest, StringCharTypes);
676 
677 namespace {
678 template <typename Char>
679 struct derived_from_string_view : fmt::basic_string_view<Char> {};
680 }  // namespace
681 
TYPED_TEST(IsStringTest,IsString)682 TYPED_TEST(IsStringTest, IsString) {
683   EXPECT_TRUE(fmt::detail::is_string<TypeParam*>::value);
684   EXPECT_TRUE(fmt::detail::is_string<const TypeParam*>::value);
685   EXPECT_TRUE(fmt::detail::is_string<TypeParam[2]>::value);
686   EXPECT_TRUE(fmt::detail::is_string<const TypeParam[2]>::value);
687   EXPECT_TRUE(fmt::detail::is_string<std::basic_string<TypeParam>>::value);
688   EXPECT_TRUE(fmt::detail::is_string<fmt::basic_string_view<TypeParam>>::value);
689   EXPECT_TRUE(
690       fmt::detail::is_string<derived_from_string_view<TypeParam>>::value);
691   using string_view = fmt::detail::std_string_view<TypeParam>;
692   EXPECT_TRUE(std::is_empty<string_view>::value !=
693               fmt::detail::is_string<string_view>::value);
694   EXPECT_TRUE(fmt::detail::is_string<my_ns::my_string<TypeParam>>::value);
695   EXPECT_FALSE(fmt::detail::is_string<my_ns::non_string>::value);
696 }
697 
TEST(CoreTest,Format)698 TEST(CoreTest, Format) {
699   // This should work without including fmt/format.h.
700 #ifdef FMT_FORMAT_H_
701 #  error fmt/format.h must not be included in the core test
702 #endif
703   EXPECT_EQ(fmt::format("{}", 42), "42");
704 }
705 
TEST(CoreTest,FormatTo)706 TEST(CoreTest, FormatTo) {
707   // This should work without including fmt/format.h.
708 #ifdef FMT_FORMAT_H_
709 #  error fmt/format.h must not be included in the core test
710 #endif
711   std::string s;
712   fmt::format_to(std::back_inserter(s), "{}", 42);
713   EXPECT_EQ(s, "42");
714 }
715 
TEST(CoreTest,ToStringViewForeignStrings)716 TEST(CoreTest, ToStringViewForeignStrings) {
717   using namespace my_ns;
718   EXPECT_EQ(to_string_view(my_string<char>("42")), "42");
719   fmt::detail::type type =
720       fmt::detail::mapped_type_constant<my_string<char>,
721                                         fmt::format_context>::value;
722   EXPECT_EQ(type, fmt::detail::type::string_type);
723 }
724 
TEST(CoreTest,FormatForeignStrings)725 TEST(CoreTest, FormatForeignStrings) {
726   using namespace my_ns;
727   EXPECT_EQ(fmt::format(my_string<char>("{}"), 42), "42");
728 }
729 
730 struct implicitly_convertible_to_string {
operator std::stringimplicitly_convertible_to_string731   operator std::string() const { return "foo"; }
732 };
733 
734 struct implicitly_convertible_to_string_view {
operator fmt::string_viewimplicitly_convertible_to_string_view735   operator fmt::string_view() const { return "foo"; }
736 };
737 
TEST(CoreTest,FormatImplicitlyConvertibleToStringView)738 TEST(CoreTest, FormatImplicitlyConvertibleToStringView) {
739   EXPECT_EQ("foo", fmt::format("{}", implicitly_convertible_to_string_view()));
740 }
741 
742 // std::is_constructible is broken in MSVC until version 2015.
743 #if !FMT_MSC_VER || FMT_MSC_VER >= 1900
744 struct explicitly_convertible_to_string_view {
operator fmt::string_viewexplicitly_convertible_to_string_view745   explicit operator fmt::string_view() const { return "foo"; }
746 };
747 
TEST(CoreTest,FormatExplicitlyConvertibleToStringView)748 TEST(CoreTest, FormatExplicitlyConvertibleToStringView) {
749   EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_view()));
750 }
751 
752 #  ifdef FMT_USE_STRING_VIEW
753 struct explicitly_convertible_to_std_string_view {
operator std::string_viewexplicitly_convertible_to_std_string_view754   explicit operator std::string_view() const { return "foo"; }
755 };
756 
TEST(CoreTest,FormatExplicitlyConvertibleToStdStringView)757 TEST(CoreTest, FormatExplicitlyConvertibleToStdStringView) {
758   EXPECT_EQ("foo",
759             fmt::format("{}", explicitly_convertible_to_std_string_view()));
760 }
761 #  endif
762 #endif
763 
764 struct disabled_rvalue_conversion {
operator const char*disabled_rvalue_conversion765   operator const char*() const& { return "foo"; }
operator const char*disabled_rvalue_conversion766   operator const char*() & { return "foo"; }
767   operator const char*() const&& = delete;
768   operator const char*() && = delete;
769 };
770 
TEST(CoreTest,DisabledRValueConversion)771 TEST(CoreTest, DisabledRValueConversion) {
772   EXPECT_EQ("foo", fmt::format("{}", disabled_rvalue_conversion()));
773 }
774