• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Formatting library for C++ - formatting library implementation 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 #define FMT_NOEXCEPT
9 #undef FMT_SHARED
10 #include "test-assert.h"
11 
12 // Include format.cc instead of format.h to test implementation.
13 #include <algorithm>
14 #include <cstring>
15 
16 #include "../src/format.cc"
17 #include "fmt/printf.h"
18 #include "gmock.h"
19 #include "gtest-extra.h"
20 #include "util.h"
21 
22 #ifdef _WIN32
23 #  include <windows.h>
24 #  undef max
25 #endif
26 
27 using fmt::detail::bigint;
28 using fmt::detail::fp;
29 using fmt::detail::max_value;
30 
31 static_assert(!std::is_copy_constructible<bigint>::value, "");
32 static_assert(!std::is_copy_assignable<bigint>::value, "");
33 
TEST(BigIntTest,Construct)34 TEST(BigIntTest, Construct) {
35   EXPECT_EQ("", fmt::format("{}", bigint()));
36   EXPECT_EQ("42", fmt::format("{}", bigint(0x42)));
37   EXPECT_EQ("123456789abcedf0", fmt::format("{}", bigint(0x123456789abcedf0)));
38 }
39 
TEST(BigIntTest,Compare)40 TEST(BigIntTest, Compare) {
41   bigint n1(42);
42   bigint n2(42);
43   EXPECT_EQ(compare(n1, n2), 0);
44   n2 <<= 32;
45   EXPECT_LT(compare(n1, n2), 0);
46   bigint n3(43);
47   EXPECT_LT(compare(n1, n3), 0);
48   EXPECT_GT(compare(n3, n1), 0);
49   bigint n4(42 * 0x100000001);
50   EXPECT_LT(compare(n2, n4), 0);
51   EXPECT_GT(compare(n4, n2), 0);
52 }
53 
TEST(BigIntTest,AddCompare)54 TEST(BigIntTest, AddCompare) {
55   EXPECT_LT(
56       add_compare(bigint(0xffffffff), bigint(0xffffffff), bigint(1) <<= 64), 0);
57   EXPECT_LT(add_compare(bigint(1) <<= 32, bigint(1), bigint(1) <<= 96), 0);
58   EXPECT_GT(add_compare(bigint(1) <<= 32, bigint(0), bigint(0xffffffff)), 0);
59   EXPECT_GT(add_compare(bigint(0), bigint(1) <<= 32, bigint(0xffffffff)), 0);
60   EXPECT_GT(add_compare(bigint(42), bigint(1), bigint(42)), 0);
61   EXPECT_GT(add_compare(bigint(0xffffffff), bigint(1), bigint(0xffffffff)), 0);
62   EXPECT_LT(add_compare(bigint(10), bigint(10), bigint(22)), 0);
63   EXPECT_LT(add_compare(bigint(0x100000010), bigint(0x100000010),
64                         bigint(0x300000010)),
65             0);
66   EXPECT_GT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
67                         bigint(0x300000000)),
68             0);
69   EXPECT_EQ(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
70                         bigint(0x300000001)),
71             0);
72   EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
73                         bigint(0x300000002)),
74             0);
75   EXPECT_LT(add_compare(bigint(0x1ffffffff), bigint(0x100000002),
76                         bigint(0x300000003)),
77             0);
78 }
79 
TEST(BigIntTest,ShiftLeft)80 TEST(BigIntTest, ShiftLeft) {
81   bigint n(0x42);
82   n <<= 0;
83   EXPECT_EQ("42", fmt::format("{}", n));
84   n <<= 1;
85   EXPECT_EQ("84", fmt::format("{}", n));
86   n <<= 25;
87   EXPECT_EQ("108000000", fmt::format("{}", n));
88 }
89 
TEST(BigIntTest,Multiply)90 TEST(BigIntTest, Multiply) {
91   bigint n(0x42);
92   EXPECT_THROW(n *= 0, assertion_failure);
93   n *= 1;
94   EXPECT_EQ("42", fmt::format("{}", n));
95   n *= 2;
96   EXPECT_EQ("84", fmt::format("{}", n));
97   n *= 0x12345678;
98   EXPECT_EQ("962fc95e0", fmt::format("{}", n));
99   bigint bigmax(max_value<uint32_t>());
100   bigmax *= max_value<uint32_t>();
101   EXPECT_EQ("fffffffe00000001", fmt::format("{}", bigmax));
102   bigmax.assign(max_value<uint64_t>());
103   bigmax *= max_value<uint64_t>();
104   EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", bigmax));
105 }
106 
TEST(BigIntTest,Accumulator)107 TEST(BigIntTest, Accumulator) {
108   fmt::detail::accumulator acc;
109   EXPECT_EQ(acc.lower, 0);
110   EXPECT_EQ(acc.upper, 0);
111   acc.upper = 12;
112   acc.lower = 34;
113   EXPECT_EQ(static_cast<uint32_t>(acc), 34);
114   acc += 56;
115   EXPECT_EQ(acc.lower, 90);
116   acc += fmt::detail::max_value<uint64_t>();
117   EXPECT_EQ(acc.upper, 13);
118   EXPECT_EQ(acc.lower, 89);
119   acc >>= 32;
120   EXPECT_EQ(acc.upper, 0);
121   EXPECT_EQ(acc.lower, 13 * 0x100000000);
122 }
123 
TEST(BigIntTest,Square)124 TEST(BigIntTest, Square) {
125   bigint n0(0);
126   n0.square();
127   EXPECT_EQ("0", fmt::format("{}", n0));
128   bigint n1(0x100);
129   n1.square();
130   EXPECT_EQ("10000", fmt::format("{}", n1));
131   bigint n2(0xfffffffff);
132   n2.square();
133   EXPECT_EQ("ffffffffe000000001", fmt::format("{}", n2));
134   bigint n3(max_value<uint64_t>());
135   n3.square();
136   EXPECT_EQ("fffffffffffffffe0000000000000001", fmt::format("{}", n3));
137   bigint n4;
138   n4.assign_pow10(10);
139   EXPECT_EQ("2540be400", fmt::format("{}", n4));
140 }
141 
TEST(BigIntTest,DivModAssignZeroDivisor)142 TEST(BigIntTest, DivModAssignZeroDivisor) {
143   bigint zero(0);
144   EXPECT_THROW(bigint(0).divmod_assign(zero), assertion_failure);
145   EXPECT_THROW(bigint(42).divmod_assign(zero), assertion_failure);
146 }
147 
TEST(BigIntTest,DivModAssignSelf)148 TEST(BigIntTest, DivModAssignSelf) {
149   bigint n(100);
150   EXPECT_THROW(n.divmod_assign(n), assertion_failure);
151 }
152 
TEST(BigIntTest,DivModAssignUnaligned)153 TEST(BigIntTest, DivModAssignUnaligned) {
154   // (42 << 340) / pow(10, 100):
155   bigint n1(42);
156   n1 <<= 340;
157   bigint n2;
158   n2.assign_pow10(100);
159   int result = n1.divmod_assign(n2);
160   EXPECT_EQ(result, 9406);
161   EXPECT_EQ("10f8353019583bfc29ffc8f564e1b9f9d819dbb4cf783e4507eca1539220p96",
162             fmt::format("{}", n1));
163 }
164 
TEST(BigIntTest,DivModAssign)165 TEST(BigIntTest, DivModAssign) {
166   // 100 / 10:
167   bigint n1(100);
168   int result = n1.divmod_assign(bigint(10));
169   EXPECT_EQ(result, 10);
170   EXPECT_EQ("0", fmt::format("{}", n1));
171   // pow(10, 100) / (42 << 320):
172   n1.assign_pow10(100);
173   result = n1.divmod_assign(bigint(42) <<= 320);
174   EXPECT_EQ(result, 111);
175   EXPECT_EQ("13ad2594c37ceb0b2784c4ce0bf38ace408e211a7caab24308a82e8f10p96",
176             fmt::format("{}", n1));
177   // 42 / 100:
178   bigint n2(42);
179   n1.assign_pow10(2);
180   result = n2.divmod_assign(n1);
181   EXPECT_EQ(result, 0);
182   EXPECT_EQ("2a", fmt::format("{}", n2));
183 }
184 
run_double_tests()185 template <bool is_iec559> void run_double_tests() {
186   fmt::print("warning: double is not IEC559, skipping FP tests\n");
187 }
188 
run_double_tests()189 template <> void run_double_tests<true>() {
190   // Construct from double.
191   EXPECT_EQ(fp(1.23), fp(0x13ae147ae147aeu, -52));
192 }
193 
TEST(FPTest,DoubleTests)194 TEST(FPTest, DoubleTests) {
195   run_double_tests<std::numeric_limits<double>::is_iec559>();
196 }
197 
TEST(FPTest,Normalize)198 TEST(FPTest, Normalize) {
199   const auto v = fp(0xbeef, 42);
200   auto normalized = normalize(v);
201   EXPECT_EQ(0xbeef000000000000, normalized.f);
202   EXPECT_EQ(-6, normalized.e);
203 }
204 
TEST(FPTest,Multiply)205 TEST(FPTest, Multiply) {
206   auto v = fp(123ULL << 32, 4) * fp(56ULL << 32, 7);
207   EXPECT_EQ(v.f, 123u * 56u);
208   EXPECT_EQ(v.e, 4 + 7 + 64);
209   v = fp(123ULL << 32, 4) * fp(567ULL << 31, 8);
210   EXPECT_EQ(v.f, (123 * 567 + 1u) / 2);
211   EXPECT_EQ(v.e, 4 + 8 + 64);
212 }
213 
TEST(FPTest,GetCachedPower)214 TEST(FPTest, GetCachedPower) {
215   using limits = std::numeric_limits<double>;
216   for (auto exp = limits::min_exponent; exp <= limits::max_exponent; ++exp) {
217     int dec_exp = 0;
218     auto fp = fmt::detail::get_cached_power(exp, dec_exp);
219     bigint exact, cache(fp.f);
220     if (dec_exp >= 0) {
221       exact.assign_pow10(dec_exp);
222       if (fp.e <= 0)
223         exact <<= -fp.e;
224       else
225         cache <<= fp.e;
226       exact.align(cache);
227       cache.align(exact);
228       auto exact_str = fmt::format("{}", exact);
229       auto cache_str = fmt::format("{}", cache);
230       EXPECT_EQ(exact_str.size(), cache_str.size());
231       EXPECT_EQ(exact_str.substr(0, 15), cache_str.substr(0, 15));
232       int diff = cache_str[15] - exact_str[15];
233       if (diff == 1)
234         EXPECT_GT(exact_str[16], '8');
235       else
236         EXPECT_EQ(diff, 0);
237     } else {
238       cache.assign_pow10(-dec_exp);
239       cache *= fp.f + 1;  // Inexact check.
240       exact.assign(1);
241       exact <<= -fp.e;
242       exact.align(cache);
243       auto exact_str = fmt::format("{}", exact);
244       auto cache_str = fmt::format("{}", cache);
245       EXPECT_EQ(exact_str.size(), cache_str.size());
246       EXPECT_EQ(exact_str.substr(0, 16), cache_str.substr(0, 16));
247     }
248   }
249 }
250 
TEST(FPTest,DragonboxMaxK)251 TEST(FPTest, DragonboxMaxK) {
252   using fmt::detail::dragonbox::floor_log10_pow2;
253   using float_info = fmt::detail::dragonbox::float_info<float>;
254   EXPECT_EQ(fmt::detail::const_check(float_info::max_k),
255             float_info::kappa - floor_log10_pow2(float_info::min_exponent -
256                                                  float_info::significand_bits));
257   using double_info = fmt::detail::dragonbox::float_info<double>;
258   EXPECT_EQ(
259       fmt::detail::const_check(double_info::max_k),
260       double_info::kappa - floor_log10_pow2(double_info::min_exponent -
261                                             double_info::significand_bits));
262 }
263 
TEST(FPTest,GetRoundDirection)264 TEST(FPTest, GetRoundDirection) {
265   using fmt::detail::get_round_direction;
266   using fmt::detail::round_direction;
267   EXPECT_EQ(round_direction::down, get_round_direction(100, 50, 0));
268   EXPECT_EQ(round_direction::up, get_round_direction(100, 51, 0));
269   EXPECT_EQ(round_direction::down, get_round_direction(100, 40, 10));
270   EXPECT_EQ(round_direction::up, get_round_direction(100, 60, 10));
271   for (size_t i = 41; i < 60; ++i)
272     EXPECT_EQ(round_direction::unknown, get_round_direction(100, i, 10));
273   uint64_t max = max_value<uint64_t>();
274   EXPECT_THROW(get_round_direction(100, 100, 0), assertion_failure);
275   EXPECT_THROW(get_round_direction(100, 0, 100), assertion_failure);
276   EXPECT_THROW(get_round_direction(100, 0, 50), assertion_failure);
277   // Check that remainder + error doesn't overflow.
278   EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 2));
279   // Check that 2 * (remainder + error) doesn't overflow.
280   EXPECT_EQ(round_direction::unknown,
281             get_round_direction(max, max / 2 + 1, max / 2));
282   // Check that remainder - error doesn't overflow.
283   EXPECT_EQ(round_direction::unknown, get_round_direction(100, 40, 41));
284   // Check that 2 * (remainder - error) doesn't overflow.
285   EXPECT_EQ(round_direction::up, get_round_direction(max, max - 1, 1));
286 }
287 
TEST(FPTest,FixedHandler)288 TEST(FPTest, FixedHandler) {
289   struct handler : fmt::detail::fixed_handler {
290     char buffer[10];
291     handler(int prec = 0) : fmt::detail::fixed_handler() {
292       buf = buffer;
293       precision = prec;
294     }
295   };
296   int exp = 0;
297   handler().on_digit('0', 100, 99, 0, exp, false);
298   EXPECT_THROW(handler().on_digit('0', 100, 100, 0, exp, false),
299                assertion_failure);
300   namespace digits = fmt::detail::digits;
301   EXPECT_EQ(handler(1).on_digit('0', 100, 10, 10, exp, false), digits::error);
302   // Check that divisor - error doesn't overflow.
303   EXPECT_EQ(handler(1).on_digit('0', 100, 10, 101, exp, false), digits::error);
304   // Check that 2 * error doesn't overflow.
305   uint64_t max = max_value<uint64_t>();
306   EXPECT_EQ(handler(1).on_digit('0', max, 10, max - 1, exp, false),
307             digits::error);
308 }
309 
TEST(FPTest,GrisuFormatCompilesWithNonIEEEDouble)310 TEST(FPTest, GrisuFormatCompilesWithNonIEEEDouble) {
311   fmt::memory_buffer buf;
312   format_float(0.42, -1, fmt::detail::float_specs(), buf);
313 }
314 
315 template <typename T> struct value_extractor {
operator ()value_extractor316   T operator()(T value) { return value; }
317 
operator ()value_extractor318   template <typename U> FMT_NORETURN T operator()(U) {
319     throw std::runtime_error(fmt::format("invalid type {}", typeid(U).name()));
320   }
321 
322 #if FMT_USE_INT128
323   // Apple Clang does not define typeid for __int128_t and __uint128_t.
operator ()value_extractor324   FMT_NORETURN T operator()(fmt::detail::int128_t) {
325     throw std::runtime_error("invalid type __int128_t");
326   }
327 
operator ()value_extractor328   FMT_NORETURN T operator()(fmt::detail::uint128_t) {
329     throw std::runtime_error("invalid type __uint128_t");
330   }
331 #endif
332 };
333 
TEST(FormatTest,ArgConverter)334 TEST(FormatTest, ArgConverter) {
335   long long value = max_value<long long>();
336   auto arg = fmt::detail::make_arg<fmt::format_context>(value);
337   fmt::visit_format_arg(
338       fmt::detail::arg_converter<long long, fmt::format_context>(arg, 'd'),
339       arg);
340   EXPECT_EQ(value, fmt::visit_format_arg(value_extractor<long long>(), arg));
341 }
342 
TEST(FormatTest,StrError)343 TEST(FormatTest, StrError) {
344   char* message = nullptr;
345   char buffer[BUFFER_SIZE];
346   EXPECT_ASSERT(fmt::detail::safe_strerror(EDOM, message = nullptr, 0),
347                 "invalid buffer");
348   EXPECT_ASSERT(fmt::detail::safe_strerror(EDOM, message = buffer, 0),
349                 "invalid buffer");
350   buffer[0] = 'x';
351 #if defined(_GNU_SOURCE) && !defined(__COVERITY__)
352   // Use invalid error code to make sure that safe_strerror returns an error
353   // message in the buffer rather than a pointer to a static string.
354   int error_code = -1;
355 #else
356   int error_code = EDOM;
357 #endif
358 
359   int result =
360       fmt::detail::safe_strerror(error_code, message = buffer, BUFFER_SIZE);
361   EXPECT_EQ(result, 0);
362   size_t message_size = std::strlen(message);
363   EXPECT_GE(BUFFER_SIZE - 1u, message_size);
364   EXPECT_EQ(get_system_error(error_code), message);
365 
366   // safe_strerror never uses buffer on MinGW.
367 #if !defined(__MINGW32__) && !defined(__sun)
368   result =
369       fmt::detail::safe_strerror(error_code, message = buffer, message_size);
370   EXPECT_EQ(ERANGE, result);
371   result = fmt::detail::safe_strerror(error_code, message = buffer, 1);
372   EXPECT_EQ(buffer, message);  // Message should point to buffer.
373   EXPECT_EQ(ERANGE, result);
374   EXPECT_STREQ("", message);
375 #endif
376 }
377 
TEST(FormatTest,FormatErrorCode)378 TEST(FormatTest, FormatErrorCode) {
379   std::string msg = "error 42", sep = ": ";
380   {
381     fmt::memory_buffer buffer;
382     format_to(buffer, "garbage");
383     fmt::detail::format_error_code(buffer, 42, "test");
384     EXPECT_EQ("test: " + msg, to_string(buffer));
385   }
386   {
387     fmt::memory_buffer buffer;
388     std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size() + 1,
389                        'x');
390     fmt::detail::format_error_code(buffer, 42, prefix);
391     EXPECT_EQ(msg, to_string(buffer));
392   }
393   int codes[] = {42, -1};
394   for (size_t i = 0, n = sizeof(codes) / sizeof(*codes); i < n; ++i) {
395     // Test maximum buffer size.
396     msg = fmt::format("error {}", codes[i]);
397     fmt::memory_buffer buffer;
398     std::string prefix(fmt::inline_buffer_size - msg.size() - sep.size(), 'x');
399     fmt::detail::format_error_code(buffer, codes[i], prefix);
400     EXPECT_EQ(prefix + sep + msg, to_string(buffer));
401     size_t size = fmt::inline_buffer_size;
402     EXPECT_EQ(size, buffer.size());
403     buffer.resize(0);
404     // Test with a message that doesn't fit into the buffer.
405     prefix += 'x';
406     fmt::detail::format_error_code(buffer, codes[i], prefix);
407     EXPECT_EQ(msg, to_string(buffer));
408   }
409 }
410 
TEST(FormatTest,CountCodePoints)411 TEST(FormatTest, CountCodePoints) {
412   EXPECT_EQ(4,
413             fmt::detail::count_code_points(
414                 fmt::basic_string_view<fmt::detail::char8_type>(
415                     reinterpret_cast<const fmt::detail::char8_type*>("ёжик"))));
416 }
417 
418 // Tests fmt::detail::count_digits for integer type Int.
test_count_digits()419 template <typename Int> void test_count_digits() {
420   for (Int i = 0; i < 10; ++i) EXPECT_EQ(1u, fmt::detail::count_digits(i));
421   for (Int i = 1, n = 1, end = max_value<Int>() / 10; n <= end; ++i) {
422     n *= 10;
423     EXPECT_EQ(i, fmt::detail::count_digits(n - 1));
424     EXPECT_EQ(i + 1, fmt::detail::count_digits(n));
425   }
426 }
427 
TEST(UtilTest,CountDigits)428 TEST(UtilTest, CountDigits) {
429   test_count_digits<uint32_t>();
430   test_count_digits<uint64_t>();
431 }
432 
TEST(UtilTest,WriteFallbackUIntPtr)433 TEST(UtilTest, WriteFallbackUIntPtr) {
434   std::string s;
435   fmt::detail::write_ptr<char>(
436       std::back_inserter(s),
437       fmt::detail::fallback_uintptr(reinterpret_cast<void*>(0xface)), nullptr);
438   EXPECT_EQ(s, "0xface");
439 }
440 
441 #ifdef _WIN32
TEST(UtilTest,WriteConsoleSignature)442 TEST(UtilTest, WriteConsoleSignature) {
443   decltype(WriteConsoleW)* p = fmt::detail::WriteConsoleW;
444   (void)p;
445 }
446 #endif
447